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
e81e6b1e80114ea5022ae65980c2df2069dc28d3
2,868
import Foundation public enum OpenGraphMetadata: String, CaseIterable { // Basic Metadata case title case type case image case url // Optional Metadata case audio case description case determiner case locale case localeAlternate = "locale:alternate" case siteName = "site_name" case video // Structured Properties case imageUrl = "image:url" case imageSecure_url = "image:secure_url" case imageType = "image:type" case imageWidth = "image:width" case imageHeight = "image:height" // Music case musicDuration = "music:duration" case musicAlbum = "music:album" case musicAlbumDisc = "music:album:disc" case musicAlbumMusic = "music:album:track" case musicMusician = "music:musician" case musicSong = "music:song" case musicSongDisc = "music:song:disc" case musicSongTrack = "music:song:track" case musicReleaseDate = "music:release_date" case musicCreator = "music:creator" // Video case videoActor = "video:actor" case videoActorRole = "video:actor:role" case videoDirector = "video:director" case videoWriter = "video:writer" case videoDuration = "video:duration" case videoReleaseDate = "video:releaseDate" case videoTag = "video:tag" case videoSeries = "video:series" // No Vertical case articlePublishedTime = "article:published_time" case articleModifiedTime = "article:modified_time" case articleExpirationTime = "article:expiration_time" case articleAuthor = "article:author" case articleSection = "article:section" case articleTag = "article:tag" case bookAuthor = "book:author" case bookIsbn = "book:isbn" case bookReleaseDate = "book:release_date" case bookTag = "book:tag" case profileFirstName = "profile:first_name" case profileLastName = "profile:last_name" case profileUsername = "profile:username" case profileGender = "profile:gender" } #if !swift(>=4.2) public protocol CaseIterable { associatedtype AllCases: Collection where AllCases.Element == Self static var allCases: AllCases { get } } extension CaseIterable where Self: Hashable { public static var allCases: [Self] { return [Self](AnySequence { () -> AnyIterator<Self> in var raw = 0 var first: Self? return AnyIterator { let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) } if raw == 0 { first = current } else if current == first { return nil } raw += 1 return current } }) } } #endif
31.516484
82
0.609484
e0fdd22394b3bf12ad306c9c38fa31840955ef4e
449
// // WDSeparator.swift // Wordist // // Created by Aamir on 08/09/17. // Copyright © 2017 AamirAnwar. All rights reserved. // import UIKit enum WDSeparatorType { case WDSeparatorTypeMiddle } class WDSeparator: UIView { convenience init(type:WDSeparatorType, frame:CGRect) { self.init(frame: frame) switch type { case .WDSeparatorTypeMiddle: self.backgroundColor = WDSeparatorGray } } }
20.409091
58
0.654788
50ef94e180c9de4a756641f0c7c0aea0d8952b58
815
import Foundation struct PinboardWeightedTag : Comparable { let tagName: String let tagCount: Int init(tagName: String, tagCount: Int) { self.tagName = tagName self.tagCount = tagCount } static func < (first: PinboardWeightedTag , second: PinboardWeightedTag) -> Bool { return first.tagCount < second.tagCount } static func <= (first: PinboardWeightedTag , second: PinboardWeightedTag) -> Bool { return first.tagCount <= second.tagCount } static func > (first: PinboardWeightedTag , second: PinboardWeightedTag) -> Bool { return first.tagCount > second.tagCount } static func >= (first: PinboardWeightedTag , second: PinboardWeightedTag) -> Bool { return first.tagCount >= second.tagCount } }
29.107143
87
0.651534
d6fd2c5e47a8793e8c8ede455c30d08b90282bc3
594
// // PickerViewDataSourceProtocol.swift // PickerViewKit // // Created by crelies on 17.03.18. // Copyright (c) 2018 Christian Elies. All rights reserved. // import Foundation /// Protocol describing the structure of a `PickerViewDataSource`. /// public protocol PickerViewDataSourceProtocol: class, UIPickerViewDataSource { var columns: [PickerViewColumn] { get } init(columns: [PickerViewColumn]) func updateColumns(columns: [PickerViewColumn]) func updateColumn(atIndex index: Int, column: PickerViewColumn) func updateRows(inColumn column: Int, rows: [PickerViewRowProtocol]) }
29.7
77
0.771044
39e1243989958a46306957a3455ed32de8fd9058
8,143
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftAWSLambdaRuntime open source project // // Copyright (c) 2017-2020 Apple Inc. and the SwiftAWSLambdaRuntime project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Dispatch import Logging import NIOCore // MARK: - InitializationContext extension Lambda { /// Lambda runtime initialization context. /// The Lambda runtime generates and passes the `InitializationContext` to the Handlers /// ``ByteBufferLambdaHandler/makeHandler(context:)`` or ``LambdaHandler/init(context:)`` /// as an argument. public struct InitializationContext { /// `Logger` to log with /// /// - note: The `LogLevel` can be configured using the `LOG_LEVEL` environment variable. public let logger: Logger /// The `EventLoop` the Lambda is executed on. Use this to schedule work with. /// /// - note: The `EventLoop` is shared with the Lambda runtime engine and should be handled with extra care. /// Most importantly the `EventLoop` must never be blocked. public let eventLoop: EventLoop /// `ByteBufferAllocator` to allocate `ByteBuffer` public let allocator: ByteBufferAllocator init(logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator) { self.eventLoop = eventLoop self.logger = logger self.allocator = allocator } /// This interface is not part of the public API and must not be used by adopters. This API is not part of semver versioning. public static func __forTestsOnly( logger: Logger, eventLoop: EventLoop ) -> InitializationContext { InitializationContext( logger: logger, eventLoop: eventLoop, allocator: ByteBufferAllocator() ) } } } // MARK: - Context /// Lambda runtime context. /// The Lambda runtime generates and passes the `Context` to the Lambda handler as an argument. public struct LambdaContext: CustomDebugStringConvertible { final class _Storage { var requestID: String var traceID: String var invokedFunctionARN: String var deadline: DispatchWallTime var cognitoIdentity: String? var clientContext: String? var logger: Logger var eventLoop: EventLoop var allocator: ByteBufferAllocator init( requestID: String, traceID: String, invokedFunctionARN: String, deadline: DispatchWallTime, cognitoIdentity: String?, clientContext: String?, logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator ) { self.requestID = requestID self.traceID = traceID self.invokedFunctionARN = invokedFunctionARN self.deadline = deadline self.cognitoIdentity = cognitoIdentity self.clientContext = clientContext self.logger = logger self.eventLoop = eventLoop self.allocator = allocator } } private var storage: _Storage /// The request ID, which identifies the request that triggered the function invocation. public var requestID: String { self.storage.requestID } /// The AWS X-Ray tracing header. public var traceID: String { self.storage.traceID } /// The ARN of the Lambda function, version, or alias that's specified in the invocation. public var invokedFunctionARN: String { self.storage.invokedFunctionARN } /// The timestamp that the function times out public var deadline: DispatchWallTime { self.storage.deadline } /// For invocations from the AWS Mobile SDK, data about the Amazon Cognito identity provider. public var cognitoIdentity: String? { self.storage.cognitoIdentity } /// For invocations from the AWS Mobile SDK, data about the client application and device. public var clientContext: String? { self.storage.clientContext } /// `Logger` to log with /// /// - note: The `LogLevel` can be configured using the `LOG_LEVEL` environment variable. public var logger: Logger { self.storage.logger } /// The `EventLoop` the Lambda is executed on. Use this to schedule work with. /// This is useful when implementing the `EventLoopLambdaHandler` protocol. /// /// - note: The `EventLoop` is shared with the Lambda runtime engine and should be handled with extra care. /// Most importantly the `EventLoop` must never be blocked. public var eventLoop: EventLoop { self.storage.eventLoop } /// `ByteBufferAllocator` to allocate `ByteBuffer` /// This is useful when implementing `EventLoopLambdaHandler` public var allocator: ByteBufferAllocator { self.storage.allocator } init(requestID: String, traceID: String, invokedFunctionARN: String, deadline: DispatchWallTime, cognitoIdentity: String? = nil, clientContext: String? = nil, logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator) { self.storage = _Storage( requestID: requestID, traceID: traceID, invokedFunctionARN: invokedFunctionARN, deadline: deadline, cognitoIdentity: cognitoIdentity, clientContext: clientContext, logger: logger, eventLoop: eventLoop, allocator: allocator ) } public func getRemainingTime() -> TimeAmount { let deadline = self.deadline.millisSinceEpoch let now = DispatchWallTime.now().millisSinceEpoch let remaining = deadline - now return .milliseconds(remaining) } public var debugDescription: String { "\(Self.self)(requestID: \(self.requestID), traceID: \(self.traceID), invokedFunctionARN: \(self.invokedFunctionARN), cognitoIdentity: \(self.cognitoIdentity ?? "nil"), clientContext: \(self.clientContext ?? "nil"), deadline: \(self.deadline))" } /// This interface is not part of the public API and must not be used by adopters. This API is not part of semver versioning. public static func __forTestsOnly( requestID: String, traceID: String, invokedFunctionARN: String, timeout: DispatchTimeInterval, logger: Logger, eventLoop: EventLoop ) -> LambdaContext { LambdaContext( requestID: requestID, traceID: traceID, invokedFunctionARN: invokedFunctionARN, deadline: .now() + timeout, logger: logger, eventLoop: eventLoop, allocator: ByteBufferAllocator() ) } } // MARK: - ShutdownContext extension Lambda { /// Lambda runtime shutdown context. /// The Lambda runtime generates and passes the `ShutdownContext` to the Lambda handler as an argument. public final class ShutdownContext { /// `Logger` to log with /// /// - note: The `LogLevel` can be configured using the `LOG_LEVEL` environment variable. public let logger: Logger /// The `EventLoop` the Lambda is executed on. Use this to schedule work with. /// /// - note: The `EventLoop` is shared with the Lambda runtime engine and should be handled with extra care. /// Most importantly the `EventLoop` must never be blocked. public let eventLoop: EventLoop internal init(logger: Logger, eventLoop: EventLoop) { self.eventLoop = eventLoop self.logger = logger } } }
35.099138
252
0.626182
75c0ad2e2972e0f2303ea859f4e4632e6670e1b1
1,022
// // Coronalert // // Devside and all other contributors // copyright owners license this file to you 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 extension CountdownTimer { // only get hours, but round up var hourCeil:Int { get { let components = Calendar.current.dateComponents( [.hour, .minute, .second], from: Date(), to: end ) if components.minute! <= 0 && components.second! <= 0 { return components.hour! } return components.hour! + 1 } } }
24.333333
62
0.693738
eb9ded71903e7ec19751aedf61245babfea4ab85
5,875
import Algorithms @testable import SwiftTreys import XCTest final class ErrorTests: XCTestCase { func testCardFromCharsThrows() throws { let validRanks = "A23456789TJQKA" let validSuits = "chsd" let invalidRanks: [Character] = chain( UnicodeScalar("A").value ... UnicodeScalar("Z").value, UnicodeScalar("0").value ... UnicodeScalar("9").value ) .reduce(into: []) { arr, i in let scalar = UnicodeScalar(i)! let character = Character(scalar) guard !validRanks.contains(character) else { return } arr.append(character) } let invalidSuits: [Character] = (UnicodeScalar("a").value ... UnicodeScalar("z").value).reduce(into: []) { arr, i in let scalar = UnicodeScalar(i)! let character = Character(scalar) guard !validSuits.contains(character) else { return } arr.append(character) } for rank in invalidRanks { XCTAssertThrowsError(try Card(rankChar: rank, suitChar: "c")) { error in guard let error = error as? ParseCardError, case let .invalidRank(originalInput: i, incorrectChar: r) = error else { return XCTFail() } XCTAssertEqual(rank, r) XCTAssertEqual( error.description, """ Error parsing input '\(i)' as a Card: Invalid \ rank character '\(r)', expected one of [23456789TJQKA] """ ) } } for suit in invalidSuits { XCTAssertThrowsError(try Card(rankChar: "A", suitChar: suit)) { error in guard let error = error as? ParseCardError, case let .invalidSuit(originalInput: i, incorrectChar: s) = error else { return XCTFail() } XCTAssertEqual(suit, s) XCTAssertEqual( error.description, """ Error parsing input '\(i)' as a Card: Invalid \ suit character '\(s)', expected one of [chsd] """ ) } } } func testCardParseThrows() throws { let threeCharInput = "abc" let emptyInput = "" XCTAssertThrowsError(try Card.parse(threeCharInput)) { error in guard let error = error as? ParseCardError, case let .invalidLength(originalInput: i) = error else { return XCTFail() } XCTAssertEqual(i, threeCharInput) XCTAssertEqual( error.description, """ Error parsing input '\(threeCharInput)' as a Card: Found \ input of length \(threeCharInput.count), expected 2 """ ) } XCTAssertThrowsError(try Card.parse(emptyInput)) { error in guard let error = error as? ParseCardError, case let .invalidLength(originalInput: i) = error else { return XCTFail() } XCTAssertEqual(i, emptyInput) XCTAssertEqual( error.description, """ Error parsing input '' as a Card: Found \ input of length 0, expected 2 """ ) } let invalidRank = "tc" let invalidSuit = "5H" XCTAssertThrowsError(try Card.parse(invalidRank)) { error in guard let error = error as? ParseCardError, case .invalidRank(originalInput: _, incorrectChar: _) = error else { return XCTFail() } } XCTAssertThrowsError(try Card.parse(invalidSuit)) { error in guard let error = error as? ParseCardError, case .invalidSuit(originalInput: _, incorrectChar: _) = error else { return XCTFail() } } } func testEvaluationDuplicateErrors() throws { let oneDup = try Card.parseArray(strings: ["5c", "5c", "Ad", "3h", "7d"]) for hand in oneDup.permutations(ofCount: 5) { assert(hand.count == 5) XCTAssertThrowsError(try Evaluator.evaluate(cards: hand)) { error in guard let error = error as? EvaluationError, case let .cardsNotUnique(h) = error else { return XCTFail() } XCTAssertEqual(hand, h) XCTAssertEqual( error.description, """ Cannot evaluate a poker hand with a set of cards that \ are not unique. Cards duplicated at least once: \ 5c """ ) } } let oneTrip = try Card.parseArray(strings: ["5c", "5c", "5c", "3h", "7d"]) for hand in oneTrip.permutations(ofCount: 5) { assert(hand.count == 5) XCTAssertThrowsError(try Evaluator.evaluate(cards: hand)) { error in guard let error = error as? EvaluationError, case let .cardsNotUnique(h) = error else { return XCTFail() } XCTAssertEqual(hand, h) XCTAssertEqual( error.description, """ Cannot evaluate a poker hand with a set of cards that \ are not unique. Cards duplicated at least once: \ 5c """ ) } } let multiDup = try Card.parseArray(strings: ["5c", "5c", "3h", "3h", "7d"]) for hand in multiDup.permutations(ofCount: 5) { assert(hand.count == 5) XCTAssertThrowsError(try Evaluator.evaluate(cards: hand)) { error in guard let error = error as? EvaluationError, case let .cardsNotUnique(h) = error else { return XCTFail() } XCTAssertEqual(hand, h) XCTAssert(error.description.contains("5c") && error.description.contains("3h")) } } } func testEvaluationInvalidCountErrors() { let deck = Card.generateDeck() for i in 0 ..< 5 { let cards = deck[0 ..< i] assert(cards.count == i && i < 5) XCTAssertThrowsError(try Evaluator.evaluate(cards: cards)) { error in guard let error = error as? EvaluationError, case let .invalidHandSize(size) = error else { return XCTFail() } XCTAssertEqual(i, size) XCTAssertEqual( error.description, """ Cannot evaluate a poker hand with a set of less than 5 \ cards. Number of cards received: \(i) """ ) } } } }
34.156977
120
0.60017
9b6f3740d2755cfba9a5d6a51d6b7f7b3a5fdeff
2,189
// // AmityCommunityMemberScreenViewModelProtocol.swift // AmityUIKit // // Created by Sarawoot Khunsri on 15/10/2563 BE. // Copyright © 2563 Amity. All rights reserved. // import UIKit import AmitySDK protocol AmityCommunityMemberScreenViewModelDelegate: AnyObject { func screenViewModelDidGetMember() func screenViewModel(_ viewModel: AmityCommunityMemberScreenViewModel, loadingState state: AmityLoadingState) func screenViewModel(_ viewModel: AmityCommunityMemberScreenViewModel, didRemoveUserAt indexPath: IndexPath) func screenViewModelDidAddMemberSuccess() func screenViewModelDidAddRoleSuccess() func screenViewModelDidRemoveRoleSuccess() func screenViewModel(_ viewModel: AmityCommunityMemberScreenViewModel, failure error: AmityError) } protocol AmityCommunityMemberScreenViewModelDataSource { var community: AmityCommunityModel { get } func numberOfMembers() -> Int func member(at indexPath: IndexPath) -> AmityCommunityMembershipModel func getReportUserStatus(at indexPath: IndexPath, completion: ((Bool) -> Void)?) func prepareData() -> [AmitySelectMemberModel] func getCommunityEditUserPermission(_ completion: ((Bool) -> Void)?) } protocol AmityCommunityMemberScreenViewModelAction { func getMember(viewType: AmityCommunityMemberViewType) func loadMore() func addUser(users: [AmitySelectMemberModel]) func removeUser(at indexPath: IndexPath) func reportUser(at indexPath: IndexPath) func unreportUser(at indexPath: IndexPath) func addRole(at indexPath: IndexPath) func removeRole(at indexPath: IndexPath) } protocol AmityCommunityMemberScreenViewModelType: AmityCommunityMemberScreenViewModelAction, AmityCommunityMemberScreenViewModelDataSource { var delegate: AmityCommunityMemberScreenViewModelDelegate? { get set } var action: AmityCommunityMemberScreenViewModelAction { get } var dataSource: AmityCommunityMemberScreenViewModelDataSource { get } } extension AmityCommunityMemberScreenViewModelType { var action: AmityCommunityMemberScreenViewModelAction { return self } var dataSource: AmityCommunityMemberScreenViewModelDataSource { return self } }
41.301887
140
0.803106
67faa8f7018151b9a4b4f0917d2e5449b78cbab6
1,792
// // Copyright © 2019 Essential Developer. All rights reserved. // import UIKit import MVVM extension FeedViewController { func simulateUserInitiatedFeedReload() { refreshControl?.simulatePullToRefresh() } @discardableResult func simulateFeedImageViewVisible(at index: Int) -> FeedImageCell? { return feedImageView(at: index) as? FeedImageCell } @discardableResult func simulateFeedImageViewNotVisible(at row: Int) -> FeedImageCell? { let view = simulateFeedImageViewVisible(at: row) let delegate = tableView.delegate let index = IndexPath(row: row, section: feedImagesSection) delegate?.tableView?(tableView, didEndDisplaying: view!, forRowAt: index) return view } func simulateFeedImageViewNearVisible(at row: Int) { let ds = tableView.prefetchDataSource let index = IndexPath(row: row, section: feedImagesSection) ds?.tableView(tableView, prefetchRowsAt: [index]) } func simulateFeedImageViewNotNearVisible(at row: Int) { simulateFeedImageViewNearVisible(at: row) let ds = tableView.prefetchDataSource let index = IndexPath(row: row, section: feedImagesSection) ds?.tableView?(tableView, cancelPrefetchingForRowsAt: [index]) } var isShowingLoadingIndicator: Bool { return refreshControl?.isRefreshing == true } var errorMessage: String? { let view = tableView.tableHeaderView as? ErrorView return view?.message } func numberOfRenderedFeedImageViews() -> Int { return tableView.numberOfRows(inSection: feedImagesSection) } func feedImageView(at row: Int) -> UITableViewCell? { let ds = tableView.dataSource let index = IndexPath(row: row, section: feedImagesSection) return ds?.tableView(tableView, cellForRowAt: index) } private var feedImagesSection: Int { return 0 } }
27.151515
75
0.748326
4b031775b276738e3b322162a7cbfba1414c5680
10,344
// // ViewController.swift // Tip Calculator // // Created by Robert Reyes-Enamorado on 1/10/22. // import UIKit class ViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var billAmountLabel: UILabel! @IBOutlet weak var billAmountTextField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var tipAmountLabel: UILabel! @IBOutlet weak var partyLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var partySizeStepper: UIStepper! @IBOutlet weak var total: UILabel! @IBOutlet weak var partySizeLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var splitPerPersonLabel: UILabel! @IBOutlet weak var splitLabel: UILabel! @IBOutlet weak var roundControl: UISegmentedControl! let defaults = UserDefaults.standard var tipValue:Double? var totalValue:Double? var splitValue:Double? var currency = "" var tipPercentage = 0.0 var defaultBillAmount:String? var calculationDate:NSDate? var expirationDate:NSDate? override func viewDidLoad() { super.viewDidLoad() currencyBasedOnRegion() // Change text field placeholder text & summon keyboard on start billAmountTextField.placeholder = currency billAmountTextField.becomeFirstResponder() // Apply defaults for segmented controls tipControl.selectedSegmentIndex = defaults.integer(forKey: "%") roundControl.selectedSegmentIndex = defaults.integer(forKey: "Round") defaultTip() rememberBillAmount() // Edit stepper increment and decrement image colors partySizeStepper.setDecrementImage(partySizeStepper.decrementImage(for: .normal), for: .normal) partySizeStepper.setIncrementImage(partySizeStepper.incrementImage(for: .normal), for: .normal) calculateTip(Any.self) } func currencyBasedOnRegion() { // Get the current region let userLocation = Locale.current.regionCode // Change the currency based on the region switch userLocation { case "FR", "DE", "IE", "NL", "PT", "ES": currency = "€" break case "GB": currency = "£" break case "JP", "CN": currency = "¥" break default: currency = "$" } } func rememberBillAmount() { // Assign dates to constants let currentDate = NSDate() let expireDate:NSDate = defaults.object(forKey: "Expiration") as! NSDate // Calculate which date is later if currentDate.laterDate(expireDate as Date) == currentDate as Date { // Executes if time expired billAmountTextField.text = "" partySizeStepper.value = 1 } else { // Exececutes if time has not expired billAmountTextField.text = defaults.string(forKey: "Bill") partySizeStepper.value = Double(defaults.integer(forKey: "Party")) } } func defaultTip() { let tipIndex = defaults.integer(forKey: "%") switch tipIndex { case 1: tipPercentage = 0.18 break case 2: tipPercentage = 0.20 break default: tipPercentage = 0.15 } } @IBAction func calculateTip(_ sender: Any) { // Get bill amount from text field input let bill = Double(billAmountTextField.text!) ?? 0 // Calculate required values tipValue = bill * tipPercentage totalValue = bill + tipValue! // Use stepper & calculate Split Per Person let size = Int(partySizeStepper.value) splitValue = (totalValue ?? 0)/Double(size) // Update the Party Size, Tip Amount, & Total labels partySizeLabel.text = String(size) tipAmountLabel.text = String(format: "\(currency)%.2f", tipValue!) totalLabel.text = String(format: "\(currency)%.2f", totalValue!) roundSplitValue(partySize: size) // Update Split Amount label splitLabel.text = String(format: "\(currency)%.2f", splitValue!) displayAnimations() // Set Calculation Date & an Expiration Date for 10 minutes later calculationDate = NSDate() expirationDate = calculationDate?.addingTimeInterval(600) // Save the Expriation Date, Bill Amount, and Party Size defaults.set(expirationDate, forKey: "Expiration") defaults.set(billAmountTextField.text, forKey: "Bill") defaults.set(partySizeStepper.value, forKey: "Party") defaults.synchronize() } @IBAction func didMoveTipContol(_ sender: Any) { let index = tipControl.selectedSegmentIndex // Store Tip Percentage based on index value switch index { case 1: tipPercentage = 0.18 break case 2: tipPercentage = 0.20 break default: tipPercentage = 0.15 } calculateTip(Any.self) } func roundSplitValue (partySize: Int) { // Rounding if roundControl.selectedSegmentIndex == 1 { splitValue = (totalValue ?? 0)/Double(partySize) } else if roundControl.selectedSegmentIndex == 2 { splitValue = (totalValue ?? 0)/Double(partySize) splitValue = splitValue!.rounded(.up) } else { splitValue = (totalValue ?? 0)/Double(partySize) splitValue = splitValue!.rounded(.down) } } func DarkModeEditor() { let boolValue = defaults.bool(forKey: "Dark Mode") // Toggle Dark Mode or Default Mode if boolValue == true { self.navigationController?.navigationBar.barStyle = .black self.view.backgroundColor = .black titleLabel.textColor = .white billAmountTextField.textColor = .white billAmountTextField.keyboardAppearance = .dark billAmountTextField.attributedPlaceholder = NSAttributedString(string: currency, attributes: [NSAttributedString.Key.foregroundColor : UIColor.lightText]) billAmountLabel.textColor = .white tipLabel.textColor = .white partyLabel.textColor = .white total.textColor = .white tipAmountLabel.textColor = .white partySizeLabel.textColor = .white totalLabel.textColor = .white splitPerPersonLabel.textColor = .white tipControl.backgroundColor = .secondaryLabel tipControl.selectedSegmentTintColor = .systemGreen tipControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: UIControl.State.normal) roundControl.backgroundColor = .secondaryLabel roundControl.selectedSegmentTintColor = .systemGreen roundControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: UIControl.State.normal) partySizeStepper.backgroundColor = .secondaryLabel partySizeStepper.tintColor = .white } else if boolValue == false{ self.navigationController?.navigationBar.barStyle = .default self.view.backgroundColor = .systemBackground titleLabel.textColor = .black billAmountTextField.textColor = .black billAmountTextField.keyboardAppearance = .light billAmountTextField.attributedPlaceholder = NSAttributedString(string: currency, attributes: [NSAttributedString.Key.foregroundColor : UIColor.lightGray]) billAmountLabel.textColor = .black tipLabel.textColor = .black partyLabel.textColor = .black total.textColor = .black tipAmountLabel.textColor = .black partySizeLabel.textColor = .black totalLabel.textColor = .black splitPerPersonLabel.textColor = .black tipControl.selectedSegmentTintColor = .systemGreen tipControl.backgroundColor = .systemBackground tipControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: UIControl.State.normal) roundControl.selectedSegmentTintColor = .systemGreen roundControl.backgroundColor = .systemBackground roundControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: UIControl.State.normal) partySizeStepper.backgroundColor = .systemGray6 partySizeStepper.tintColor = .black } } func displayAnimations() { UIView.animate(withDuration: 0.05, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0 ,animations: { self.splitLabel.center = CGPoint(x: 274, y:446+2) }, completion: nil) UIView.animate(withDuration: 0.05, delay: 0.05, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0, animations: { self.splitLabel.center = CGPoint(x: 274, y:446-2) }, completion: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) DarkModeEditor() tipControl.selectedSegmentIndex = defaults.integer(forKey: "%") roundControl.selectedSegmentIndex = defaults.integer(forKey: "Round") defaultTip() calculateTip(Any.self) } }
34.365449
166
0.589327
7666eee6607bda71fc561a471db4b508065f3625
586
// // ViewController.swift // Aula12_01_App01 // // Created by SP11793 on 22/03/22. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "App 1" view.backgroundColor = .blue } @IBAction func getViewController() { let customUrl = "NavigationSchemes://" if let url = URL(string: customUrl) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } } }
17.235294
53
0.544369
6993c588a619c6a3b480f6cc7cfad9f2d1a1d14a
637
// // DispatchQueue+LPKit.swift // LPKit <https://github.com/leo-lp/LPKit> // // Created by pengli on 2018/5/21. // Copyright © 2018年 pengli. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import Dispatch import Foundation.NSThread public extension DispatchQueue { /// 如果当前self是主队列,且线程是主线程,则block将立即被调用 func lp_safeAsync(_ block: @escaping ()->()) { if self === DispatchQueue.main && Thread.isMainThread { block() } else { async { block() } } } }
23.592593
73
0.631083
286e38accd35068a45a215c47637966c1af2a4f3
3,068
// // CwlSwitch_iOS.swift // CwlViews_iOS // // Created by Matt Gallagher on 2017/12/20. // Copyright © 2017 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved. // // // Permission to use, copy, modify, and/or distribute this software for any purpose with or without // fee is hereby granted, provided that the above copyright notice and this permission notice // appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE // AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE // OF THIS SOFTWARE. // #if os(iOS) extension BindingParser where Downcast: SwitchBinding { // You can easily convert the `Binding` cases to `BindingParser` using the following Xcode-style regex: // Replace: case ([^\(]+)\((.+)\)$ // With: public static var $1: BindingParser<$2, Switch.Binding, Downcast> { return .init(extract: { if case .$1(let x) = \$0 { return x } else { return nil } }, upcast: { \$0.asSwitchBinding() }) } // 0. Static bindings are applied at construction and are subsequently immutable. // 1. Value bindings may be applied at construction and may subsequently change. public static var isOn: BindingParser<Dynamic<SetOrAnimate<Bool>>, Switch.Binding, Downcast> { return .init(extract: { if case .isOn(let x) = $0 { return x } else { return nil } }, upcast: { $0.asSwitchBinding() }) } public static var offImage: BindingParser<Dynamic<UIImage?>, Switch.Binding, Downcast> { return .init(extract: { if case .offImage(let x) = $0 { return x } else { return nil } }, upcast: { $0.asSwitchBinding() }) } public static var onImage: BindingParser<Dynamic<UIImage?>, Switch.Binding, Downcast> { return .init(extract: { if case .onImage(let x) = $0 { return x } else { return nil } }, upcast: { $0.asSwitchBinding() }) } public static var onTintColor: BindingParser<Dynamic<UIColor>, Switch.Binding, Downcast> { return .init(extract: { if case .onTintColor(let x) = $0 { return x } else { return nil } }, upcast: { $0.asSwitchBinding() }) } public static var thumbTintColor: BindingParser<Dynamic<UIColor>, Switch.Binding, Downcast> { return .init(extract: { if case .thumbTintColor(let x) = $0 { return x } else { return nil } }, upcast: { $0.asSwitchBinding() }) } public static var tintColor: BindingParser<Dynamic<UIColor>, Switch.Binding, Downcast> { return .init(extract: { if case .tintColor(let x) = $0 { return x } else { return nil } }, upcast: { $0.asSwitchBinding() }) } // 2. Signal bindings are performed on the object after construction. // 3. Action bindings are triggered by the object after construction. // 4. Delegate bindings require synchronous evaluation within the object's context. } #endif
66.695652
226
0.715776
22261d9fff50742797706735ddac7d2e92645aa6
3,878
// // Storage.swift // Navigation // // Created by Andrey Antipov on 18.10.2020. // Copyright © 2020 Andrey Antipov. All rights reserved. // import Foundation struct Storage { static let posts = [ Post(author: "Побег из Шоушенка", description: """ Бухгалтер Энди Дюфрейн обвинён в убийстве собственной жены и её любовника. \ Оказавшись в тюрьме под названием Шоушенк, он сталкивается с жестокостью и беззаконием, \ царящими по обе стороны решётки. Каждый, кто попадает в эти стены, становится их рабом \ до конца жизни. Но Энди, обладающий живым умом и доброй душой, находит подход как к заключённым, \ так и к охранникам, добиваясь их особого к себе расположения. """, image: "TheShawshankRedemption", likes: 659411, views: 723753), Post(author: "Зеленая миля (Фрэнк Дарабонт)", description: """ Пол Эджкомб - начальник блока смертников в тюрьме «Холодная гора», \ каждый из узников которого однажды проходит «зеленую милю» по пути к месту казни. \ Пол повидал много заключённых и надзирателей за время работы. Однако гигант Джон Коффи, \ обвинённый в страшном преступлении, стал одним из самых необычных обитателей блока. """, image: "TheGreenMile", likes: 565114, views: 623609), Post(author: "Форрест Гамп (Роберт Земекис)", description: """ От лица главного героя Форреста Гампа, слабоумного безобидного человека с благородным и \ открытым сердцем, рассказывается история его необыкновенной жизни. Фантастическим образом \ превращается он в известного футболиста, героя войны, преуспевающего бизнесмена. \ Он становится миллиардером, но остается таким же бесхитростным, глупым и добрым. \ Форреста ждет постоянный успех во всем, а он любит девочку, с которой дружил в детстве, \ но взаимность приходит слишком поздно. """, image: "ForrestGump", likes: 524497, views: 588529 ), Post(author: "Список Шиндлера (Стивен Спилберг)", description: """ Фильм рассказывает реальную историю загадочного Оскара Шиндлера, члена нацистской партии, \ преуспевающего фабриканта, спасшего во время Второй мировой войны почти 1200 евреев. """, image: "SchindlersList", likes: 299305, views: 339386), Post(author: "1+1 (Оливье Накаш, Эрик Толедано)", description: """ Пострадав в результате несчастного случая, богатый аристократ Филипп нанимает в помощники человека, \ который менее всего подходит для этой работы, – молодого жителя предместья Дрисса, \ только что освободившегося из тюрьмы. \ Несмотря на то, что Филипп прикован к инвалидному креслу, Дриссу удается привнести \ в размеренную жизнь аристократа дух приключений. """, image: "Intouchables", likes: 1042476, views: 1183690) ] static let profiles = [ Profile(name: "Маша", status: "Online", image: "Masha", age: 22, karma: 347), Profile(name: "Ольга", status: "Offline", image: "Olga", age: 34, karma: 2347), Profile(name: "Петя", status: "Will be back", image: "Petya", age: 26, karma: 47), Profile(name: "Егор", status: "Online", image: "Egor", age: 28, karma: 4347), Profile(name: "Жана", status: "On line", image: "Jana", age: 24, karma: 647), Profile(name: "Билл", status: "On line", image: "Bill", age: 32, karma: 3) ] static let photos = [ "photo_00", "photo_01", "photo_02", "photo_03", "photo_04", "photo_05", "photo_06", "photo_07", "photo_08", "photo_09", "photo_10", "photo_11", "photo_12", "photo_13", "photo_14", "photo_15", "photo_16", "photo_17", "photo_18", "photo_19", "photo_20" ] }
59.661538
114
0.646467
113a57aab418843fd61fb285d303062e3a0bd519
888
// // PwrARNavTests.swift // PwrARNavTests // // Created by Oleksii Furman on 08/11/2018. // Copyright © 2018 Oleksii Furman. All rights reserved. // import XCTest class PwrARNavTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.117647
111
0.652027
6a03ea82702fadfe2f871d1fa0802c14941c98f7
3,307
// // PlaySoundsViewController.swift // Pick Your Pitch // // Created by xengar on 2017-11-29. // Copyright © 2017 xengar. All rights reserved. // import UIKit import AVFoundation // MARK: - PlaySoundsViewController: UIViewController class PlaySoundsViewController: UIViewController { // MARK: Properties let SliderValueKey = "Slider Value Key" var audioPlayer:AVAudioPlayer! var receivedAudio:RecordedAudio! var audioEngine:AVAudioEngine! var audioFile:AVAudioFile! // MARK: Outlets @IBOutlet weak var sliderView: UISlider! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var stopButton: UIButton! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() do { audioPlayer = try AVAudioPlayer(contentsOf: receivedAudio.filePathUrl as URL) } catch _ { audioPlayer = nil } audioPlayer.enableRate = true audioEngine = AVAudioEngine() do { audioFile = try AVAudioFile(forReading: receivedAudio.filePathUrl as URL) } catch _ { audioFile = nil } setUserInterfaceToPlayMode(false) // read the value for slider from defaults let sliderValue = UserDefaults.standard.float(forKey: "sliderValue") sliderView.value = sliderValue } // MARK: Set Interface func setUserInterfaceToPlayMode(_ isPlayMode: Bool) { startButton.isHidden = isPlayMode stopButton.isHidden = !isPlayMode sliderView.isEnabled = !isPlayMode } // MARK: Actions @IBAction func playAudio(_ sender: UIButton) { // Get the pitch from the slider let pitch = sliderView.value // Play the sound playAudioWithVariablePitch(pitch) // Set the UI setUserInterfaceToPlayMode(true) // Save the slider value UserDefaults.standard.set(sliderView.value, forKey: "sliderValue") } @IBAction func stopAudio(_ sender: UIButton) { audioPlayer.stop() audioEngine.stop() audioEngine.reset() } @IBAction func sliderDidMove(_ sender: UISlider) { print("Slider vaue: \(sliderView.value)") } // MARK: Play Audio func playAudioWithVariablePitch(_ pitch: Float){ audioPlayer.stop() audioEngine.stop() audioEngine.reset() let audioPlayerNode = AVAudioPlayerNode() audioEngine.attach(audioPlayerNode) let changePitchEffect = AVAudioUnitTimePitch() changePitchEffect.pitch = pitch audioEngine.attach(changePitchEffect) audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil) audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil) audioPlayerNode.scheduleFile(audioFile, at: nil) { // When the audio completes, set the user interface on the main thread DispatchQueue.main.async {self.setUserInterfaceToPlayMode(false) } } do { try audioEngine.start() } catch _ { } audioPlayerNode.play() } }
27.330579
89
0.617478
8913dd5700573040e92e23f579d396ab607f18e0
1,934
// // Copyright (C) 2020 Twilio, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class CommunityTwilioAccessTokenStore: TwilioAccessTokenStoreReading { private let api: APIRequesting private let appSettingsStore: AppSettingsStoreWriting private let authStore: AuthStoreReading private let remoteConfigStore: RemoteConfigStoreWriting init( api: APIRequesting, appSettingsStore: AppSettingsStoreWriting, authStore: AuthStoreReading, remoteConfigStore: RemoteConfigStoreWriting ) { self.api = api self.appSettingsStore = appSettingsStore self.authStore = authStore self.remoteConfigStore = remoteConfigStore } func fetchTwilioAccessToken(roomName: String, completion: @escaping (Result<String, APIError>) -> Void) { let request = CommunityCreateTwilioAccessTokenRequest( passcode: authStore.passcode ?? "", userIdentity: appSettingsStore.userIdentity, createRoom: true, roomName: roomName ) api.request(request) { [weak self] result in guard let self = self else { return } if let roomType = try? result.get().roomType { self.remoteConfigStore.roomType = roomType } completion(result.map { $0.token }) } } }
34.535714
109
0.668046
e57e90ae16c75835c8fe28ce38d6abd8a9a55f83
478
import Superb extension GitHubBasicAuthProvider { static var shared: GitHubBasicAuthProvider { return Superb.register( GitHubBasicAuthProvider() ) } } extension GitHubOAuthProvider { static var shared: GitHubOAuthProvider { return Superb.register( GitHubOAuthProvider( clientId: Secrets.GitHubOAuth.clientId, clientSecret: Secrets.GitHubOAuth.clientSecret, redirectURI: Secrets.GitHubOAuth.callbackURL ) ) } }
21.727273
55
0.715481
464a7593d570733b41e4800ec68112c22cd5c276
203
// // JSON.swift // EoKoe // // Created by Jaime Costa Marques on 03/05/18. // Copyright © 2018 Jaime Costa Marques. All rights reserved. // import Foundation public typealias JSON = [String: Any]
16.916667
62
0.684729
64114457e2f888873f80c3865a2d7c870b7b4508
681
// // RunResult.swift // Bluejay // // Created by Jeremy Chiang on 2017-06-01. // Copyright © 2017 Steamclock Software. All rights reserved. // import Foundation /// Indicates a successful, cancelled, or failed `run(backgroundTask:completionOnMainThread:)` attempt, where the success case contains the value returned at the end of the background task. public enum RunResult<R> { /// The background task is successful, and the returned value is captured in the associated value. case success(R) /// The background task is cancelled for a reason. case cancelled /// The background task has failed unexpectedly with an error. case failure(Swift.Error) }
34.05
189
0.734214
75e09f8e1b4f9c3d8704bf7960e37f4369d7afd7
1,175
// // RegistrarOperationTests.swift // ChikaCoreTests // // Created by Mounir Ybanez on 1/8/18. // Copyright © 2018 Nir. All rights reserved. // import XCTest @testable import ChikaCore class RegistrarOperationTests: XCTestCase { func testRegisterA() { let registrar = RegistrarMock() let operation = RegistrarOperation() var ok = operation.withEmail("[email protected]").register(using: registrar) XCTAssertFalse(ok) ok = operation.withPassword("me12345").register(using: registrar) XCTAssertFalse(ok) ok = operation.withEmail("[email protected]").withPassword("me12345").register(using: registrar) XCTAssertTrue(ok) } func testRegisterB() { let exp = expectation(description: "testRegisterB") let registrar = RegistrarMock() let operation = RegistrarOperation() let completion: (Result<Auth>) -> Void = { _ in exp.fulfill() } let ok = operation.withEmail("[email protected]").withPassword("me12345").withCompletion(completion).register(using: registrar) XCTAssertTrue(ok) wait(for: [exp], timeout: 1.0) } }
30.128205
127
0.636596
8977e03725859ef445cf65788bfda382ffcb8b73
2,287
// EvictExpiredRecordsPersistenceTask.swift // RxCache // // Copyright (c) 2016 Victor Albertos https://github.com/VictorAlbertos // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import RxSwift class EvictExpiredRecordsPersistence { private let hasRecordExpired: HasRecordExpired private let persistence : Persistence init (persistence : Persistence) { self.hasRecordExpired = HasRecordExpired() self.persistence = persistence } func startEvictingExpiredRecords() -> Observable<String> { return Observable.create { subscriber in let allKeys = self.persistence.allKeys() allKeys.forEach({ (key) -> () in if let record : Record<CacheablePlaceholder> = self.persistence.retrieveRecord(key) where self.hasRecordExpired.hasRecordExpired(record) { self.persistence.evict(key) subscriber.onNext(key) } }) subscriber.onCompleted() return NopDisposable.instance } } } class CacheablePlaceholder : GlossCacheable { func toJSON() -> JSON? { return [String : AnyObject]() } required init(json: JSON) { } }
39.431034
154
0.686489
46efbde9c40b6e8a6b67ba1fe95de9b6d735f4ed
7,720
// RUN: rm -rf %t && mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/has_accessibility.swift -D DEFINE_VAR_FOR_SCOPED_IMPORT -enable-testing // RUN: %target-swift-frontend -typecheck -primary-file %t/main.swift %S/Inputs/accessibility_other.swift -module-name accessibility -I %t -sdk "" -enable-access-control -verify -verify-ignore-unknown // RUN: %target-swift-frontend -typecheck -primary-file %t/main.swift %S/Inputs/accessibility_other.swift -module-name accessibility -I %t -sdk "" -disable-access-control -D ACCESS_DISABLED // RUN: not %target-swift-frontend -typecheck -primary-file %t/main.swift %S/Inputs/accessibility_other.swift -module-name accessibility -I %t -sdk "" -D TESTABLE 2>&1 | %FileCheck -check-prefix=TESTABLE %s #if TESTABLE @testable import has_accessibility #else import has_accessibility #endif // This deliberately has the wrong import kind. import var has_accessibility.zz // expected-error {{variable 'zz' does not exist in module 'has_accessibility'}} func markUsed<T>(_ t: T) {} markUsed(has_accessibility.x) markUsed(has_accessibility.y) // expected-error {{module 'has_accessibility' has no member named 'y'}} markUsed(has_accessibility.z) // expected-error {{module 'has_accessibility' has no member named 'z'}} // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE: :[[@LINE-3]]:10: error: module 'has_accessibility' has no member named 'z' markUsed(accessibility.a) markUsed(accessibility.b) markUsed(accessibility.c) // expected-error {{module 'accessibility' has no member named 'c'}} markUsed(x) markUsed(y) // expected-error {{use of unresolved identifier 'y'}} markUsed(z) // expected-error {{use of unresolved identifier 'z'}} // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE: :[[@LINE-3]]:10: error: use of unresolved identifier 'z' markUsed(a) markUsed(b) markUsed(c) // expected-error {{use of unresolved identifier 'c'}} Foo.x() Foo.y() // expected-error {{'y' is inaccessible due to 'internal' protection level}} Foo.z() // expected-error {{'z' is inaccessible due to 'private' protection level}} // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE: :[[@LINE-3]]:{{[^:]+}}: error: 'z' is inaccessible due to 'private' protection level Foo.a() Foo.b() Foo.c() // expected-error {{'c' is inaccessible due to 'private' protection level}} _ = Foo() // expected-error {{'Foo' initializer is inaccessible due to 'internal' protection level}} // <rdar://problem/27982012> QoI: Poor diagnostic for inaccessible initializer struct rdar27982012 { var x: Int private init(_ x: Int) { self.x = x } // expected-note {{'init' declared here}} } _ = { rdar27982012($0.0) }((1, 2)) // expected-error {{initializer is inaccessible due to 'private' protection level}} // TESTABLE-NOT: :[[@LINE-1]]:{{[^:]+}}: _ = PrivateInit() // expected-error {{'PrivateInit' initializer is inaccessible due to 'private' protection level}} // TESTABLE: :[[@LINE-1]]:{{[^:]+}}: error: 'PrivateInit' initializer is inaccessible due to 'private' protection level var s = StructWithPrivateSetter() s.x = 42 // expected-error {{cannot assign to property: 'x' setter is inaccessible}} class Sub : Base { func test() { value = 4 // expected-error {{cannot assign to property: 'value' setter is inaccessible}} self.value = 4 // expected-error {{cannot assign to property: 'value' setter is inaccessible}} super.value = 4 // expected-error {{cannot assign to property: 'value' setter is inaccessible}} // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: method() // expected-error {{'method' is inaccessible due to 'internal' protection level}} self.method() // expected-error {{'method' is inaccessible due to 'internal' protection level}} super.method() // expected-error {{'method' is inaccessible due to 'internal' protection level}} // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: // TESTABLE-NOT: :[[@LINE-3]]:{{[^:]+}}: } } class ObservingOverrider : Base { override var value: Int { // expected-error {{cannot observe read-only property 'value'; it can't change}} willSet { markUsed(newValue) } } } class ReplacingOverrider : Base { override var value: Int { get { return super.value } set { super.value = newValue } // expected-error {{cannot assign to property: 'value' setter is inaccessible}} } } protocol MethodProto { func method() // expected-note * {{protocol requires function 'method()' with type '() -> ()'}} } extension OriginallyEmpty : MethodProto {} #if !ACCESS_DISABLED extension HiddenMethod : MethodProto {} // expected-error {{type 'HiddenMethod' does not conform to protocol 'MethodProto'}} // TESTABLE-NOT: :[[@LINE-1]]:{{[^:]+}}: extension Foo : MethodProto {} // expected-error {{type 'Foo' does not conform to protocol 'MethodProto'}} #endif protocol TypeProto { associatedtype TheType // expected-note * {{protocol requires nested type 'TheType'}} } extension OriginallyEmpty {} #if !ACCESS_DISABLED extension HiddenType : TypeProto {} // expected-error {{type 'HiddenType' does not conform to protocol 'TypeProto'}} // TESTABLE-NOT: :[[@LINE-1]]:{{[^:]+}}: extension Foo : TypeProto {} // expected-error {{type 'Foo' does not conform to protocol 'TypeProto'}} #endif #if !ACCESS_DISABLED private func privateInBothFiles() {} // no-warning private func privateInPrimaryFile() {} // expected-error {{invalid redeclaration}} func privateInOtherFile() {} // expected-note {{previously declared here}} #endif #if !ACCESS_DISABLED struct ConformerByTypeAlias : TypeProto { private typealias TheType = Int // expected-error {{type alias 'TheType' must be declared internal because it matches a requirement in internal protocol 'TypeProto'}} {{3-10=internal}} } struct ConformerByLocalType : TypeProto { private struct TheType {} // expected-error {{struct 'TheType' must be declared internal because it matches a requirement in internal protocol 'TypeProto'}} {{3-10=internal}} } private struct PrivateConformerByLocalType : TypeProto { struct TheType {} // okay } private struct PrivateConformerByLocalTypeBad : TypeProto { private struct TheType {} // expected-error {{struct 'TheType' must be as accessible as its enclosing type because it matches a requirement in protocol 'TypeProto'}} {{3-10=fileprivate}} } #endif public protocol Fooable { func foo() // expected-note * {{protocol requires function 'foo()'}} } #if !ACCESS_DISABLED internal struct FooImpl: Fooable, HasDefaultImplementation {} // expected-error {{type 'FooImpl' does not conform to protocol 'Fooable'}} public struct PublicFooImpl: Fooable, HasDefaultImplementation {} // expected-error {{type 'PublicFooImpl' does not conform to protocol 'Fooable'}} // TESTABLE-NOT: method 'foo()' internal class TestableSub: InternalBase {} // expected-error {{undeclared type 'InternalBase'}} public class TestablePublicSub: InternalBase {} // expected-error {{undeclared type 'InternalBase'}} // TESTABLE-NOT: undeclared type 'InternalBase' #endif // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: 'y' declared here // <unknown>:0: error: unexpected note produced: 'z' declared here // <unknown>:0: error: unexpected note produced: 'init()' declared here // <unknown>:0: error: unexpected note produced: 'method()' declared here // <unknown>:0: error: unexpected note produced: 'method' declared here // <unknown>:0: error: unexpected note produced: 'method' declared here
44.883721
206
0.699741
89c36d81afbc56663f7974e845e92d5199e0f107
1,251
// // AddQueryVC.swift // AwesomeHelper // // Created by Serhii Londar on 1/16/18. // Copyright © 2018 slon. All rights reserved. // import UIKit enum AddQueryVCMode { case create case edit } class AddQueryVC: BaseVC { @IBOutlet weak var queryTextField: UITextField! = nil @IBOutlet weak var addQueryButton: UIButton! = nil override var presenter: AddQueryPresenter { return _presenter as! AddQueryPresenter } override func viewDidLoad() { super.viewDidLoad() queryTextField.placeholder = "Please enter search query here" if self.presenter.mode == .edit { queryTextField.text = self.presenter.query?.query addQueryButton.setTitle("Update Query", for: .normal) } else { addQueryButton.setTitle("Add Query", for: .normal) } } @IBAction func addQueryButtonPressed(_ sender: Any) { if let queryText = self.queryTextField.text { if self.presenter.mode == .create { self.presenter.addQuery(queryText) } else { self.presenter.editQuery(queryText) } } else { self.showErrorAlert("Query can't be empty") } } }
26.617021
69
0.606715
1ebb29722eae13f27e6b28d4885ce9b6cf384b19
2,605
// // AppDelegate.swift // // Copyright (c) 2016-present, LINE Corporation. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by LINE Corporation. // // As with any software that integrates with the LINE Corporation platform, your use of this software // is subject to the LINE Developers Agreement [http://terms2.line.me/LINE_Developers_Agreement]. // This copyright notice shall be included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import LineSDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { #if LINE_SDK_INTERNAL Constant.toBeta() #endif // Modify Config.xcconfig to setup your LINE channel ID. if let channelID = Bundle.main.infoDictionary?["LINE Channel ID"] as? String, let _ = Int(channelID) { LoginManager.shared.setup(channelID: channelID, universalLinkURL: nil) } else { fatalError("Please set correct channel ID in Config.xcconfig file.") } window!.tintColor = UIColor(red: 91 / 255, green: 192 / 255, blue: 110 / 255, alpha: 1.0) return true } func application( _ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return LoginManager.shared.application(application, open: url, options: options) } func application( _ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { return LoginManager.shared.application(application, open: userActivity.webpageURL) } }
36.690141
102
0.689827
9cd83d6b1499269a45d4dc4e5d2e9a55bed0bded
1,781
// // Extensions.swift // WorkersFreeTime // // Created by 栗志 on 2018/9/27. // Copyright © 2018年 com.lizhi1026. All rights reserved. // import UIKit extension UIColor { static func colorWithHexString(_ hex:String, alpha: Double=1.0) -> UIColor { var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString = (cString as NSString).substring(from: 1) } if (cString.count != 6) { return UIColor.gray } let rString = (cString as NSString).substring(to: 2) let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2) let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(alpha)) } static func rgb(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat) -> UIColor { return UIColor.init(red: r / 255, green: g / 255, blue: b / 255, alpha: 1.0) } static func colorFromHex(_ Hex: UInt32) -> UIColor { return UIColor.init(red: CGFloat((Hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((Hex & 0xFF00) >> 8) / 255.0, blue: CGFloat((Hex & 0xFF)) / 255.0, alpha: 1.0) } }
35.62
123
0.544076
6488d84dabde9b35b2099988deb8f87ff23735c3
11,026
// // MaskedTextFieldDelegate.swift // InputMask // // Created by Egor Taflanidi on 17.08.28. // Copyright © 28 Heisei Egor Taflanidi. All rights reserved. // import Foundation import UIKit /** ### MaskedTextFieldDelegateListener Allows clients to obtain value extracted by the mask from user input. Provides callbacks from listened UITextField. */ @objc public protocol MaskedTextFieldDelegateListener: UITextFieldDelegate { /** Callback to return extracted value and to signal whether the user has complete input. */ @objc optional func textField( _ textField: UITextField, didFillMandatoryCharacters complete: Bool, didExtractValue value: String ) } /** ### MaskedTextFieldDelegate UITextFieldDelegate, which applies masking to the user input. Might be used as a decorator, which forwards UITextFieldDelegate calls to its own listener. */ @IBDesignable open class MaskedTextFieldDelegate: NSObject, UITextFieldDelegate { private var _maskFormat: String private var _autocomplete: Bool private var _autocompleteOnFocus: Bool public var mask: Mask @IBInspectable public var maskFormat: String { get { return self._maskFormat } set(newFormat) { self._maskFormat = newFormat self.mask = try! Mask.getOrCreate(withFormat: newFormat) } } @IBInspectable public var autocomplete: Bool { get { return self._autocomplete } set(newAutocomplete) { self._autocomplete = newAutocomplete } } @IBInspectable public var autocompleteOnFocus: Bool { get { return self._autocompleteOnFocus } set(newAutocompleteOnFocus) { self._autocompleteOnFocus = newAutocompleteOnFocus } } open weak var listener: MaskedTextFieldDelegateListener? public init(format: String) { self._maskFormat = format self.mask = try! Mask.getOrCreate(withFormat: format) self._autocomplete = false self._autocompleteOnFocus = false super.init() } public override convenience init() { self.init(format: "") } open func put(text: String, into field: UITextField) { let result: Mask.Result = self.mask.apply( toText: CaretString( string: text, caretPosition: text.endIndex ), autocomplete: self._autocomplete ) field.text = result.formattedText.string let position: Int = result.formattedText.string.distance(from: result.formattedText.string.startIndex, to: result.formattedText.caretPosition) self.setCaretPosition(position, inField: field) self.listener?.textField?( field, didFillMandatoryCharacters: result.complete, didExtractValue: result.extractedValue ) } /** Maximal length of the text inside the field. - returns: Total available count of mandatory and optional characters inside the text field. */ open func placeholder() -> String { return self.mask.placeholder() } /** Minimal length of the text inside the field to fill all mandatory characters in the mask. - returns: Minimal satisfying count of characters inside the text field. */ open func acceptableTextLength() -> Int { return self.mask.acceptableTextLength() } /** Maximal length of the text inside the field. - returns: Total available count of mandatory and optional characters inside the text field. */ open func totalTextLength() -> Int { return self.mask.totalTextLength() } /** Minimal length of the extracted value with all mandatory characters filled. - returns: Minimal satisfying count of characters in extracted value. */ open func acceptableValueLength() -> Int { return self.mask.acceptableValueLength() } /** Maximal length of the extracted value. - returns: Total available count of mandatory and optional characters for extracted value. */ open func totalValueLength() -> Int { return self.mask.totalValueLength() } // MARK: - UITextFieldDelegate open func textField( _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let extractedValue: String let complete: Bool if isDeletion( inRange: range, string: string ) { (extractedValue, complete) = self.deleteText(inRange: range, inField: textField) } else { (extractedValue, complete) = self.modifyText(inRange: range, inField: textField, withText: string) } self.listener?.textField?( textField, didFillMandatoryCharacters: complete, didExtractValue: extractedValue ) let _ = self.listener?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) return false } open func deleteText( inRange range: NSRange, inField field: UITextField ) -> (String, Bool) { let text: String = self.replaceCharacters( inText: field.text, range: range, withCharacters: "" ) let result: Mask.Result = self.mask.apply( toText: CaretString( string: text, caretPosition: text.index(text.startIndex, offsetBy: range.location) ), autocomplete: false ) field.text = result.formattedText.string self.setCaretPosition(range.location, inField: field) return (result.extractedValue, result.complete) } open func modifyText( inRange range: NSRange, inField field: UITextField, withText text: String ) -> (String, Bool) { let updatedText: String = self.replaceCharacters( inText: field.text, range: range, withCharacters: text ) let result: Mask.Result = self.mask.apply( toText: CaretString( string: updatedText, caretPosition: updatedText.index(updatedText.startIndex, offsetBy: self.caretPosition(inField: field) + text.count) ), autocomplete: self.autocomplete ) field.text = result.formattedText.string let position: Int = result.formattedText.string.distance(from: result.formattedText.string.startIndex, to: result.formattedText.caretPosition) self.setCaretPosition(position, inField: field) return (result.extractedValue, result.complete) } open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return self.listener?.textFieldShouldBeginEditing?(textField) ?? true } open func textFieldDidBeginEditing(_ textField: UITextField) { if self._autocompleteOnFocus && textField.text!.isEmpty { let _ = self.textField( textField, shouldChangeCharactersIn: NSMakeRange(0, 0), replacementString: "" ) } self.listener?.textFieldDidBeginEditing?(textField) } open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return self.listener?.textFieldShouldEndEditing?(textField) ?? true } open func textFieldDidEndEditing(_ textField: UITextField) { self.listener?.textFieldDidEndEditing?(textField) } open func textFieldShouldClear(_ textField: UITextField) -> Bool { let shouldClear: Bool = self.listener?.textFieldShouldClear?(textField) ?? true if shouldClear { let result: Mask.Result = self.mask.apply( toText: CaretString( string: "", caretPosition: "".endIndex ), autocomplete: self.autocomplete ) self.listener?.textField?( textField, didFillMandatoryCharacters: result.complete, didExtractValue: result.extractedValue ) } return shouldClear } open func textFieldShouldReturn(_ textField: UITextField) -> Bool { return self.listener?.textFieldShouldReturn?(textField) ?? true } open override var debugDescription: String { get { return self.mask.debugDescription } } open override var description: String { get { return self.debugDescription } } } internal extension MaskedTextFieldDelegate { func isDeletion(inRange range: NSRange, string: String) -> Bool { return 0 < range.length && 0 == string.count } func replaceCharacters(inText text: String?, range: NSRange, withCharacters newText: String) -> String { if let text = text { if 0 < range.length { let result = NSMutableString(string: text) result.replaceCharacters(in: range, with: newText) return result as String } else { let result = NSMutableString(string: text) result.insert(newText, at: range.location) return result as String } } else { return "" } } func caretPosition(inField field: UITextField) -> Int { // Workaround for non-optional `field.beginningOfDocument`, which could actually be nil if field doesn't have focus guard field.isFirstResponder else { return field.text?.count ?? 0 } if let range: UITextRange = field.selectedTextRange { let selectedTextLocation: UITextPosition = range.start return field.offset(from: field.beginningOfDocument, to: selectedTextLocation) } else { return 0 } } func setCaretPosition(_ position: Int, inField field: UITextField) { // Workaround for non-optional `field.beginningOfDocument`, which could actually be nil if field doesn't have focus guard field.isFirstResponder else { return } if position > field.text!.count { return } let from: UITextPosition = field.position(from: field.beginningOfDocument, offset: position)! let to: UITextPosition = field.position(from: from, offset: 0)! field.selectedTextRange = field.textRange(from: from, to: to) } }
31.059155
134
0.603483
46a478959179d2bf85990fa052ad7e98061f3704
9,700
import Foundation /** A closure that, when evaluated, returns a dictionary of key-value pairs that can be accessed from within a group of shared examples. */ public typealias SharedExampleContext = () -> [String: Any] /** A closure that is used to define a group of shared examples. This closure may contain any number of example and example groups. */ public typealias SharedExampleClosure = (@escaping SharedExampleContext) -> Void #if canImport(Darwin) // swiftlint:disable type_name @objcMembers internal class _WorldBase: NSObject {} #else internal class _WorldBase: NSObject {} // swiftlint:enable type_name #endif /** A collection of state Quick builds up in order to work its magic. World is primarily responsible for maintaining a mapping of QuickSpec classes to root example groups for those classes. It also maintains a mapping of shared example names to shared example closures. You may configure how Quick behaves by calling the -[World configure:] method from within an overridden +[QuickConfiguration configure:] method. */ internal final class World: _WorldBase { /** The example group that is currently being run. The DSL requires that this group is correctly set in order to build a correct hierarchy of example groups and their examples. */ internal var currentExampleGroup: ExampleGroup! /** The example metadata of the test that is currently being run. This is useful for using the Quick test metadata (like its name) at runtime. */ internal var currentExampleMetadata: ExampleMetadata? internal var numberOfExamplesRun = 0 /** A flag that indicates whether additional test suites are being run within this test suite. This is only true within the context of Quick functional tests. */ #if canImport(Darwin) // Convention of generating Objective-C selector has been changed on Swift 3 @objc(isRunningAdditionalSuites) internal var isRunningAdditionalSuites = false #else internal var isRunningAdditionalSuites = false #endif private var specs: [String: ExampleGroup] = [:] private var sharedExamples: [String: SharedExampleClosure] = [:] private let configuration = Configuration() internal private(set) var isConfigurationFinalized = false internal var exampleHooks: ExampleHooks { return configuration.exampleHooks } internal var suiteHooks: SuiteHooks { return configuration.suiteHooks } // MARK: Singleton Constructor override private init() {} private(set) static var sharedWorld = World() static func anotherWorld<T>(block: (World) -> T) -> T { let previous = sharedWorld defer { sharedWorld = previous } let newWorld = World() sharedWorld = newWorld return block(newWorld) } // MARK: Public Interface /** Exposes the World's Configuration object within the scope of the closure so that it may be configured. This method must not be called outside of an overridden +[QuickConfiguration configure:] method. - parameter closure: A closure that takes a Configuration object that can be mutated to change Quick's behavior. */ internal func configure(_ closure: QuickConfigurer) { assert( !isConfigurationFinalized, // swiftlint:disable:next line_length "Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method." ) closure(configuration) } /** Finalizes the World's configuration. Any subsequent calls to World.configure() will raise. */ internal func finalizeConfiguration() { isConfigurationFinalized = true } /** Returns `true` if the root example group for the given spec class has been already initialized. - parameter specClass: The QuickSpec class for which is checked for the existing root example group. - returns: Whether the root example group for the given spec class has been already initialized or not. */ internal func isRootExampleGroupInitialized(forSpecClass specClass: QuickSpec.Type) -> Bool { let name = String(describing: specClass) return specs.keys.contains(name) } /** Returns an internally constructed root example group for the given QuickSpec class. A root example group with the description "root example group" is lazily initialized for each QuickSpec class. This root example group wraps the top level of a -[QuickSpec spec] method--it's thanks to this group that users can define beforeEach and it closures at the top level, like so: override func spec() { // These belong to the root example group beforeEach {} it("is at the top level") {} } - parameter specClass: The QuickSpec class for which to retrieve the root example group. - returns: The root example group for the class. */ internal func rootExampleGroup(forSpecClass specClass: QuickSpec.Type) -> ExampleGroup { let name = String(describing: specClass) if let group = specs[name] { return group } else { let group = ExampleGroup( description: "root example group", flags: [:], isInternalRootExampleGroup: true ) specs[name] = group return group } } /** Returns all examples that should be run for a given spec class. There are two filtering passes that occur when determining which examples should be run. That is, these examples are the ones that are included by inclusion filters, and are not excluded by exclusion filters. - parameter specClass: The QuickSpec subclass for which examples are to be returned. - returns: A list of examples to be run as test invocations. */ internal func examples(forSpecClass specClass: QuickSpec.Type) -> [Example] { // 1. Grab all included examples. let included = includedExamples // 2. Grab the intersection of (a) examples for this spec, and (b) included examples. let spec = rootExampleGroup(forSpecClass: specClass).examples.filter { included.contains($0) } // 3. Remove all excluded examples. return spec.filter { example in !self.configuration.exclusionFilters.contains { $0(example) } } } // MARK: Internal internal func registerSharedExample(_ name: String, closure: @escaping SharedExampleClosure) { raiseIfSharedExampleAlreadyRegistered(name) sharedExamples[name] = closure } internal func sharedExample(_ name: String) -> SharedExampleClosure { raiseIfSharedExampleNotRegistered(name) return sharedExamples[name]! } internal var includedExampleCount: Int { return includedExamples.count } internal lazy var cachedIncludedExampleCount: Int = self.includedExampleCount internal var beforesCurrentlyExecuting: Bool { let suiteBeforesExecuting = suiteHooks.phase == .beforesExecuting let exampleBeforesExecuting = exampleHooks.phase == .beforesExecuting var groupBeforesExecuting = false if let runningExampleGroup = currentExampleMetadata?.example.group { groupBeforesExecuting = runningExampleGroup.phase == .beforesExecuting } return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting } internal var aftersCurrentlyExecuting: Bool { let suiteAftersExecuting = suiteHooks.phase == .aftersExecuting let exampleAftersExecuting = exampleHooks.phase == .aftersExecuting var groupAftersExecuting = false if let runningExampleGroup = currentExampleMetadata?.example.group { groupAftersExecuting = runningExampleGroup.phase == .aftersExecuting } return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting } internal func performWithCurrentExampleGroup(_ group: ExampleGroup, closure: () -> Void) { let previousExampleGroup = currentExampleGroup currentExampleGroup = group closure() currentExampleGroup = previousExampleGroup } private var allExamples: [Example] { var all: [Example] = [] for (_, group) in specs { group.walkDownExamples { all.append($0) } } return all } private var includedExamples: [Example] { let all = allExamples let included = all.filter { example in self.configuration.inclusionFilters.contains { $0(example) } } if included.isEmpty, configuration.runAllWhenEverythingFiltered { return all } else { return included } } private func raiseIfSharedExampleAlreadyRegistered(_ name: String) { if sharedExamples[name] != nil { raiseError("A shared example named '\(name)' has already been registered.") } } private func raiseIfSharedExampleNotRegistered(_ name: String) { if sharedExamples[name] == nil { raiseError("No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(sharedExamples.keys))'") } } }
36.742424
239
0.672165
5b3bd568b6acdb3dc2804f79d9c64404aa3ef2db
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A{struct S<T where g:N{let c{class B<T where T:B<n>
37.833333
87
0.753304
e235814fca59ae99c57c59a0278384d72b26c1fc
547
// // ImageTableViewCell.swift // NACardSDK // // Created by Ruan Gustavo on 30/08/18. // Copyright © 2018 Natura. All rights reserved. // import UIKit class ImageTableViewCell: UITableViewCell { @IBOutlet weak var mImageView: UIImageView! 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 } }
20.259259
65
0.66362
01ee67035abd90db745a7d968e893b6228f21376
301
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { if true { class B<T { init<T : a { func g<1 { enum b { var b { } } println(x: a { class b> { if true { class case c, struct
15.05
87
0.684385
64241c6c4a1b9256909dbdd6a5c6fe9ea9108712
1,238
// // ClearButtonWhileEditingModifier.swift // ZamzamUI // // Created by Basem Emara on 2021-03-14. // Copyright © 2021 Zamzam Inc. All rights reserved. // import SwiftUI private struct ClearButtonWhileEditingModifier: ViewModifier { @Binding var text: String func body(content: Content) -> some View { content .overlay( HStack { Spacer() Button(action: { text = "" }) { Label(LocalizedStringKey("Clear"), systemImage: "multiply.circle.fill") .labelStyle(.iconOnly) .foregroundColor(.secondary) .padding(8) } } .opacity(!text.isEmpty ? 0.8 : 0) ) } } public extension View { /// The standard clear button is displayed at the trailling side of the text field, when the text field has contents, /// as a way for the user to remove text quickly. This button appears automatically based on the value set for this property. func clearButtonWhileEditing(_ text: Binding<String>) -> some View { modifier(ClearButtonWhileEditingModifier(text: text)) } }
32.578947
129
0.573506
9104e1c592d50312901dfca878769f21dcdd8452
223
// // Result.swift // SpeedTestLib // // Created by dhaurylenka on 2/5/18. // Copyright © 2018 Exadel. All rights reserved. // import Foundation public enum Result<T, E: Error> { case value(T) case error(E) }
14.866667
49
0.64574
ff1cc57066be8ec504728eb834b7881632e4ffe5
1,432
// // FocusOnUITests.swift // FocusOnUITests // // Created by Alexandra Ivanova on 23/12/2021. // import XCTest class FocusOnUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.302326
182
0.657123
215f4a2dbf1e5ad595eb9bc4dff24c64de9043e2
397
// // ZeroPaddingTextView.swift // UI // // Created by George Tsifrikas on 28/10/2018. // Copyright © 2018 George Tsifrikas. All rights reserved. // import UIKit @IBDesignable class ZeroPaddingTextView: UITextView { override func layoutSubviews() { super.layoutSubviews() textContainerInset = UIEdgeInsets.zero textContainer.lineFragmentPadding = 0 } }
19.85
59
0.690176
d98c6c4542e7146db2d0e8b911c76826efb28e39
957
// // DouYuZBTests.swift // DouYuZBTests // // Created by DuLu on 15/06/2017. // Copyright © 2017 DuLu. All rights reserved. // import XCTest @testable import DouYuZB class DouYuZBTests: 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. } } }
25.864865
111
0.629049
4b24af2d13e57fe7c4db62894f6d7a6f305df84c
321
// // ProductCollectionHeaderView.swift // CleanArchitecture // // Created by Tuan Truong on 9/9/20. // Copyright © 2020 Sun Asterisk. All rights reserved. // import UIKit import Reusable final class ProductCollectionHeaderView: UICollectionReusableView, NibReusable { @IBOutlet weak var titleLabel: UILabel! }
21.4
80
0.760125
086e53dc02348439832e68ee56106df29806b04d
1,378
/*: # Capacitance This page features a circuit with a resistor-capacitor circuit. A capacitor is passive circuit component and it has the ability to store electric charge using an electric field. The current across a capacitor is equal to the capacitance of the capacitor and the voltage change per unit time. ![Equation for Capacitance](Capacitance.PNG) **Task:** Capacitate My Current 1. Tap `Run My Code` button on the right. 2. Click on the `Solve` button. What is the voltage across the capacitor? 3. Tap on the `Next Time Step` button. This should solve the circuit values after a time step of 10 millisecond. What happens to voltage and current? Does it increase or decrease? 4. Change the value of the capacitance? How does it affect the rate of change of the voltage and current? In a direct current circuit, the capacitor would have stored its full capacity after five time constants, thus, the capacitor will cause the circuit to short. Go to the [Next Page](@next) where you will learn about inductors. */ import SwiftUI import PlaygroundSupport let preset: CircuitPreset = .resistorCapacitor PlaygroundPage.current.wantsFullScreenLiveView = true PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.setLiveView( MainView() .environmentObject(CircuitEnvironment(circuit: preset.circuit)) .ignoresSafeArea() )
49.214286
292
0.783745
23d94fe1511bea40a645b48964b276a876ade17c
3,373
// // TodoItemViewController.swift // VandelayDemo // // Created by Daniel Saidi on 2016-06-21. // Copyright © 2016 Daniel Saidi. All rights reserved. // import UIKit class TodoItemViewController: UITableViewController { // MARK: - View lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadData() } // MARK: - Properties var repository: TodoItemRepository! private var hasItems: Bool { return items.count > 0 } private var items = [TodoItem]() // MARK: - Actions @IBAction func add() { let title = "Add todo" let message = "Enter todo description" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in let item = TodoItem(name: alert.textFields![0].text!) self.repository.add(item) self.reloadData() }) present(alert, animated: true, completion: nil) } } // MARK: - Private Functions private extension TodoItemViewController { func reloadData() { items = repository.getItems() tableView.reloadData() } } // MARK: - UITableViewDataSource extension TodoItemViewController { override func numberOfSections(in view: UITableView) -> Int { return 1 } override func tableView(_ view: UITableView, numberOfRowsInSection section: Int) -> Int { return max(items.count, 1) } override func tableView(_ view: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return hasItems } override func tableView(_ view: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if hasItems { return tableView(view, cellForItemAt: indexPath) } else { return tableView.dequeueReusableCell(withIdentifier: "NoItemsCell")! } } private func tableView(_ view: UITableView, cellForItemAt indexPath: IndexPath) -> UITableViewCell { let cell = view.dequeueReusableCell(withIdentifier: "ItemCell")! let item = items[indexPath.row] cell.textLabel?.text = item.name return cell } override func tableView(_ view: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else { return } let item = items[indexPath.row] repository.delete(item) reloadData() } override func tableView(_ view: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard hasItems else { return } let item = items[indexPath.row] cell.accessoryType = item.completed ? .checkmark : .none } } // MARK: - UITableViewDelegate extension TodoItemViewController { override func tableView(_ view: UITableView, didSelectRowAt indexPath: IndexPath) { view.deselectRow(at: indexPath, animated: true) guard hasItems else { return } var item = items[indexPath.row] item.completed = !item.completed reloadData() } }
28.82906
132
0.646012
d5df0e6573603585e91006678ff14b2b65efb79b
3,790
// // RunInfoUseCaseTests.swift // speedruntechTests // // Created by Javier Morgaz García on 16/8/18. // Copyright © 2018 Javier Morgaz García. All rights reserved. // import XCTest import CocoaLumberjack @testable import speedruntech class RunInfoUseCaseTests: XCTestCase { private var restClientStub: RestClientStubInterface! private var runInfoUseCase: RunInfoUseCase! private var resourceUrl: String! private var asyncExpectation: XCTestExpectation! override func setUp() { super.setUp() //Given let bundle = Bundle(for: type(of: self)) let pathJsonResponseFolder = bundle.url(forResource: "Mocks/Json/Response", withExtension: nil)!.absoluteString restClientStub = RestClientStub(baseUrl: pathJsonResponseFolder) runInfoUseCase = RunInfoUseCase(restClient: restClientStub) } func test_getRuns_Success() { //Given asyncExpectation = expectation(description: "\(#function)") restClientStub.mockPath = "Runs/runs_ok" //When runInfoUseCase.getRuns(gameId: "", success: { runs in //Then XCTAssert(!runs.isEmpty) self.asyncExpectation.fulfill() //When }, failure: { //Then XCTAssert(false) self.asyncExpectation.fulfill() }) waitForExpectations(timeout: 1, handler: nil) } func test_getRuns_Failure() { //Given asyncExpectation = expectation(description: "\(#function)") restClientStub.mockPath = "Runs/runs_ko" //When runInfoUseCase.getRuns(gameId: "", success: { _ in //Then XCTAssert(false) self.asyncExpectation.fulfill() //When }, failure: { //Then XCTAssert(true) self.asyncExpectation.fulfill() }) waitForExpectations(timeout: 1, handler: nil) } func test_getUser_Success() { //Given asyncExpectation = expectation(description: "\(#function)") restClientStub.mockPath = "User/user_ok" //When runInfoUseCase.getUser(userId: "", success: { user in //Then XCTAssert(!user.name.isEmpty) self.asyncExpectation.fulfill() //When }, failure: { //Then XCTAssert(false) self.asyncExpectation.fulfill() }) waitForExpectations(timeout: 1, handler: nil) } func test_getUser_Failure() { //Given asyncExpectation = expectation(description: "\(#function)") restClientStub.mockPath = "User/user_ko" //When runInfoUseCase.getUser(userId: "", success: { _ in //Then XCTAssert(false) self.asyncExpectation.fulfill() //When }, failure: { //Then XCTAssert(true) self.asyncExpectation.fulfill() }) waitForExpectations(timeout: 1, handler: nil) } func test_openVideo_Succes() { //Given let jsonDictionary = TestUtils.jsonModel(withName: "Run_ok") //When guard let run = Run(jsonDictionary: jsonDictionary) else { return } //Then XCTAssertTrue(runInfoUseCase.openVideoFrom(run: run)) } func test_openVideo_Failure() { //Given let jsonDictionary = TestUtils.jsonModel(withName: "Run_ko") //When guard let run = Run(jsonDictionary: jsonDictionary) else { return } //Then XCTAssertFalse(runInfoUseCase.openVideoFrom(run: run)) } }
27.664234
119
0.573087
647c21d78062741ab06d3ab6eca1c0b49154f45e
228
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {enum c{struct S{struct d{class a{class b:A}}}enum S<T:T.e
38
87
0.75
2f225187e86653cc74a1786cbd93e8bb50c77696
324
// // ViewController.swift // Paging // // Created by Squirrel on 2019/6/28. // Copyright © 2019 Squirrel. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
15.428571
58
0.657407
2660404e53c71a27f58b49198f64c6508047aa5a
1,289
// // UABParkingFinder_iOSUITests.swift // UABParkingFinder-iOSUITests // // Created by Rofael Aleezada on 12/24/17. // Copyright © 2017 Rofael Aleezada. All rights reserved. // import XCTest class UABParkingFinder_iOSUITests: 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. } }
34.837838
182
0.67339
48264ee6fe9493733acb2adb47317e6d6e1f1619
7,288
// // HTTPAdapter.swift // proxyDemo // // Created by 方冬冬 on 2021/1/20. // import Foundation protocol AdapterDelegate { func didBecomeReadyToForwardWith(socket:HTTPAdapter) func didRead(data:Data,from:HTTPAdapter) func didWrite(data:Data,from:HTTPAdapter) func didConnect() func readData() } class HTTPAdapter:NSObject, GCDAsyncSocketDelegate { enum HTTPAdapterStatus { case invalid, connecting, readingResponse, forwarding, stopped } /// The host domain of the HTTP proxy. let serverHost: String /// The port of the HTTP proxy. let serverPort: Int /// The authentication information for the HTTP proxy. let auth: HTTPAuthentication? /// Whether the connection to the proxy should be secured or not. var secured: Bool var internalStatus: HTTPAdapterStatus = .invalid open var session: ConnectSession! var adapterSocket: GCDAsyncSocket! var delegate: AdapterDelegate? deinit { print("HttpAdapter deinit") } public init(serverHost: String, serverPort: Int,secured: Bool, auth: HTTPAuthentication?) { self.serverHost = serverHost self.serverPort = serverPort self.auth = auth self.secured = secured adapterSocket = GCDAsyncSocket.init(delegate: nil, delegateQueue: DispatchQueue.main) } public func openSocketWith(session: ConnectSession) { // guard !isCancelled else { // return // } do { internalStatus = .forwarding adapterSocket.delegate = self print("ip: \(session.ipAddress) \r\nport:\(serverPort)") try adapterSocket.connect(toHost: session.ipAddress, onPort: UInt16(serverPort), withTimeout: -1) if secured { // startTLSWith(settings: nil) } } catch {} self.session = session } func startTLSWith(settings: [AnyHashable: Any]!) { if let settings = settings as? [String: NSObject] { adapterSocket.startTLS(ensureSendPeerName(tlsSettings: settings)) } else { adapterSocket.startTLS(ensureSendPeerName(tlsSettings: nil)) } } private func ensureSendPeerName(tlsSettings: [String: NSObject]? = nil) -> [String: NSObject] { var setting = tlsSettings ?? [:] guard setting[kCFStreamSSLPeerName as String] == nil else { return setting } setting[kCFStreamSSLPeerName as String] = serverHost as NSString return setting } func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { // guard let url = URL(string: "\(session.host):\(session.port)") else { // return // } // let message = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "CONNECT" as CFString, url as CFURL, kCFHTTPVersion1_1).takeRetainedValue() // if let authData = auth { // CFHTTPMessageSetHeaderFieldValue(message, "Proxy-Authorization" as CFString, authData.authString() as CFString?) // } // CFHTTPMessageSetHeaderFieldValue(message, "Host" as CFString, "\(session.host):\(session.port)" as CFString?) // CFHTTPMessageSetHeaderFieldValue(message, "Content-Length" as CFString, "0" as CFString?) // // guard let requestData = CFHTTPMessageCopySerializedMessage(message)?.takeRetainedValue() else { // return // } // // print("adapter write data:\(String.init(data: requestData as Data, encoding: String.Encoding.utf8))") // // internalStatus = .readingResponse //// adapterSocket.write(data: requestData as Data) // adapterSocket.write(requestData as Data, withTimeout: -1, tag: 0) // adapterSocket.readData(to: Utils.HTTPData.DoubleCRLF, withTimeout: -1, tag: 1) // socket.readDataTo(data: Utils.HTTPData.DoubleCRLF) print("adapter didConnectToHost") // if !secured { delegate?.didConnect() // } } func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { print("adapter read data:\(String(describing: String.init(data: data, encoding: String.Encoding.utf8)))") sock.readData(withTimeout: -1, tag: 0) // switch internalStatus { // case .readingResponse: // internalStatus = .forwarding // delegate?.didBecomeReadyToForwardWith(socket: self) // // case .forwarding: // delegate?.didRead(data: data, from: self) // default: // return // } delegate?.didRead(data: data, from: self) } func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) { if internalStatus == .forwarding { delegate?.readData() } } func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { print("adapter err:\(err?.localizedDescription)") } func socketDidSecure(_ sock: GCDAsyncSocket) { print("adapter socketDidSecure") // delegate?.didConnect() } // override public func didConnectWith(socket: RawTCPSocketProtocol) { // super.didConnectWith(socket: socket) // // guard let url = URL(string: "\(session.host):\(session.port)") else { // observer?.signal(.errorOccured(HTTPAdapterError.invalidURL, on: self)) // disconnect() // return // } // let message = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "CONNECT" as CFString, url as CFURL, kCFHTTPVersion1_1).takeRetainedValue() // if let authData = auth { // CFHTTPMessageSetHeaderFieldValue(message, "Proxy-Authorization" as CFString, authData.authString() as CFString?) // } // CFHTTPMessageSetHeaderFieldValue(message, "Host" as CFString, "\(session.host):\(session.port)" as CFString?) // CFHTTPMessageSetHeaderFieldValue(message, "Content-Length" as CFString, "0" as CFString?) // // guard let requestData = CFHTTPMessageCopySerializedMessage(message)?.takeRetainedValue() else { // observer?.signal(.errorOccured(HTTPAdapterError.serailizationFailure, on: self)) // disconnect() // return // } // // internalStatus = .readingResponse // write(data: requestData as Data) // socket.readDataTo(data: Utils.HTTPData.DoubleCRLF) // } // // override public func didRead(data: Data, from socket: RawTCPSocketProtocol) { // super.didRead(data: data, from: socket) // // switch internalStatus { // case .readingResponse: // internalStatus = .forwarding // observer?.signal(.readyForForward(self)) // delegate?.didBecomeReadyToForwardWith(socket: self) // case .forwarding: // observer?.signal(.readData(data, on: self)) // delegate?.didRead(data: data, from: self) // default: // return // } // } // // override public func didWrite(data: Data?, by socket: RawTCPSocketProtocol) { // super.didWrite(data: data, by: socket) // if internalStatus == .forwarding { // observer?.signal(.wroteData(data, on: self)) // delegate?.didWrite(data: data, by: self) // } // } }
35.207729
147
0.629802
f48c80545c698b57ca5afbb1dc28b5f6ec612694
1,224
// // SocialMediaLinks.swift // SMHSSchedule (iOS) // // Created by Jevon Mao on 5/24/21. // import SwiftUI struct SocialMediaLinks: View { var body: some View { VStack { Group { HStack { Text("Follow SMCHS") .font(.title3, weight: .semibold) Spacer() NavigationLink(destination: SocialDetailView()) { Text("See More") .foregroundColor(appPrimary) .font(.callout, weight: .medium) } } } .padding(.horizontal) Divider() SocialMediaIcons() } .edgesIgnoringSafeArea(.horizontal) .padding(.vertical) } } struct SocialMediaLinks_Previews: PreviewProvider { static var previews: some View { SocialMediaLinks() } } struct SocialMediaIcon: Hashable { var imageName: String var url: URL init(imageName: String, url: String) { self.imageName = imageName self.url = URL(string: url)! } }
25.5
73
0.468954
4680a4f5bf570b2eb480f26511423957e38b6795
211
// 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 c { init { } func c<d : d var d: c
21.1
87
0.729858
efb6fab473d762244849bb82880dd86840e71ead
27,250
// // PreferencesTests.swift // Tests // // Copyright © 2021 Kartik Venugopal. All rights reserved. // // This software is licensed under the MIT software license. // See the file "LICENSE" in the project root directory for license terms. // import XCTest class PreferencesTests: PreferencesTestCase { private typealias PlaylistDefaults = PreferencesDefaults.Playlist private typealias PlaybackDefaults = PreferencesDefaults.Playback private typealias SoundDefaults = PreferencesDefaults.Sound private typealias HistoryDefaults = PreferencesDefaults.History private typealias ViewDefaults = PreferencesDefaults.View private typealias MediaKeysDefaults = PreferencesDefaults.Controls.MediaKeys private typealias GesturesDefaults = PreferencesDefaults.Controls.Gestures private typealias RemoteControlDefaults = PreferencesDefaults.Controls.RemoteControl private typealias MusicBrainzDefaults = PreferencesDefaults.Metadata.MusicBrainz // MARK: init() tests ------------------------------ func testInit_noValues() { doTestInit(userDefs: UserDefaults(), playlistOnStartup: nil, playlistFile: nil, tracksFolder: nil, viewOnStartup: nil, showNewTrackInPlaylist: nil, showChaptersList: nil, primarySeekLengthOption: nil, primarySeekLengthConstant: nil, primarySeekLengthPercentage: nil, secondarySeekLengthOption: nil, secondarySeekLengthConstant: nil, secondarySeekLengthPercentage: nil, autoplayOnStartup: nil, autoplayAfterAddingTracks: nil, autoplayAfterAddingOption: nil, rememberLastPositionOption: nil, outputDeviceOnStartup: nil, volumeDelta: nil, volumeOnStartupOption: nil, startupVolumeValue: nil, panDelta: nil, eqDelta: nil, pitchDelta: nil, timeDelta: nil, effectsSettingsOnStartupOption: nil, masterPresetOnStartup_name: nil, rememberEffectsSettingsOption: nil, recentlyAddedListSize: nil, recentlyPlayedListSize: nil, appModeOnStartup: nil, layoutOnStartup: nil, snapToWindows: nil, snapToScreen: nil, windowGap: nil, mediaKeysEnabled: nil, skipKeyBehavior: nil, repeatSpeed: nil, allowVolumeControl: nil, allowSeeking: nil, allowTrackChange: nil, allowPlaylistNavigation: nil, allowPlaylistTabToggle: nil, volumeControlSensitivity: nil, seekSensitivity: nil, remoteControlEnabled: nil, trackChangeOrSeekingOption: nil, httpTimeout: nil, enableCoverArtSearch: nil, enableOnDiskCoverArtCache: nil) } func testInit() { for _ in 1...(runLongRunningTests ? 1000 : 100) { let playlistStartupOptions = randomPlaylistStartupOptions() doTestInit(userDefs: UserDefaults(), playlistOnStartup: playlistStartupOptions.option, playlistFile: playlistStartupOptions.playlistFile, tracksFolder: playlistStartupOptions.tracksFolder, viewOnStartup: randomPlaylistViewOnStartup(), showNewTrackInPlaylist: .random(), showChaptersList: .random(), primarySeekLengthOption: randomSeekLengthOption(), primarySeekLengthConstant: randomSeekLengthConstant(), primarySeekLengthPercentage: randomPercentage(), secondarySeekLengthOption: randomSeekLengthOption(), secondarySeekLengthConstant: randomSeekLengthConstant(), secondarySeekLengthPercentage: randomPercentage(), autoplayOnStartup: .random(), autoplayAfterAddingTracks: .random(), autoplayAfterAddingOption: randomAutoplayAfterAddingOption(), rememberLastPositionOption: randomRememberLastPositionOption(), outputDeviceOnStartup: randomOutputDevice(), volumeDelta: randomVolumeDelta(), volumeOnStartupOption: .randomCase(), startupVolumeValue: randomStartupVolumeValue(), panDelta: randomPanDelta(), eqDelta: randomEQDelta(), pitchDelta: randomPitchDelta(), timeDelta: randomTimeDelta(), effectsSettingsOnStartupOption: .randomCase(), masterPresetOnStartup_name: randomMasterPresetName(), rememberEffectsSettingsOption: .randomCase(), recentlyAddedListSize: randomHistoryListSize(), recentlyPlayedListSize: randomHistoryListSize(), appModeOnStartup: randomNillableAppModeOnStartup(), layoutOnStartup: randomNillableLayoutOnStartup(), snapToWindows: randomNillableBool(), snapToScreen: randomNillableBool(), windowGap: randomNillableWindowGap(), mediaKeysEnabled: .random(), skipKeyBehavior: randomSkipKeyBehavior(), repeatSpeed: randomRepeatSpeed(), allowVolumeControl: .random(), allowSeeking: .random(), allowTrackChange: .random(), allowPlaylistNavigation: .random(), allowPlaylistTabToggle: .random(), volumeControlSensitivity: .randomCase(), seekSensitivity: .randomCase(), remoteControlEnabled: .random(), trackChangeOrSeekingOption: randomTrackChangeOrSeekingOption(), httpTimeout: randomHTTPTimeout(), enableCoverArtSearch: .random(), enableOnDiskCoverArtCache: .random()) } } private func doTestInit(userDefs: UserDefaults, playlistOnStartup: PlaylistStartupOptions?, playlistFile: URL?, tracksFolder: URL?, viewOnStartup: PlaylistViewOnStartup?, showNewTrackInPlaylist: Bool?, showChaptersList: Bool?, primarySeekLengthOption: SeekLengthOptions?, primarySeekLengthConstant: Int?, primarySeekLengthPercentage: Int?, secondarySeekLengthOption: SeekLengthOptions?, secondarySeekLengthConstant: Int?, secondarySeekLengthPercentage: Int?, autoplayOnStartup: Bool?, autoplayAfterAddingTracks: Bool?, autoplayAfterAddingOption: AutoplayAfterAddingOptions?, rememberLastPositionOption: RememberSettingsForTrackOptions?, outputDeviceOnStartup: OutputDeviceOnStartup?, volumeDelta: Float?, volumeOnStartupOption: VolumeStartupOptions?, startupVolumeValue: Float?, panDelta: Float?, eqDelta: Float?, pitchDelta: Int?, timeDelta: Float?, effectsSettingsOnStartupOption: EffectsSettingsStartupOptions?, masterPresetOnStartup_name: String?, rememberEffectsSettingsOption: RememberSettingsForTrackOptions?, recentlyAddedListSize: Int?, recentlyPlayedListSize: Int?, appModeOnStartup: AppModeOnStartup?, layoutOnStartup: LayoutOnStartup?, snapToWindows: Bool?, snapToScreen: Bool?, windowGap: Float?, mediaKeysEnabled: Bool?, skipKeyBehavior: SkipKeyBehavior?, repeatSpeed: SkipKeyRepeatSpeed?, allowVolumeControl: Bool?, allowSeeking: Bool?, allowTrackChange: Bool?, allowPlaylistNavigation: Bool?, allowPlaylistTabToggle: Bool?, volumeControlSensitivity: ScrollSensitivity?, seekSensitivity: ScrollSensitivity?, remoteControlEnabled: Bool?, trackChangeOrSeekingOption: TrackChangeOrSeekingOptions?, httpTimeout: Int?, enableCoverArtSearch: Bool?, enableOnDiskCoverArtCache: Bool?) { userDefs[PlaylistPreferences.key_viewOnStartupOption] = viewOnStartup?.option.rawValue userDefs[PlaylistPreferences.key_viewOnStartupViewName] = viewOnStartup?.viewName userDefs[PlaylistPreferences.key_playlistOnStartup] = playlistOnStartup?.rawValue userDefs[PlaylistPreferences.key_playlistFile] = playlistFile?.path userDefs[PlaylistPreferences.key_tracksFolder] = tracksFolder?.path userDefs[PlaylistPreferences.key_showNewTrackInPlaylist] = showNewTrackInPlaylist userDefs[PlaylistPreferences.key_showChaptersList] = showChaptersList userDefs[PlaybackPreferences.key_primarySeekLengthOption] = primarySeekLengthOption?.rawValue userDefs[PlaybackPreferences.key_primarySeekLengthConstant] = primarySeekLengthConstant userDefs[PlaybackPreferences.key_primarySeekLengthPercentage] = primarySeekLengthPercentage userDefs[PlaybackPreferences.key_secondarySeekLengthOption] = secondarySeekLengthOption?.rawValue userDefs[PlaybackPreferences.key_secondarySeekLengthConstant] = secondarySeekLengthConstant userDefs[PlaybackPreferences.key_secondarySeekLengthPercentage] = secondarySeekLengthPercentage userDefs[PlaybackPreferences.key_autoplayOnStartup] = autoplayOnStartup userDefs[PlaybackPreferences.key_autoplayAfterAddingTracks] = autoplayAfterAddingTracks userDefs[PlaybackPreferences.key_autoplayAfterAddingOption] = autoplayAfterAddingOption?.rawValue userDefs[PlaybackPreferences.key_rememberLastPositionOption] = rememberLastPositionOption?.rawValue userDefs[SoundPreferences.key_outputDeviceOnStartup_option] = outputDeviceOnStartup?.option.rawValue userDefs[SoundPreferences.key_outputDeviceOnStartup_preferredDeviceName] = outputDeviceOnStartup?.preferredDeviceName userDefs[SoundPreferences.key_outputDeviceOnStartup_preferredDeviceUID] = outputDeviceOnStartup?.preferredDeviceUID userDefs[SoundPreferences.key_volumeDelta] = volumeDelta userDefs[SoundPreferences.key_volumeOnStartup_option] = volumeOnStartupOption?.rawValue userDefs[SoundPreferences.key_volumeOnStartup_value] = startupVolumeValue userDefs[SoundPreferences.key_panDelta] = panDelta userDefs[SoundPreferences.key_eqDelta] = eqDelta userDefs[SoundPreferences.key_pitchDelta] = pitchDelta userDefs[SoundPreferences.key_timeDelta] = timeDelta userDefs[SoundPreferences.key_effectsSettingsOnStartup_option] = effectsSettingsOnStartupOption?.rawValue userDefs[SoundPreferences.key_effectsSettingsOnStartup_masterPreset] = masterPresetOnStartup_name userDefs[SoundPreferences.key_rememberEffectsSettingsOption] = rememberEffectsSettingsOption?.rawValue userDefs[HistoryPreferences.key_recentlyAddedListSize] = recentlyAddedListSize userDefs[HistoryPreferences.key_recentlyPlayedListSize] = recentlyPlayedListSize userDefs[ViewPreferences.key_appModeOnStartup_option] = appModeOnStartup?.option.rawValue userDefs[ViewPreferences.key_appModeOnStartup_modeName] = appModeOnStartup?.modeName userDefs[ViewPreferences.key_layoutOnStartup_option] = layoutOnStartup?.option.rawValue userDefs[ViewPreferences.key_layoutOnStartup_layoutName] = layoutOnStartup?.layoutName userDefs[ViewPreferences.key_snapToWindows] = snapToWindows userDefs[ViewPreferences.key_snapToScreen] = snapToScreen userDefs[ViewPreferences.key_windowGap] = windowGap userDefs[MediaKeysControlsPreferences.key_enabled] = mediaKeysEnabled userDefs[MediaKeysControlsPreferences.key_skipKeyBehavior] = skipKeyBehavior?.rawValue userDefs[MediaKeysControlsPreferences.key_repeatSpeed] = repeatSpeed?.rawValue userDefs[GesturesControlsPreferences.key_allowPlaylistNavigation] = allowPlaylistNavigation userDefs[GesturesControlsPreferences.key_allowPlaylistTabToggle] = allowPlaylistTabToggle userDefs[GesturesControlsPreferences.key_allowSeeking] = allowSeeking userDefs[GesturesControlsPreferences.key_allowTrackChange] = allowTrackChange userDefs[GesturesControlsPreferences.key_allowVolumeControl] = allowVolumeControl userDefs[GesturesControlsPreferences.key_seekSensitivity] = seekSensitivity?.rawValue userDefs[GesturesControlsPreferences.key_volumeControlSensitivity] = volumeControlSensitivity?.rawValue userDefs[RemoteControlPreferences.key_enabled] = remoteControlEnabled userDefs[RemoteControlPreferences.key_trackChangeOrSeekingOption] = trackChangeOrSeekingOption?.rawValue userDefs[MusicBrainzPreferences.key_httpTimeout] = httpTimeout userDefs[MusicBrainzPreferences.key_enableCoverArtSearch] = enableCoverArtSearch userDefs[MusicBrainzPreferences.key_enableOnDiskCoverArtCache] = enableOnDiskCoverArtCache let prefs = Preferences(defaults: userDefs) XCTAssertEqual(prefs.playlistPreferences.viewOnStartup.option, viewOnStartup?.option ?? PlaylistDefaults.viewOnStartup.option) XCTAssertEqual(prefs.playlistPreferences.viewOnStartup.viewName, viewOnStartup?.viewName ?? PlaylistDefaults.viewOnStartup.viewName) var expectedPlaylistOnStartup: PlaylistStartupOptions = playlistOnStartup ?? PlaylistDefaults.playlistOnStartup var expectedPlaylistFile: URL? = playlistFile ?? PlaylistDefaults.playlistFile var expectedTracksFolder: URL? = tracksFolder ?? PlaylistDefaults.tracksFolder if let thePlaylistOnStartup = playlistOnStartup { if thePlaylistOnStartup == .loadFile, playlistFile == nil { expectedPlaylistOnStartup = PlaylistDefaults.playlistOnStartup expectedPlaylistFile = PlaylistDefaults.playlistFile } else if thePlaylistOnStartup == .loadFolder, tracksFolder == nil { expectedPlaylistOnStartup = PlaylistDefaults.playlistOnStartup expectedTracksFolder = PlaylistDefaults.tracksFolder } } XCTAssertEqual(prefs.playlistPreferences.playlistOnStartup, expectedPlaylistOnStartup) XCTAssertEqual(prefs.playlistPreferences.playlistFile, expectedPlaylistFile) XCTAssertEqual(prefs.playlistPreferences.tracksFolder, expectedTracksFolder) XCTAssertEqual(prefs.playlistPreferences.showNewTrackInPlaylist, showNewTrackInPlaylist ?? PlaylistDefaults.showNewTrackInPlaylist) XCTAssertEqual(prefs.playlistPreferences.showChaptersList, showChaptersList ?? PlaylistDefaults.showChaptersList) XCTAssertEqual(prefs.playbackPreferences.primarySeekLengthOption, primarySeekLengthOption ?? PlaybackDefaults.primarySeekLengthOption) XCTAssertEqual(prefs.playbackPreferences.primarySeekLengthConstant, primarySeekLengthConstant ?? PlaybackDefaults.primarySeekLengthConstant) XCTAssertEqual(prefs.playbackPreferences.primarySeekLengthPercentage, primarySeekLengthPercentage ?? PlaybackDefaults.primarySeekLengthPercentage) XCTAssertEqual(prefs.playbackPreferences.secondarySeekLengthOption, secondarySeekLengthOption ?? PlaybackDefaults.secondarySeekLengthOption) XCTAssertEqual(prefs.playbackPreferences.secondarySeekLengthConstant, secondarySeekLengthConstant ?? PlaybackDefaults.secondarySeekLengthConstant) XCTAssertEqual(prefs.playbackPreferences.secondarySeekLengthPercentage, secondarySeekLengthPercentage ?? PlaybackDefaults.secondarySeekLengthPercentage) XCTAssertEqual(prefs.playbackPreferences.autoplayOnStartup, autoplayOnStartup ?? PlaybackDefaults.autoplayOnStartup) XCTAssertEqual(prefs.playbackPreferences.autoplayAfterAddingTracks, autoplayAfterAddingTracks ?? PlaybackDefaults.autoplayAfterAddingTracks) XCTAssertEqual(prefs.playbackPreferences.autoplayAfterAddingOption, autoplayAfterAddingOption ?? PlaybackDefaults.autoplayAfterAddingOption) XCTAssertEqual(prefs.playbackPreferences.rememberLastPositionOption, rememberLastPositionOption ?? PlaybackDefaults.rememberLastPositionOption) var expectedOutputDeviceOnStartupOption = outputDeviceOnStartup?.option ?? SoundDefaults.outputDeviceOnStartup.option if outputDeviceOnStartup?.option == .specific && (outputDeviceOnStartup?.preferredDeviceName == nil || outputDeviceOnStartup?.preferredDeviceUID == nil) { expectedOutputDeviceOnStartupOption = SoundDefaults.outputDeviceOnStartup.option } XCTAssertEqual(prefs.soundPreferences.outputDeviceOnStartup.option, expectedOutputDeviceOnStartupOption) XCTAssertEqual(prefs.soundPreferences.outputDeviceOnStartup.preferredDeviceName, outputDeviceOnStartup?.preferredDeviceName ?? SoundDefaults.outputDeviceOnStartup.preferredDeviceName) XCTAssertEqual(prefs.soundPreferences.outputDeviceOnStartup.preferredDeviceUID, outputDeviceOnStartup?.preferredDeviceUID ?? SoundDefaults.outputDeviceOnStartup.preferredDeviceUID) XCTAssertEqual(prefs.soundPreferences.volumeDelta, volumeDelta ?? SoundDefaults.volumeDelta) XCTAssertEqual(prefs.soundPreferences.volumeOnStartupOption, volumeOnStartupOption ?? SoundDefaults.volumeOnStartupOption) XCTAssertEqual(prefs.soundPreferences.startupVolumeValue, startupVolumeValue ?? SoundDefaults.startupVolumeValue) XCTAssertEqual(prefs.soundPreferences.panDelta, panDelta ?? SoundDefaults.panDelta) XCTAssertEqual(prefs.soundPreferences.eqDelta, eqDelta ?? SoundDefaults.eqDelta) XCTAssertEqual(prefs.soundPreferences.pitchDelta, pitchDelta ?? SoundDefaults.pitchDelta) XCTAssertEqual(prefs.soundPreferences.timeDelta, timeDelta ?? SoundDefaults.timeDelta) var expectedEffectsSettingsOnStartupOption = effectsSettingsOnStartupOption ?? SoundDefaults.effectsSettingsOnStartupOption if effectsSettingsOnStartupOption == .applyMasterPreset && masterPresetOnStartup_name == nil { expectedEffectsSettingsOnStartupOption = SoundDefaults.effectsSettingsOnStartupOption } XCTAssertEqual(prefs.soundPreferences.effectsSettingsOnStartupOption, expectedEffectsSettingsOnStartupOption) XCTAssertEqual(prefs.soundPreferences.masterPresetOnStartup_name, masterPresetOnStartup_name ?? SoundDefaults.masterPresetOnStartup_name) XCTAssertEqual(prefs.soundPreferences.rememberEffectsSettingsOption, rememberEffectsSettingsOption ?? SoundDefaults.rememberEffectsSettingsOption) XCTAssertEqual(prefs.historyPreferences.recentlyAddedListSize, recentlyAddedListSize ?? HistoryDefaults.recentlyAddedListSize) XCTAssertEqual(prefs.historyPreferences.recentlyPlayedListSize, recentlyPlayedListSize ?? HistoryDefaults.recentlyPlayedListSize) var expectedAppModeOnStartup = appModeOnStartup?.option ?? ViewDefaults.appModeOnStartup.option if expectedAppModeOnStartup == .specific && appModeOnStartup?.modeName == nil { expectedAppModeOnStartup = ViewDefaults.appModeOnStartup.option } XCTAssertEqual(prefs.viewPreferences.appModeOnStartup.option, expectedAppModeOnStartup) XCTAssertEqual(prefs.viewPreferences.appModeOnStartup.modeName, appModeOnStartup?.modeName ?? ViewDefaults.appModeOnStartup.modeName) var expectedLayoutOnStartup = layoutOnStartup?.option ?? ViewDefaults.layoutOnStartup.option if expectedLayoutOnStartup == .specific && layoutOnStartup?.layoutName == nil { expectedLayoutOnStartup = ViewDefaults.layoutOnStartup.option } XCTAssertEqual(prefs.viewPreferences.layoutOnStartup.option, expectedLayoutOnStartup) XCTAssertEqual(prefs.viewPreferences.layoutOnStartup.layoutName, layoutOnStartup?.layoutName ?? ViewDefaults.layoutOnStartup.layoutName) XCTAssertEqual(prefs.viewPreferences.snapToWindows, snapToWindows ?? ViewDefaults.snapToWindows) XCTAssertEqual(prefs.viewPreferences.snapToScreen, snapToScreen ?? ViewDefaults.snapToScreen) XCTAssertEqual(prefs.viewPreferences.windowGap, windowGap ?? ViewDefaults.windowGap) XCTAssertEqual(prefs.controlsPreferences.mediaKeys.enabled, mediaKeysEnabled ?? MediaKeysDefaults.enabled) XCTAssertEqual(prefs.controlsPreferences.mediaKeys.skipKeyBehavior, skipKeyBehavior ?? MediaKeysDefaults.skipKeyBehavior) XCTAssertEqual(prefs.controlsPreferences.mediaKeys.repeatSpeed, repeatSpeed ?? MediaKeysDefaults.repeatSpeed) XCTAssertEqual(prefs.controlsPreferences.gestures.allowPlaylistNavigation, allowPlaylistNavigation ?? GesturesDefaults.allowPlaylistNavigation) XCTAssertEqual(prefs.controlsPreferences.gestures.allowPlaylistTabToggle, allowPlaylistTabToggle ?? GesturesDefaults.allowPlaylistTabToggle) XCTAssertEqual(prefs.controlsPreferences.gestures.allowSeeking, allowSeeking ?? GesturesDefaults.allowSeeking) XCTAssertEqual(prefs.controlsPreferences.gestures.allowTrackChange, allowTrackChange ?? GesturesDefaults.allowTrackChange) XCTAssertEqual(prefs.controlsPreferences.gestures.allowVolumeControl, allowVolumeControl ?? GesturesDefaults.allowVolumeControl) XCTAssertEqual(prefs.controlsPreferences.gestures.seekSensitivity, seekSensitivity ?? GesturesDefaults.seekSensitivity) XCTAssertEqual(prefs.controlsPreferences.gestures.volumeControlSensitivity, volumeControlSensitivity ?? GesturesDefaults.volumeControlSensitivity) XCTAssertEqual(prefs.controlsPreferences.remoteControl.enabled, remoteControlEnabled ?? RemoteControlDefaults.enabled) XCTAssertEqual(prefs.controlsPreferences.remoteControl.trackChangeOrSeekingOption, trackChangeOrSeekingOption ?? RemoteControlDefaults.trackChangeOrSeekingOption) XCTAssertEqual(prefs.metadataPreferences.musicBrainz.httpTimeout, httpTimeout ?? MusicBrainzDefaults.httpTimeout) XCTAssertEqual(prefs.metadataPreferences.musicBrainz.enableCoverArtSearch, enableCoverArtSearch ?? MusicBrainzDefaults.enableCoverArtSearch) XCTAssertEqual(prefs.metadataPreferences.musicBrainz.enableOnDiskCoverArtCache, enableOnDiskCoverArtCache ?? MusicBrainzDefaults.enableOnDiskCoverArtCache) } // MARK: persist() tests ------------------------------ func testPersist() { for _ in 1...(runLongRunningTests ? 1000 : 100) { let defaults = UserDefaults() doTestPersist(prefs: randomPreferences(defaults: defaults), userDefs: defaults) } } func testPersist_serializeAndDeserialize() { for _ in 1...(runLongRunningTests ? 1000 : 100) { let userDefs: UserDefaults = UserDefaults() let serializedPrefs = randomPreferences(defaults: userDefs) doTestPersist(prefs: serializedPrefs, userDefs: userDefs) let deserializedPrefs = Preferences(defaults: userDefs) compare(prefs: deserializedPrefs, userDefs: userDefs) } } private func doTestPersist(prefs: Preferences, userDefs: UserDefaults) { prefs.persist() compare(prefs: prefs, userDefs: userDefs) } private func compare(prefs: Preferences, userDefs: UserDefaults) { compare(prefs: prefs.playlistPreferences, userDefs: userDefs) compare(prefs: prefs.playbackPreferences, userDefs: userDefs) compare(prefs: prefs.soundPreferences, userDefs: userDefs) compare(prefs: prefs.viewPreferences, userDefs: userDefs) compare(prefs: prefs.historyPreferences, userDefs: userDefs) compare(prefs: prefs.controlsPreferences, userDefs: userDefs) compare(prefs: prefs.metadataPreferences, userDefs: userDefs) } private func randomPreferences(defaults: UserDefaults) -> Preferences { let prefs = Preferences(defaults: defaults) prefs.playlistPreferences = randomPlaylistPreferences() prefs.playbackPreferences = randomPlaybackPreferences() prefs.soundPreferences = randomSoundPreferences() prefs.historyPreferences = randomHistoryPreferences() prefs.viewPreferences = randomViewPreferences() prefs.controlsPreferences = randomControlsPreferences() prefs.metadataPreferences = randomMetadataPreferences() return prefs } }
56.770833
163
0.667817
46dc7b41f8ffea2b7f8e447a10df303f7d63e481
11,745
// ==================================================================== // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You 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 /// /// dump data in hexadecimal format /// /// ported to swift /// 2016 by Jürgen Mülbert public class HexDump { public static let EOL = "\n" /// all static methods, so no need for a public constructor private func HexDump() { } /** dump an array of bytes to an OutputStream - Parameters - data the byte array to be dumped - offset its offset, whatever that might mean - stream the OutputStream to which the data is to be written - index initial index into the byte array - length number of characters to output - Throws: IOException is thrown if anything goes wrong writing the data to stream - Throws: ArrayIndexOutOfBoundsException if the index is outside the data array's bounds - Throws: IllegalArgumentException if the output stream is null */ public static func dump(data: String, offset: Int, stream: String, index: Int, length: Int) { if (stream.isEmpty) { NSException.init(name: "IllegalArgumentException", reason: "connot write to nullstream", userInfo: nil ).raise() } do { try data.writeToFile(stream, atomically: false, encoding: NSASCIIStringEncoding) } catch { /* error handling here */ NSException.init(name: "FileException", reason: "The file is unreadable", userInfo: nil ).raise() } } /** dump an array of bytes to an OutputStream - Parameters - data the byte array to be dumped - offset its offset, whatever that might mean - stream the OutputStream to which the data is to be written - index initial index into the byte array - Throws: IOException is thrown if anything goes wrong writing the data to stream - Throws: ArrayIndexOutOfBoundsException if the index is outside the data array's bounds - Throws: IllegalArgumentException if the output stream is null */ public static func dump(data: String, offset: Int, stream: String, index: Int) { dump(data, offset:offset, stream:stream, index:Int.max) } // // dump an array of bytes to a String // // @param data the byte array to be dumped // @param offset its offset, whatever that might mean // @param index initial index into the byte array // // @exception ArrayIndexOutOfBoundsException if the index is // outside the data array's bounds // @return output string // public static func dump(data: String, offset: Int, index: Int) -> String { return dump(data, offset:offset, index:index, length: Int.max); } // // dump an array of bytes to a String // // @param data the byte array to be dumped // @param offset its offset, whatever that might mean // @param index initial index into the byte array // @param length number of characters to output // // @exception ArrayIndexOutOfBoundsException if the index is // outside the data array's bounds // @return output string // public static func dump(data: String, offset:Int, index: Int, length: Int) ->String { if (data.isEmpty) { return "No Data" + EOL } let data_length:Int = (length == Int.max || length < 0 || index+length < 0) ? data.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) : min(data.lengthOfBytesUsingEncoding(NSASCIIStringEncoding), index+length) if ((index < 0) || (index >= data.lengthOfBytesUsingEncoding(NSASCIIStringEncoding))) { let errorString: String = "illegal index: \(data.lengthOfBytesUsingEncoding(NSASCIIStringEncoding)) into array of length" NSException.init(name: "ArrayIndexOutOfBounds", reason: errorString, userInfo: nil ).raise() } var display_offset: Int = offset + index var dataBuffer = [UInt8](data.utf8) var stringBuffer: String = String() for (var j:Int = index; j < data_length; j += 16) { var chars_read: Int = data_length - j if (chars_read > 16) { chars_read = 16 } stringBuffer.appendContentsOf(String(format: "%08x", display_offset)) for (var k:Int = 0; k < 16; k++) { if (k < chars_read) { stringBuffer.appendContentsOf(" ") let addString = NSString(format: "%02x", dataBuffer[k + j]) stringBuffer.appendContentsOf(addString as String) } else { stringBuffer.appendContentsOf(" ") } } stringBuffer.appendContentsOf(" ") for (var k:Int = 0; k < chars_read; k++) { let char = NSString(format: "%c", dataBuffer[k+j]) stringBuffer.appendContentsOf(char as String) } stringBuffer.appendContentsOf(EOL) display_offset += chars_read } return stringBuffer } // // Dumps <code>bytesToDump</code> bytes to an output stream. // // @param in The stream to read from // @param out The output stream // @param start The index to use as the starting position for the left hand side label // @param bytesToDump The number of bytes to output. Use -1 to read until the end of file. // public static func dump(inFile: String, outFile: String, start: Int, bytesToDump: Int) { var fileContent: String? var pointerToUint:UnsafeMutablePointer<UInt>! pointerToUint = UnsafeMutablePointer<UInt>.alloc(1) if (bytesToDump == -1) { do { fileContent = try String(contentsOfFile: inFile, encoding: NSUTF8StringEncoding) try fileContent!.writeToFile(outFile, atomically: false, encoding: NSUTF8StringEncoding) // dump(fileContent!, offset:0, stream:outFile, index:start, length:fileContent!.length) } catch { /* error handling here */ NSException.init(name: "FileException", reason: "The file is unreadable", userInfo: nil ).raise() } } else { do { // buf = try NSData(contentsOfFile: inFile) var outBytes: NSData = NSData(bytesNoCopy: pointerToUint, length: bytesToDump, freeWhenDone: true) outBytes.writeToFile(outFile, atomically: false) // dump(outBytes, offset:0, stream:outFile, index:start, length:outBytes.length) } catch { /* error handling here */ NSException.init(name: "FileException", reason: "The file is unreadable", userInfo: nil ).raise() } } } // TODO ---------------------------------------------------- // TODO Make this // TODO ---------------------------------------------------- // public static func toAscii(dataB: UInt16) -> UInt16 { // let controlCharSet = NSCharacterSet.controlCharacterSet() // let printableCharSet = NSCharacterSet.alphanumericCharacterSet() // var charB: UInt16 = (dataB & 0xFF) // if (controlCharSet.characterIsMember(dataB)) { // charB = // } else if (!printableCharSet.characterIsMember(dataB)) { // charB = (UInt16) "." // } // return dataB // } /** Converts the parameter to a hex value. Parameter value The value to convert Return The result right padded with 0 */ public static func toHex(value: Int8) ->String { let hexString: String = (NSString(format: "%4X", value ) as String) as String return hexString } // // Converts the parameter to a hex value. // // @param value The value to convert // @return The result right padded with 0 // public static func toHex(value: Int16) ->String { let hexString: String = (NSString(format: "%8X", value ) as String) as String return hexString } // // Converts the parameter to a hex value. // // @param value The value to convert // @return The result right padded with 0 // public static func toHex(value: Int32) ->String { let hexString: String = (NSString(format: "%16X", value ) as String) as String return hexString } // // Converts the parameter to a hex value. // // @param value The value to convert // @return The result right padded with 0 // public static func toHex(value: Int) ->String { let hexString: String = (NSString(format: "%32X", value) as String) as String return hexString } // // @return string of 16 (zero padded) uppercase hex chars and prefixed with '0x' // public static func longToHex(value: Int) -> String { let hexString: String = "0x" + (NSString(format: "%16X", value) as String) as String return hexString } // // @return string of 8 (zero padded) uppercase hex chars and prefixed with '0x' // public static func intToHex(value: Int) -> String { let hexString: String = "0x" + (NSString(format: "%8X", (value & 0xFFFFFFFF)) as String) as String return hexString } // // @return string of 4 (zero padded) uppercase hex chars and prefixed with '0x' // public static func shortToHex(value: Int) -> String { let hexString: String = "0x" + (NSString(format:"%4X", (value & 0xFFFF)) as String) as String return hexString } // // @return string of 2 (zero padded) uppercase hex chars and prefixed with '0x' // public static func byteToHex(value: Int) -> String { let hexString:String = "0x" + (NSString(format:"%2X", (value & 0xFF)) as String) as String return hexString } }
36.588785
133
0.555641
d9b0945e4e670501d4b8276153b5c47975b40ae2
1,329
import Combine import Foundation public protocol PonyServiceProtocol { func allCharacters(query: CharacterQueryParameters?) -> AnyPublisher<Ponies, Error> func characters(byId: Int, query: CharacterQueryParameters?) -> AnyPublisher<Ponies, Error> func characters(byKind: String, query: CharacterQueryParameters?) -> AnyPublisher<Ponies, Error> func characters(byOccupation: String, query: CharacterQueryParameters?) -> AnyPublisher<Ponies, Error> func characters(byResidence: String, query: CharacterQueryParameters?) -> AnyPublisher<Ponies, Error> #if swift(>=5.5) @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) func allCharacters(query: CharacterQueryParameters?) async throws -> Ponies @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) func characters(byId: Int, query: CharacterQueryParameters?) async throws -> Ponies @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) func characters(byKind: String, query: CharacterQueryParameters?) async throws -> Ponies @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) func characters(byOccupation: String, query: CharacterQueryParameters?) async throws -> Ponies @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) func characters(byResidence: String, query: CharacterQueryParameters?) async throws -> Ponies #endif }
57.782609
103
0.763732
4beb4dcced9236ac1c57cbdf9487d92917038c6e
9,352
@testable import KsApi import Prelude import XCTest final class ProjectTests: XCTestCase { func testFundingProgress() { let halfFunded = Project.template |> Project.lens.stats.fundingProgress .~ 0.5 XCTAssertEqual(0.5, halfFunded.stats.fundingProgress) XCTAssertEqual(50, halfFunded.stats.percentFunded) let badGoalData = Project.template |> Project.lens.stats.pledged .~ 0 <> Project.lens.stats.goal .~ 0 XCTAssertEqual(0.0, badGoalData.stats.fundingProgress) XCTAssertEqual(0, badGoalData.stats.percentFunded) } func testEndsIn48Hours_WithJustLaunchedProject() { let justLaunched = Project.template |> Project.lens.dates.launchedAt .~ Date(timeIntervalSince1970: 1_475_361_315).timeIntervalSince1970 XCTAssertEqual(false, justLaunched.endsIn48Hours(today: Date(timeIntervalSince1970: 1_475_361_315))) } func testEndsIn48Hours_WithEndingSoonProject() { let endingSoon = Project.template |> Project.lens.dates.deadline .~ (Date(timeIntervalSince1970: 1_475_361_315) .timeIntervalSince1970 - 60.0 * 60.0) XCTAssertEqual(true, endingSoon.endsIn48Hours(today: Date(timeIntervalSince1970: 1_475_361_315))) } func testEndsIn48Hours_WithTimeZoneEdgeCaseProject() { let edgeCase = Project.template |> Project.lens.dates.deadline .~ (Date(timeIntervalSince1970: 1_475_361_315) .timeIntervalSince1970 - 60.0 * 60.0 * 47.0) XCTAssertEqual(true, edgeCase.endsIn48Hours(today: Date(timeIntervalSince1970: 1_475_361_315))) } func testEquatable() { XCTAssertEqual(Project.template, Project.template) XCTAssertNotEqual(Project.template, Project.template |> Project.lens.id %~ { $0 + 1 }) } func testDescription() { XCTAssertNotEqual("", Project.template.debugDescription) } func testJSONParsing_WithCompleteData() { let project = Project.decodeJSONDictionary([ "id": 1, "name": "Project", "blurb": "The project blurb", "staff_pick": false, "pledged": 1_000, "goal": 2_000, "category": [ "id": 1, "name": "Art", "parent_id": 5, "parent_name": "Parent Category", "slug": "art", "position": 1 ], "creator": [ "id": 1, "name": "Blob", "avatar": [ "medium": "http://www.kickstarter.com/medium.jpg", "small": "http://www.kickstarter.com/small.jpg" ] ], "photo": [ "full": "http://www.kickstarter.com/full.jpg", "med": "http://www.kickstarter.com/med.jpg", "small": "http://www.kickstarter.com/small.jpg", "1024x768": "http://www.kickstarter.com/1024x768.jpg" ], "location": [ "country": "US", "id": 1, "displayable_name": "Brooklyn, NY", "name": "Brooklyn" ], "video": [ "id": 1, "high": "kickstarter.com/video.mp4" ], "backers_count": 10, "currency_symbol": "$", "currency": "USD", "currency_trailing_code": false, "country": "US", "launched_at": 1_000, "deadline": 1_000, "state_changed_at": 1_000, "static_usd_rate": 1.0, "slug": "project", "urls": [ "web": [ "project": "https://www.kickstarter.com/projects/blob/project" ] ], "state": "live" ]) XCTAssertNil(project.error) XCTAssertEqual("US", project.value?.country.countryCode) XCTAssertEqual(1, project.value?.category.id) XCTAssertEqual("Art", project.value?.category.name) XCTAssertEqual(5, project.value?.category.parentId) XCTAssertEqual("Parent Category", project.value?.category.parentName) } func testJSONParsing_WithMemberData() { let memberData = Project.MemberData.decodeJSONDictionary([ "last_update_published_at": 123_456_789, "permissions": [ "edit_project", "bad_data", "edit_faq", "post", "comment", "bad_data", "view_pledges", "fulfillment" ], "unread_messages_count": 1, "unseen_activity_count": 2 ]) XCTAssertNil(memberData.error) XCTAssertEqual(123_456_789, memberData.value?.lastUpdatePublishedAt) XCTAssertEqual(1, memberData.value?.unreadMessagesCount) XCTAssertEqual(2, memberData.value?.unseenActivityCount) XCTAssertEqual( [.editProject, .editFaq, .post, .comment, .viewPledges, .fulfillment], memberData.value?.permissions ?? [] ) } func testJSONParsing_WithPesonalizationData() { let project = Project.decodeJSONDictionary([ "id": 1, "name": "Project", "blurb": "The project blurb", "staff_pick": false, "pledged": 1_000, "goal": 2_000, "category": [ "id": 1, "name": "Art", "parent_id": 5, "parent_name": "Parent Category", "slug": "art", "position": 1 ], "creator": [ "id": 1, "name": "Blob", "avatar": [ "medium": "http://www.kickstarter.com/medium.jpg", "small": "http://www.kickstarter.com/small.jpg" ] ], "photo": [ "full": "http://www.kickstarter.com/full.jpg", "med": "http://www.kickstarter.com/med.jpg", "small": "http://www.kickstarter.com/small.jpg", "1024x768": "http://www.kickstarter.com/1024x768.jpg" ], "location": [ "country": "US", "id": 1, "displayable_name": "Brooklyn, NY", "name": "Brooklyn" ], "video": [ "id": 1, "high": "kickstarter.com/video.mp4" ], "backers_count": 10, "currency_symbol": "$", "currency": "USD", "currency_trailing_code": false, "country": "US", "launched_at": 1_000, "deadline": 1_000, "state_changed_at": 1_000, "static_usd_rate": 1.0, "slug": "project", "urls": [ "web": [ "project": "https://www.kickstarter.com/projects/my-cool-projects" ] ], "state": "live", "is_backing": true, "is_starred": true ]) XCTAssertNil(project.error) XCTAssertEqual("US", project.value?.country.countryCode) XCTAssertEqual(true, project.value?.personalization.isBacking) } func testPledgedUsd() { let project = .template |> Project.lens.stats.staticUsdRate .~ 2.0 |> Project.lens.stats.pledged .~ 1_000 XCTAssertEqual(2_000, project.stats.pledgedUsd) } func testDuration() { let launchedAt = DateComponents() |> \.day .~ 15 |> \.month .~ 3 |> \.year .~ 2_020 |> \.timeZone .~ TimeZone(secondsFromGMT: 0) // 1 month after launch let deadline = DateComponents() |> \.day .~ 14 |> \.month .~ 4 |> \.year .~ 2_020 |> \.timeZone .~ TimeZone(secondsFromGMT: 0) let calendar = Calendar(identifier: .gregorian) let deadlineInterval = calendar.date(from: deadline)?.timeIntervalSince1970 let launchedAtInterval = calendar.date(from: launchedAt)?.timeIntervalSince1970 let project = Project.template |> Project.lens.dates.deadline .~ deadlineInterval! |> Project.lens.dates.launchedAt .~ launchedAtInterval! XCTAssertEqual(30, project.dates.duration(using: calendar)) } func testHoursRemaining() { let deadline = DateComponents() |> \.day .~ 2 |> \.month .~ 3 |> \.year .~ 2_020 |> \.timeZone .~ TimeZone(secondsFromGMT: 0) // 24 hours before deadline let now = DateComponents() |> \.day .~ 1 |> \.month .~ 3 |> \.year .~ 2_020 |> \.timeZone .~ TimeZone(secondsFromGMT: 0) let calendar = Calendar(identifier: .gregorian) let nowDate = calendar.date(from: now) let deadlineInterval = calendar.date(from: deadline)?.timeIntervalSince1970 let project = Project.template |> Project.lens.dates.deadline .~ deadlineInterval! XCTAssertEqual(24, project.dates.hoursRemaining(from: nowDate!, using: calendar)) } func testHoursRemaining_LessThanZero() { let deadline = DateComponents() |> \.day .~ 2 |> \.month .~ 3 |> \.year .~ 2_020 |> \.timeZone .~ TimeZone(secondsFromGMT: 0) // 24 hours after deadline let now = DateComponents() |> \.day .~ 3 |> \.month .~ 3 |> \.year .~ 2_020 |> \.timeZone .~ TimeZone(secondsFromGMT: 0) let calendar = Calendar(identifier: .gregorian) let nowDate = calendar.date(from: now) let deadlineInterval = calendar.date(from: deadline)?.timeIntervalSince1970 let project = Project.template |> Project.lens.dates.deadline .~ deadlineInterval! XCTAssertEqual(0, project.dates.hoursRemaining(from: nowDate!, using: calendar)) } func testGoalMet_PledgedIsLessThanGoal() { let project = Project.template |> \.stats.goal .~ 1_000 |> \.stats.pledged .~ 50 XCTAssertFalse(project.stats.goalMet) } func testGoalMet_PledgedEqualToGoal() { let project = Project.template |> \.stats.goal .~ 1_000 |> \.stats.pledged .~ 1_000 XCTAssertTrue(project.stats.goalMet) } func testGoalMet_PledgedIsGreaterThanGoal() { let project = Project.template |> \.stats.goal .~ 1_000 |> \.stats.pledged .~ 2_000 XCTAssertTrue(project.stats.goalMet) } }
29.501577
106
0.612382
46b6ef07656d358a212466371deed7ed674b4242
2,089
// // File.swift // Business_Search // // Created by admin on 7/28/19. // Copyright © 2019 admin. All rights reserved. // import UIKit extension BusinessDetailsController { func addHandlers(){ viewObject.phoneNumberButton.addTarget(self, action: #selector(handlePhoneNumberButton(sender:)), for: .touchUpInside) viewObject.visitYelpPageButton.addTarget(self, action: #selector(handleVisitYelpPageButton(_:)), for: .touchUpInside) viewObject.directionsButton.addTarget(self, action: #selector(handleMapItButton(_:)), for: .touchUpInside) viewObject.markFavoriteButton.addTarget(self, action: #selector(handleUpdateFavorites(sender:)), for: .touchUpInside) } @objc func handleUpdateFavorites(sender: UIButton){ if let result = businessViewModel.changeFavorite(business: currentBusiness) { if result { favoriteViewModel.createFavorite(business: currentBusiness) viewObject.changeTitle(isFavorite: result) } else { favoriteViewModel.deleteFavorite(business: currentBusiness) viewObject.changeTitle(isFavorite: result) } } else { print("Error 77A: Unable to reset Favorite on currentBusiness") } } @objc func handlePhoneNumberButton(sender: UIButton){ guard let numberString = sender.titleLabel?.text else {return} coordinator?.loadPhoneCallScreen(number: numberString) } @objc func handleVisitYelpPageButton(_ sender: UIButton){ if let urlStringExists = viewModel.getUrlString, urlStringExists._isValidURL { coordinator?.loadSafariBrowser(url: urlStringExists) } else { coordinator?.loadSafariBrowser(url: "https://www.yelp.com") } } @objc func handleMapItButton(_ sender: UIButton){ guard let currentLocation = locationManager.location?.coordinate else {print("Unable to get current Location"); return} coordinator?.loadAppleMap(currentLocation: currentLocation) } }
38.685185
127
0.681187
ac144fcb4038cba5c2853ddc67e3781e7e9fbcec
2,171
// // AppDelegate.swift // textAdventureIOS // // Created by Eden on 7/22/18. // Copyright © 2018 Eden Mugg. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.191489
285
0.754952
bb263e09bfc705d8176ecba19f73b0ea717f6cf7
958
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/Inputs/SilentPlaygroundsRuntime.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test // XFAIL: * // FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode // UNSUPPORTED: OS=linux-gnu class X { var foo: Int { get { return 1 } set { } } } _ = X().foo // CHECK: [16:1-16:12] pc before // the reason this is XFAILed is because it returns [12:3-11:13]. // CHECK-NEXT: [12:3-12:19] pc before // CHECK-NEXT: [12:3-12:19] pc after // CHECK-NEXT: [12:9-12:17] pc before // CHECK-NEXT: [12:9-12:17] pc after // CHECK-NEXT: [16:1-16:12] pc after
33.034483
197
0.677453
9befc2835108559ca0a5fec84f2285ef61aead25
58,225
// // SignalProducerLiftingSpec.swift // ReactiveSwift // // Created by Neil Pankey on 6/14/15. // Copyright © 2015 GitHub. All rights reserved. // import Dispatch import Foundation import Result @testable import Nimble import Quick @testable import ReactiveSwift class SignalProducerLiftingSpec: QuickSpec { override func spec() { describe("map") { it("should transform the values of the signal") { let (producer, observer) = SignalProducer<Int, NoError>.pipe() let mappedProducer = producer.map { String($0 + 1) } var lastValue: String? mappedProducer.startWithValues { lastValue = $0 return } expect(lastValue).to(beNil()) observer.send(value: 0) expect(lastValue) == "1" observer.send(value: 1) expect(lastValue) == "2" } it("should raplace the values of the signal to constant new value") { let (producer, observer) = SignalProducer<String, NoError>.pipe() let mappedProducer = producer.map(value: 1) var lastValue: Int? mappedProducer.startWithValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: "foo") expect(lastValue) == 1 observer.send(value: "foobar") expect(lastValue) == 1 } } describe("mapError") { it("should transform the errors of the signal") { let (producer, observer) = SignalProducer<Int, TestError>.pipe() let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 100, userInfo: nil) var error: NSError? producer .mapError { _ in producerError } .startWithFailed { error = $0 } expect(error).to(beNil()) observer.send(error: TestError.default) expect(error) == producerError } } describe("lazyMap") { describe("with a scheduled binding") { var token: Lifetime.Token! var lifetime: Lifetime! var destination: [String] = [] var tupleProducer: SignalProducer<(character: String, other: Int), NoError>! var tupleObserver: Signal<(character: String, other: Int), NoError>.Observer! var theLens: SignalProducer<String, NoError>! var getterCounter: Int = 0 var lensScheduler: TestScheduler! var targetScheduler: TestScheduler! var target: BindingTarget<String>! beforeEach { destination = [] token = Lifetime.Token() lifetime = Lifetime(token) let (producer, observer) = SignalProducer<(character: String, other: Int), NoError>.pipe() tupleProducer = producer tupleObserver = observer lensScheduler = TestScheduler() targetScheduler = TestScheduler() getterCounter = 0 theLens = tupleProducer.lazyMap(on: lensScheduler) { (tuple: (character: String, other: Int)) -> String in getterCounter += 1 return tuple.character } target = BindingTarget<String>(on: targetScheduler, lifetime: lifetime) { destination.append($0) } target <~ theLens } it("should not propagate values until scheduled") { // Send a value along tupleObserver.send(value: (character: "🎃", other: 42)) // The destination should not change value, and the getter // should not have evaluated yet, as neither has been scheduled expect(destination) == [] expect(getterCounter) == 0 // Advance both schedulers lensScheduler.advance() targetScheduler.advance() // The destination receives the previously-sent value, and the // getter obviously evaluated expect(destination) == ["🎃"] expect(getterCounter) == 1 } it("should evaluate the getter only when scheduled") { // Send a value along tupleObserver.send(value: (character: "🎃", other: 42)) // The destination should not change value, and the getter // should not have evaluated yet, as neither has been scheduled expect(destination) == [] expect(getterCounter) == 0 // When the getter's scheduler advances, the getter should // be evaluated, but the destination still shouldn't accept // the new value lensScheduler.advance() expect(getterCounter) == 1 expect(destination) == [] // Sending other values along shouldn't evaluate the getter tupleObserver.send(value: (character: "😾", other: 42)) tupleObserver.send(value: (character: "🍬", other: 13)) tupleObserver.send(value: (character: "👻", other: 17)) expect(getterCounter) == 1 expect(destination) == [] // Push the scheduler along for the lens, and the getter // should evaluate lensScheduler.advance() expect(getterCounter) == 2 // ...but the destination still won't receive the value expect(destination) == [] // Finally, pushing the target scheduler along will // propagate only the first and last values targetScheduler.advance() expect(getterCounter) == 2 expect(destination) == ["🎃", "👻"] } } it("should return the result of the getter on each value change") { let initialValue = (character: "🎃", other: 42) let nextValue = (character: "😾", other: 74) let scheduler = TestScheduler() let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe() let theLens: SignalProducer<String, NoError> = tupleProducer.lazyMap(on: scheduler) { $0.character } var output: [String] = [] theLens.startWithValues { value in output.append(value) } tupleObserver.send(value: initialValue) scheduler.advance() expect(output) == ["🎃"] tupleObserver.send(value: nextValue) scheduler.advance() expect(output) == ["🎃", "😾"] } it("should evaluate its getter lazily") { let initialValue = (character: "🎃", other: 42) let nextValue = (character: "😾", other: 74) let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe() let scheduler = TestScheduler() var output: [String] = [] var getterEvaluated = false let theLens: SignalProducer<String, NoError> = tupleProducer.lazyMap(on: scheduler) { (tuple: (character: String, other: Int)) -> String in getterEvaluated = true return tuple.character } // No surprise here, but the getter should not be evaluated // since the underlying producer has yet to be started. expect(getterEvaluated).to(beFalse()) // Similarly, sending values won't cause anything to happen. tupleObserver.send(value: initialValue) expect(output).to(beEmpty()) expect(getterEvaluated).to(beFalse()) // Start the signal, appending future values to the output array theLens.startWithValues { value in output.append(value) } // Even when the producer has yet to start, there should be no // evaluation of the getter expect(getterEvaluated).to(beFalse()) // Now we send a value through the producer tupleObserver.send(value: initialValue) // The getter should still not be evaluated, as it has not yet // been scheduled expect(getterEvaluated).to(beFalse()) // Now advance the scheduler to allow things to proceed scheduler.advance() // Now the getter gets evaluated, and the output is what we'd // expect expect(getterEvaluated).to(beTrue()) expect(output) == ["🎃"] // And now subsequent values continue to come through tupleObserver.send(value: nextValue) scheduler.advance() expect(output) == ["🎃", "😾"] } it("should evaluate its getter lazily on a different scheduler") { let initialValue = (character: "🎃", other: 42) let nextValue = (character: "😾", other: 74) let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe() let scheduler = TestScheduler() var output: [String] = [] var getterEvaluated = false let theLens: SignalProducer<String, NoError> = tupleProducer.lazyMap(on: scheduler) { (tuple: (character: String, other: Int)) -> String in getterEvaluated = true return tuple.character } // No surprise here, but the getter should not be evaluated // since the underlying producer has yet to be started. expect(getterEvaluated).to(beFalse()) // Similarly, sending values won't cause anything to happen. tupleObserver.send(value: initialValue) expect(output).to(beEmpty()) expect(getterEvaluated).to(beFalse()) // Start the signal, appending future values to the output array theLens.startWithValues { value in output.append(value) } // Even when the producer has yet to start, there should be no // evaluation of the getter expect(getterEvaluated).to(beFalse()) tupleObserver.send(value: initialValue) // The getter should still not get evaluated, as it was not yet // scheduled expect(getterEvaluated).to(beFalse()) expect(output).to(beEmpty()) scheduler.run() // Now that the scheduler's run, things can continue to move forward expect(getterEvaluated).to(beTrue()) expect(output) == ["🎃"] tupleObserver.send(value: nextValue) // Subsequent values should still be held up by the scheduler // not getting run expect(output) == ["🎃"] scheduler.run() expect(output) == ["🎃", "😾"] } it("should evaluate its getter lazily on the scheduler we specify") { let initialValue = (character: "🎃", other: 42) let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), NoError>.pipe() let labelKey = DispatchSpecificKey<String>() let testQueue = DispatchQueue(label: "test queue", target: .main) testQueue.setSpecific(key: labelKey, value: "test queue") testQueue.suspend() let testScheduler = QueueScheduler(internalQueue: testQueue) var output: [String] = [] var isOnTestQueue = false let theLens = tupleProducer.lazyMap(on: testScheduler) { (tuple: (character: String, other: Int)) -> String in isOnTestQueue = DispatchQueue.getSpecific(key: labelKey) == "test queue" return tuple.character } // Start the signal, appending future values to the output array theLens.startWithValues { value in output.append(value) } testQueue.resume() expect(isOnTestQueue).to(beFalse()) expect(output).to(beEmpty()) tupleObserver.send(value: initialValue) expect(isOnTestQueue).toEventually(beTrue()) expect(output).toEventually(equal(["🎃"])) } it("should interrupt ASAP and discard outstanding events") { testAsyncASAPInterruption(op: "lazyMap") { $0.lazyMap(on: $1) { $0 } } } it("should interrupt on the given scheduler") { testAsyncInterruptionScheduler(op: "lazyMap") { $0.lazyMap(on: $1) { $0 } } } } describe("filter") { it("should omit values from the producer") { let (producer, observer) = SignalProducer<Int, NoError>.pipe() let mappedProducer = producer.filter { $0 % 2 == 0 } var lastValue: Int? mappedProducer.startWithValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: 0) expect(lastValue) == 0 observer.send(value: 1) expect(lastValue) == 0 observer.send(value: 2) expect(lastValue) == 2 } } describe("skipNil") { it("should forward only non-nil values") { let (producer, observer) = SignalProducer<Int?, NoError>.pipe() let mappedProducer = producer.skipNil() var lastValue: Int? mappedProducer.startWithValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: nil) expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: nil) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 } } describe("scan(_:_:)") { it("should incrementally accumulate a value") { let (baseProducer, observer) = SignalProducer<String, NoError>.pipe() let producer = baseProducer.scan("", +) var lastValue: String? producer.startWithValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: "a") expect(lastValue) == "a" observer.send(value: "bb") expect(lastValue) == "abb" } } describe("scan(into:_:)") { it("should incrementally accumulate a value") { let (baseProducer, observer) = SignalProducer<String, NoError>.pipe() let producer = baseProducer.scan(into: "") { $0 += $1 } var lastValue: String? producer.startWithValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: "a") expect(lastValue) == "a" observer.send(value: "bb") expect(lastValue) == "abb" } } describe("reduce(_:_:)") { it("should accumulate one value") { let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe() let producer = baseProducer.reduce(1, +) var lastValue: Int? var completed = false producer.start { event in switch event { case let .value(value): lastValue = value case .completed: completed = true case .failed, .interrupted: break } } expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue).to(beNil()) expect(completed) == false observer.sendCompleted() expect(completed) == true expect(lastValue) == 4 } it("should send the initial value if none are received") { let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe() let producer = baseProducer.reduce(1, +) var lastValue: Int? var completed = false producer.start { event in switch event { case let .value(value): lastValue = value case .completed: completed = true case .failed, .interrupted: break } } expect(lastValue).to(beNil()) expect(completed) == false observer.sendCompleted() expect(lastValue) == 1 expect(completed) == true } } describe("reduce(into:_:)") { it("should accumulate one value") { let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe() let producer = baseProducer.reduce(into: 1) { $0 += $1 } var lastValue: Int? var completed = false producer.start { event in switch event { case let .value(value): lastValue = value case .completed: completed = true case .failed, .interrupted: break } } expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue).to(beNil()) expect(completed) == false observer.sendCompleted() expect(completed) == true expect(lastValue) == 4 } it("should send the initial value if none are received") { let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe() let producer = baseProducer.reduce(into: 1) { $0 += $1 } var lastValue: Int? var completed = false producer.start { event in switch event { case let .value(value): lastValue = value case .completed: completed = true case .failed, .interrupted: break } } expect(lastValue).to(beNil()) expect(completed) == false observer.sendCompleted() expect(lastValue) == 1 expect(completed) == true } } describe("skip") { it("should skip initial values") { let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe() let producer = baseProducer.skip(first: 1) var lastValue: Int? producer.startWithValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue) == 2 } it("should not skip any values when 0") { let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe() let producer = baseProducer.skip(first: 0) var lastValue: Int? producer.startWithValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 } } describe("skipRepeats") { it("should skip duplicate Equatable values") { let (baseProducer, observer) = SignalProducer<Bool, NoError>.pipe() let producer = baseProducer.skipRepeats() var values: [Bool] = [] producer.startWithValues { values.append($0) } expect(values) == [] observer.send(value: true) expect(values) == [ true ] observer.send(value: true) expect(values) == [ true ] observer.send(value: false) expect(values) == [ true, false ] observer.send(value: true) expect(values) == [ true, false, true ] } it("should skip values according to a predicate") { let (baseProducer, observer) = SignalProducer<String, NoError>.pipe() let producer = baseProducer.skipRepeats { $0.count == $1.count } var values: [String] = [] producer.startWithValues { values.append($0) } expect(values) == [] observer.send(value: "a") expect(values) == [ "a" ] observer.send(value: "b") expect(values) == [ "a" ] observer.send(value: "cc") expect(values) == [ "a", "cc" ] observer.send(value: "d") expect(values) == [ "a", "cc", "d" ] } } describe("skipWhile") { var producer: SignalProducer<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var lastValue: Int? beforeEach { let (baseProducer, incomingObserver) = SignalProducer<Int, NoError>.pipe() producer = baseProducer.skip { $0 < 2 } observer = incomingObserver lastValue = nil producer.startWithValues { lastValue = $0 } } it("should skip while the predicate is true") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue) == 2 observer.send(value: 0) expect(lastValue) == 0 } it("should not skip any values when the predicate starts false") { expect(lastValue).to(beNil()) observer.send(value: 3) expect(lastValue) == 3 observer.send(value: 1) expect(lastValue) == 1 } } describe("skipUntil") { var producer: SignalProducer<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var triggerObserver: Signal<(), NoError>.Observer! var lastValue: Int? = nil beforeEach { let (baseProducer, baseIncomingObserver) = SignalProducer<Int, NoError>.pipe() let (triggerProducer, incomingTriggerObserver) = SignalProducer<(), NoError>.pipe() producer = baseProducer.skip(until: triggerProducer) observer = baseIncomingObserver triggerObserver = incomingTriggerObserver lastValue = nil producer.start { event in switch event { case let .value(value): lastValue = value case .failed, .completed, .interrupted: break } } } it("should skip values until the trigger fires") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue).to(beNil()) triggerObserver.send(value: ()) observer.send(value: 0) expect(lastValue) == 0 } it("should skip values until the trigger completes") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue).to(beNil()) triggerObserver.sendCompleted() observer.send(value: 0) expect(lastValue) == 0 } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .skip(until: .init(value: ())) } } describe("take") { it("should take initial values") { let (baseProducer, observer) = SignalProducer<Int, NoError>.pipe() let producer = baseProducer.take(first: 2) var lastValue: Int? var completed = false producer.start { event in switch event { case let .value(value): lastValue = value case .completed: completed = true case .failed, .interrupted: break } } expect(lastValue).to(beNil()) expect(completed) == false observer.send(value: 1) expect(lastValue) == 1 expect(completed) == false observer.send(value: 2) expect(lastValue) == 2 expect(completed) == true } it("should complete immediately after taking given number of values") { let numbers = [ 1, 2, 4, 4, 5 ] let testScheduler = TestScheduler() let producer: SignalProducer<Int, NoError> = SignalProducer { observer, _ in // workaround `Class declaration cannot close over value 'observer' defined in outer scope` let observer = observer testScheduler.schedule { for number in numbers { observer.send(value: number) } } } var completed = false producer .take(first: numbers.count) .startWithCompleted { completed = true } expect(completed) == false testScheduler.run() expect(completed) == true } it("should interrupt when 0") { let numbers = [ 1, 2, 4, 4, 5 ] let testScheduler = TestScheduler() let producer: SignalProducer<Int, NoError> = SignalProducer { observer, _ in // workaround `Class declaration cannot close over value 'observer' defined in outer scope` let observer = observer testScheduler.schedule { for number in numbers { observer.send(value: number) } } } var result: [Int] = [] var interrupted = false producer .take(first: 0) .start { event in switch event { case let .value(number): result.append(number) case .interrupted: interrupted = true case .failed, .completed: break } } expect(interrupted) == true testScheduler.run() expect(result).to(beEmpty()) } } describe("collect") { it("should collect all values") { let (original, observer) = SignalProducer<Int, NoError>.pipe() let producer = original.collect() let expectedResult = [ 1, 2, 3 ] var result: [Int]? producer.startWithValues { value in expect(result).to(beNil()) result = value } for number in expectedResult { observer.send(value: number) } expect(result).to(beNil()) observer.sendCompleted() expect(result) == expectedResult } it("should complete with an empty array if there are no values") { let (original, observer) = SignalProducer<Int, NoError>.pipe() let producer = original.collect() var result: [Int]? producer.startWithValues { result = $0 } expect(result).to(beNil()) observer.sendCompleted() expect(result) == [] } it("should forward errors") { let (original, observer) = SignalProducer<Int, TestError>.pipe() let producer = original.collect() var error: TestError? producer.startWithFailed { error = $0 } expect(error).to(beNil()) observer.send(error: .default) expect(error) == TestError.default } it("should collect an exact count of values") { let (original, observer) = SignalProducer<Int, NoError>.pipe() let producer = original.collect(count: 3) var observedValues: [[Int]] = [] producer.startWithValues { value in observedValues.append(value) } var expectation: [[Int]] = [] for i in 1...7 { observer.send(value: i) if i % 3 == 0 { expectation.append([Int]((i - 2)...i)) expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC() } else { expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC() } } observer.sendCompleted() expectation.append([7]) expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC() } it("should collect values until it matches a certain value") { let (original, observer) = SignalProducer<Int, NoError>.pipe() let producer = original.collect { _, value in value != 5 } var expectedValues = [ [5, 5], [42, 5], ] producer.startWithValues { value in expect(value) == expectedValues.removeFirst() } producer.startWithCompleted { expect(expectedValues._bridgeToObjectiveC()) == []._bridgeToObjectiveC() } expectedValues .flatMap { $0 } .forEach(observer.send(value:)) observer.sendCompleted() } it("should collect values until it matches a certain condition on values") { let (original, observer) = SignalProducer<Int, NoError>.pipe() let producer = original.collect { values in values.reduce(0, +) == 10 } var expectedValues = [ [1, 2, 3, 4], [5, 6, 7, 8, 9], ] producer.startWithValues { value in expect(value) == expectedValues.removeFirst() } producer.startWithCompleted { expect(expectedValues._bridgeToObjectiveC()) == []._bridgeToObjectiveC() } expectedValues .flatMap { $0 } .forEach(observer.send(value:)) observer.sendCompleted() } } describe("takeUntil") { var producer: SignalProducer<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var triggerObserver: Signal<(), NoError>.Observer! var lastValue: Int? = nil var completed: Bool = false beforeEach { let (baseProducer, baseIncomingObserver) = SignalProducer<Int, NoError>.pipe() let (triggerProducer, incomingTriggerObserver) = SignalProducer<(), NoError>.pipe() producer = baseProducer.take(until: triggerProducer) observer = baseIncomingObserver triggerObserver = incomingTriggerObserver lastValue = nil completed = false producer.start { event in switch event { case let .value(value): lastValue = value case .completed: completed = true case .failed, .interrupted: break } } } it("should take values until the trigger fires") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 expect(completed) == false triggerObserver.send(value: ()) expect(completed) == true } it("should take values until the trigger completes") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 expect(completed) == false triggerObserver.sendCompleted() expect(completed) == true } it("should complete if the trigger fires immediately") { expect(lastValue).to(beNil()) expect(completed) == false triggerObserver.send(value: ()) expect(completed) == true expect(lastValue).to(beNil()) } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .take(until: .init(value: ())) } } describe("takeUntilReplacement") { var producer: SignalProducer<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var replacementObserver: Signal<Int, NoError>.Observer! var lastValue: Int? = nil var completed: Bool = false beforeEach { let (baseProducer, incomingObserver) = SignalProducer<Int, NoError>.pipe() let (replacementProducer, incomingReplacementObserver) = SignalProducer<Int, NoError>.pipe() producer = baseProducer.take(untilReplacement: replacementProducer) observer = incomingObserver replacementObserver = incomingReplacementObserver lastValue = nil completed = false producer.start { event in switch event { case let .value(value): lastValue = value case .completed: completed = true case .failed, .interrupted: break } } } it("should take values from the original then the replacement") { expect(lastValue).to(beNil()) expect(completed) == false observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 replacementObserver.send(value: 3) expect(lastValue) == 3 expect(completed) == false observer.send(value: 4) expect(lastValue) == 3 expect(completed) == false replacementObserver.send(value: 5) expect(lastValue) == 5 expect(completed) == false replacementObserver.sendCompleted() expect(completed) == true } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .take(untilReplacement: .init(value: 0)) } } describe("takeWhile") { var producer: SignalProducer<Int, NoError>! var observer: Signal<Int, NoError>.Observer! beforeEach { let (baseProducer, incomingObserver) = SignalProducer<Int, NoError>.pipe() producer = baseProducer.take { $0 <= 4 } observer = incomingObserver } it("should take while the predicate is true") { var latestValue: Int! var completed = false producer.start { event in switch event { case let .value(value): latestValue = value case .completed: completed = true case .failed, .interrupted: break } } for value in -1...4 { observer.send(value: value) expect(latestValue) == value expect(completed) == false } observer.send(value: 5) expect(latestValue) == 4 expect(completed) == true } it("should complete if the predicate starts false") { var latestValue: Int? var completed = false producer.start { event in switch event { case let .value(value): latestValue = value case .completed: completed = true case .failed, .interrupted: break } } observer.send(value: 5) expect(latestValue).to(beNil()) expect(completed) == true } } describe("observeOn") { it("should send events on the given scheduler") { let testScheduler = TestScheduler() let (producer, observer) = SignalProducer<Int, NoError>.pipe() var result: [Int] = [] producer .observe(on: testScheduler) .startWithValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) expect(result).to(beEmpty()) testScheduler.run() expect(result) == [ 1, 2 ] } it("should interrupt ASAP and discard outstanding events") { testAsyncASAPInterruption(op: "observe(on:)") { $0.observe(on: $1) } } it("should interrupt on the given scheduler") { testAsyncInterruptionScheduler(op: "observe(on:)") { $0.observe(on: $1) } } } describe("delay") { it("should send events on the given scheduler after the interval") { let testScheduler = TestScheduler() let producer: SignalProducer<Int, NoError> = SignalProducer { observer, _ in testScheduler.schedule { observer.send(value: 1) } testScheduler.schedule(after: .seconds(5)) { observer.send(value: 2) observer.sendCompleted() } } var result: [Int] = [] var completed = false producer .delay(10, on: testScheduler) .start { event in switch event { case let .value(number): result.append(number) case .completed: completed = true case .failed, .interrupted: break } } testScheduler.advance(by: .seconds(4)) // send initial value expect(result).to(beEmpty()) testScheduler.advance(by: .seconds(10)) // send second value and receive first expect(result) == [ 1 ] expect(completed) == false testScheduler.advance(by: .seconds(10)) // send second value and receive first expect(result) == [ 1, 2 ] expect(completed) == true } it("should schedule errors immediately") { let testScheduler = TestScheduler() let producer: SignalProducer<Int, TestError> = SignalProducer { observer, _ in // workaround `Class declaration cannot close over value 'observer' defined in outer scope` let observer = observer testScheduler.schedule { observer.send(error: TestError.default) } } var errored = false producer .delay(10, on: testScheduler) .startWithFailed { _ in errored = true } testScheduler.advance() expect(errored) == true } it("should interrupt ASAP and discard outstanding events") { testAsyncASAPInterruption(op: "delay") { $0.delay(10.0, on: $1) } } it("should interrupt on the given scheduler") { testAsyncInterruptionScheduler(op: "delay") { $0.delay(10.0, on: $1) } } } describe("throttle") { var scheduler: TestScheduler! var observer: Signal<Int, NoError>.Observer! var producer: SignalProducer<Int, NoError>! beforeEach { scheduler = TestScheduler() let (baseProducer, baseObserver) = SignalProducer<Int, NoError>.pipe() observer = baseObserver producer = baseProducer.throttle(1, on: scheduler) } it("should send values on the given scheduler at no less than the interval") { var values: [Int] = [] producer.startWithValues { value in values.append(value) } expect(values) == [] observer.send(value: 0) expect(values) == [] scheduler.advance() expect(values) == [ 0 ] observer.send(value: 1) observer.send(value: 2) expect(values) == [ 0 ] scheduler.advance(by: .milliseconds(1500)) expect(values) == [ 0, 2 ] scheduler.advance(by: .seconds(3)) expect(values) == [ 0, 2 ] observer.send(value: 3) expect(values) == [ 0, 2 ] scheduler.advance() expect(values) == [ 0, 2, 3 ] observer.send(value: 4) observer.send(value: 5) scheduler.advance() expect(values) == [ 0, 2, 3 ] scheduler.rewind(by: .seconds(2)) expect(values) == [ 0, 2, 3 ] observer.send(value: 6) scheduler.advance() expect(values) == [ 0, 2, 3, 6 ] observer.send(value: 7) observer.send(value: 8) scheduler.advance() expect(values) == [ 0, 2, 3, 6 ] scheduler.run() expect(values) == [ 0, 2, 3, 6, 8 ] } it("should schedule completion immediately") { var values: [Int] = [] var completed = false producer.start { event in switch event { case let .value(value): values.append(value) case .completed: completed = true case .failed, .interrupted: break } } observer.send(value: 0) scheduler.advance() expect(values) == [ 0 ] observer.send(value: 1) observer.sendCompleted() expect(completed) == false scheduler.run() expect(values) == [ 0 ] expect(completed) == true } it("should interrupt ASAP and discard outstanding events") { testAsyncASAPInterruption(op: "throttle") { $0.throttle(10.0, on: $1) } } it("should interrupt on the given scheduler") { testAsyncInterruptionScheduler(op: "throttle") { $0.throttle(10.0, on: $1) } } } describe("debounce") { it("should interrupt ASAP and discard outstanding events") { testAsyncASAPInterruption(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: true) } } it("should interrupt ASAP and discard outstanding events") { testAsyncASAPInterruption(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: false) } } it("should interrupt on the given scheduler") { testAsyncInterruptionScheduler(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: true) } } it("should interrupt on the given scheduler") { testAsyncInterruptionScheduler(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: false) } } } describe("sampleWith") { var sampledProducer: SignalProducer<(Int, String), NoError>! var observer: Signal<Int, NoError>.Observer! var samplerObserver: Signal<String, NoError>.Observer! beforeEach { let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe() let (sampler, incomingSamplerObserver) = SignalProducer<String, NoError>.pipe() sampledProducer = producer.sample(with: sampler) observer = incomingObserver samplerObserver = incomingSamplerObserver } it("should forward the latest value when the sampler fires") { var result: [String] = [] sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") } observer.send(value: 1) observer.send(value: 2) samplerObserver.send(value: "a") expect(result) == [ "2a" ] } it("should do nothing if sampler fires before signal receives value") { var result: [String] = [] sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") } samplerObserver.send(value: "a") expect(result).to(beEmpty()) } it("should send lates value multiple times when sampler fires multiple times") { var result: [String] = [] sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") } observer.send(value: 1) samplerObserver.send(value: "a") samplerObserver.send(value: "b") expect(result) == [ "1a", "1b" ] } it("should complete when both inputs have completed") { var completed = false sampledProducer.startWithCompleted { completed = true } observer.sendCompleted() expect(completed) == false samplerObserver.sendCompleted() expect(completed) == true } it("should emit an initial value if the sampler is a synchronous SignalProducer") { let producer = SignalProducer<Int, NoError>([1]) let sampler = SignalProducer<String, NoError>(value: "a") let result = producer.sample(with: sampler) var valueReceived: String? result.startWithValues { valueReceived = "\($0.0)\($0.1)" } expect(valueReceived) == "1a" } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .sample(with: .init(value: 0)) } } describe("sampleOn") { var sampledProducer: SignalProducer<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var samplerObserver: Signal<(), NoError>.Observer! beforeEach { let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe() let (sampler, incomingSamplerObserver) = SignalProducer<(), NoError>.pipe() sampledProducer = producer.sample(on: sampler) observer = incomingObserver samplerObserver = incomingSamplerObserver } it("should forward the latest value when the sampler fires") { var result: [Int] = [] sampledProducer.startWithValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) samplerObserver.send(value: ()) expect(result) == [ 2 ] } it("should do nothing if sampler fires before signal receives value") { var result: [Int] = [] sampledProducer.startWithValues { result.append($0) } samplerObserver.send(value: ()) expect(result).to(beEmpty()) } it("should send lates value multiple times when sampler fires multiple times") { var result: [Int] = [] sampledProducer.startWithValues { result.append($0) } observer.send(value: 1) samplerObserver.send(value: ()) samplerObserver.send(value: ()) expect(result) == [ 1, 1 ] } it("should complete when both inputs have completed") { var completed = false sampledProducer.startWithCompleted { completed = true } observer.sendCompleted() expect(completed) == false samplerObserver.sendCompleted() expect(completed) == true } it("should emit an initial value if the sampler is a synchronous SignalProducer") { let producer = SignalProducer<Int, NoError>([1]) let sampler = SignalProducer<(), NoError>(value: ()) let result = producer.sample(on: sampler) var valueReceived: Int? result.startWithValues { valueReceived = $0 } expect(valueReceived) == 1 } describe("memory") { class Payload { let action: () -> Void init(onDeinit action: @escaping () -> Void) { self.action = action } deinit { action() } } var sampledProducer: SignalProducer<Payload, NoError>! var samplerObserver: Signal<(), NoError>.Observer! var observer: Signal<Payload, NoError>.Observer! // Mitigate the "was written to, but never read" warning. _ = samplerObserver beforeEach { let (producer, incomingObserver) = SignalProducer<Payload, NoError>.pipe() let (sampler, _samplerObserver) = Signal<(), NoError>.pipe() sampledProducer = producer.sample(on: sampler) samplerObserver = _samplerObserver observer = incomingObserver } it("should free payload when interrupted after complete of incoming producer") { var payloadFreed = false let disposable = sampledProducer.start() observer.send(value: Payload { payloadFreed = true }) observer.sendCompleted() expect(payloadFreed) == false disposable.dispose() expect(payloadFreed) == true } } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .sample(on: .init(value: ())) } } describe("withLatest(from: signal)") { var withLatestProducer: SignalProducer<(Int, String), NoError>! var observer: Signal<Int, NoError>.Observer! var sampleeObserver: Signal<String, NoError>.Observer! beforeEach { let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe() let (samplee, incomingSampleeObserver) = Signal<String, NoError>.pipe() withLatestProducer = producer.withLatest(from: samplee) observer = incomingObserver sampleeObserver = incomingSampleeObserver } it("should forward the latest value when the receiver fires") { var result: [String] = [] withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") } sampleeObserver.send(value: "a") sampleeObserver.send(value: "b") observer.send(value: 1) expect(result) == [ "1b" ] } it("should do nothing if receiver fires before samplee sends value") { var result: [String] = [] withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") } observer.send(value: 1) expect(result).to(beEmpty()) } it("should send latest value with samplee value multiple times when receiver fires multiple times") { var result: [String] = [] withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") } sampleeObserver.send(value: "a") observer.send(value: 1) observer.send(value: 2) expect(result) == [ "1a", "2a" ] } it("should complete when receiver has completed") { var completed = false withLatestProducer.startWithCompleted { completed = true } observer.sendCompleted() expect(completed) == true } it("should not affect when samplee has completed") { var event: Signal<(Int, String), NoError>.Event? = nil withLatestProducer.start { event = $0 } sampleeObserver.sendCompleted() expect(event).to(beNil()) } it("should not affect when samplee has interrupted") { var event: Signal<(Int, String), NoError>.Event? = nil withLatestProducer.start { event = $0 } sampleeObserver.sendInterrupted() expect(event).to(beNil()) } } describe("withLatest(from: producer)") { var withLatestProducer: SignalProducer<(Int, String), NoError>! var observer: Signal<Int, NoError>.Observer! var sampleeObserver: Signal<String, NoError>.Observer! beforeEach { let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe() let (samplee, incomingSampleeObserver) = SignalProducer<String, NoError>.pipe() withLatestProducer = producer.withLatest(from: samplee) observer = incomingObserver sampleeObserver = incomingSampleeObserver } it("should forward the latest value when the receiver fires") { var result: [String] = [] withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") } sampleeObserver.send(value: "a") sampleeObserver.send(value: "b") observer.send(value: 1) expect(result) == [ "1b" ] } it("should do nothing if receiver fires before samplee sends value") { var result: [String] = [] withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") } observer.send(value: 1) expect(result).to(beEmpty()) } it("should send latest value with samplee value multiple times when receiver fires multiple times") { var result: [String] = [] withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") } sampleeObserver.send(value: "a") observer.send(value: 1) observer.send(value: 2) expect(result) == [ "1a", "2a" ] } it("should complete when receiver has completed") { var completed = false withLatestProducer.startWithCompleted { completed = true } observer.sendCompleted() expect(completed) == true } it("should not affect when samplee has completed") { var event: Signal<(Int, String), NoError>.Event? = nil withLatestProducer.start { event = $0 } sampleeObserver.sendCompleted() expect(event).to(beNil()) } it("should not affect when samplee has interrupted") { var event: Signal<(Int, String), NoError>.Event? = nil withLatestProducer.start { event = $0 } sampleeObserver.sendInterrupted() expect(event).to(beNil()) } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .withLatest(from: .init(value: 0)) } } describe("combineLatestWith") { var combinedProducer: SignalProducer<(Int, Double), NoError>! var observer: Signal<Int, NoError>.Observer! var otherObserver: Signal<Double, NoError>.Observer! beforeEach { let (producer, incomingObserver) = SignalProducer<Int, NoError>.pipe() let (otherSignal, incomingOtherObserver) = SignalProducer<Double, NoError>.pipe() combinedProducer = producer.combineLatest(with: otherSignal) observer = incomingObserver otherObserver = incomingOtherObserver } it("should forward the latest values from both inputs") { var latest: (Int, Double)? combinedProducer.startWithValues { latest = $0 } observer.send(value: 1) expect(latest).to(beNil()) // is there a better way to test tuples? otherObserver.send(value: 1.5) expect(latest?.0) == 1 expect(latest?.1) == 1.5 observer.send(value: 2) expect(latest?.0) == 2 expect(latest?.1) == 1.5 } it("should complete when both inputs have completed") { var completed = false combinedProducer.startWithCompleted { completed = true } observer.sendCompleted() expect(completed) == false otherObserver.sendCompleted() expect(completed) == true } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .combineLatest(with: .init(value: 0)) } } describe("zipWith") { var leftObserver: Signal<Int, NoError>.Observer! var rightObserver: Signal<String, NoError>.Observer! var zipped: SignalProducer<(Int, String), NoError>! beforeEach { let (leftProducer, incomingLeftObserver) = SignalProducer<Int, NoError>.pipe() let (rightProducer, incomingRightObserver) = SignalProducer<String, NoError>.pipe() leftObserver = incomingLeftObserver rightObserver = incomingRightObserver zipped = leftProducer.zip(with: rightProducer) } it("should combine pairs") { var result: [String] = [] zipped.startWithValues { result.append("\($0.0)\($0.1)") } leftObserver.send(value: 1) leftObserver.send(value: 2) expect(result) == [] rightObserver.send(value: "foo") expect(result) == [ "1foo" ] leftObserver.send(value: 3) rightObserver.send(value: "bar") expect(result) == [ "1foo", "2bar" ] rightObserver.send(value: "buzz") expect(result) == [ "1foo", "2bar", "3buzz" ] rightObserver.send(value: "fuzz") expect(result) == [ "1foo", "2bar", "3buzz" ] leftObserver.send(value: 4) expect(result) == [ "1foo", "2bar", "3buzz", "4fuzz" ] } it("should complete when the shorter signal has completed") { var result: [String] = [] var completed = false zipped.start { event in switch event { case let .value(left, right): result.append("\(left)\(right)") case .completed: completed = true case .failed, .interrupted: break } } expect(completed) == false leftObserver.send(value: 0) leftObserver.sendCompleted() expect(completed) == false expect(result) == [] rightObserver.send(value: "foo") expect(completed) == true expect(result) == [ "0foo" ] } it("should be able to fallback to SignalProducer for contextual lookups") { _ = SignalProducer<Int, NoError>.empty .zip(with: .init(value: 0)) } } describe("materialize") { it("should reify events from the signal") { let (producer, observer) = SignalProducer<Int, TestError>.pipe() var latestEvent: Signal<Int, TestError>.Event? producer .materialize() .startWithValues { latestEvent = $0 } observer.send(value: 2) expect(latestEvent).toNot(beNil()) if let latestEvent = latestEvent { switch latestEvent { case let .value(value): expect(value) == 2 case .failed, .completed, .interrupted: fail() } } observer.send(error: TestError.default) if let latestEvent = latestEvent { switch latestEvent { case .failed: break case .value, .completed, .interrupted: fail() } } } } describe("dematerialize") { typealias IntEvent = Signal<Int, TestError>.Event var observer: Signal<IntEvent, NoError>.Observer! var dematerialized: SignalProducer<Int, TestError>! beforeEach { let (producer, incomingObserver) = SignalProducer<IntEvent, NoError>.pipe() observer = incomingObserver dematerialized = producer.dematerialize() } it("should send values for Value events") { var result: [Int] = [] dematerialized .assumeNoErrors() .startWithValues { result.append($0) } expect(result).to(beEmpty()) observer.send(value: .value(2)) expect(result) == [ 2 ] observer.send(value: .value(4)) expect(result) == [ 2, 4 ] } it("should error out for Error events") { var errored = false dematerialized.startWithFailed { _ in errored = true } expect(errored) == false observer.send(value: .failed(TestError.default)) expect(errored) == true } it("should complete early for Completed events") { var completed = false dematerialized.startWithCompleted { completed = true } expect(completed) == false observer.send(value: IntEvent.completed) expect(completed) == true } } describe("takeLast") { var observer: Signal<Int, TestError>.Observer! var lastThree: SignalProducer<Int, TestError>! beforeEach { let (producer, incomingObserver) = SignalProducer<Int, TestError>.pipe() observer = incomingObserver lastThree = producer.take(last: 3) } it("should send the last N values upon completion") { var result: [Int] = [] lastThree .assumeNoErrors() .startWithValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) observer.send(value: 4) expect(result).to(beEmpty()) observer.sendCompleted() expect(result) == [ 2, 3, 4 ] } it("should send less than N values if not enough were received") { var result: [Int] = [] lastThree .assumeNoErrors() .startWithValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) observer.sendCompleted() expect(result) == [ 1, 2 ] } it("should send nothing when errors") { var result: [Int] = [] var errored = false lastThree.start { event in switch event { case let .value(value): result.append(value) case .failed: errored = true case .completed, .interrupted: break } } observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) expect(errored) == false observer.send(error: TestError.default) expect(errored) == true expect(result).to(beEmpty()) } } describe("timeoutWithError") { var testScheduler: TestScheduler! var producer: SignalProducer<Int, TestError>! var observer: Signal<Int, TestError>.Observer! beforeEach { testScheduler = TestScheduler() let (baseProducer, incomingObserver) = SignalProducer<Int, TestError>.pipe() producer = baseProducer.timeout(after: 2, raising: TestError.default, on: testScheduler) observer = incomingObserver } it("should complete if within the interval") { var completed = false var errored = false producer.start { event in switch event { case .completed: completed = true case .failed: errored = true case .value, .interrupted: break } } testScheduler.schedule(after: .seconds(1)) { observer.sendCompleted() } expect(completed) == false expect(errored) == false testScheduler.run() expect(completed) == true expect(errored) == false } it("should error if not completed before the interval has elapsed") { var completed = false var errored = false producer.start { event in switch event { case .completed: completed = true case .failed: errored = true case .value, .interrupted: break } } testScheduler.schedule(after: .seconds(3)) { observer.sendCompleted() } expect(completed) == false expect(errored) == false testScheduler.run() expect(completed) == false expect(errored) == true } it("should be available for NoError") { let producer: SignalProducer<Int, TestError> = SignalProducer<Int, NoError>.never .timeout(after: 2, raising: TestError.default, on: testScheduler) _ = producer } } describe("attempt") { it("should forward original values upon success") { let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe() let producer = baseProducer.attempt { _ in return .success(()) } var current: Int? producer .assumeNoErrors() .startWithValues { value in current = value } for value in 1...5 { observer.send(value: value) expect(current) == value } } it("should error if an attempt fails") { let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe() let producer = baseProducer.attempt { _ in return .failure(.default) } var error: TestError? producer.startWithFailed { err in error = err } observer.send(value: 42) expect(error) == TestError.default } } describe("attemptMap") { it("should forward mapped values upon success") { let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe() let producer = baseProducer.attemptMap { num -> Result<Bool, TestError> in return .success(num % 2 == 0) } var even: Bool? producer .assumeNoErrors() .startWithValues { value in even = value } observer.send(value: 1) expect(even) == false observer.send(value: 2) expect(even) == true } it("should error if a mapping fails") { let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe() let producer = baseProducer.attemptMap { _ -> Result<Bool, TestError> in return .failure(.default) } var error: TestError? producer.startWithFailed { err in error = err } observer.send(value: 42) expect(error) == TestError.default } } describe("combinePrevious") { var observer: Signal<Int, NoError>.Observer! let initialValue: Int = 0 var latestValues: (Int, Int)? beforeEach { latestValues = nil let (signal, baseObserver) = SignalProducer<Int, NoError>.pipe() observer = baseObserver signal.combinePrevious(initialValue).startWithValues { latestValues = $0 } } it("should forward the latest value with previous value") { expect(latestValues).to(beNil()) observer.send(value: 1) expect(latestValues?.0) == initialValue expect(latestValues?.1) == 1 observer.send(value: 2) expect(latestValues?.0) == 1 expect(latestValues?.1) == 2 } } } } private func testAsyncInterruptionScheduler( op: String, file: FileString = #file, line: UInt = #line, transform: (SignalProducer<Int, NoError>, TestScheduler) -> SignalProducer<Int, NoError> ) { var isInterrupted = false let scheduler = TestScheduler() let producer = transform(SignalProducer(0 ..< 128), scheduler) let failedExpectations = gatherFailingExpectations { let disposable = producer.startWithInterrupted { isInterrupted = true } expect(isInterrupted) == false disposable.dispose() expect(isInterrupted) == false scheduler.run() expect(isInterrupted) == true } if !failedExpectations.isEmpty { fail("The async operator `\(op)` does not interrupt on the appropriate scheduler.", location: SourceLocation(file: file, line: line)) } } private func testAsyncASAPInterruption( op: String, file: FileString = #file, line: UInt = #line, transform: (SignalProducer<Int, NoError>, TestScheduler) -> SignalProducer<Int, NoError> ) { var valueCount = 0 var interruptCount = 0 var unexpectedEventCount = 0 let scheduler = TestScheduler() let disposable = transform(SignalProducer(0 ..< 128), scheduler) .start { event in switch event { case .value: valueCount += 1 case .interrupted: interruptCount += 1 case .failed, .completed: unexpectedEventCount += 1 } } expect(interruptCount) == 0 expect(unexpectedEventCount) == 0 expect(valueCount) == 0 disposable.dispose() scheduler.run() let failedExpectations = gatherFailingExpectations { expect(interruptCount) == 1 expect(unexpectedEventCount) == 0 expect(valueCount) == 0 } if !failedExpectations.isEmpty { fail("The ASAP interruption test of the async operator `\(op)` has failed.", location: SourceLocation(file: file, line: line)) } }
26.514117
143
0.650923
903bf8eddc1de2de90d16bc9ee74be1cfc21480f
1,585
// // UIViewController+KMNavigationBar.swift // KMNavigationBarDemo // // Created by KM on 2018/5/24. // Copyright © 2018年 KM. All rights reserved. // import UIKit public extension UIViewController { var navigationBarHelper: KMNavigationBarHelper { if let helper: KMNavigationBarHelper = associatedObject(for: &UIViewController.barHelperKey) { return helper } else { let helper = KMNavigationBarHelper(viewController: self) setAssociatedObject(helper, forKey: &UIViewController.barHelperKey, policy: .retainNonatomic) return helper } } /// barHelperKey private static var barHelperKey: Void? } public class KMNavigationBarHelper: NSObject { public fileprivate(set) var option: KMNavigationBarOption = KMNavigationBarOption.default.option() //() fileprivate weak var viewController: UIViewController? fileprivate weak var navigationBar: UINavigationBar? required init(viewController: UIViewController) { self.viewController = viewController self.navigationBar = viewController.navigationController?.navigationBar if let preference = viewController.navigationController?.preference.mutableCopy() as? KMNavigationBarOption { self.option = preference } super.init() } public func performUpdate(_ update: ((KMNavigationBarOption) -> Void)? = nil) { guard let bar = self.navigationBar as? KMNavigationBar else { return } update?(option) bar.updateToOption(option) } }
32.346939
117
0.692744
e9edb9f9fa5de9596a584e72ab14cf83c05d718b
115
import Foundation enum CrowdloanFlow: String, Codable { case karura = "Karura" case bifrost = "Bifrost" }
16.428571
37
0.695652
20166154a85d24c885ecaa6e029547dc85774adc
713
// // ContentView.swift // SwiftUIAnimation // // Created by Luan Nguyen on 04/01/2021. // import SwiftUI struct ContentView: View { // MARK: - BODY var body: some View { VStack(spacing: 100) { TitleView() .offset(y: 100) Spacer() IconsView() Spacer() CardsView() .offset(y: -100) } //: VSTACK .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) } } // MARK: - PREVIEW #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif
18.763158
86
0.507714
71c444f3cf884ee6f9e687bc06e385c176fed4fb
2,006
// // TestSupport.swift // Succulent // // Created by Karl von Randow on 29/05/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import XCTest protocol SucculentTest { var baseURL: URL! { get } var session: URLSession! { get } func GET(_ path: String, completion: @escaping (_ data: Data?, _ response: HTTPURLResponse?, _ error: Error?) -> ()) func POST(_ path: String, body: Data, completion: @escaping (_ data: Data?, _ response: HTTPURLResponse?, _ error: Error?) -> ()) } extension SucculentTest where Self: XCTestCase { func GET(_ path: String, completion: @escaping (_ data: Data?, _ response: HTTPURLResponse?, _ error: Error?) -> ()) { let url = URL(string: path, relativeTo: baseURL)! let expectation = self.expectation(description: "Loaded URL") let dataTask = session.dataTask(with: url) { (data, response, error) in completion(data, response as? HTTPURLResponse, error) expectation.fulfill() } dataTask.resume() self.waitForExpectations(timeout: 10) { (error) in if let error = error { completion(nil, nil, error) } } } func POST(_ path: String, body: Data, completion: @escaping (_ data: Data?, _ response: HTTPURLResponse?, _ error: Error?) -> ()) { let url = URL(string: path, relativeTo: baseURL)! let expectation = self.expectation(description: "Loaded URL") var req = URLRequest(url: url) req.httpMethod = "POST" let dataTask = session.uploadTask(with: req, from: body) { (data, response, error) in completion(data, response as? HTTPURLResponse, error) expectation.fulfill() } dataTask.resume() self.waitForExpectations(timeout: 10) { (error) in if let error = error { completion(nil, nil, error) } } } }
33.433333
135
0.591226
ed9364ec54edfaae22ad60ac958c0cc67b98d21f
653
// // CourseMediaInfo.swift // edX // // Created by Akiva Leffert on 12/7/15. // Copyright © 2015 edX. All rights reserved. // import Foundation open class CourseMediaInfo: NSObject { let name: String? let uri: String? public init(name : String?, uri : String?) { self.name = name self.uri = uri } public init(dict : [AnyHashable: Any]?) { self.name = dict?["name"] as? String self.uri = dict?["uri"] as? String super.init() } open var dictionary : [String:AnyObject] { return stripNullsFrom(["name" : name as AnyObject, "uri" : uri as AnyObject]) } }
21.766667
85
0.580398
5bcfe041d8dd67673dcb9ae59e4ade95eae4d211
1,337
// // CLLocationManager+Rx.swift // Sky // // Created by kuroky on 2019/1/7. // Copyright © 2019 Kuroky. All rights reserved. // import Foundation import RxSwift import RxCocoa import CoreLocation extension CLLocationManager: HasDelegate { public typealias Delegate = CLLocationManagerDelegate } class CLLocationManagerDelegateProxy: DelegateProxy<CLLocationManager, CLLocationManagerDelegate>, DelegateProxyType, CLLocationManagerDelegate { weak private(set) var locationManager: CLLocationManager? init(locationManager: ParentObject) { self.locationManager = locationManager super.init(parentObject: locationManager, delegateProxy: CLLocationManagerDelegateProxy.self) } static func registerKnownImplementations() { self.register { CLLocationManagerDelegateProxy(locationManager: $0) } } } extension Reactive where Base: CLLocationManager { var delegate: CLLocationManagerDelegateProxy { return CLLocationManagerDelegateProxy.proxy(for: base) } var didUpdateLocations: Observable<[CLLocation]> { let sel = #selector(CLLocationManagerDelegate.locationManager(_:didUpdateLocations:)) return delegate.methodInvoked(sel).map { parameters in parameters[1] as! [CLLocation] } } }
28.446809
145
0.725505
61146dd068aceb33cdd21d751d7e5d1891c2d6ff
886
//===----------------------------------------------------------------------===// // // This source file is part of the Cyllene open source project // // Copyright (c) 2017 Chris Daley // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // See http://www.apache.org/licenses/LICENSE-2.0 for license information // //===----------------------------------------------------------------------===// import TimeSpecification protocol TouchGrabProtocol { //func down (grab:TouchGrab, time:TimeSpecification, touchId:int, sx:Fixed, sy:Fixed) -> Void func up (grab:TouchGrab, time:TimeSpecification, touchId: Int) -> Void //func motion (grab:TouchGrab, time:TimeSpecification, touchId: Int, sx:Fixed, sy:Fixed) -> Void func frame (grab:TouchGrab) -> Void func cancel (grab:TouchGrab) -> Void }
31.642857
97
0.594808
162cd388a86abd2d53f9a3b035a75202e088d66d
235
// // Source.swift // // Created by Balraj Singh on 12/01/19 // Copyright (c) . All rights reserved. // import Foundation public struct Source: Codable { // MARK: Properties public var id: String? public var name: String? }
15.666667
40
0.668085
39c95b776879a63eaefced6fdd0e70dcf5c27748
130
import XCTest import ClusterCounterTests var tests = [XCTestCaseEntry]() tests += ClusterCounterTests.allTests() XCTMain(tests)
16.25
39
0.8
b926ca09ff2c9e08a361dd11cc6a8bdbff6e0b6b
3,188
final class PrTable: NSTableView, NSPasteboardItemDataProvider { override var allowsVibrancy: Bool { return true } func cell(at theEvent: NSEvent) -> NSView? { let globalLocation = theEvent.locationInWindow let localLocation = convert(globalLocation, from: nil) return view(atColumn: column(at: localLocation), row: row(at: localLocation), makeIfNecessary: false) } override func mouseDown(with theEvent: NSEvent) { dragOrigin = nil } override func mouseUp(with theEvent: NSEvent) { if let prView = cell(at: theEvent) as? TrailerCell, let item = prView.associatedDataItem { let isAlternative = ((theEvent.modifierFlags.intersection(.option)) == .option) app.selected(item, alternativeSelect: isAlternative, window: window) } } func scale(image: NSImage, toFillSize: CGSize) -> NSImage { let targetFrame = CGRect(origin: .zero, size: toFillSize) let sourceImageRep = image.bestRepresentation(for: targetFrame, context: nil, hints: nil) let targetImage = NSImage(size: toFillSize) targetImage.lockFocus() sourceImageRep!.draw(in: targetFrame) targetImage.unlockFocus() return targetImage } private var dragOrigin: NSEvent? override func mouseDragged(with theEvent: NSEvent) { if let origin = dragOrigin { func fastDistance(_ a: CGFloat, _ b: CGFloat) -> CGFloat { let dx = fabs(a) let dy = fabs(b) return (dx < dy) ? dy + 0.337 * dx : dx + 0.337 * dy } let l = theEvent.locationInWindow let o = origin.locationInWindow if fastDistance(o.y - l.y, o.x - l.x) < 15 { return } } else { dragOrigin = theEvent return } draggingUrl = nil if let prView = cell(at: dragOrigin!) as? TrailerCell, let url = prView.associatedDataItem?.webUrl { draggingUrl = url let dragIcon = scale(image: NSApp.applicationIconImage, toFillSize: CGSize(width: 32, height: 32)) let pbItem = NSPasteboardItem() pbItem.setDataProvider(self, forTypes: [.string]) let dragItem = NSDraggingItem(pasteboardWriter: pbItem) var dragPosition = convert(theEvent.locationInWindow, from: nil) dragPosition.x -= 17 dragPosition.y -= 17 dragItem.setDraggingFrame(CGRect(origin: dragPosition, size: dragIcon.size), contents: dragIcon) let draggingSession = beginDraggingSession(with: [dragItem], event: theEvent, source: self) draggingSession.animatesToStartingPositionsOnCancelOrFail = true } } override func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { return (context == .outsideApplication) ? .copy : NSDragOperation() } private var draggingUrl: String? func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) { if let pasteboard = pasteboard, type == .string && draggingUrl != nil { pasteboard.setData(draggingUrl!.data(using: String.Encoding.utf8)!, forType: .string) draggingUrl = nil } } override func ignoreModifierKeys(for session: NSDraggingSession) -> Bool { return true } override func validateProposedFirstResponder(_ responder: NSResponder, for event: NSEvent?) -> Bool { return true } }
33.208333
132
0.728043
26d3836eafbd2ee2c0310c116a674683ecdbe50c
1,243
// // ssfeRecorderUITests.swift // ssfeRecorderUITests // // Created by Guest on 6/6/16. // Copyright © 2016 Guest. All rights reserved. // import XCTest class ssfeRecorderUITests: 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.594595
182
0.663717
2167c892b744be2b08c61ac60cf166e08ac7f32f
2,337
import XCTest @testable import SwiftLib_Plus final class LockTests: XCTestCase { func testLockPerformance() { let timeMs = performanceTimer(description: "\(#function), line: \(#line)", warningTimeMs: 100.0) { for _ in 1...100000 { DispatchQueue.lock(self) { /* no op */ } } } XCTAssertTrue(timeMs < 100.0) } func testLockForStruct() { struct TestLocker { } let testLocker = TestLocker(); lockHelper(locker: testLocker) } func testLockForInt() { let testLocker = 10; lockHelper(locker: testLocker) } func testLockForArray() { let testLocker = [10, 20]; lockHelper(locker: testLocker) } func testLock() { lockHelper(locker: self) } func lockHelper(locker: Any) { let taskAExpectation = XCTestExpectation(description: "TaskA") let taskBExpectation = XCTestExpectation(description: "TaskB") var countA = 0 var countB = 0 DispatchQueue.global(qos: .userInitiated).async { DispatchQueue.lock(locker) { let isMain = countA == 0 && countB == 0 for _ in 1...10 { countA += 1 if isMain { XCTAssertTrue(countB == 0) } else { XCTAssertTrue(countB == 10) } } } taskAExpectation.fulfill() } DispatchQueue.global(qos: .userInitiated).async { DispatchQueue.lock(locker) { let isMain = countA == 0 && countB == 0 for _ in 1...10 { countB += 1 if isMain { XCTAssertTrue(countA == 0) } else { XCTAssertTrue(countA == 10) } } taskAExpectation.fulfill() } taskBExpectation.fulfill() } wait(for: [taskAExpectation, taskBExpectation], timeout: 1.0) } //static var allTests = [ // ("testExample", testExample), //] }
26.556818
106
0.459564
01efac82b88151710f58ffa97fc0d39b1f71bb72
493
// // ViewController.swift // YBIMSDK_IOS // // Created by 宋明 on 02/07/2020. // Copyright (c) 2020 宋明. 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.72
80
0.663286
1a4b28b461747635c2cbff490c9549964d3f47bf
4,625
// // AppDelegate.swift // Prime Number Checker iOS10 // // Created by Carlyn Maw on 8/24/16. // Copyright © 2016 carlynorama. All rights reserved. // import UIKit import CoreData @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:. // 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: "Prime_Number_Checker_iOS10") 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)") } } } }
49.202128
285
0.688865
bf52bf4ce49ee13872443ccce6a5e6f1373edcbd
748
import XCTest import JVBadgeView class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.793103
111
0.601604
d702f79baf0cbe310389e0ea15361dcbe309ac08
1,075
// // ThreadSafeObject.swift // MyFoundationExtensions // // Created by Andrew Krotov on 20.02.2020. // Copyright © 2020 Andrew Krotov. All rights reserved. // import Foundation @propertyWrapper public class ThreadSafeObject<ObjectType> { // MARK: - Public properties public var wrappedValue: ObjectType { get { var result = defaultValue isolationQueue.sync { result = value } return result } set { isolationQueue.async(flags: .barrier) { [weak self] in self?.value = newValue } } } // MARK: - Private properties private let isolationQueue: DispatchQueue private let defaultValue: ObjectType private var value: ObjectType // MARK: - Initialization public init(queueName: String, defaultValue: ObjectType) { isolationQueue = DispatchQueue(label: queueName, attributes: .concurrent) self.defaultValue = defaultValue value = defaultValue } }
23.888889
81
0.60186
089805342989d8e21a34c017dd815f698549d2e3
2,323
// // Totals.swift // VendRegisterExtension // // Created by Vend on 05/08/2017. // Copyright (c) 2017 Vend. All rights reserved. // import Foundation /// The totals for the sale public struct Totals : Codable { /// The tax on the sale public var tax: NSDecimalNumber /// The total price on the sale public var price: NSDecimalNumber /// The amount of the sale that has already been paid public var paid: NSDecimalNumber /// The remaining amount on the sale to be paid public var toPay: NSDecimalNumber public init(tax: NSDecimalNumber, price: NSDecimalNumber, paid: NSDecimalNumber, toPay: NSDecimalNumber) { self.tax = tax self.price = price self.paid = paid self.toPay = toPay } enum CodingKeys: CodingKey { case tax case price case paid case toPay } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let taxString = try container.decode(String.self, forKey: CodingKeys.tax) tax = NSDecimalNumber(string: taxString) let priceString = try container.decode(String.self, forKey: CodingKeys.price) price = NSDecimalNumber(string: priceString) let paidString = try container.decode(String.self, forKey: CodingKeys.paid) paid = NSDecimalNumber(string: paidString) let toPayString = try container.decode(String.self, forKey: CodingKeys.toPay) toPay = NSDecimalNumber(string: toPayString) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) let numberFormatter = NumberFormatter() numberFormatter.maximumIntegerDigits = 5 numberFormatter.generatesDecimalNumbers = true numberFormatter.numberStyle = .decimal try container.encode(numberFormatter.string(from: tax), forKey: CodingKeys.tax) try container.encode(numberFormatter.string(from: price), forKey: CodingKeys.price) try container.encode(numberFormatter.string(from: paid), forKey: CodingKeys.paid) try container.encode(numberFormatter.string(from: toPay), forKey: CodingKeys.toPay) } }
32.71831
110
0.664227
91b7dddde48b750a681088327a2e29ea7c61cc15
3,448
// This file was automatically generated and should not be edited. import Apollo public final class UserInfoQuery: GraphQLQuery { public let operationDefinition = "query UserInfo {\n me {\n __typename\n id\n name\n email\n path\n resourceUrl\n }\n}" public init() { } public struct Data: GraphQLSelectionSet { public static let possibleTypes = ["Query"] public static let selections: [GraphQLSelection] = [ GraphQLField("me", type: .object(Me.selections)), ] public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(me: Me? = nil) { self.init(unsafeResultMap: ["__typename": "Query", "me": me.flatMap { (value: Me) -> ResultMap in value.resultMap }]) } /// The currently authenticated user public var me: Me? { get { return (resultMap["me"] as? ResultMap).flatMap { Me(unsafeResultMap: $0) } } set { resultMap.updateValue(newValue?.resultMap, forKey: "me") } } public struct Me: GraphQLSelectionSet { public static let possibleTypes = ["User"] public static let selections: [GraphQLSelection] = [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("name", type: .scalar(String.self)), GraphQLField("email", type: .scalar(String.self)), GraphQLField("path", type: .nonNull(.scalar(String.self))), GraphQLField("resourceUrl", type: .nonNull(.scalar(String.self))), ] public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, name: String? = nil, email: String? = nil, path: String, resourceUrl: String) { self.init(unsafeResultMap: ["__typename": "User", "id": id, "name": name, "email": email, "path": path, "resourceUrl": resourceUrl]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } /// The ID of an object public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } /// The user's profile name public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } /// The user's profile email public var email: String? { get { return resultMap["email"] as? String } set { resultMap.updateValue(newValue, forKey: "email") } } /// The Http URL for the user public var path: String { get { return resultMap["path"]! as! String } set { resultMap.updateValue(newValue, forKey: "path") } } /// The Http URL for the user public var resourceUrl: String { get { return resultMap["resourceUrl"]! as! String } set { resultMap.updateValue(newValue, forKey: "resourceUrl") } } } } }
28.495868
140
0.578886
6285397cdc899fee96284d6584bee0e13eda50ce
7,486
// // AppDelegate.swift // Flicks // // Created by Christopher Yang on 1/18/16. // Copyright © 2016 Christopher Yang. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController nowPlayingViewController.endpoint = "now_playing" nowPlayingNavigationController.tabBarItem.title = "Now Playing" nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playing") let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController topRatedViewController.endpoint = "top_rated" topRatedNavigationController.tabBarItem.title = "Top Rated" topRatedNavigationController.tabBarItem.image = UIImage(named: "top_rated") let tabBarController = UITabBarController() tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController] window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.Flicks" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Flicks", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() 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 NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
54.246377
291
0.724552
56f5edecca6ffc4ab432b73137bf8b5922c7137d
2,758
// // SceneDelegate.swift // H4X0R News // // Created by Angela Yu on 08/09/2019. // Copyright © 2019 Angela Yu. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
42.430769
147
0.705221
ffe0eb22ef435f7dfd0342a0bf931178b2b77729
3,599
import XCTest import Cuckoo @testable import WalletKit class PFromWitnessExtractorTests: XCTestCase { private var scriptConverter: MockScriptConverter! private var extractor: ScriptExtractor! private var data: Data! private var redeemScriptData: Data! private var mockDataLastChunk: MockChunk! private var mockScript: MockScript! private var mockRedeemScript: MockScript! override func setUp() { super.setUp() data = Data(hex: "020000")! redeemScriptData = Data() mockDataLastChunk = MockChunk(scriptData: data, index: 0) mockScript = MockScript(with: Data(), chunks: []) stub(mockScript) { mock in when(mock.length.get).thenReturn(1) when(mock.chunks.get).thenReturn([mockDataLastChunk]) } mockRedeemScript = MockScript(with: Data(), chunks: []) scriptConverter = MockScriptConverter() stub(scriptConverter) { mock in when(mock.decode(data: any())).thenReturn(mockRedeemScript) } extractor = PFromWitnessExtractor() } override func tearDown() { data = nil redeemScriptData = nil mockDataLastChunk = nil mockRedeemScript = nil mockScript = nil scriptConverter = nil extractor = nil super.tearDown() } func testValidExtract() { stub(mockDataLastChunk) { mock in when(mock.data.get).thenReturn(redeemScriptData) } stub(mockRedeemScript) { mock in when(mock.length.get).thenReturn(0) when(mock.validate(opCodes: any())).thenDoNothing() when(mock.chunks.get).thenReturn([Chunk(scriptData: Data([0x00]), index: 0), Chunk(scriptData: Data([0x00]), index: 0, payloadRange: 0..<0)]) } do { let test = try extractor.extract(from: mockScript, converter: scriptConverter) XCTAssertEqual(test, redeemScriptData) } catch let error { XCTFail("\(error) Exception Thrown") } } func testWrongScriptLength() { stub(mockScript) { mock in when(mock.length.get).thenReturn(20) } do { let _ = try extractor.extract(from: mockScript, converter: scriptConverter) XCTFail("No Error found!") } catch let error as ScriptError { XCTAssertEqual(error, ScriptError.wrongScriptLength) } catch { XCTFail("\(error) Exception Thrown") } } func testWrongSequence() { stub(mockDataLastChunk) { mock in when(mock.data.get).thenReturn(nil) } do { let _ = try extractor.extract(from: mockScript, converter: scriptConverter) XCTFail("No Error found!") } catch let error as ScriptError { XCTAssertEqual(error, ScriptError.wrongSequence) } catch { XCTFail("\(error) Exception Thrown") } } func testWrongSequenceTwoChunks() { stub(mockDataLastChunk) { mock in when(mock.data.get).thenReturn(redeemScriptData) } stub(mockScript) { mock in when(mock.chunks.get).thenReturn([mockDataLastChunk, mockDataLastChunk]) } do { let _ = try extractor.extract(from: mockScript, converter: scriptConverter) XCTFail("No Error found!") } catch let error as ScriptError { XCTAssertEqual(error, ScriptError.wrongSequence) } catch { XCTFail("\(error) Exception Thrown") } } }
30.5
153
0.603223
ed0df39b7331c62dba89b30658f5d6779b5b07a8
7,093
// // VideoUtil.swift // SwiftFFmpeg // // Created by sunlubo on 2018/8/2. // import CFFmpeg // MARK: - AVPictureType public enum AVPictureType: UInt32 { /// Undefined case none = 0 /// Intra case I /// Predicted case P /// Bi-dir predicted case B /// S(GMC)-VOP MPEG-4 case S /// Switching Intra case SI /// Switching Predicted case SP /// BI type case BI internal var native: CFFmpeg.AVPictureType { CFFmpeg.AVPictureType(rawValue) } internal init(native: CFFmpeg.AVPictureType) { guard let type = AVPictureType(rawValue: native.rawValue) else { fatalError("Unknown picture type: \(native)") } self = type } } // MARK: - AVPictureType + CustomStringConvertible extension AVPictureType: CustomStringConvertible { public var description: String { let char = av_get_picture_type_char(native) let scalar = Unicode.Scalar(Int(char))! return String(Character(scalar)) } } public typealias AVComponentDescriptor = CFFmpeg.AVComponentDescriptor public struct AVPixelFormatDescriptor { let cDescriptorPtr: UnsafePointer<AVPixFmtDescriptor> var cDescriptor: AVPixFmtDescriptor { return cDescriptorPtr.pointee } init(cDescriptorPtr: UnsafePointer<AVPixFmtDescriptor>) { self.cDescriptorPtr = cDescriptorPtr } /// The name of the pixel format descriptor. public var name: String { String(cString: cDescriptor.name) ?? "unknown" } /// The number of components each pixel has, (1-4) public var numberOfComponents: Int { Int(cDescriptor.nb_components) } /// Amount to shift the luma width right to find the chroma width. /// For YV12 this is 1 for example. /// chroma_width = AV_CEIL_RSHIFT(luma_width, log2_chroma_w) /// The note above is needed to ensure rounding up. /// This value only refers to the chroma components. public var log2ChromaW: Int { Int(cDescriptor.log2_chroma_w) } /// Amount to shift the luma height right to find the chroma height. /// For YV12 this is 1 for example. /// chroma_height= AV_CEIL_RSHIFT(luma_height, log2_chroma_h) /// The note above is needed to ensure rounding up. /// This value only refers to the chroma components. public var log2ChromaH: Int { Int(cDescriptor.log2_chroma_h) } /// Parameters that describe how pixels are packed. /// If the format has 1 or 2 components, then luma is 0. /// If the format has 3 or 4 components: /// if the RGB flag is set then 0 is red, 1 is green and 2 is blue; /// otherwise 0 is luma, 1 is chroma-U and 2 is chroma-V. /// /// If present, the Alpha channel is always the last component. public var componentDescriptors: [SwiftFFmpeg.AVComponentDescriptor] { [cDescriptor.comp.0, cDescriptor.comp.1, cDescriptor.comp.2, cDescriptor.comp.3] } /// A wrapper around the C property for flags, containing AV_PIX_FMT_FLAG constants in a option set. public var flags: AVPixelFormatFlags { AVPixelFormatFlags(rawValue: cDescriptor.flags) } /// Alternative comma-separated names. public var alias: String? { String(cString: cDescriptor.alias) } /// Return the number of bits per pixel used by the pixel format /// described by pixdesc. Note that this is not the same as the number /// of bits per sample. /// The returned number of bits refers to the number of bits actually /// used for storing the pixel information, that is padding bits are /// not counted. public var bitsPerPixel: Int { Int(av_get_bits_per_pixel(cDescriptorPtr)) } /// Return the number of bits per pixel for the pixel format described by pixdesc, including any padding or unused bits. public var bitsPerPixelPadded: Int { Int(av_get_padded_bits_per_pixel(cDescriptorPtr)) } /// @return an AVPixelFormat id described by desc, or AV_PIX_FMT_NONE if desc /// is not a valid pointer to a pixel format descriptor. public var id: AVPixelFormat { av_pix_fmt_desc_get_id(cDescriptorPtr) } } public struct AVPixelFormatFlags: OptionSet { public let rawValue: UInt64 public init(rawValue: UInt64) { self.rawValue = rawValue } /// Pixel format is big-endian. public static let BE = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_BE)) /// Pixel format has a palette in data[1], values are indexes in this palette. public static let PAL = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_PAL)) /// All values of a component are bit-wise packed end to end. public static let BITSTREAM = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_BITSTREAM)) /// Pixel format is an HW accelerated format. public static let HWACCEL = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_HWACCEL)) /// At least one pixel component is not in the first data plane. public static let PLANAR = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_PLANAR)) /// The pixel format contains RGB-like data (as opposed to YUV/grayscale). public static let RGB = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_RGB)) /// The pixel format is "pseudo-paletted". This means that it contains a /// fixed palette in the 2nd plane but the palette is fixed/constant for each /// PIX_FMT. This allows interpreting the data as if it was PAL8, which can /// in some cases be simpler. Or the data can be interpreted purely based on /// the pixel format without using the palette. /// An example of a pseudo-paletted format is AV_PIX_FMT_GRAY8 /// @deprecated This flag is deprecated, and will be removed. When it is removed, /// the extra palette allocation in AVFrame.data[1] is removed as well. Only /// actual paletted formats (as indicated by AV_PIX_FMT_FLAG_PAL) will have a /// palette. Starting with FFmpeg versions which have this flag deprecated, the /// extra "pseudo" palette is already ignored, and API users are not required to /// allocate a palette for AV_PIX_FMT_FLAG_PSEUDOPAL formats (it was required /// before the deprecation, though). public static let PSEUDOPAL = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_PSEUDOPAL)) /// The pixel format has an alpha channel. This is set on all formats that /// support alpha in some way, including AV_PIX_FMT_PAL8. The alpha is always /// straight, never pre-multiplied. /// If a codec or a filter does not support alpha, it should set all alpha to /// opaque, or use the equivalent pixel formats without alpha component, e.g. /// AV_PIX_FMT_RGB0 (or AV_PIX_FMT_RGB24 etc.) instead of AV_PIX_FMT_RGBA. public static let ALPHA = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_ALPHA)) /// The pixel format is following a Bayer pattern public static let BAYER = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_BAYER)) /// The pixel format contains IEEE-754 floating point values. Precision (double, /// single, or half) should be determined by the pixel size (64, 32, or 16 bits). public static let FLOAT = AVPixelFormatFlags(rawValue: UInt64(AV_PIX_FMT_FLAG_FLOAT)) } extension AVPixelFormat: CustomStringConvertible { public var description: String { name } }
36.188776
122
0.734245
f7171ba6978e7d4dd5b010377f40e368b2700f20
1,613
//// //// AuthRouter.swift //// client //// //// Created by Anurag Agnihotri on 1/23/16. //// Copyright © 2016 LocusIdeas. All rights reserved. //// import Foundation import Alamofire /** This Enum is used for handling all the Auth Parameters. - EmailSignIn: This case is when the user is signing in using EmailId and Password */ enum AuthRouter: BaseRouterProtocol { case EmailSignIn(EmailSignInAuthRequestBody) case EmailSignUp(EmailSignUpAuthRequestBody) case FacebookAuth(FacebookAuthRequestBody) var path: String { switch self { case .EmailSignIn: return "/api/users/login" case .EmailSignUp: return "/api/users/register" case .FacebookAuth: return "/api/users/auth" } } var method: Alamofire.Method { switch self { case .EmailSignIn: return .POST case .EmailSignUp: return .POST case .FacebookAuth: return .POST } } var parameters: AnyObject? { switch self { default: return nil } } var body: BaseRequestBody? { switch self { case .EmailSignIn(let requestBody): return requestBody case .EmailSignUp(let requestBody): return requestBody case .FacebookAuth(let requestBody): return requestBody } } }
20.679487
83
0.523249
d9d3f8bb1d3588414ecdcfd8cec2a758121b8133
8,681
import Foundation import SourceKittenFramework public struct ForceUnwrappingRule: OptInRule, ConfigurationProviderRule, AutomaticTestableRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "force_unwrapping", name: "Force Unwrapping", description: "Force unwrapping should be avoided.", kind: .idiomatic, nonTriggeringExamples: [ Example("if let url = NSURL(string: query)"), Example("navigationController?.pushViewController(viewController, animated: true)"), Example("let s as! Test"), Example("try! canThrowErrors()"), Example("let object: Any!"), Example("@IBOutlet var constraints: [NSLayoutConstraint]!"), Example("setEditing(!editing, animated: true)"), Example("navigationController.setNavigationBarHidden(!navigationController." + "navigationBarHidden, animated: true)"), Example("if addedToPlaylist && (!self.selectedFilters.isEmpty || " + "self.searchBar?.text?.isEmpty == false) {}"), Example("print(\"\\(xVar)!\")"), Example("var test = (!bar)"), Example("var a: [Int]!"), Example("private var myProperty: (Void -> Void)!"), Example("func foo(_ options: [AnyHashable: Any]!) {"), Example("func foo() -> [Int]!"), Example("func foo() -> [AnyHashable: Any]!"), Example("func foo() -> [Int]! { return [] }"), Example("return self") ], triggeringExamples: [ Example("let url = NSURL(string: query)↓!"), Example("navigationController↓!.pushViewController(viewController, animated: true)"), Example("let unwrapped = optional↓!"), Example("return cell↓!"), Example("let url = NSURL(string: \"http://www.google.com\")↓!"), Example("let dict = [\"Boooo\": \"👻\"]func bla() -> String { return dict[\"Boooo\"]↓! }"), Example("let dict = [\"Boooo\": \"👻\"]func bla() -> String { return dict[\"Boooo\"]↓!.contains(\"B\") }"), Example("let a = dict[\"abc\"]↓!.contains(\"B\")"), Example("dict[\"abc\"]↓!.bar(\"B\")"), Example("if dict[\"a\"]↓!!!! {"), Example("var foo: [Bool]! = dict[\"abc\"]↓!"), Example(""" context("abc") { var foo: [Bool]! = dict["abc"]↓! } """), Example("open var computed: String { return foo.bar↓! }"), Example("return self↓!") ] ) public func validate(file: SwiftLintFile) -> [StyleViolation] { return violationRanges(in: file).map { StyleViolation(ruleDescription: Self.description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } // capture previous of "!" // http://userguide.icu-project.org/strings/regexp private static let pattern = "([^\\s\\p{Ps}])(!+)" // Match any variable declaration // Has a small bug in @IBOutlet due suffix "let" // But that does not compromise the filtering for var declarations private static let varDeclarationPattern = "\\s?(?:let|var)\\s+[^=\\v{]*!" private static let functionReturnPattern = "\\)\\s*->\\s*[^\\n\\{=]*!" private static let regularExpression = regex(pattern) private static let varDeclarationRegularExpression = regex(varDeclarationPattern) private static let excludingSyntaxKindsForFirstCapture = SyntaxKind.commentAndStringKinds.union([.keyword, .typeidentifier]) private static let excludingSyntaxKindsForSecondCapture = SyntaxKind.commentAndStringKinds private func violationRanges(in file: SwiftLintFile) -> [NSRange] { let syntaxMap = file.syntaxMap let varDeclarationRanges = Self.varDeclarationRegularExpression .matches(in: file) .compactMap { match -> NSRange? in return match.range } let functionDeclarationRanges = regex(Self.functionReturnPattern) .matches(in: file) .compactMap { match -> NSRange? in return match.range } return Self.regularExpression .matches(in: file) .compactMap { match -> NSRange? in if match.range.intersects(varDeclarationRanges) || match.range.intersects(functionDeclarationRanges) { return nil } return violationRange(match: match, syntaxMap: syntaxMap, file: file) } } private func violationRange(match: NSTextCheckingResult, syntaxMap: SwiftLintSyntaxMap, file: SwiftLintFile) -> NSRange? { if match.numberOfRanges < 3 { return nil } let firstRange = match.range(at: 1) let secondRange = match.range(at: 2) guard let matchByteFirstRange = file.stringView .NSRangeToByteRange(start: firstRange.location, length: firstRange.length), let matchByteSecondRange = file.stringView .NSRangeToByteRange(start: secondRange.location, length: secondRange.length) else { return nil } // check first captured range // If not empty, first captured range is comment, string, typeidentifier or keyword that is not `self`. // We checks "not empty" because kinds may empty without filtering. guard !isFirstRangeExcludedToken(byteRange: matchByteFirstRange, syntaxMap: syntaxMap, file: file) else { return nil } let violationRange = NSRange(location: NSMaxRange(firstRange), length: 0) let kindsInFirstRange = syntaxMap.kinds(inByteRange: matchByteFirstRange) // if first captured range is identifier or keyword (self), generate violation if !Set(kindsInFirstRange).isDisjoint(with: [.identifier, .keyword]) { return violationRange } // check if firstCapturedString is either ")" or "]" // and '!' is not within comment or string // and matchByteFirstRange is not a type annotation let firstCapturedString = file.stringView.substring(with: firstRange) if [")", "]"].contains(firstCapturedString) { // check second capture '!' let kindsInSecondRange = syntaxMap.kinds(inByteRange: matchByteSecondRange) let forceUnwrapNotInCommentOrString = !kindsInSecondRange .contains(where: Self.excludingSyntaxKindsForSecondCapture.contains) if forceUnwrapNotInCommentOrString && !isTypeAnnotation(in: file, byteRange: matchByteFirstRange) { return violationRange } } return nil } // check if first captured range is comment, string, typeidentifier, or a keyword that is not `self`. private func isFirstRangeExcludedToken(byteRange: ByteRange, syntaxMap: SwiftLintSyntaxMap, file: SwiftLintFile) -> Bool { let tokens = syntaxMap.tokens(inByteRange: byteRange) return tokens.contains { token in guard let kind = token.kind, Self.excludingSyntaxKindsForFirstCapture.contains(kind) else { return false } // check for `self guard kind == .keyword else { return true } return file.contents(for: token) != "self" } } // check deepest kind matching range in structure is a typeAnnotation private func isTypeAnnotation(in file: SwiftLintFile, byteRange: ByteRange) -> Bool { let kinds = file.structureDictionary.kinds(forByteOffset: byteRange.location) guard let lastItem = kinds.last, let lastKind = SwiftDeclarationKind(rawValue: lastItem.kind), SwiftDeclarationKind.variableKinds.contains(lastKind) else { return false } // range is in some "source.lang.swift.decl.var.*" let varRange = ByteRange(location: lastItem.byteRange.location, length: byteRange.location - lastItem.byteRange.location) if let varDeclarationString = file.stringView.substringWithByteRange(varRange), varDeclarationString.contains("=") { // if declarations contains "=", range is not type annotation return false } // range is type annotation of declaration return true } }
45.689474
118
0.605345
fe16830161af19d8508c01d97f9ac6a637a9744f
968
// // FavoriteListWorker.swift // WeatherForecast // // Created by MacOS on 7.03.2022. // import UIKit import Realm import RealmSwift protocol FavoriteListWorkingLogic: AnyObject { func fetchFavoriteList() -> Results<CityListResponse> func deleteAllFromDatabase() func deleteFromDb(city: CityListResponse) } final class FavoriteListWorker: FavoriteListWorkingLogic { private var database:Realm static let sharedInstance = FavoriteListWorker() private init() { database = try! Realm() } func fetchFavoriteList() -> Results<CityListResponse> { let object = database.objects(CityListResponse.self) return object; } func deleteAllFromDatabase() { try! database.write { database.deleteAll() } } func deleteFromDb(city: CityListResponse) { try! database.write { database.delete(city) } } }
18.615385
60
0.636364
46f3c3cbea7a9247ad54b735ca332074902ba1fe
1,688
// // PlayerViewMusicList.swift // ACHNBrowserUI // // Created by Thomas Ricouard on 28/06/2020. // Copyright © 2020 Thomas Ricouard. All rights reserved. // import SwiftUI import Backend import UI struct PlayerViewMusicList: View { @EnvironmentObject private var playerManager: MusicPlayerManager @EnvironmentObject private var items: Items @Binding var playerMode: PlayerMode var namespace: Namespace.ID var body: some View { VStack { PlayerViewSmall(playerMode: $playerMode, namespace: namespace) Spacer() List { ForEach(items.categories[.music] ?? []) { item in Button(action: { if let song = playerManager.matchSongFrom(item: item) { playerManager.currentSong = song playerManager.isPlaying = true withAnimation(.spring(response: 0.5, dampingFraction: 0.75, blendDuration: 0)) { playerMode = .playerExpanded } } }) { HStack { ItemImage(path: item.finalImage, size: 50) Text(item.localizedName) .foregroundColor(.white) } } }.listRowBackground(Color.acTabBarTint) } .animation(.interactiveSpring()) .transition(.scale) }.padding() } }
33.098039
79
0.472749
f755f78c9aea332af97dc393895a642f7342c537
23,925
//===----------------------------------------------------------------------===// // // 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 Braket { // MARK: Enums public enum CancellationStatus: String, CustomStringConvertible, Codable { case cancelled = "CANCELLED" case cancelling = "CANCELLING" public var description: String { return self.rawValue } } public enum DeviceStatus: String, CustomStringConvertible, Codable { case offline = "OFFLINE" case online = "ONLINE" public var description: String { return self.rawValue } } public enum DeviceType: String, CustomStringConvertible, Codable { case qpu = "QPU" case simulator = "SIMULATOR" public var description: String { return self.rawValue } } public enum QuantumTaskStatus: String, CustomStringConvertible, Codable { case cancelled = "CANCELLED" case cancelling = "CANCELLING" case completed = "COMPLETED" case created = "CREATED" case failed = "FAILED" case queued = "QUEUED" case running = "RUNNING" public var description: String { return self.rawValue } } public enum SearchQuantumTasksFilterOperator: String, CustomStringConvertible, Codable { case between = "BETWEEN" case equal = "EQUAL" case gt = "GT" case gte = "GTE" case lt = "LT" case lte = "LTE" public var description: String { return self.rawValue } } // MARK: Shapes public struct CancelQuantumTaskRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "quantumTaskArn", location: .uri(locationName: "quantumTaskArn")) ] /// The client token associated with the request. public let clientToken: String /// The ARN of the task to cancel. public let quantumTaskArn: String public init(clientToken: String = CancelQuantumTaskRequest.idempotencyToken(), quantumTaskArn: String) { self.clientToken = clientToken self.quantumTaskArn = quantumTaskArn } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 64) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.quantumTaskArn, name: "quantumTaskArn", parent: name, max: 256) try self.validate(self.quantumTaskArn, name: "quantumTaskArn", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case clientToken } } public struct CancelQuantumTaskResponse: AWSDecodableShape { /// The status of the cancellation request. public let cancellationStatus: CancellationStatus /// The ARN of the task. public let quantumTaskArn: String public init(cancellationStatus: CancellationStatus, quantumTaskArn: String) { self.cancellationStatus = cancellationStatus self.quantumTaskArn = quantumTaskArn } private enum CodingKeys: String, CodingKey { case cancellationStatus case quantumTaskArn } } public struct CreateQuantumTaskRequest: AWSEncodableShape { /// The action associated with the task. public let action: String /// The client token associated with the request. public let clientToken: String /// The ARN of the device to run the task on. public let deviceArn: String /// The parameters for the device to run the task on. public let deviceParameters: String? /// The S3 bucket to store task result files in. public let outputS3Bucket: String /// The key prefix for the location in the S3 bucket to store task results in. public let outputS3KeyPrefix: String /// The number of shots to use for the task. public let shots: Int64 /// Tags to be added to the quantum task you're creating. public let tags: [String: String]? public init(action: String, clientToken: String = CreateQuantumTaskRequest.idempotencyToken(), deviceArn: String, deviceParameters: String? = nil, outputS3Bucket: String, outputS3KeyPrefix: String, shots: Int64, tags: [String: String]? = nil) { self.action = action self.clientToken = clientToken self.deviceArn = deviceArn self.deviceParameters = deviceParameters self.outputS3Bucket = outputS3Bucket self.outputS3KeyPrefix = outputS3KeyPrefix self.shots = shots self.tags = tags } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 64) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.deviceArn, name: "deviceArn", parent: name, max: 256) try self.validate(self.deviceArn, name: "deviceArn", parent: name, min: 1) try self.validate(self.deviceParameters, name: "deviceParameters", parent: name, max: 2048) try self.validate(self.deviceParameters, name: "deviceParameters", parent: name, min: 1) try self.validate(self.outputS3Bucket, name: "outputS3Bucket", parent: name, max: 63) try self.validate(self.outputS3Bucket, name: "outputS3Bucket", parent: name, min: 3) try self.validate(self.outputS3KeyPrefix, name: "outputS3KeyPrefix", parent: name, max: 1024) try self.validate(self.outputS3KeyPrefix, name: "outputS3KeyPrefix", parent: name, min: 1) try self.validate(self.shots, name: "shots", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case action case clientToken case deviceArn case deviceParameters case outputS3Bucket case outputS3KeyPrefix case shots case tags } } public struct CreateQuantumTaskResponse: AWSDecodableShape { /// The ARN of the task created by the request. public let quantumTaskArn: String public init(quantumTaskArn: String) { self.quantumTaskArn = quantumTaskArn } private enum CodingKeys: String, CodingKey { case quantumTaskArn } } public struct DeviceSummary: AWSDecodableShape { /// The ARN of the device. public let deviceArn: String /// The name of the device. public let deviceName: String /// The status of the device. public let deviceStatus: DeviceStatus /// The type of the device. public let deviceType: DeviceType /// The provider of the device. public let providerName: String public init(deviceArn: String, deviceName: String, deviceStatus: DeviceStatus, deviceType: DeviceType, providerName: String) { self.deviceArn = deviceArn self.deviceName = deviceName self.deviceStatus = deviceStatus self.deviceType = deviceType self.providerName = providerName } private enum CodingKeys: String, CodingKey { case deviceArn case deviceName case deviceStatus case deviceType case providerName } } public struct GetDeviceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "deviceArn", location: .uri(locationName: "deviceArn")) ] /// The ARN of the device to retrieve. public let deviceArn: String public init(deviceArn: String) { self.deviceArn = deviceArn } public func validate(name: String) throws { try self.validate(self.deviceArn, name: "deviceArn", parent: name, max: 256) try self.validate(self.deviceArn, name: "deviceArn", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct GetDeviceResponse: AWSDecodableShape { /// The ARN of the device. public let deviceArn: String /// Details about the capabilities of the device. public let deviceCapabilities: String /// The name of the device. public let deviceName: String /// The status of the device. public let deviceStatus: DeviceStatus /// The type of the device. public let deviceType: DeviceType /// The name of the partner company for the device. public let providerName: String public init(deviceArn: String, deviceCapabilities: String, deviceName: String, deviceStatus: DeviceStatus, deviceType: DeviceType, providerName: String) { self.deviceArn = deviceArn self.deviceCapabilities = deviceCapabilities self.deviceName = deviceName self.deviceStatus = deviceStatus self.deviceType = deviceType self.providerName = providerName } private enum CodingKeys: String, CodingKey { case deviceArn case deviceCapabilities case deviceName case deviceStatus case deviceType case providerName } } public struct GetQuantumTaskRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "quantumTaskArn", location: .uri(locationName: "quantumTaskArn")) ] /// the ARN of the task to retrieve. public let quantumTaskArn: String public init(quantumTaskArn: String) { self.quantumTaskArn = quantumTaskArn } public func validate(name: String) throws { try self.validate(self.quantumTaskArn, name: "quantumTaskArn", parent: name, max: 256) try self.validate(self.quantumTaskArn, name: "quantumTaskArn", parent: name, min: 1) } private enum CodingKeys: CodingKey {} } public struct GetQuantumTaskResponse: AWSDecodableShape { /// The time at which the task was created. @CustomCoding<ISO8601DateCoder> public var createdAt: Date /// The ARN of the device the task was run on. public let deviceArn: String /// The parameters for the device on which the task ran. public let deviceParameters: String /// The time at which the task ended. @OptionalCustomCoding<ISO8601DateCoder> public var endedAt: Date? /// The reason that a task failed. public let failureReason: String? /// The S3 bucket where task results are stored. public let outputS3Bucket: String /// The folder in the S3 bucket where task results are stored. public let outputS3Directory: String /// The ARN of the task. public let quantumTaskArn: String /// The number of shots used in the task. public let shots: Int64 /// The status of the task. public let status: QuantumTaskStatus /// The tags that belong to this task. public let tags: [String: String]? public init(createdAt: Date, deviceArn: String, deviceParameters: String, endedAt: Date? = nil, failureReason: String? = nil, outputS3Bucket: String, outputS3Directory: String, quantumTaskArn: String, shots: Int64, status: QuantumTaskStatus, tags: [String: String]? = nil) { self.createdAt = createdAt self.deviceArn = deviceArn self.deviceParameters = deviceParameters self.endedAt = endedAt self.failureReason = failureReason self.outputS3Bucket = outputS3Bucket self.outputS3Directory = outputS3Directory self.quantumTaskArn = quantumTaskArn self.shots = shots self.status = status self.tags = tags } private enum CodingKeys: String, CodingKey { case createdAt case deviceArn case deviceParameters case endedAt case failureReason case outputS3Bucket case outputS3Directory case quantumTaskArn case shots case status case tags } } public struct ListTagsForResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] /// Specify the resourceArn for the resource whose tags to display. public let resourceArn: String public init(resourceArn: String) { self.resourceArn = resourceArn } private enum CodingKeys: CodingKey {} } public struct ListTagsForResourceResponse: AWSDecodableShape { /// Displays the key, value pairs of tags associated with this resource. public let tags: [String: String]? public init(tags: [String: String]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct QuantumTaskSummary: AWSDecodableShape { /// The time at which the task was created. @CustomCoding<ISO8601DateCoder> public var createdAt: Date /// The ARN of the device the task ran on. public let deviceArn: String /// The time at which the task finished. @OptionalCustomCoding<ISO8601DateCoder> public var endedAt: Date? /// The S3 bucket where the task result file is stored.. public let outputS3Bucket: String /// The folder in the S3 bucket where the task result file is stored. public let outputS3Directory: String /// The ARN of the task. public let quantumTaskArn: String /// The shots used for the task. public let shots: Int64 /// The status of the task. public let status: QuantumTaskStatus /// Displays the key, value pairs of tags associated with this quantum task. public let tags: [String: String]? public init(createdAt: Date, deviceArn: String, endedAt: Date? = nil, outputS3Bucket: String, outputS3Directory: String, quantumTaskArn: String, shots: Int64, status: QuantumTaskStatus, tags: [String: String]? = nil) { self.createdAt = createdAt self.deviceArn = deviceArn self.endedAt = endedAt self.outputS3Bucket = outputS3Bucket self.outputS3Directory = outputS3Directory self.quantumTaskArn = quantumTaskArn self.shots = shots self.status = status self.tags = tags } private enum CodingKeys: String, CodingKey { case createdAt case deviceArn case endedAt case outputS3Bucket case outputS3Directory case quantumTaskArn case shots case status case tags } } public struct SearchDevicesFilter: AWSEncodableShape { /// The name to use to filter results. public let name: String /// The values to use to filter results. public let values: [String] public init(name: String, values: [String]) { self.name = name self.values = values } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.values.forEach { try validate($0, name: "values[]", parent: name, max: 256) try validate($0, name: "values[]", parent: name, min: 1) } try self.validate(self.values, name: "values", parent: name, max: 10) try self.validate(self.values, name: "values", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case name case values } } public struct SearchDevicesRequest: AWSEncodableShape { /// The filter values to use to search for a device. public let filters: [SearchDevicesFilter] /// The maximum number of results to return in the response. public let maxResults: Int? /// A token used for pagination of results returned in the response. Use the token returned from the previous request continue results where the previous request ended. public let nextToken: String? public init(filters: [SearchDevicesFilter], maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.filters, name: "filters", parent: name, max: 10) try self.validate(self.filters, name: "filters", parent: name, min: 0) try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case filters case maxResults case nextToken } } public struct SearchDevicesResponse: AWSDecodableShape { /// An array of DeviceSummary objects for devices that match the specified filter values. public let devices: [DeviceSummary] /// A token used for pagination of results, or null if there are no additional results. Use the token value in a subsequent request to continue results where the previous request ended. public let nextToken: String? public init(devices: [DeviceSummary], nextToken: String? = nil) { self.devices = devices self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case devices case nextToken } } public struct SearchQuantumTasksFilter: AWSEncodableShape { /// The name of the device used for the task. public let name: String /// An operator to use in the filter. public let `operator`: SearchQuantumTasksFilterOperator /// The values to use for the filter. public let values: [String] public init(name: String, operator: SearchQuantumTasksFilterOperator, values: [String]) { self.name = name self.`operator` = `operator` self.values = values } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.values.forEach { try validate($0, name: "values[]", parent: name, max: 256) try validate($0, name: "values[]", parent: name, min: 1) } try self.validate(self.values, name: "values", parent: name, max: 10) try self.validate(self.values, name: "values", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case name case `operator` case values } } public struct SearchQuantumTasksRequest: AWSEncodableShape { /// Array of SearchQuantumTasksFilter objects. public let filters: [SearchQuantumTasksFilter] /// Maximum number of results to return in the response. public let maxResults: Int? /// A token used for pagination of results returned in the response. Use the token returned from the previous request continue results where the previous request ended. public let nextToken: String? public init(filters: [SearchQuantumTasksFilter], maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.filters, name: "filters", parent: name, max: 10) try self.validate(self.filters, name: "filters", parent: name, min: 0) try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case filters case maxResults case nextToken } } public struct SearchQuantumTasksResponse: AWSDecodableShape { /// A token used for pagination of results, or null if there are no additional results. Use the token value in a subsequent request to continue results where the previous request ended. public let nextToken: String? /// An array of QuantumTaskSummary objects for tasks that match the specified filters. public let quantumTasks: [QuantumTaskSummary] public init(nextToken: String? = nil, quantumTasks: [QuantumTaskSummary]) { self.nextToken = nextToken self.quantumTasks = quantumTasks } private enum CodingKeys: String, CodingKey { case nextToken case quantumTasks } } public struct TagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")) ] /// Specify the resourceArn of the resource to which a tag will be added. public let resourceArn: String /// Specify the tags to add to the resource. public let tags: [String: String] public init(resourceArn: String, tags: [String: String]) { self.resourceArn = resourceArn self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct TagResourceResponse: AWSDecodableShape { public init() {} } public struct UntagResourceRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resourceArn")), AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys")) ] /// Specify the resourceArn for the resource from which to remove the tags. public let resourceArn: String /// pecify the keys for the tags to remove from the resource. public let tagKeys: [String] public init(resourceArn: String, tagKeys: [String]) { self.resourceArn = resourceArn self.tagKeys = tagKeys } private enum CodingKeys: CodingKey {} } public struct UntagResourceResponse: AWSDecodableShape { public init() {} } }
39.157119
282
0.619979
08d58a40a5c7d6bf791e68f4637fe3ba696537dd
1,015
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "BluetoothDarwin", products: [ .library( name: "BluetoothDarwin", targets: ["BluetoothDarwin"] ) ], dependencies: [ .package( url: "https://github.com/PureSwift/Bluetooth.git", .branch("master") ) ], targets: [ .target( name: "BluetoothDarwin", dependencies: [ .product( name: "Bluetooth", package: "Bluetooth" ), .product( name: "BluetoothHCI", package: "Bluetooth" ), "CBluetoothDarwin" ] ), .target( name: "CBluetoothDarwin" ), .testTarget( name: "BluetoothDarwinTests", dependencies: [ "BluetoothDarwin" ] ) ] )
23.068182
62
0.419704
79f44a5f93260c89f5be67921dbbe5cf41a413d1
2,171
// // AppDelegate.swift // MediaCacheDemo // // Created by SoalHunag on 2019/2/27. // Copyright © 2019 soso. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.191489
285
0.755412
1dfa9922145f7b9909b48a1abaa6b7f48ab80ea1
7,757
// // RouteDetailViewController.swift // TCAT // // Created by Matthew Barker on 2/11/17. // Copyright © 2017 cuappdev. All rights reserved. // import NotificationBannerSwift import UIKit class CustomNavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate { /// Attributed string details for the back button text of a navigation controller static let buttonTitleTextAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.getFont(.regular, size: 14) ] private let additionalWidth: CGFloat = 30 private let additionalHeight: CGFloat = 100 /// Attributed string details for the title text of a navigation controller private let titleTextAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.getFont(.regular, size: 18), .foregroundColor: Colors.black ] private let banner = StatusBarNotificationBanner(title: Constants.Banner.noInternetConnection, style: .danger) private var screenshotObserver: NSObjectProtocol? override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) view.backgroundColor = Colors.white customizeAppearance() ReachabilityManager.shared.addListener(self) { [weak self] connection in guard let self = self else { return } switch connection { case .wifi, .cellular: self.banner.dismiss() case .none: self.banner.show(queuePosition: .front, on: self) self.banner.autoDismiss = false self.banner.isUserInteractionEnabled = false } self.setNeedsStatusBarAppearanceUpdate() } } open override var childForStatusBarStyle: UIViewController? { return visibleViewController } override var preferredStatusBarStyle: UIStatusBarStyle { return banner.isDisplaying ? .lightContent : .default } override func viewDidLoad() { super.viewDidLoad() if responds(to: #selector(getter: interactivePopGestureRecognizer)) { interactivePopGestureRecognizer?.delegate = self delegate = self } // Add screenshot listener, log view controller name let notifName = UIApplication.userDidTakeScreenshotNotification screenshotObserver = NotificationCenter.default.addObserver(forName: notifName, object: nil, queue: .main) { _ in guard let currentViewController = self.visibleViewController else { return } let payload = ScreenshotTakenPayload(location: "\(type(of: currentViewController))") Analytics.shared.log(payload) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let screenshotObserver = screenshotObserver { NotificationCenter.default.removeObserver(screenshotObserver) } } private func customizeAppearance() { navigationBar.backgroundColor = Colors.white navigationBar.barTintColor = Colors.white navigationBar.tintColor = Colors.primaryText navigationBar.titleTextAttributes = titleTextAttributes navigationItem.backBarButtonItem?.setTitleTextAttributes( CustomNavigationController.buttonTitleTextAttributes, for: .normal ) } /// Return an instance of custom back button private func customBackButton() -> UIBarButtonItem { let backButton = UIButton() backButton.setImage(#imageLiteral(resourceName: "back"), for: .normal) backButton.tintColor = Colors.primaryText let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.getFont(.regular, size: 14.0), .foregroundColor: Colors.primaryText, .baselineOffset: 0.3 ] let attributedString = NSMutableAttributedString(string: " " + Constants.Buttons.back, attributes: attributes) backButton.setAttributedTitle(attributedString, for: .normal) backButton.sizeToFit() // Expand frame to create bigger touch area backButton.frame = CGRect(x: backButton.frame.minX, y: backButton.frame.minY, width: backButton.frame.width + additionalWidth, height: backButton.frame.height + additionalHeight) backButton.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: additionalWidth) backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside) return UIBarButtonItem(customView: backButton) } /// Move back one view controller in navigationController stack @objc private func backAction() { _ = popViewController(animated: true) } // MARK: - UINavigationController Functions override func pushViewController(_ viewController: UIViewController, animated: Bool) { if responds(to: #selector(getter: interactivePopGestureRecognizer)) { interactivePopGestureRecognizer?.isEnabled = false } super.pushViewController(viewController, animated: animated) if viewControllers.count > 1 { navigationBar.titleTextAttributes = titleTextAttributes // Add back button for non-modal non-peeked screens if !viewController.isModal { viewController.navigationItem.hidesBackButton = true viewController.navigationItem.setLeftBarButton(customBackButton(), animated: true) } } } override func popViewController(animated: Bool) -> UIViewController? { let viewController = super.popViewController(animated: animated) if let homeMapVC = viewControllers.last as? HomeMapViewController { homeMapVC.navigationItem.leftBarButtonItem = nil } return viewController } override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { super.present(viewControllerToPresent, animated: flag, completion: completion) banner.dismiss() } // MARK: - UINavigationControllerDelegate Functions func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { setNavigationBarHidden(viewController is ParentHomeMapViewController, animated: animated) } func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { interactivePopGestureRecognizer?.isEnabled = (responds(to: #selector(getter: interactivePopGestureRecognizer)) && viewControllers.count > 1) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } } class OnboardingNavigationController: UINavigationController { override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true } open override var childForStatusBarStyle: UIViewController? { return visibleViewController } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // Do NOT remove this initializer; OnboardingNavigationController will crash without it. override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } }
39.375635
186
0.699368
26a52cc61020d68f27ab148f66f26f648ddb9e75
9,452
// // AppDelegate.swift // VBVMI // // Created by Thomas Carey on 31/01/16. // Copyright © 2016 Tom Carey. All rights reserved. // import UIKit import CoreData import AlamofireImage import Fabric import Crashlytics import XCGLogger import Reachability import VimeoNetworking let logger: XCGLogger = { // let logger = XCGLogger.default // logger.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil, fileLevel: .debug) // NSLogger support // only log to the external window // Create a logger object with no destinations let log = XCGLogger(identifier: "versebyverse", includeDefaultDestinations: false) // Create a destination for the system console log (via NSLog) let systemDestination = AppleSystemLogDestination(identifier: "versebyverse.systemDestination") // Optionally set some configuration options systemDestination.outputLevel = .debug systemDestination.showLogIdentifier = false systemDestination.showFunctionName = true systemDestination.showThreadName = true systemDestination.showLevel = true systemDestination.showFileName = true systemDestination.showLineNumber = true systemDestination.showDate = true // Add the destination to the logger log.add(destination: systemDestination) return log }() let VBVMIImageCache = AutoPurgingImageCache() let MainContextChangedNotification = "UpdatedMainContext" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { logger.info("🍕Application will finish with options: \(launchOptions ?? [:])") //Fabric.sharedSDK().debug = true // DDTTYLogger.sharedInstance().colorsEnabled = true // DDLog.addLogger(DDTTYLogger.sharedInstance(), withLevel: .Verbose) //DDLog.addLogger(DDASLLogger.sharedInstance(), withLevel: .Warning) // DDLog.addLogger(CrashlyticsLogger.sharedInstance(), withLevel: .Warning) // let fileLogger: DDFileLogger = DDFileLogger() // File Logger // fileLogger.rollingFrequency = 60*60*24 // 24 hours // fileLogger.logFileManager.maximumNumberOfLogFiles = 7 // DDLog.addLogger(fileLogger) // DDTTYLogger.sharedInstance().setForegroundColor(UIColor(red:0.066667, green:0.662745, blue:0.054902, alpha:1.0), backgroundColor: nil, forFlag: DDLogFlag.Info) URLCache.shared.removeAllCachedResponses() //Move all of the old resources to the Application support directory let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) if let originURL = urls.first { let oldResources = originURL.appendingPathComponent("resources") if fileManager.fileExists(atPath: oldResources.path) { let destinationURL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("resources") if let destinationURL = destinationURL { let _ = try? fileManager.moveItem(at: oldResources, to: destinationURL) } } } let imageDownloader = ImageDownloader(configuration: ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: .fifo, maximumActiveDownloads: 10, imageCache: VBVMIImageCache) UIImageView.af_sharedImageDownloader = imageDownloader logger.info("🍕Creating Context Coordinator") let _ = ContextCoordinator.sharedInstance DispatchQueue.global(qos: .background).async { logger.info("🍕Dispatching the Downloads") APIDataManager.core() APIDataManager.allTheChannels() let reachability = Reachability() if reachability?.connection == .wifi { APIDataManager.allTheArticles() APIDataManager.allTheAnswers() } else { APIDataManager.latestArticles() APIDataManager.latestAnswers() } } return true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. Fabric.with([Crashlytics.self]) logger.info("🍕Application did finish Launching with options: \(launchOptions ?? [:])") Theme.default.applyTheme() logger.info("🍕Creating Sound Manager") let _ = SoundManager.sharedInstance 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. logger.info("🍕Resign Active") } 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. logger.info("🍕Background") } 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. URLCache.shared.removeAllCachedResponses() logger.info("🍕Foreground") } 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. logger.info("🍕Active") } 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. ContextCoordinator.sharedInstance.saveContext() logger.info("🍕Terminated") } func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { application.ignoreSnapshotOnNextApplicationLaunch() return true } func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { return true } func application(_ application: UIApplication, didUpdate userActivity: NSUserActivity) { logger.info("🍕user activity: \(userActivity)") } fileprivate static var _resourcesURL: URL? = nil fileprivate static func addSkipBackupAttributeToItemAtURL(_ filePath:String) -> Bool { let myUrl = URL(fileURLWithPath: filePath) assert(FileManager.default.fileExists(atPath: filePath), "File \(filePath) does not exist") var success: Bool do { try (myUrl as NSURL).setResourceValue(true, forKey:URLResourceKey.isExcludedFromBackupKey) success = true } catch let error as NSError { success = false logger.info("🍕Error excluding \(myUrl.lastPathComponent) from backup \(error)"); } return success } static func resourcesURL() -> URL? { if let url = _resourcesURL { return url } let fileManager = FileManager.default #if os(tvOS) let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) #else let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) #endif if let documentDirectory: URL = urls.first { // This is where the database should be in the application support directory let rootURL = documentDirectory.appendingPathComponent("resources") let path = rootURL.path if !fileManager.fileExists(atPath: path) { do { try fileManager.createDirectory(at: rootURL, withIntermediateDirectories: true, attributes: nil) } catch let error { logger.error("Error creating resources directory: \(error)") return nil } } _resourcesURL = rootURL return rootURL } else { logger.info("🍕Couldn't get documents directory!") } return nil } }
41.638767
285
0.669911
d5f1bd723c39ac25ecdfe13ef0a75fca8e8058fc
3,643
// // AppDelegate.swift // Calculator // // Created by Sara Fryzlewicz on 12/15/20. // import UIKit import CoreData @main 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. } // 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: "Calculator") 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)") } } } }
44.426829
199
0.667582
1d1d91d3cb12426acb2b9b24b9239dfbd93e9ab3
632
// // DateFormatter+CustomFormatter.swift // Git-Connect // // Created by Shubham Bairagi on 27/02/20. // Copyright © 2020 sb. All rights reserved. // import Foundation extension DateFormatter { static private let customDateFormatter = DateFormatter() static func string(from date: Date, format: String) -> String { customDateFormatter.dateFormat = format return customDateFormatter.string(from: date) } static func date(from string: String, format: String) -> Date? { customDateFormatter.dateFormat = format return customDateFormatter.date(from: string) } }
25.28
68
0.683544
6988dcdbd61d190e051f89e064c47ce74e552bcc
2,632
// // SceneDelegate.swift // Drawing // // Created by Nicholas Fox on 1/10/20. // Copyright © 2020 Nicholas Fox. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
40.492308
143
0.739362
08497397f129d76b8638bbb8a2843a7074d49a27
6,090
// // VideoWriterDelegate.swift // Video Recording Example // // Created by Nathan Beaumont on 12/12/19. // Copyright © 2019 Nathan Beaumont. All rights reserved. // import AVFoundation import AVKit import Foundation class VideoWriterDelegate: NSObject { // MARK: Static Properties private static var outputSettings: [String: Any] { return [AVVideoCodecKey : AVVideoCodecType.h264, AVVideoWidthKey : 720, AVVideoHeightKey : 1280, AVVideoCompressionPropertiesKey : [AVVideoAverageBitRateKey : 2300000], ] } // MARK: AV Writing Properties private var audioWriterInput: AVAssetWriterInput private var outputFileLocation: URL? private weak var homeViewController: HomeViewControllerProtocol! private var audioVideoWriter: AVAssetWriter? private var videoWriterInput: AVAssetWriterInput private var sessionAtSourceTime: CMTime // MARK: Computed Properties private var canWrite: Bool { return homeViewController.isRecording && audioVideoWriter != nil && audioVideoWriter?.status == .writing } static private func videoFileLocation() -> URL { let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) guard let documentDirectory: URL = urls.first else { fatalError("Document Error") } let videoOutputUrl = documentDirectory.appendingPathComponent("OutputVideo.mp4") if FileManager.default.fileExists(atPath: videoOutputUrl.path) { do { try FileManager.default.removeItem(atPath: videoOutputUrl.path) } catch { print("Unable to delete file: \(error) : \(#function).") } } return videoOutputUrl } // MARK: Object Lifecycle Methods init(homeViewController: HomeViewControllerProtocol) { self.homeViewController = homeViewController audioWriterInput = AVAssetWriterInput(mediaType: AVMediaType.audio, outputSettings: nil) audioWriterInput.expectsMediaDataInRealTime = true videoWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: VideoWriterDelegate.outputSettings) videoWriterInput.expectsMediaDataInRealTime = true sessionAtSourceTime = CMTime.zero super.init() } private func setUpWriter() { do { let filePath = VideoWriterDelegate.videoFileLocation() outputFileLocation = filePath audioVideoWriter = try AVAssetWriter(outputURL: filePath, fileType: AVFileType.mov) if audioVideoWriter?.canAdd(videoWriterInput) ?? false { audioVideoWriter?.add(videoWriterInput) print("video input added") } if audioVideoWriter?.canAdd(audioWriterInput) ?? false { audioVideoWriter?.add(audioWriterInput) print("audio input added") } audioVideoWriter?.startWriting() } catch let error { debugPrint(error.localizedDescription) } } // MARK: Start recording public func start() { guard !homeViewController.isRecording else { return } homeViewController.isRecording = true setUpWriter() print(homeViewController.isRecording) print(audioVideoWriter ?? "") if audioVideoWriter?.status == .writing { print("status writing") } else if audioVideoWriter?.status == .failed { print("status failed") } else if audioVideoWriter?.status == .cancelled { print("status cancelled") } else if audioVideoWriter?.status == .unknown { print("status unknown") } else { print("status completed") } } // MARK: Stop recording public func stop() { guard self.homeViewController.isRecording else { return } self.homeViewController.isRecording = false self.videoWriterInput.markAsFinished() self.audioWriterInput.markAsFinished() print("marked as finished") self.homeViewController.captureSession.stopRunning() self.audioVideoWriter?.endSession(atSourceTime: self.sessionAtSourceTime) self.audioVideoWriter?.finishWriting { [weak self] in guard let filePath = self?.outputFileLocation?.path else { return } let videoURL = URL(fileURLWithPath: filePath) print("finished writing \(String(describing: videoURL.path))") print(FileManager.default.fileExists(atPath: videoURL.path)) print(String(describing: self?.outputFileLocation!.absoluteString)) let player = AVPlayer(url: videoURL) self?.homeViewController.didFinishRecordingVideo(player: player, videoFilePath: videoURL) } } } // MARK: AVCaptureVideoDataOutputSampleBufferDelegate extension VideoWriterDelegate: AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate { func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { let writable = canWrite if writable { sessionAtSourceTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) audioVideoWriter?.startSession(atSourceTime: sessionAtSourceTime) print("Writing") } if output == homeViewController?.videoDataOutput { connection.videoOrientation = .portrait } if writable, output == homeViewController.videoDataOutput, (videoWriterInput.isReadyForMoreMediaData) { videoWriterInput.append(sampleBuffer) print("video buffering") } else if writable, output == homeViewController.audioDataOutput, (audioWriterInput.isReadyForMoreMediaData) { audioWriterInput.append(sampleBuffer) print("audio buffering") } } }
36.25
129
0.660591
1d89b01a98bdd8239203cfa4dde7f1d3d1405315
3,284
// Copyright (c) 2020-2021 InSeven Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import SwiftUI import BookmarksCore struct BookmarksView: View { enum SheetType { case settings } @Environment(\.manager) var manager: BookmarksManager @ObservedObject var store: Store var tag: String? @State var sheet: SheetType? @State var search = "" var items: [Item] { store.rawItems.filter { (tag == nil || $0.tags.contains(tag!)) && search.isEmpty || $0.title.localizedStandardContains(search) || $0.url.absoluteString.localizedStandardContains(search) || $0.tags.contains(where: { $0.localizedStandardContains(search) } ) } } var body: some View { VStack { HStack { TextField("Search", text: $search) .modifier(SearchBoxModifier(text: $search)) .padding() } ScrollView { LazyVGrid(columns: [GridItem(.adaptive(minimum: 160), spacing: 16)], spacing: 16) { ForEach(items) { item in BookmarkCell(item: item) .onTapGesture { UIApplication.shared.open(item.url) } .contextMenu(ContextMenu(menuItems: { Button("Share") { print("Share") print(item.identifier) } })) } } .padding() } } .sheet(item: $sheet) { sheet in switch sheet { case .settings: NavigationView { SettingsView(settings: manager.settings) } } } .navigationBarItems(leading: Button(action: { sheet = .settings }) { Image(systemName: "gearshape") .foregroundColor(.accentColor) }) } } extension BookmarksView.SheetType: Identifiable { public var id: Self { self } }
34.93617
99
0.559074
087c0fe0d3880692d2f40e2630ae176e9cef99ec
10,382
// File created from ScreenTemplate // $ createScreen.sh Verify KeyVerificationVerifyByScanning /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation enum KeyVerificationVerifyByScanningViewModelError: Error { case unknown } final class KeyVerificationVerifyByScanningViewModel: KeyVerificationVerifyByScanningViewModelType { // MARK: - Properties // MARK: Private private let session: MXSession private let keyVerificationRequest: MXKeyVerificationRequest private let qrCodeDataCoder: MXQRCodeDataCoder private let keyVerificationManager: MXKeyVerificationManager private var qrCodeTransaction: MXQRCodeTransaction? private var scannedQRCodeData: MXQRCodeData? // MARK: Public weak var viewDelegate: KeyVerificationVerifyByScanningViewModelViewDelegate? weak var coordinatorDelegate: KeyVerificationVerifyByScanningViewModelCoordinatorDelegate? // MARK: - Setup init(session: MXSession, keyVerificationRequest: MXKeyVerificationRequest) { self.session = session self.keyVerificationManager = self.session.crypto.keyVerificationManager self.keyVerificationRequest = keyVerificationRequest self.qrCodeDataCoder = MXQRCodeDataCoder() } deinit { self.removePendingQRCodeTransaction() } // MARK: - Public func process(viewAction: KeyVerificationVerifyByScanningViewAction) { switch viewAction { case .loadData: self.loadData() case .scannedCode(payloadData: let payloadData): self.scannedQRCode(payloadData: payloadData) case .cannotScan: self.startSASVerification() case .acknowledgeOtherScannedMyCode(let acknowledgeOtherScannedMyCode): self.acknowledgeOtherScannedMyCode(acknowledgeOtherScannedMyCode) case .cancel: self.cancel() case .acknowledgeMyUserScannedOtherCode: self.acknowledgeScanOtherCode() } } // MARK: - Private private func loadData() { let qrCodePlayloadData: Data? let canShowScanAction: Bool self.qrCodeTransaction = self.keyVerificationManager.qrCodeTransaction(withTransactionId: self.keyVerificationRequest.requestId) if let supportedVerificationMethods = self.keyVerificationRequest.myMethods { if let qrCodeData = self.qrCodeTransaction?.qrCodeData { qrCodePlayloadData = self.qrCodeDataCoder.encode(qrCodeData) } else { qrCodePlayloadData = nil } canShowScanAction = self.canShowScanAction(from: supportedVerificationMethods) } else { qrCodePlayloadData = nil canShowScanAction = false } let viewData = KeyVerificationVerifyByScanningViewData(qrCodeData: qrCodePlayloadData, showScanAction: canShowScanAction) self.update(viewState: .loaded(viewData: viewData)) self.registerTransactionDidStateChangeNotification() } private func canShowScanAction(from verificationMethods: [String]) -> Bool { return verificationMethods.contains(MXKeyVerificationMethodQRCodeScan) } private func cancel() { self.cancelQRCodeTransaction() self.keyVerificationRequest.cancel(with: MXTransactionCancelCode.user(), success: nil, failure: nil) self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModelDidCancel(self) } private func cancelQRCodeTransaction() { guard let transaction = self.qrCodeTransaction else { return } transaction.cancel(with: MXTransactionCancelCode.user()) } private func update(viewState: KeyVerificationVerifyByScanningViewState) { self.viewDelegate?.keyVerificationVerifyByScanningViewModel(self, didUpdateViewState: viewState) } // MARK: QR code private func scannedQRCode(payloadData: Data) { self.scannedQRCodeData = self.qrCodeDataCoder.decode(payloadData) let isQRCodeValid = self.scannedQRCodeData != nil self.update(viewState: .scannedCodeValidated(isValid: isQRCodeValid)) } private func acknowledgeScanOtherCode() { guard let scannedQRCodeData = self.scannedQRCodeData else { return } guard let qrCodeTransaction = self.qrCodeTransaction else { return } qrCodeTransaction.userHasScannedOtherQrCodeData(scannedQRCodeData) self.update(viewState: .loading) } private func acknowledgeOtherScannedMyCode(_ acknowledgeOtherScannedMyCode: Bool) { guard let qrCodeTransaction = self.qrCodeTransaction else { return } self.update(viewState: .loading) qrCodeTransaction.otherUserScannedMyQrCode(acknowledgeOtherScannedMyCode) } private func removePendingQRCodeTransaction() { guard let qrCodeTransaction = self.qrCodeTransaction else { return } self.keyVerificationManager.removeQRCodeTransaction(withTransactionId: qrCodeTransaction.transactionId) } // MARK: SAS private func startSASVerification() { self.update(viewState: .loading) self.session.crypto.keyVerificationManager.beginKeyVerification(from: self.keyVerificationRequest, method: MXKeyVerificationMethodSAS, success: { [weak self] (keyVerificationTransaction) in guard let self = self else { return } // Remove pending QR code transaction, as we are going to use SAS verification self.removePendingQRCodeTransaction() if keyVerificationTransaction is MXOutgoingSASTransaction == false { NSLog("[KeyVerificationVerifyByScanningViewModel] SAS transaction should be outgoing") self.unregisterTransactionDidStateChangeNotification() self.update(viewState: .error(KeyVerificationVerifyByScanningViewModelError.unknown)) } }, failure: { [weak self] (error) in guard let self = self else { return } self.update(viewState: .error(error)) } ) } // MARK: - MXKeyVerificationTransactionDidChange private func registerTransactionDidStateChangeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(transactionDidStateChange(notification:)), name: .MXKeyVerificationTransactionDidChange, object: nil) } private func unregisterTransactionDidStateChangeNotification() { NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationTransactionDidChange, object: nil) } @objc private func transactionDidStateChange(notification: Notification) { guard let transaction = notification.object as? MXKeyVerificationTransaction else { return } guard self.keyVerificationRequest.requestId == transaction.transactionId else { NSLog("[KeyVerificationVerifyByScanningViewModel] transactionDidStateChange: Not for our transaction (\(self.keyVerificationRequest.requestId)): \(transaction.transactionId)") return } if let sasTransaction = transaction as? MXSASTransaction { self.sasTransactionDidStateChange(sasTransaction) } else if let qrCodeTransaction = transaction as? MXQRCodeTransaction { self.qrCodeTransactionDidStateChange(qrCodeTransaction) } } private func sasTransactionDidStateChange(_ transaction: MXSASTransaction) { switch transaction.state { case MXSASTransactionStateShowSAS: self.unregisterTransactionDidStateChangeNotification() self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModel(self, didStartSASVerificationWithTransaction: transaction) case MXSASTransactionStateCancelled: guard let reason = transaction.reasonCancelCode else { return } self.unregisterTransactionDidStateChangeNotification() self.update(viewState: .cancelled(reason)) case MXSASTransactionStateCancelledByMe: guard let reason = transaction.reasonCancelCode else { return } self.unregisterTransactionDidStateChangeNotification() self.update(viewState: .cancelledByMe(reason)) default: break } } private func qrCodeTransactionDidStateChange(_ transaction: MXQRCodeTransaction) { switch transaction.state { case .verified: self.unregisterTransactionDidStateChangeNotification() self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModelDidCompleteQRCodeVerification(self) case .qrScannedByOther: self.update(viewState: .otherUserScannedMyCode) case .cancelled: guard let reason = transaction.reasonCancelCode else { return } self.unregisterTransactionDidStateChangeNotification() self.update(viewState: .cancelled(reason)) case .cancelledByMe: guard let reason = transaction.reasonCancelCode else { return } self.unregisterTransactionDidStateChangeNotification() self.update(viewState: .cancelledByMe(reason)) default: break } } }
38.594796
197
0.672414
c1ddcba5882eb4c5cd1f87d6a0fc8696deb3dc3e
919
// // CabinSeatRow1Pos3SwitchCushion.swift // VSSGraphQL // // Generated by VSSGraphQL on 21.10.2020. // Copyright © 2020 High Mobility GmbH. All rights reserved. // import Foundation public struct CabinSeatRow1Pos3SwitchCushion: GraphQLObjectType { /// Seat cushion backward/shorten switch engaged public var backward: Bool? = nil /// Seat cushion down switch engaged public var down: Bool? = nil /// Seat cushion forward/lengthen switch engaged public var forward: Bool? = nil /// Seat cushion up switch engaged public var up: Bool? = nil // MARK: GraphQLObjectType public static var scalars: [String : Any] { [ "backward" : Bool.self, "down" : Bool.self, "forward" : Bool.self, "up" : Bool.self ] } public static var objects: [String : GraphQLObjectType.Type] { [:] } }
22.414634
66
0.618063
2989436c283cfc3ccdd696c892d9ba4f741b89b3
813
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Light-Swift-Untar", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library(name: "Light-Swift-Untar", targets: ["Light-Swift-Untar"]), ], dependencies: [], 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: "Light-Swift-Untar", dependencies: [], path: "."), ] )
38.714286
122
0.654367
900491e4351c0dcac707e6510101529442656d5b
4,069
// // PhotoMapViewController.swift // Photo Map // // Created by Nicholas Aiwazian on 10/15/15. // Copyright © 2015 Timothy Lee. All rights reserved. // import UIKit import MapKit class PhotoMapViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, LocationsViewControllerDelegate, MKMapViewDelegate { var selectedImage: UIImage? @IBOutlet weak var mapView: MKMapView! @IBAction func onCamera(_ sender: Any) { let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true if UIImagePickerController.isSourceTypeAvailable(.camera) { print("Camera is available 📸") vc.sourceType = .camera } else { print("Camera 🚫 available so we will use photo library instead") vc.sourceType = .photoLibrary } self.present(vc, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // Get the image captured by the UIImagePickerController let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage // let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage // Do something with the images (based on your use case) self.selectedImage = originalImage // Dismiss UIImagePickerController to go back to your original view controller dismiss(animated: true, completion: { self.performSegue(withIdentifier: "tagSegue", sender: nil) }) } override func viewDidLoad() { super.viewDidLoad() //one degree of latitude is approximately 111 kilometers (69 miles) at all times. let sfRegion = MKCoordinateRegionMake(CLLocationCoordinate2DMake(37.783333, -122.416667), MKCoordinateSpanMake(0.1, 0.1)) mapView.setRegion(sfRegion, animated: false) mapView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let locationsViewController = segue.destination as! LocationsViewController locationsViewController.delegate = self } func locationsPickedLocation(controller: LocationsViewController, latitude: NSNumber, longitude: NSNumber) { let locationCoordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude)) let annotation = MKPointAnnotation() annotation.coordinate = locationCoordinate annotation.title = String(describing: locationCoordinate.latitude) annotation.subtitle = "Picture!" mapView.addAnnotation(annotation) self.navigationController?.popToViewController(self, animated: true) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let reuseID = "myAnnotationView" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID) if (annotationView == nil) { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID) annotationView!.canShowCallout = true annotationView!.leftCalloutAccessoryView = UIImageView(frame: CGRect(x:0, y:0, width: 50, height: 50)) } let imageView = annotationView?.leftCalloutAccessoryView as! UIImageView imageView.image = selectedImage return annotationView } }
36.990909
165
0.679528
e8243b678507645efd5dfddbad9db05f5bb38362
4,281
// // QuickReportVC.swift // PathFinder // // Created by Fury on 26/07/2019. // Copyright © 2019 Fury. All rights reserved. // import UIKit import MessageUI class QuickReportVC: UIViewController { private let quickReportView: QuickReportView = { let view = QuickReportView() view.translatesAutoresizingMaskIntoConstraints = false return view }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5) setupQuickReportView() quickReportView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) startAnimations(isCancel: false) } private func startAnimations(isCancel: Bool) { if isCancel { UIView.animate(withDuration: 0.3) { self.quickReportView.topView.transform = CGAffineTransform(translationX: 0, y: -600) } UIView.animate(withDuration: 0.3, animations: { self.quickReportView.bottomView.transform = CGAffineTransform(translationX: 0, y: 600) self.quickReportView.policeCallButton.transform = CGAffineTransform(translationX: 0, y: 550) }) { (Bool) in self.dismiss(animated: false) } } else { UIView.animate(withDuration: 0.3) { self.quickReportView.topView.transform = CGAffineTransform(translationX: 0, y: self.view.frame.midY) } UIView.animate(withDuration: 0.3) { self.quickReportView.bottomView.transform = CGAffineTransform(translationX: 0, y: -250) self.quickReportView.policeCallButton.transform = CGAffineTransform(translationX: 0, y: -350) } } } private func setupQuickReportView() { let guide = view.safeAreaLayoutGuide view.addSubview(quickReportView) quickReportView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true quickReportView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true quickReportView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true quickReportView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true } } extension QuickReportVC: QuickReportViewDelegate { func touchUpAllButton(_ sender: UIButton) { switch sender.tag { case 0: if MFMessageComposeViewController.canSendText() { let recipients: [String] = ["01062658667"] let messageontroller = MFMessageComposeViewController() messageontroller.messageComposeDelegate = self messageontroller.recipients = recipients messageontroller.body = "텍스트" self.present(messageontroller, animated: true, completion: nil) } case 1: if MFMessageComposeViewController.canSendText() { let recipients: [String] = ["01062658667"] let messageontroller = MFMessageComposeViewController() messageontroller.messageComposeDelegate = self messageontroller.recipients = recipients messageontroller.body = "텍스트" self.present(messageontroller, animated: true, completion: nil) } case 2: if MFMessageComposeViewController.canSendText() { let recipients: [String] = ["01062658667"] let messageontroller = MFMessageComposeViewController() messageontroller.messageComposeDelegate = self messageontroller.recipients = recipients messageontroller.body = "텍스트" self.present(messageontroller, animated: true, completion: nil) } case 3: if MFMessageComposeViewController.canSendText() { let recipients: [String] = ["01062658667"] let messageontroller = MFMessageComposeViewController() messageontroller.messageComposeDelegate = self messageontroller.recipients = recipients messageontroller.body = "텍스트" self.present(messageontroller, animated: true, completion: nil) } default: break } } func touchUpCancelButton() { startAnimations(isCancel: true) } } extension QuickReportVC: MFMessageComposeViewControllerDelegate { func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { controller.dismiss(animated: true, completion: nil) } }
35.380165
127
0.707311
6442153c5a8eb9b8be7205964a2cb18a167c772b
188
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a={class case,
26.857143
87
0.765957
1d53fc52eb92924270063692a126601e48f07b1a
11,994
// // FirstViewController.swift // rememberbreast // // Created by Rodrigo Villamil Pérez on 18/7/18. // Copyright © 2018 Rodrigo Villamil Pérez. All rights reserved. // import UIKit import UserNotifications import os.log class BreastFeedingViewController: UIViewController { // MARK: - Internal vars var chronometerBreastRight = Chronometer() var chronometerBreastLeft = Chronometer() var breastFeedingStaticsStore = BreastFeedingStaticsStore() // MARK: - Internal Constants let measurementQualityThreshold = 10 //Seconds let notificationTimeInterval = 900.0 // Seconds // MARK: - IBOutlets @IBOutlet weak var lblYourBabyToday: UILabel! @IBOutlet weak var lblNumberBreastFeeding: UILabel! @IBOutlet weak var lblBreastSide: UILabel! @IBOutlet weak var lblTimerRightBreast: UILabel! @IBOutlet weak var lblElapsedTimeLeftBreast: UILabel! @IBOutlet weak var lblTimerLeftBreast: UILabel! @IBOutlet weak var lblElapsedTimeRightBreast: UILabel! @IBOutlet weak var buttonLeftBreast: UIButton! @IBOutlet weak var buttonRightBreast: UIButton! @IBOutlet weak var tbItemChronometer: UITabBarItem! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() self.initChronometer() self.l18n() self.initNotificationCenter() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) self.updateView() } // MARK: - My functions // http://www.thomashanning.com/push-notifications-local-notifications-tutorial/#Sending_local_notifications func initChronometer(){ self.chronometerBreastRight.onTick = { tic in self.lblTimerRightBreast.text = SimpleDateFormatter.secondsToHHmmss(tic) } self.chronometerBreastLeft.onTick = { tic in self.lblTimerLeftBreast.text = SimpleDateFormatter.secondsToHHmmss(tic) } } func initNotificationCenter () { NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } @objc func applicationWillEnterForeground () { os_log("###### applicationWillEnterForeground #####") if (chronometerBreastRight.state == .resumed ) { self.chronometerBreastRight.start() os_log("applicationWillEnterForeground - chronometerBreastRight.start") } if (chronometerBreastLeft.state == .resumed ) { self.chronometerBreastLeft.start() os_log("applicationWillEnterForeground - chronometerBreastLeft.start") } // https://stackoverflow.com/questions/31951142/how-to-cancel-a-localnotification-with-the-press-of-a-button-in-swift os_log("applicationWillEnterForeground - removeAllPendingNotificationRequests") UNUserNotificationCenter.current().removeAllPendingNotificationRequests() os_log("applicationWillEnterForeground - removeAllDeliveredNotifications") UNUserNotificationCenter.current().removeAllDeliveredNotifications() os_log("applicationWillEnterForeground - updateView") self.updateView() os_log("applicationWillEnterForeground - OK") } @objc func applicationDidEnterBackground () { os_log("###### applicationDidEnterBackground #####") os_log("applicationDidEnterBackground - chronometerBreastRight.resume") self.chronometerBreastRight.resume() // Maybe the state be stopped os_log("applicationDidEnterBackground - chronometerBreastLeft.resume") self.chronometerBreastLeft.resume() if (chronometerBreastRight.state == .resumed ) || (chronometerBreastLeft.state == .resumed ) { os_log("applicationDidEnterBackground - requestLocalPushNotification") self.requestLocalPushNotification() } os_log("applicationDidEnterBackground - OK") } func l18n () { self.tbItemChronometer.title = NSLocalizedString("tbItemChronometer.title", comment: "") } func updateView(){ let today = Date() // Today is .. self.lblYourBabyToday.text = NSLocalizedString("lblYourBabyToday.text", comment: "") + SimpleDateFormatter.dateToStringMMMddyyy (today) // // Number of breastFeeding for today // self.lblNumberBreastFeeding.text = "\(NSLocalizedString("lblNumberBreastFeeding.text", comment: "")) \(breastFeedingStaticsStore.findTotalBreastFeedings(forDate: today))" // // Latest breastfeeding: Right or Left breast and elapsed time // var breastSideText = NSLocalizedString("breastSideText_select_the_breast", comment: "") if let lastestBreastFeeding = breastFeedingStaticsStore.findLatestBreastFeeding() { breastSideText = NSLocalizedString("breastSideText_left", comment: "") if (lastestBreastFeeding.chestRight) { breastSideText = NSLocalizedString("breastSideText_right", comment: "") } let componentsElapsedTime = Calendar.current.dateComponents( [.hour, .minute], from: lastestBreastFeeding.endDateTime!, to: today) breastSideText += (" ,\(NSLocalizedString("since", comment: ""))\(componentsElapsedTime.hour ?? 0) \(NSLocalizedString("hours", comment: "")) \(componentsElapsedTime.minute ?? 0) \(NSLocalizedString("minutes", comment: ""))") } self.lblBreastSide.text = breastSideText // // Elapsed time from now for left breast // self.lblElapsedTimeLeftBreast.text = (NSLocalizedString("lblElapsedTimeLeftBreast.text", comment: "")) if let latestBreastFeedingLeft = breastFeedingStaticsStore.findLatestBreastFeeding(forChestRight: false) { let componentsElapsedTimeLeftBreast = Calendar.current.dateComponents( [.hour, .minute], from: latestBreastFeedingLeft.endDateTime!, to: today) self.lblElapsedTimeLeftBreast.text = ("\(NSLocalizedString("last", comment: "")) \(componentsElapsedTimeLeftBreast.hour ?? 0) h \(componentsElapsedTimeLeftBreast.minute ?? 0) m") } // // Elapsed time from now for right breast // self.lblElapsedTimeRightBreast.text = (NSLocalizedString("lblElapsedTimeRightBreast.text", comment: "")) if let latestBreastFeedingRight = breastFeedingStaticsStore.findLatestBreastFeeding(forChestRight: true) { let componentsElapsedTimeRightBreast = Calendar.current.dateComponents( [.hour, .minute], from: latestBreastFeedingRight.endDateTime!, to: today) self.lblElapsedTimeRightBreast.text = ("\(NSLocalizedString("last", comment: "")) \(componentsElapsedTimeRightBreast.hour ?? 0) h \(componentsElapsedTimeRightBreast.minute ?? 0) m") } // Contador de notificaciones locales UIApplication.shared.applicationIconBadgeNumber = 0 } func showDialogMaybeWrongMeasure (chronometer: Chronometer, chestRight: Bool) { let alert = UIAlertController( title: (NSLocalizedString("dlg.wrongmeasure.title", comment: "")), message:"\(NSLocalizedString("dlg.wrongmeasure.message_prefix", comment: "")) \(self.measurementQualityThreshold) \(NSLocalizedString("dlg.wrongmeasure.message_sufix", comment: ""))", preferredStyle: .alert) alert.addAction(UIAlertAction(title: (NSLocalizedString("yes", comment: "")), style: .default, handler: { _ in self.breastFeedingStaticsStore.insert( beginDateTime:chronometer.startDateTime! , endDateTime: chronometer.stopDateTime!, chestRight: chestRight, duration: chronometer.seconds) self.updateView() })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) self.present(alert, animated: true) } func performButtonClicked ( uiButton: UIButton, chronometer: Chronometer, chestRight: Bool, lblTimerBreast: UILabel) { if !uiButton.isSelected { chronometer.start() lblTimerBreast.textColor = UIColor.rbTextChronometerRunning }else { chronometer.stop() lblTimerBreast.textColor = UIColor.rbTextChronometerStopped if (chronometer.seconds <= self.measurementQualityThreshold) { showDialogMaybeWrongMeasure( chronometer: chronometer, chestRight: chestRight) } else { breastFeedingStaticsStore.insert( beginDateTime:chronometer.startDateTime! , endDateTime: chronometer.stopDateTime!, chestRight: chestRight, duration: chronometer.seconds) } lblTimerBreast.text = SimpleDateFormatter.secondsToHHmmss(0) } uiButton.isSelected = !uiButton.isSelected updateView() } func requestLocalPushNotification(){ let localNotificationContent = UNMutableNotificationContent() localNotificationContent.title = NSLocalizedString( "requestLocalPushNotification.title", comment: "") localNotificationContent.body = NSLocalizedString( "requestLocalPushNotification.body", comment: "") localNotificationContent.sound = UNNotificationSound.default localNotificationContent.badge = 1 // Cada 900 segundos y se repite let trigger = UNTimeIntervalNotificationTrigger( timeInterval: self.notificationTimeInterval, repeats: true) let request = UNNotificationRequest(identifier: "anyChronometerStarted", content: localNotificationContent, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } // MARK: - IBActions @IBAction func rightBreastButtonClicked(_ sender: UIButton) { performButtonClicked (uiButton: sender, chronometer: chronometerBreastRight, chestRight: true, lblTimerBreast:lblTimerRightBreast) } @IBAction func leftBreastButtonClicked(_ sender: UIButton) { performButtonClicked (uiButton: sender, chronometer: chronometerBreastLeft, chestRight: false, lblTimerBreast:lblTimerLeftBreast) } }
44.095588
226
0.610889
3841ab7fd38006cccbd2bab076e56a84767b4f30
161
// // TimerState.swift // pock-timer-widget // // Created by p-x9 on 2021/03/08. // import Foundation public enum TimerState { case running, stopping }
12.384615
34
0.664596
14a0513d363ad2966bc4b035071b49ba60b55c0f
594
// // Created by Yildirim Adiguzel on 3.05.2020. // Copyright © 2020 RelevantBox. All rights reserved. // import Foundation class FeedbackEvent { private var event: Dictionary<String, Any> = Dictionary<String, Any>() class func create(name: String) -> FeedbackEvent { let feedbackEvent = FeedbackEvent() feedbackEvent.event["n"] = name return feedbackEvent } func addParameter(key: String, value: Any) -> FeedbackEvent { event[key] = value return self } func toMap() -> Dictionary<String, Any> { return event } }
22.846154
74
0.638047
d6833251ffa888d578eb413f42e7ed5f48d7a3b6
15,042
// RUN: %target-typecheck-verify-swift -parse-as-library // See also rdar://15626843. static var gvu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class var gvu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override static var gvu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override class var gvu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static override var gvu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class override var gvu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static var gvu7: Int { // expected-error {{static properties may only be declared on a type}}{{1-8=}} return 42 } class var gvu8: Int { // expected-error {{class properties may only be declared on a type}}{{1-7=}} return 42 } static let glu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} class let glu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} override static let glu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} override class let glu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static override let glu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} class override let glu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static var gvi1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class var gvi2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static var gvi3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class var gvi4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override var gvi5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override var gvi6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} static let gli1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class let gli2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static let gli3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class let gli4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override let gli5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override let gli6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} func inGlobalFunc() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{3-10=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{3-9=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{3-10=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{3-9=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } struct InMemberFunc { func member() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{5-12=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{5-11=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{5-12=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{5-11=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } } struct S { // expected-note 3{{extended type declared here}} expected-note{{did you mean 'S'?}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension S { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } enum E { // expected-note 3{{extended type declared here}} expected-note{{did you mean 'E'?}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension E { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } class C { // expected-note{{did you mean 'C'?}} static var v1: Int = 0 class final var v3: Int = 0 // expected-error {{class stored properties not supported}} class var v4: Int = 0 // expected-error {{class stored properties not supported}} static var v5: Int { return 0 } class var v6: Int { return 0 } static final var v7: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} class final let l3: Int = 0 // expected-error {{class stored properties not supported}} static final let l4 = 2 // expected-error {{static declarations are already final}} {{10-16=}} } extension C { static var ev1: Int = 0 class final var ev2: Int = 0 // expected-error {{class stored properties not supported}} class var ev3: Int = 0 // expected-error {{class stored properties not supported}} static var ev4: Int { return 0 } class var ev5: Int { return 0 } static final var ev6: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} class final let el3: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} static final let el4: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} } protocol P { // expected-note{{did you mean 'P'?}} expected-note{{extended type declared here}} // Both `static` and `class` property requirements are equivalent in protocols rdar://problem/17198298 static var v1: Int { get } class var v2: Int { get } // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}} static final var v3: Int { get } // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} class let l2: Int // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}} expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} } extension P { class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } struct S1 { // rdar://15626843 static var x: Int // expected-error {{'static var' declaration requires an initializer expression or getter/setter specifier}} var y = 1 static var z = 5 } extension S1 { static var zz = 42 static var xy: Int { return 5 } } enum E1 { static var y: Int { get {} } } class C1 { class var x: Int // expected-error {{class stored properties not supported}} expected-error {{'class var' declaration requires an initializer expression or getter/setter specifier}} } class C2 { var x: Int = 19 class var x: Int = 17 // expected-error{{class stored properties not supported}} func xx() -> Int { return self.x + C2.x } } class ClassHasVars { static var computedStatic: Int { return 0 } // expected-note 3{{overridden declaration is here}} final class var computedFinalClass: Int { return 0 } // expected-note 3{{overridden declaration is here}} class var computedClass: Int { return 0 } var computedInstance: Int { return 0 } } class ClassOverridesVars : ClassHasVars { override static var computedStatic: Int { return 1 } // expected-error {{cannot override static var}} override static var computedFinalClass: Int { return 1 } // expected-error {{static var overrides a 'final' class var}} override class var computedClass: Int { return 1 } override var computedInstance: Int { return 1 } } class ClassOverridesVars2 : ClassHasVars { override final class var computedStatic: Int { return 1 } // expected-error {{cannot override static var}} override final class var computedFinalClass: Int { return 1 } // expected-error {{class var overrides a 'final' class var}} } class ClassOverridesVars3 : ClassHasVars { override class var computedStatic: Int { return 1 } // expected-error {{cannot override static var}} override class var computedFinalClass: Int { return 1 } // expected-error {{class var overrides a 'final' class var}} } struct S2 { var x: Int = 19 static var x: Int = 17 func xx() -> Int { return self.x + C2.x } } // Mutating vs non-mutating conflict with static stored property witness - rdar://problem/19887250 protocol Proto { static var name: String {get set} } struct ProtoAdopter : Proto { static var name: String = "name" // no error, even though static setters aren't mutating } // Make sure the logic remains correct if we synthesized accessors for our stored property protocol ProtosEvilTwin { static var name: String {get set} } extension ProtoAdopter : ProtosEvilTwin {} // rdar://18990358 public struct Foo { // expected-note {{to match this opening '{'}}} public static let S { a // expected-error{{computed property must have an explicit type}} {{22-22=: <# Type #>}} // expected-error@-1{{type annotation missing in pattern}} // expected-error@-2{{'let' declarations cannot be computed properties}} {{17-20=var}} // expected-error@-3{{use of unresolved identifier 'a'}} } // expected-error@+1 {{expected '}' in struct}}
55.505535
294
0.698245