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
|
---|---|---|---|---|---|
e092f9f59c230bc116deb6756d4a2242c9c24f7f | 2,934 | //
// Smartphone.swift
// eStore
//
// Created by Vladislav Kondrashkov on 2/20/19.
// Copyright © 2019 Vladislav Kondrashkov. All rights reserved.
//
import ObjectMapper
class Smartphone: ImmutableMappable {
let id: String
let imageUrl: String?
let name: String
let brand: String
let operatingSystem: OperatingSystem
let display: Display
let ram: Int
let flashMemory: Int
let processor: String
let color: String
let batteryCapacity: Int
let price: Int
let stockCount: Int
required init(map: Map) throws {
id = try map.value("id")
imageUrl = try? map.value("imageUrl")
name = try map.value("name")
brand = try map.value("brand")
operatingSystem = try OperatingSystem(rawValue: map.value("operatingSystem")) ?? .unknown
display = Display(width: try map.value("display.width"), height: try map.value("display.height"))
ram = try map.value("ram")
flashMemory = try map.value("flashMemory")
processor = try map.value("processor")
color = try map.value("color")
batteryCapacity = try map.value("batteryCapacity")
price = try map.value("price")
stockCount = try map.value("stockCount")
}
func mapping(map: Map) {
id >>> map["id"]
imageUrl >>> map["imageUrl"]
name >>> map["name"]
brand >>> map["brand"]
operatingSystem.rawValue >>> map["operatingSystem"]
display.width >>> map["display.width"]
display.height >>> map["display.height"]
ram >>> map["ram"]
flashMemory >>> map["flashMemory"]
processor >>> map["processor"]
color >>> map["color"]
batteryCapacity >>> map["batteryCapacity"]
price >>> map["price"]
stockCount >>> map["stockCount"]
}
}
// MARK: - StoreItemConvertible implementation
extension Smartphone: StoreItemConvertible {
func toStoreItem() -> StoreItem {
var specifications: [Specification] = []
specifications.append(Specification(name: "Operating system", value: operatingSystem))
specifications.append(Specification(name: "Display", value: display))
specifications.append(Specification(name: "RAM", value: "\(ram) GB"))
specifications.append(Specification(name: "Flash memory", value: "\(flashMemory) GB"))
specifications.append(Specification(name: "Processor", value: processor))
specifications.append(Specification(name: "Color", value: color))
specifications.append(Specification(name: "Battery capacity", value: "\(batteryCapacity) mAh"))
let storeItem = StoreItem(
id: id,
imageUrl: imageUrl,
name: name,
brand: brand,
type: .Smartphone,
specifications: specifications,
price: price,
stockCount: stockCount
)
return storeItem
}
}
| 34.928571 | 105 | 0.619973 |
ef59ebc897c45a34494532d9bdcdceb9403f0bcc | 1,763 | //
// ViewController.swift
// SearchTextFieldMinimalExample
//
// Created by Michiel Boertjes on 04/09/2018.
// Copyright © 2018 Michiel Boertjes. All rights reserved.
//
import UIKit
import SearchTextField
class ViewController: UIViewController {
@IBOutlet weak var exampleSearchTextField: SearchTextField!
override func viewDidLoad() {
super.viewDidLoad()
configureSimpleSearchTextField()
// Do any additional setup after loading the view, typically from a nib.
}
// 1 - Configure a simple search text view
fileprivate func configureSimpleSearchTextField() {
// Start visible even without user's interaction as soon as created - Default: false
// exampleSearchTextField.startVisibleWithoutInteraction = true
// Set data source
let suggestions = ["no i am not", "hell yeah", "maybe, not sure yet", "do you even lift", "no hold on, I think I got it"];
exampleSearchTextField.filterStrings(suggestions)
exampleSearchTextField.itemSelectionHandler = { filteredResults, itemPosition in
// Just in case you need the item position
let item = filteredResults[itemPosition]
print("Item at position \(itemPosition): \(item.title)")
// Do whatever you want with the picked item
self.exampleSearchTextField.text = item.title
}
}
// Hide keyboard when touching the screen
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 32.054545 | 130 | 0.66194 |
ef0b7a73dc6699e44b93042cb4a8f47cf2b1cbe8 | 548 | //
// RoleDivision.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class RoleDivision: Codable {
/** Role to be associated with the given division which forms a grant */
public var roleId: String?
/** Division associated with the given role which forms a grant */
public var divisionId: String?
public init(roleId: String?, divisionId: String?) {
self.roleId = roleId
self.divisionId = divisionId
}
}
| 18.266667 | 76 | 0.645985 |
4a095b427f2050b2d6c198e2ae41f971786ad08a | 1,129 | /*
* Copyright 2017 WalmartLabs
* 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
/**
* GENERATED CODE: DO NOT MODIFY
* Do not modify the content of this class as it will be regenerated every time an api-impl-regen command is executed.
* @see <a href:"https://electrode.gitbooks.io/electrode-native/content/v/master/cli/regen-api-impl.html"></a>
* <p>
* <p>
* Marker interface that is used for request handler implementations inside an api.
*/
@objc public protocol MoviesApiRequestHandlerDelegate
{
func registerGetTopRatedMoviesRequestHandler()
func registerGetMovieDetailRequestHandler()
}
| 37.633333 | 118 | 0.758193 |
391e38ad08bedfe1ae9272332f9af179c72311c6 | 892 | //
// LocksmithServer.swift
// Locksmith
//
// Created by Alan Stephensen on 6/09/2014.
// Copyright (c) 2014 Alan Stephensen. All rights reserved.
//
import Cocoa
protocol LocksmithServerDelegate {
func locksmithServerIsNowTrusted()
func locksmithServerShortcutsModified()
}
class LocksmithServer: NSObject {
var delegate: LocksmithServerDelegate?
func isProcessTrusted() -> NSNumber {
let isTrusted = AXIsProcessTrusted() == 1
if isTrusted {
delegate?.locksmithServerIsNowTrusted()
}
return NSNumber(bool: isTrusted)
}
func askForTrust() {
let trusted = kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString
let options = [trusted: true]
AXIsProcessTrustedWithOptions(options);
}
func reloadShortcuts() {
delegate?.locksmithServerShortcutsModified()
}
}
| 24.108108 | 81 | 0.67713 |
f75d9c1079a42ca8fb25aaa4b9f2cc387cf39c1a | 5,964 | //
// ViewController.swift
// CoreMLDemo
//
// Created by Jon Manning on 9/2/18.
// Copyright © 2018 Jon Manning. All rights reserved.
//
import UIKit
// BEGIN camera_import
import AVFoundation
// END camera_import
// BEGIN vision_import
import Vision
// END vision_import
// BEGIN camera_viewcontroller
class ViewController: UIViewController {
// BEGIN camera_label
@IBOutlet weak var outputLabel: UILabel!
// END camera_label
// BEGIN vision_model
// Produces a Vision wrapper for a CoreML model.
lazy var model : VNCoreMLModel = {
let coreMLModel = Inceptionv3().model
do {
return try VNCoreMLModel(for: Inceptionv3().model)
} catch let error {
fatalError("Failed to create model! \(error)")
}
}()
// END vision_model
// An output that's used to capture still images.
let photoOutput = AVCapturePhotoOutput()
override func viewDidLoad() {
super.viewDidLoad()
let captureSession = AVCaptureSession()
// Search for available capture devices that are
// 1. on the rear of the device
// 2. are a wide angle camera (not a telephoto)
// 3. can capture video
let availableDevices = AVCaptureDevice.DiscoverySession(
deviceTypes: [.builtInWideAngleCamera],
mediaType: AVMediaType.video,
position: .back).devices
// Find the first one
guard let rearCamera = availableDevices.first else {
fatalError("No suitable capture device found!")
}
// Set up the capture device and add it to the capture session
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: rearCamera)
captureSession.addInput(captureDeviceInput)
} catch {
print("Failed to create the device input! \(error)")
}
// Add the photo capture output to the session.
captureSession.addOutput(photoOutput)
// BEGIN camera_output_delegate_setup
let captureOutput = AVCaptureVideoDataOutput()
// Set up the video output, and add it to the capture session
// Tell the capture output to notify us every time it captures a frame of video
captureOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
captureSession.addOutput(captureOutput)
// END camera_output_delegate_setup
// Create a preview layer for the session
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
// Add it to the view, underneath everything
previewLayer.frame = view.frame
view.layer.insertSublayer(previewLayer, at: 0)
// Start the session
captureSession.startRunning()
}
// Called when the user taps on the view.
@IBAction func capturePhoto(_ sender: Any) {
// Specify that we want to capture a JPEG
// image from the camera.
let settings = AVCapturePhotoSettings(format: [
AVVideoCodecKey: AVVideoCodecType.jpeg
])
// Signal that we want to capture a photo, and it
// should notify this object when done
photoOutput.capturePhoto(
with: settings,
delegate: self
)
}
}
// Contains methods that respond to a photo being captured.
extension ViewController : AVCapturePhotoCaptureDelegate {
// Called after a requested photo has finished being
// captured.
func photoOutput(
_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photo: AVCapturePhoto,
error: Error?) {
if let error = error {
print("Error processing photo: \(error)")
} else if let jpegData = photo.fileDataRepresentation() {
// jpegData now contains an encoded JPEG image
// that we can use
let photoSizeKilobytes = jpegData.count / 1024
print("Captured a photo! It was " +
"\(photoSizeKilobytes)kb in size.")
}
}
}
// END camera_viewcontroller
// BEGIN vision_capturedelegate
extension ViewController : AVCaptureVideoDataOutputSampleBufferDelegate {
// Called every time a frame is captured
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// Create a request that uses the model
let request = VNCoreMLRequest(model: model) { (finishedRequest, error) in
// Ensure that we have an array of results
guard let results = finishedRequest.results
as? [VNClassificationObservation] else {
return
}
// Ensure that we have at least one result
guard let observation = results.first else {
return
}
// This whole queue runs on a background
// queue, so we need to be sure we update
// the UI on the main queue
OperationQueue.main.addOperation {
self.outputLabel.text =
"\(observation.identifier)"
}
}
// Convert the frame into a CVPixelBuffer, which
// Vision can use
guard let pixelBuffer: CVPixelBuffer =
CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
// Create and execute a handler that uses this request
let handler = VNImageRequestHandler(
cvPixelBuffer: pixelBuffer,
options: [:]
)
try? handler.perform([request])
}
}
// END vision_capturedelegate
| 31.893048 | 129 | 0.597586 |
d5e1048b685722f459d79e9e1dc3f7e3a2257e1f | 402 | //
// DateTests.swift
// Date
//
// Created by Bernardo Breder.
//
//
import XCTest
@testable import DateTests
extension DateTests {
static var allTests : [(String, (DateTests) -> () throws -> Void)] {
return [
("testDay", testDay),
("testDayTime", testDayTime),
("testIntValue", testIntValue),
("testMonth", testMonth),
]
}
}
XCTMain([
testCase(DateTests.allTests),
])
| 13.862069 | 69 | 0.626866 |
6a56b3094fbf3ba9a0525bf2f40541add0ed0e92 | 2,383 | //
// FileLogger.swift
// LogsManager
//
// Created by Anton Plebanovich on 6/5/19.
// Copyright © 2019 Anton Plebanovich. All rights reserved.
//
import CocoaLumberjack
import Foundation
import RoutableLogger
open class FileLogger: DDFileLogger, BaseLogger {
// ******************************* MARK: - BaseLogger
public let logLevel: DDLogLevel
public var mode: LoggerMode
public let dateFormatter: DateFormatter?
public required init(mode: LoggerMode,
logLevel: DDLogLevel,
dateFormatter: DateFormatter? = BaseLogFormatter.dateFormatter,
logsDirectory: String? = nil) {
self.logLevel = logLevel
self.mode = mode
self.dateFormatter = dateFormatter
let fileManager: DDLogFileManagerDefault
if let logsDirectory = logsDirectory {
fileManager = DDLogFileManagerDefault(logsDirectory: logsDirectory)
} else {
let defaultLogsDirectory = FileManager.default
.urls(for: .documentDirectory, in: .userDomainMask)
.last!
.appendingPathComponent("LogsManager", isDirectory: true)
.path
var isDirectory: ObjCBool = true
if !FileManager.default.fileExists(atPath: defaultLogsDirectory, isDirectory: &isDirectory) {
do {
try FileManager.default.createDirectory(atPath: defaultLogsDirectory, withIntermediateDirectories: true, attributes: nil)
} catch {
RoutableLogger.logError("Unable to create default logs directory", error: error, data: ["defaultLogsDirectory": defaultLogsDirectory])
}
}
fileManager = DDLogFileManagerDefault(logsDirectory: defaultLogsDirectory)
}
super.init(logFileManager: fileManager, completionQueue: nil)
setup()
}
private func setup() {
logFormatter = BaseFileLogFormatter(mode: mode, dateFormatter: dateFormatter)
}
// ******************************* MARK: - DDFileLogger Overrides
override public func log(message logMessage: DDLogMessage) {
guard shouldLog(message: logMessage) else { return }
super.log(message: logMessage)
}
}
| 35.044118 | 154 | 0.600923 |
8a60e20188e86bba2c08e1628e5d05c6e5b92eb7 | 384 | import UIKit
import XCPlayground
let showView = UIView(frame: <#T##CGRect#>(x: 0, y: 0, width: 300, height: 300))
var window: UIWindow?
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
let rectangle = UIView(frame: <#T##CGRect#>(x: 0, y: 0, width: 300, height: 300))
| 29.538462 | 81 | 0.729167 |
ddb1ad43faea80ea3e8bc77d1d08b8c30945c26b | 4,472 | //
// DataProvider.swift
// yahna
//
// Created by Ernesto Badillo on 9/19/19.
// Copyright © 2019 Ernesto Badillo. All rights reserved.
//
import Foundation
import Combine
class DataProvider {
enum DataProviderError : Error {
case invalidItem
}
public static let shared = DataProvider()
let topStories = ItemsViewModel(.topStories)
let newStories = ItemsViewModel(.newStories)
let askStories = ItemsViewModel(.askStories)
let showStories = ItemsViewModel(.showStories)
let jobStories = ItemsViewModel(.jobStories)
private var itemsViewModelsCache: NSCache<NSNumber, ItemAndCommentsViewModel> = {
let cache = NSCache<NSNumber, ItemAndCommentsViewModel>()
cache.countLimit = 100
return cache
}()
public func itemViewModel(_ item: Item) -> ItemAndCommentsViewModel {
if let vm = itemsViewModelsCache.object(forKey: item.id as NSNumber) {
return vm
} else {
let vm = ItemAndCommentsViewModel(item)
itemsViewModelsCache.setObject(vm, forKey: item.id as NSNumber)
return vm
}
}
@discardableResult
public func refreshViewModel<T : RefreshableViewModel>(_ viewModel: T, force: Bool = false) -> AnyPublisher<T, Never> {
assert(Thread.isMainThread)
if !force,
viewModel.state.error == nil,
let lastRefreshTime = viewModel.lastRefreshTime,
Date().timeIntervalSince(lastRefreshTime) < TimeInterval(120) {
return Just(viewModel).eraseToAnyPublisher()
}
if !force,
viewModel.state.isRefreshing {
return Just(viewModel).eraseToAnyPublisher()
}
viewModel.onRefreshStarted()
let combinedPublisher: AnyPublisher<(Item?, [Item]), Error>
let parentPublisher: AnyPublisher<Item?, Error>
if case let ParentId.item(id: id) = viewModel.parentId {
parentPublisher = NetworkDataProvider.shared.getItem(id: id)
.tryMap { (jsonItem) -> Item? in
guard let item = Item(jsonItem: jsonItem) else { throw DataProviderError.invalidItem }
return item
}.eraseToAnyPublisher()
} else {
parentPublisher = Just(nil as Item?).tryMap({ $0 }).eraseToAnyPublisher()
}
let itemsPublisher = NetworkDataProvider.shared.getItems(viewModel.parentId)
.tryMap({ (jsonItems) -> [Item] in jsonItems.compactMap { (jsonItem) in Item(jsonItem: jsonItem) } })
.eraseToAnyPublisher()
combinedPublisher = parentPublisher
.combineLatest(itemsPublisher)
.eraseToAnyPublisher()
var result: [Item]?
let finalPublisher = combinedPublisher
.map({ (parent, items) -> [Item] in
if let parent = parent {
var idToItemMap = [Int64: Item]()
idToItemMap[parent.id] = parent
items.forEach { idToItemMap[$0.id] = $0 }
idToItemMap.values.forEach {
if let parentId = $0.parent, let parent = idToItemMap[parentId] {
if parent.kids == nil {
parent.kids = [Item]()
}
parent.kids?.append($0)
}
}
parent.calcDescendantCountsAndSortKids()
parent.setAllItemsAndDepths()
return [parent]
} else {
return items
}
}).receive(on: RunLoop.main)
return Future<T, Never> { promise in
_ = finalPublisher
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
viewModel.onRefreshCompleted(result, error: nil)
case .failure(let anError):
viewModel.onRefreshCompleted(result, error: anError)
}
promise(.success(viewModel))
}, receiveValue: { refreshResult in
result = refreshResult
})
}.eraseToAnyPublisher()
}
}
| 35.776 | 123 | 0.542039 |
f5db3d121945a88e766993d05a1c3a59ae90a0d5 | 433 | import Foundation
/**
Class represents the URef
*/
public class URef {
let UREF_PREFIX:String = "uref"
public var value:String?
/**
Get URef object from string
- Parameter : a String represents the URef object
- Returns: URef object
*/
public static func fromStringToUref(from:String)->URef {
let uref:URef = URef();
uref.value = from;
return uref;
}
}
| 19.681818 | 60 | 0.600462 |
39d2083929801012142466d48dc297d317e0ac95 | 906 | //
// I_am_RichTests.swift
// I am RichTests
//
// Created by Eetu Hernesniemi on 4.9.2021.
//
import XCTest
@testable import I_am_Rich
class I_am_RichTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.647059 | 111 | 0.664459 |
ab1d7fe448ab8a627f42178d2b6428b449864750 | 303 | //
// NavigationBarComponent.swift
// UILib
//
// Created by Benji Encz on 5/16/16.
// Copyright © 2016 Benjamin Encz. All rights reserved.
//
import Foundation
struct NavigationBarComponent: Component {
let leftBarButton: BarButton?
let rightBarButton: BarButton?
let title: String
}
| 18.9375 | 56 | 0.716172 |
d6a28f71a5700023a01fea6f7ce28d68b5b51c84 | 990 | public class ListNode {
public var val: Int
public var next: ListNode?
public init() { self.val = 0; self.next = nil; }
public init(_ val: Int) { self.val = val; self.next = nil; }
public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
static func from(array: [Int]) -> ListNode? {
var head: ListNode?
var last: ListNode?
for i in 0..<array.count {
let cur = ListNode(array[i])
if head == nil {
head = cur
last = cur
} else {
last?.next = cur
last = cur
}
}
return head
}
func toArray() -> [Int] {
var result = [Int]()
var cur: ListNode? = self
while cur != nil {
result.append(cur!.val)
cur = cur!.next
}
return result
}
}
//let nodes = ListNode.from(array: Array(0..<10))
//print(nodes?.toArray())
| 26.052632 | 84 | 0.475758 |
76000db38d28f7479cf68b52c09790af5dbcb0ad | 3,214 | // Copyright (C) 2019 Parrot Drones SAS
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the Parrot Company nor the names
// of its contributors may be used to endorse or promote products
// derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
import Foundation
/// Gutma Log Manager backend
protocol GutmaLogManagerBackend: class {
/// Deletes a gutma log.
///
/// - Parameter file: URL of the file gutma log file to delete
/// - Returns: `true` if the specified file exists and was successfully deleted, `false` otherwise
func delete(file: URL) -> Bool
}
/// Core implementation of the Gutma Log Manager facility
class GutmaLogManagerCore: FacilityCore, GutmaLogManager {
/// Implementation backend
private unowned let backend: GutmaLogManagerBackend
public private(set) var files = Set<URL>()
/// Constructor
///
/// - Parameters:
/// - store: Component store owning this component
/// - backend: FirmwareManagerBackend backend
public init(store: ComponentStoreCore, backend: GutmaLogManagerBackend) {
self.backend = backend
super.init(desc: Facilities.gutmaLogManager, store: store)
}
public func delete(file: URL) -> Bool {
guard files.contains(file) else {
return false
}
return backend.delete(file: file)
}
}
/// Backend callback methods
extension GutmaLogManagerCore {
/// Changes current set of converted files.
///
/// - Parameter files: new set of files
/// - Returns: self to allow call chaining
/// - Note: Changes are not notified until notifyUpdated() is called.
@discardableResult public func update(files newValue: Set<URL>) -> GutmaLogManagerCore {
if files != newValue {
files = newValue
markChanged()
}
return self
}
}
| 39.195122 | 102 | 0.692595 |
bb268638140471d62c46314cef77135b40540299 | 1,904 | //
// Created by Artur Mkrtchyan on 2/7/18.
// Copyright © 2018 Develandoo. All rights reserved.
//
import Foundation
import UIKit
protocol ReusableCell: class {
static var nibName: String { get }
static var reuseIdentifier: String { get }
}
extension ReusableCell where Self: UIView {
static var reuseIdentifier: String {
return NSStringFromClass(self)
}
static var nibName: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
extension UITableViewCell: ReusableCell {}
extension UITableView {
func register<T: ReusableCell>(_: T.Type) {
let bundle = Bundle(for: T.self)
let isIpad = UIDevice.current.userInterfaceIdiom == .pad
var nibName = isIpad ? (T.nibName + "~iPad") : T.nibName
if let _ = bundle.path(forResource: nibName, ofType: "nib") {
} else {
nibName = T.nibName
}
let nib = UINib.init(nibName: nibName, bundle: bundle)
register(nib, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: ReusableCell>(forIndexPath indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
}
extension UIView {
func parentView<T: UIView>(of type: T.Type) -> T? {
guard let view = self.superview else {
return nil
}
return (view as? T) ?? view.parentView(of: T.self)
}
}
extension UITableViewCell {
var parentTableView: UITableView? {
return self.parentView(of: UITableView.self)
}
var ip: IndexPath? {
return parentTableView?.indexPath(for: self)
}
}
| 27.594203 | 109 | 0.612395 |
01b9dac622c59e24af8dc2e8e669c938c944b08a | 873 | //
// ViewController.swift
// ButtonLoadingAnimation
//
// Created by MUKUL on 29/10/18.
// Copyright © 2018 CoderWork. All rights reserved.
//
import UIKit
class ViewController: UIViewController,DWButtonDelegates {
@IBOutlet weak var submitButton: DWSubmitButton!
override func viewDidLoad() {
super.viewDidLoad()
submitButton.delegate = self
}
//DWSubmit Button
func selectedItemActionWithReference(sender: UIButton) {
print("button clicked")
//self.updateTestProgress(progressVal: 0.0)
submitButton.updatingDefaultProgressUntilDone = true
DispatchQueue.main.asyncAfter(deadline: .now() + 14) {
self.submitButton.completeDefaultProgress = true
}
}
func progressCompleted() {
print("progress is being completed")
}
}
| 21.292683 | 62 | 0.648339 |
e541e4958baeb8e778dd6815efac8598fcc25b74 | 744 | //
// Artist.swift
// WStest
//
// Created by Sebastian Cohausz on 12.08.18.
// Copyright © 2018 scgmbh. All rights reserved.
//
import Foundation
struct Artist: Category {
static func browseComponent(parentItem: Category?) -> BrowseComponent! {
return ArtistBrowseComponent(parentItem: parentItem)
}
static func nextType() -> Category.Type? {
return Album.self
}
let title: String
let uri: String
let type: String
let albumArt: String
let service: String
enum CodingKeys: String, CodingKey {
case title
case uri
case type
case albumArt = "albumart"
case service
}
static var categoryType: CategoryType = .artist
}
| 21.257143 | 76 | 0.627688 |
f7866da4c2b38da2168ce7f52f0bcd1762d2e6f2 | 1,436 | //
// RegisterView.swift
// SwiftUILogin
//
// Created by Derek Yang on 2019-12-26.
// Copyright © 2019 Derek Yang. All rights reserved.
//
import SwiftUI
import Combine
struct RegisterView: View {
@ObservedObject var state: RegisterViewModel
var body: some View {
VStack {
Text("Register new user")
.font(.largeTitle)
.padding()
HStack {
TextField("Username", text: $state.username)
.textFieldStyle(RoundedBorderTextFieldStyle())
if state.isUsernameValid {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
}
}
HStack {
TextField("Passcode", text: $state.passcode)
.keyboardType(.numberPad)
.textFieldStyle(RoundedBorderTextFieldStyle())
if state.isPasscodeValid {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
}
}
HStack {
TextField("Repeat Passcode", text: $state.repeatPasscode)
.keyboardType(.numberPad)
.textFieldStyle(RoundedBorderTextFieldStyle())
if state.isRepeatPasscodeValid {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
}
}
Button(action: {}) {
Text("Register")
}
.disabled(!state.allValid)
Spacer()
}
.frame(minWidth: 200, maxWidth: 300)
}
}
struct RegisterView_Previews: PreviewProvider {
static var previews: some View {
RegisterView(state: RegisterViewModel())
}
}
| 21.757576 | 61 | 0.664345 |
4624641cabbb71fc33e9b86ca594d6a696a8f5da | 4,815 | //
// WeChatBottomAlert.swift
// WeChat
//
// Created by Smile on 16/1/12.
// Copyright © 2016年 [email protected]. All rights reserved.
//
import UIKit
class WeChatBottomAlert: WeChatDrawView {
//MARKS: Properties
var isLayedOut:Bool = false//是否初始化view
var fontSize:CGFloat = 12//默认字体大小
var labelHeight:CGFloat = 25//默认标签高度
var titles = [String]()
var colors = [UIColor]()
let paddintLeft:CGFloat = 30//padding-left
let paddintTop:CGFloat = 15//padding-top
let titleFontName:String = "Avenir-Light"//默认标题字体名称
let fontName:String = "Cochin-Bold "//加粗字体
let rectHeight:CGFloat = 5;//矩形高度
var oneBlockHeight:CGFloat = 0//一块区域的高度
var oneBlockWidth:CGFloat = 0//一块区域的宽度
var otherSize:CGFloat = 18
var originX:CGFloat = 0//开始绘制x坐标
var originY:CGFloat = 0//开始绘制y坐标
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(frame: CGRect,titles:[String],colors:[UIColor]?,fontSize:CGFloat) {
//MARKS: 初始化数据
if fontSize > 0 {
self.fontSize = fontSize
}
if colors != nil {
self.colors = colors!
}
self.titles = titles
oneBlockHeight = labelHeight + paddintTop * 2
oneBlockWidth = frame.size.width - paddintLeft * 2
//MARKS: 获取Alert总高度
var totalHeight:CGFloat = 0
for(var i = 0;i < titles.count;i++){
if !titles[i].isEmpty {
totalHeight += oneBlockHeight
}
}
totalHeight += 5
var y:CGFloat = 0
if frame.origin.y < 0 {
if frame.size.height <= 0 {
y = UIScreen.mainScreen().bounds.height - totalHeight
}
}else{
y = frame.origin.y
}
originX = frame.origin.x
originY = y
//super.init(frame: CGRectMake(frame.origin.x, y, frame.size.width, totalHeight))
//初始化整个屏幕
super.init(frame: UIScreen.mainScreen().bounds)
//设置背景
self.backgroundColor = UIColor(patternImage: UIImage(named: "bg")!)
//self.alpha = 0.8
}
override func layoutSubviews() {
super.layoutSubviews()
//let shapeLayer = self.setUp()
if !isLayedOut {
//shapeLayer.frame.origin = CGPointZero
//shapeLayer.frame.size = self.layer.frame.size
if titles.count <= 1 {
return
}
var _originY:CGFloat = originY
var size:CGFloat = fontSize
for(var i = 0;i < titles.count;i++){
if titles[i].isEmpty {
continue;
}
if i == 0 {
size = fontSize
} else {
size = otherSize
}
if i != (titles.count - 1) {
var color:UIColor
var fontName:String = titleFontName
if self.colors.count > 0 {
color = self.colors[i]
} else {
color = UIColor.blackColor()
}
if i == 0 {
fontName = titleFontName
}else{
fontName = self.fontName
}
self.addSubview(drawAlertLabel(titles[i],y: _originY,size: size,color:color,isBold: false,fontName: fontName,width:UIScreen.mainScreen().bounds.width,height: oneBlockHeight))
_originY += oneBlockHeight
if titles.count >= 3 {
if i != (titles.count - 2) {
self.layer.addSublayer(drawLine(beginPointX: 0, beginPointY: _originY, endPointX: self.frame.size.width, endPointY: _originY))
}else{
self.layer.addSublayer(drawRect(beginPointX: 0, beginPointY: _originY, width: self.frame.size.width, height: rectHeight))
_originY += rectHeight
}
}
}else{
self.addSubview(drawAlertLabel(titles[i],y: _originY,size: size,color: UIColor.blackColor(),isBold: true,fontName: fontName,width:UIScreen.mainScreen().bounds.width,height: oneBlockHeight))
}
}
isLayedOut = true
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
super.removeFromSuperview()
}
}
| 32.533784 | 209 | 0.505711 |
e05786cd89aa03c86ff90f00adc9e92a77bc209b | 3,066 | //
// AppDelegate.swift
// iOSSBackAPI
//
// Created by Matheus Ribeiro on 06/07/2017.
// Copyright (c) 2017 Matheus Ribeiro. All rights reserved.
// FIVE'S DEVELOPMENT LTDA
import UIKit
import MapKit
import iOSSBackAPI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, iOSSBackAPIDelegate{
var window: UIWindow?
var sback:iOSSBackAPI!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
sback = iOSSBackAPI(key: "0a0ec49bff3978d7ce232aecf34f19a9", email: "[email protected]", cellphone: nil, uid: nil, del:self, rangeInKm: 1)
sback.pinCheck = true
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:.
}
//MARK: iOSSBackAPIDelegate
/*
func notificateWhenAPPIsActive(store_id: String, title: String, message: String) {
//Called when the application is active and the notification needs send
}
func userClickedInNotificationSBack() {
//Called when the user click in the notification SBack
}
*/
func pointsLoaded(points:[CLCircularRegion]) {
//Called when the points of region was load
(window?.rootViewController as! ViewController).points = points
(window?.rootViewController as! ViewController).addPoint()
}
}
| 45.761194 | 285 | 0.736791 |
eb876d0a4a00af434128cf9185016d56eee4c542 | 1,606 | //
// VectorableOperationsSpec.swift
// Tests
//
// Created by Dmitry Duleba on 3/23/19.
//
import XCTest
import Nimble
@testable import Alidade
//swiftlint:disable identifier_name
class VectorableOperationsSpec: XCTestCase {
final class PointsGenerator {
func randomFoundationPoint() -> CGPoint {
return CGPoint(x: CGFloat.random(in: -1000...1000), y: CGFloat.random(in: -1000...1000))
}
func randomSIMDPoint() -> CGPoint {
return CGPoint.random(in: -1000...1000)
}
}
func testRandom() {
let value = PointsGenerator().randomSIMDPoint()
expect(value.x).to(beGreaterThanOrEqualTo(-1000))
expect(value.y).to(beGreaterThanOrEqualTo(-1000))
expect(value.x).to(beLessThanOrEqualTo(1000))
expect(value.y).to(beLessThanOrEqualTo(1000))
}
func testPerformanceFoundationRandomGenerator() {
let generator = PointsGenerator()
measure {
for _ in 0...1_000 {
_ = generator.randomFoundationPoint()
}
}
}
func testPerformanceSIMDRandomGenerator() {
let generator = PointsGenerator()
measure {
for _ in 0...1_000 {
_ = generator.randomSIMDPoint()
}
}
}
func testAddPerformance() {
let generator = PointsGenerator()
measure {
for _ in 0...1_000 {
let p0 = generator.randomSIMDPoint()
let p1 = generator.randomSIMDPoint()
_ = p0 + p1
}
}
}
func testInterintegerOperations() {
let point = CGPoint([3, -4])
expect(point * 2.int).to(equal(CGPoint([6, -8])))
expect(point * Double(2)).to(equal(CGPoint([6, -8])))
}
}
| 22.619718 | 94 | 0.640722 |
e8e566c0635c81144f00abb9d239e3428d92e109 | 3,336 | //
// ReAuthenticateView.swift
// Firebase Login
//
// Created by Stewart Lynch on 2021-07-05.
// Copyright © 2021 CreaTECH Solutions. All rights reserved.
//
import SwiftUI
struct ReAuthenticateView: View {
@Binding var providers: [FBAuth.ProviderType]
@Binding var canDelete: Bool
@State private var password = ""
@State private var errorText = ""
var body: some View {
ZStack {
Color(.gray).opacity(0.4)
.ignoresSafeArea()
VStack {
if providers.count == 2 {
Text("Choose the option that you used to log in.")
.frame(height: 60)
.padding(.horizontal)
}
ForEach(providers, id: \.self) { provider in
if provider == .apple {
SignInWithAppleButtonView(handleResult: handleResult)
.padding(.top)
} else {
VStack {
SecureField("Enter your password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Authenticate") {
FBAuth.reauthenticateWithPassword(password: password) { result in
handleResult(result: result)
}
}
.padding(.vertical, 15)
.frame(width: 200)
.background(Color.blue)
.cornerRadius(8)
.foregroundColor(.white)
.opacity(password.isEmpty ? 0.6 : 1)
.disabled(password.isEmpty)
}
.padding()
}
}
Text(errorText)
.foregroundColor(.red)
.fixedSize(horizontal: false, vertical: true)
Button("Cancel") {
withAnimation {
providers = []
}
}
.padding(8)
.foregroundColor(.primary)
.background(Color(.secondarySystemBackground))
.overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.gray, lineWidth: 1))
Spacer()
}
.frame(width: 250, height: providers.count == 2 ? 350 : 230)
.background(Color(.systemBackground))
.clipShape(RoundedRectangle(cornerRadius: 30, style: .continuous))
.shadow(color: .black.opacity(0.2), radius: 20, x: 0, y: 20)
}
}
func handleResult(result: Result<Bool,Error>) {
switch result {
case .success:
// Reauthenticated now so you can delete
canDelete = true
withAnimation {
providers = []
}
case .failure(let error):
errorText = error.localizedDescription
}
}
}
struct ReAuthenticateView_Previews: PreviewProvider {
static var previews: some View {
ReAuthenticateView(providers: .constant([.apple, .password]), canDelete: .constant(false))
}
}
| 37.066667 | 98 | 0.468225 |
1176e170a98587b65ebde2d401f08881f6780f65 | 663 | //
// Response.swift
// Miio
//
// Created by Maksim Kolesnik on 05/02/2020.
//
import Foundation
public protocol Response: Collection where Element == UInt8 {
var packet: [Element] { get }
}
extension Response {
public func makeIterator() -> IndexingIterator<[Element]> {
return packet.makeIterator()
}
public func index(after i: Int) -> Int {
return packet.index(after: i)
}
public subscript(position: Int) -> Element {
return packet[position]
}
public var startIndex: Int {
return packet.startIndex
}
public var endIndex: Int {
return packet.endIndex
}
}
| 19.5 | 63 | 0.613876 |
d6cbdacc21c0d584d03d8d6bfdbb3625898d8c5a | 1,708 | //
// Ahrs2ArdupilotmegaMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// Status of secondary AHRS filter if available
public struct Ahrs2 {
/// Roll angle (rad)
public let roll: Float
/// Pitch angle (rad)
public let pitch: Float
/// Yaw angle (rad)
public let yaw: Float
/// Altitude (MSL)
public let altitude: Float
/// Latitude in degrees * 1E7
public let lat: Int32
/// Longitude in degrees * 1E7
public let lng: Int32
}
extension Ahrs2: Message {
public static let id = UInt8(178)
public static var typeName = "AHRS2"
public static var typeDescription = "Status of secondary AHRS filter if available"
public static var fieldDefinitions: [FieldDefinition] = [("roll", 0, "Float", 0, "Roll angle (rad)"), ("pitch", 4, "Float", 0, "Pitch angle (rad)"), ("yaw", 8, "Float", 0, "Yaw angle (rad)"), ("altitude", 12, "Float", 0, "Altitude (MSL)"), ("lat", 16, "Int32", 0, "Latitude in degrees * 1E7"), ("lng", 20, "Int32", 0, "Longitude in degrees * 1E7")]
public init(data: Data) throws {
roll = try data.number(at: 0)
pitch = try data.number(at: 4)
yaw = try data.number(at: 8)
altitude = try data.number(at: 12)
lat = try data.number(at: 16)
lng = try data.number(at: 20)
}
public func pack() throws -> Data {
var payload = Data(count: 24)
try payload.set(roll, at: 0)
try payload.set(pitch, at: 4)
try payload.set(yaw, at: 8)
try payload.set(altitude, at: 12)
try payload.set(lat, at: 16)
try payload.set(lng, at: 20)
return payload
}
}
| 28.949153 | 352 | 0.653396 |
38873a27c07c9bc3574b21ee8b4745c25b68847e | 1,651 | //
// MathTools.swift
// MeditationPlus
//
// Created by Erik Luimes on 12/09/15.
//
// The MIT License
// Copyright (c) 2015 Maya Interactive. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Except as contained in this notice, the name of Maya Interactive and Meditation+
// shall not be used in advertising or otherwise to promote the sale, use or other
// dealings in this Software without prior written authorization from Maya Interactive.
//
import Foundation
func clamp<T:Comparable>(value: T, lowerBound: T, upperBound: T) -> T
{
return min(max(lowerBound, value), upperBound)
}
| 42.333333 | 87 | 0.754088 |
26ba10c456e3433045d5f82f39e793d4ddd08290 | 786 | //
// Category.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** A category for a pet */
public struct Category: Codable, Hashable {
public var id: Int64?
public var name: String?
public init(id: Int64? = nil, name: String? = nil) {
self.id = id
self.name = name
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case id
case name
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encodeIfPresent(name, forKey: .name)
}
}
| 21.243243 | 67 | 0.651399 |
0a87f9eeb98e1a67afc080ae2cee90d29eb0b699 | 3,539 | //
// Zip.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
protocol ZipSinkProtocol : class
{
func next(_ index: Int)
func fail(_ error: Swift.Error)
func done(_ index: Int)
}
class ZipSink<O: ObserverType> : Sink<O>, ZipSinkProtocol {
typealias Element = O.E
let _arity: Int
let _lock = NSRecursiveLock()
// state
private var _isDone: [Bool]
init(arity: Int, observer: O) {
_isDone = [Bool](repeating: false, count: arity)
_arity = arity
super.init(observer: observer)
}
func getResult() throws -> Element {
abstractMethod()
}
func hasElements(_ index: Int) -> Bool {
abstractMethod()
}
func next(_ index: Int) {
var hasValueAll = true
for i in 0 ..< _arity {
if !hasElements(i) {
hasValueAll = false
break
}
}
if hasValueAll {
do {
let result = try getResult()
self.forwardOn(.next(result))
}
catch let e {
self.forwardOn(.error(e))
dispose()
}
}
else {
var allOthersDone = true
let arity = _isDone.count
for i in 0 ..< arity {
if i != index && !_isDone[i] {
allOthersDone = false
break
}
}
if allOthersDone {
forwardOn(.completed)
self.dispose()
}
}
}
func fail(_ error: Swift.Error) {
forwardOn(.error(error))
dispose()
}
func done(_ index: Int) {
_isDone[index] = true
var allDone = true
for done in _isDone {
if !done {
allDone = false
break
}
}
if allDone {
forwardOn(.completed)
dispose()
}
}
}
class ZipObserver<ElementType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias E = ElementType
typealias ValueSetter = (ElementType) -> ()
private var _parent: ZipSinkProtocol?
let _lock: NSRecursiveLock
// state
private let _index: Int
private let _this: Disposable
private let _setNextValue: ValueSetter
init(lock: NSRecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) {
_lock = lock
_parent = parent
_index = index
_this = this
_setNextValue = setNextValue
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
if let _ = _parent {
switch event {
case .next(_):
break
case .error(_):
_this.dispose()
case .completed:
_this.dispose()
}
}
if let parent = _parent {
switch event {
case .next(let value):
_setNextValue(value)
parent.next(_index)
case .error(let error):
parent.fail(error)
case .completed:
parent.done(_index)
}
}
}
}
| 22.398734 | 125 | 0.478384 |
1d8d2c247722c4d966584251845f3f7fb4c2eaf4 | 3,122 | //
// Array+TableSection.swift
// FunctionalTableData
//
// Created by Sherry Shao on 2018-06-14.
// Copyright © 2018 Shopify. All rights reserved.
//
import UIKit
extension Array where Element: TableSectionType {
func validateKeyUniqueness(senderName: String) {
let sectionKeys = map { $0.key }
if Set(sectionKeys).count != count {
let dupKeys = duplicateKeys()
let reason = "\(senderName) : Duplicate Section keys"
let userInfo: [String: Any] = ["Duplicates": dupKeys]
NSException(name: NSExceptionName.internalInconsistencyException, reason: reason, userInfo: userInfo).raise()
}
for section in self {
let rowKeys = section.rows.map { $0.key }
if Set(rowKeys).count != section.rows.count {
let dupKeys = section.rows.duplicateKeys()
let reason = "\(senderName) : Duplicate Section.Row keys"
let userInfo: [String: Any] = ["Section": section.key, "Duplicates": dupKeys]
NSException(name: NSExceptionName.internalInconsistencyException, reason: reason, userInfo: userInfo).raise()
}
}
}
}
extension Array where Element == CollectionSection {
func validateKeyUniqueness(senderName: String) {
let sectionKeys = map { $0.key }
if Set(sectionKeys).count != count {
let dupKeys = map{ $0.key }.duplicates()
let reason = "\(senderName) : Duplicate Section keys"
let userInfo: [String: Any] = ["Duplicates": dupKeys]
NSException(name: NSExceptionName.internalInconsistencyException, reason: reason, userInfo: userInfo).raise()
}
for section in self {
let itemKeys = section.items.map { $0.key }
if Set(itemKeys).count != section.items.count {
let dupKeys = section.items.duplicateKeys()
let reason = "\(senderName) : Duplicate Section.Row keys"
let userInfo: [String: Any] = ["Section": section.key, "Duplicates": dupKeys]
NSException(name: NSExceptionName.internalInconsistencyException, reason: reason, userInfo: userInfo).raise()
}
}
}
}
extension Array where Element: TableSectionType {
func indexPath(from itemPath: ItemPath) -> IndexPath? {
if let sectionIndex = self.firstIndex(where: { $0.key == itemPath.sectionKey }), let rowIndex = self[sectionIndex].rows.firstIndex(where: { $0.key == itemPath.rowKey }) {
return IndexPath(row: rowIndex, section: sectionIndex)
}
return nil
}
func itemPath(from indexPath: IndexPath) -> ItemPath {
let section = self[indexPath.section]
let row = section.rows[indexPath.row]
return ItemPath(sectionKey: section.key, itemKey: row.key)
}
}
private extension Array where Element: Hashable {
func duplicates() -> [Element] {
let groups = Dictionary(grouping: self, by: { $0 }).filter { $1.count > 1 }
return Array(groups.keys)
}
}
private extension Array where Element: TableSectionType {
func duplicateKeys() -> [String] {
return map { $0.key }.duplicates()
}
}
private extension Array where Element == CellConfigType {
func duplicateKeys() -> [String] {
return map { $0.key }.duplicates()
}
}
private extension Array where Element: HashableCellConfigType {
func duplicateKeys() -> [String] {
return map { $0.key }.duplicates()
}
}
| 33.212766 | 172 | 0.704356 |
d9791e9277309e35df410ae1fd5055bd07d502ef | 1,294 | //
// This source file is part of the Web3Swift.io open source project
// Copyright 2018 The Web3Swift Authors
// Licensed under Apache License v2.0
//
// LastBytesTests.swift
//
// Created by Timofey Solonin on 10/05/2018
//
import Nimble
import Quick
@testable import Web3Swift
final class LastBytesTests: XCTestCase {
func testTakesLastBytesCorrectlyWhenSufficient() {
expect{
try LastBytes(
origin: SimpleBytes(
bytes: [
0x01, 0x02, 0x03, 0x04, 0x05
]
),
length: 3
).value()
}.to(
equal(
Data(
[
0x03, 0x04, 0x05
]
)
)
)
}
func testTakesLastBytesCorrectlyWhenInsufficient() {
expect{
try LastBytes(
origin: SimpleBytes(
bytes: [
0x01, 0x02
]
),
length: 3
).value()
}.to(
equal(
Data(
[
0x01, 0x02
]
)
)
)
}
}
| 21.566667 | 67 | 0.395672 |
5bff5a8790f65a50d4b0250ec16c8532dfd72d70 | 876 | //
// NDAViewController.swift
// Ringo-iOS
//
// Created by Gautam Mittal on 6/12/15.
// Copyright © 2015 Gautam Mittal. All rights reserved.
//
import UIKit
class NDAViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.333333 | 106 | 0.674658 |
e5cdcb5cecb1598a03200a651fbc76559842bdac | 2,901 | //
// YYShopcartBottomView.swift
// DiYa
//
// Created by wangyang on 2017/12/18.
// Copyright © 2017年 wangyang. All rights reserved.
//
import UIKit
@objc protocol YYShopcartBottomViewDelegate {
@objc optional
func didAllSelectedGoods(isSelected:Bool)
func didCommitOrder()
func didClickDeleteGoods()
func didClickFavorateGoods()
}
class YYShopcartBottomView: UIView {
@IBOutlet weak var priceLabel : UILabel!
@IBOutlet weak var deleteButton : UIButton!
@IBOutlet weak var favorateButton : UIButton!
@IBOutlet weak var commitButton : UIButton!
@IBOutlet weak var selectedButton : UIButton!
weak var delegate : YYShopcartBottomViewDelegate?
var isEditing : Bool? {
didSet {
guard let isEditing = isEditing else {
return
}
if isEditing {
deleteButton.isHidden = false
favorateButton.isHidden = false
priceLabel.isHidden = true
commitButton.isHidden = true
}else {
deleteButton.isHidden = true
favorateButton.isHidden = true
priceLabel.isHidden = false
commitButton.isHidden = false
}
}
}
var allSelected : Bool? {
didSet {
guard let allSelected = allSelected else {
return
}
selectedButton.isSelected = allSelected
}
}
var price:String? {
didSet {
guard let price = price else {
return
}
let string = "合计:¥\(price)(不含运费)"
let attributedStr = NSMutableAttributedString(string: string)
attributedStr.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 12),
NSAttributedStringKey.foregroundColor:UIColor.hexString(colorString: "333333")], range: NSRange(location: 0, length: 3))
attributedStr.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)], range: NSRange(location: 3, length: string.count - 3 - 6))
attributedStr.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 10)], range: NSRange(location: string.count - 6, length: 6))
priceLabel.attributedText = attributedStr
}
}
@IBAction func clickSelectedButton(_ sender : UIButton) {
sender.isSelected = !sender.isSelected
delegate?.didAllSelectedGoods?(isSelected: sender.isSelected)
}
@IBAction func commitOrder(_ sender : UIButton) {
delegate?.didCommitOrder()
}
@IBAction func favoriteGoods(_ sender : UIButton) {
delegate?.didClickFavorateGoods()
}
@IBAction func deleteButton(_ sender : UIButton) {
delegate?.didClickDeleteGoods()
}
}
| 31.879121 | 161 | 0.608066 |
f52caf57acdeb98862e6ca9ed34cda4c1f8e9183 | 17,734 | // Must be able to run xcrun-return-self.sh
// REQUIRES: shell
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -static-stdlib %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix SIMPLE_STATIC -implicit-check-not -rpath %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-none-linux-androideabi -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7 %s < %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7-NEGATIVE %s < %t.android.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.cygwin.txt
// RUN: %FileCheck -check-prefix CYGWIN-x86_64 %s < %t.cygwin.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.windows.txt
// RUN: %FileCheck -check-prefix WINDOWS-x86_64 %s < %t.windows.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-unknown-linux-gnu %s -Lbar -o dynlib.out 2>&1 > %t.linux.dynlib.txt
// RUN: %FileCheck -check-prefix LINUX_DYNLIB-x86_64 %s < %t.linux.dynlib.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Fsystem car -F cdr -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 -Xlinker -rpath -Xlinker customrpath -L foo %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix IOS-linker-order %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Xlinker -rpath -Xlinker customrpath -L foo %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-linker-order %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Xclang-linker -foo -Xclang-linker foopath %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-clang-linker-order %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -Xclang-linker -foo -Xclang-linker foopath %s 2>&1 > %t.windows.txt
// RUN: %FileCheck -check-prefix WINDOWS-clang-linker-order %s < %t.windows.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | %FileCheck -check-prefix DEBUG %s
// RUN: %empty-directory(%t)
// RUN: touch %t/a.o
// RUN: touch %t/a.swiftmodule
// RUN: touch %t/b.o
// RUN: touch %t/b.swiftmodule
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o %t/a.swiftmodule %t/b.o %t/b.swiftmodule -o linker | %FileCheck -check-prefix LINK-SWIFTMODULES %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s > %t.simple-macosx10.10.txt
// RUN: %FileCheck %s < %t.simple-macosx10.10.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple-macosx10.10.txt
// RUN: %empty-directory(%t)
// RUN: touch %t/a.o
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | %FileCheck -check-prefix COMPILE_AND_LINK %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-filelist-threshold=0 -o linker 2>&1 | %FileCheck -check-prefix FILELIST %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_LINUX %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s
// Here we specify an output file name using '-o'. For ease of writing these
// tests, we happen to specify the same file name as is inferred in the
// INFERRED_NAMED_DARWIN tests above: 'libLINKER.dylib'.
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s
// There are more RUN lines further down in the file.
// CHECK: swift
// CHECK: -o [[OBJECTFILE:.*]]
// CHECK-NEXT: {{(bin/)?}}ld{{"? }}
// CHECK-DAG: [[OBJECTFILE]]
// CHECK-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)macosx]]
// CHECK-DAG: -rpath [[STDLIB_PATH]]
// CHECK-DAG: -lSystem
// CHECK-DAG: -arch x86_64
// CHECK: -o {{[^ ]+}}
// SIMPLE: {{(bin/)?}}ld{{"? }}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -o linker
// SIMPLE_STATIC: swift
// SIMPLE_STATIC: -o [[OBJECTFILE:.*]]
// SIMPLE_STATIC-NEXT: {{(bin/)?}}ld{{"? }}
// SIMPLE_STATIC: [[OBJECTFILE]]
// SIMPLE_STATIC: -lobjc
// SIMPLE_STATIC: -lSystem
// SIMPLE_STATIC: -arch x86_64
// SIMPLE_STATIC: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift_static(/|\\\\)macosx]]
// SIMPLE_STATIC: -lc++
// SIMPLE_STATIC: -framework Foundation
// SIMPLE_STATIC: -force_load_swift_libs
// SIMPLE_STATIC: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}}
// SIMPLE_STATIC: -no_objc_category_merging
// SIMPLE_STATIC: -o linker
// IOS_SIMPLE: swift
// IOS_SIMPLE: -o [[OBJECTFILE:.*]]
// IOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// IOS_SIMPLE-DAG: [[OBJECTFILE]]
// IOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)iphonesimulator}}
// IOS_SIMPLE-DAG: -lSystem
// IOS_SIMPLE-DAG: -arch x86_64
// IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}}
// IOS_SIMPLE: -o linker
// tvOS_SIMPLE: swift
// tvOS_SIMPLE: -o [[OBJECTFILE:.*]]
// tvOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// tvOS_SIMPLE-DAG: [[OBJECTFILE]]
// tvOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)appletvsimulator}}
// tvOS_SIMPLE-DAG: -lSystem
// tvOS_SIMPLE-DAG: -arch x86_64
// tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}}
// tvOS_SIMPLE: -o linker
// watchOS_SIMPLE: swift
// watchOS_SIMPLE: -o [[OBJECTFILE:.*]]
// watchOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// watchOS_SIMPLE-DAG: [[OBJECTFILE]]
// watchOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)watchsimulator}}
// watchOS_SIMPLE-DAG: -lSystem
// watchOS_SIMPLE-DAG: -arch i386
// watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}}
// watchOS_SIMPLE: -o linker
// LINUX-x86_64: swift
// LINUX-x86_64: -o [[OBJECTFILE:.*]]
// LINUX-x86_64: clang++{{(\.exe)?"? }}
// LINUX-x86_64-DAG: -pie
// LINUX-x86_64-DAG: [[OBJECTFILE]]
// LINUX-x86_64-DAG: -lswiftCore
// LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-x86_64-DAG: -F foo -iframework car -F cdr
// LINUX-x86_64-DAG: -framework bar
// LINUX-x86_64-DAG: -L baz
// LINUX-x86_64-DAG: -lboo
// LINUX-x86_64-DAG: -Xlinker -undefined
// LINUX-x86_64: -o linker
// LINUX-armv6: swift
// LINUX-armv6: -o [[OBJECTFILE:.*]]
// LINUX-armv6: clang++{{(\.exe)?"? }}
// LINUX-armv6-DAG: -pie
// LINUX-armv6-DAG: [[OBJECTFILE]]
// LINUX-armv6-DAG: -lswiftCore
// LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-armv6-DAG: -target armv6-unknown-linux-gnueabihf
// LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv6-DAG: -F foo -iframework car -F cdr
// LINUX-armv6-DAG: -framework bar
// LINUX-armv6-DAG: -L baz
// LINUX-armv6-DAG: -lboo
// LINUX-armv6-DAG: -Xlinker -undefined
// LINUX-armv6: -o linker
// LINUX-armv7: swift
// LINUX-armv7: -o [[OBJECTFILE:.*]]
// LINUX-armv7: clang++{{(\.exe)?"? }}
// LINUX-armv7-DAG: -pie
// LINUX-armv7-DAG: [[OBJECTFILE]]
// LINUX-armv7-DAG: -lswiftCore
// LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-armv7-DAG: -target armv7-unknown-linux-gnueabihf
// LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv7-DAG: -F foo -iframework car -F cdr
// LINUX-armv7-DAG: -framework bar
// LINUX-armv7-DAG: -L baz
// LINUX-armv7-DAG: -lboo
// LINUX-armv7-DAG: -Xlinker -undefined
// LINUX-armv7: -o linker
// LINUX-thumbv7: swift
// LINUX-thumbv7: -o [[OBJECTFILE:.*]]
// LINUX-thumbv7: clang++{{(\.exe)?"? }}
// LINUX-thumbv7-DAG: -pie
// LINUX-thumbv7-DAG: [[OBJECTFILE]]
// LINUX-thumbv7-DAG: -lswiftCore
// LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-thumbv7-DAG: -target thumbv7-unknown-linux-gnueabihf
// LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-thumbv7-DAG: -F foo -iframework car -F cdr
// LINUX-thumbv7-DAG: -framework bar
// LINUX-thumbv7-DAG: -L baz
// LINUX-thumbv7-DAG: -lboo
// LINUX-thumbv7-DAG: -Xlinker -undefined
// LINUX-thumbv7: -o linker
// ANDROID-armv7: swift
// ANDROID-armv7: -o [[OBJECTFILE:.*]]
// ANDROID-armv7: clang++{{(\.exe)?"? }}
// ANDROID-armv7-DAG: -pie
// ANDROID-armv7-DAG: [[OBJECTFILE]]
// ANDROID-armv7-DAG: -lswiftCore
// ANDROID-armv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift]]
// ANDROID-armv7-DAG: -target armv7-none-linux-androideabi
// ANDROID-armv7-DAG: -F foo -iframework car -F cdr
// ANDROID-armv7-DAG: -framework bar
// ANDROID-armv7-DAG: -L baz
// ANDROID-armv7-DAG: -lboo
// ANDROID-armv7-DAG: -Xlinker -undefined
// ANDROID-armv7: -o linker
// ANDROID-armv7-NEGATIVE-NOT: -Xlinker -rpath
// CYGWIN-x86_64: swift
// CYGWIN-x86_64: -o [[OBJECTFILE:.*]]
// CYGWIN-x86_64: clang++{{(\.exe)?"? }}
// CYGWIN-x86_64-DAG: [[OBJECTFILE]]
// CYGWIN-x86_64-DAG: -lswiftCore
// CYGWIN-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift]]
// CYGWIN-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// CYGWIN-x86_64-DAG: -F foo -iframework car -F cdr
// CYGWIN-x86_64-DAG: -framework bar
// CYGWIN-x86_64-DAG: -L baz
// CYGWIN-x86_64-DAG: -lboo
// CYGWIN-x86_64-DAG: -Xlinker -undefined
// CYGWIN-x86_64: -o linker
// WINDOWS-x86_64: swift
// WINDOWS-x86_64: -o [[OBJECTFILE:.*]]
// WINDOWS-x86_64: clang++{{(\.exe)?"? }}
// WINDOWS-x86_64-DAG: [[OBJECTFILE]]
// WINDOWS-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)windows(/|\\\\)x86_64]]
// WINDOWS-x86_64-DAG: -F foo -iframework car -F cdr
// WINDOWS-x86_64-DAG: -framework bar
// WINDOWS-x86_64-DAG: -L baz
// WINDOWS-x86_64-DAG: -lboo
// WINDOWS-x86_64-DAG: -Xlinker -undefined
// WINDOWS-x86_64: -o linker
// COMPLEX: {{(bin/)?}}ld{{"? }}
// COMPLEX-DAG: -dylib
// COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -lfoo
// COMPLEX-DAG: -framework bar
// COMPLEX-DAG: -L baz
// COMPLEX-DAG: -F garply -F car -F cdr
// COMPLEX-DAG: -undefined dynamic_lookup
// COMPLEX-DAG: -macosx_version_min 10.9.1
// COMPLEX: -o sdk.out
// LINUX_DYNLIB-x86_64: swift
// LINUX_DYNLIB-x86_64: -o [[OBJECTFILE:.*]]
// LINUX_DYNLIB-x86_64: -o {{"?}}[[AUTOLINKFILE:.*]]
// LINUX_DYNLIB-x86_64: clang++{{(\.exe)?"? }}
// LINUX_DYNLIB-x86_64-DAG: -shared
// LINUX_DYNLIB-x86_64-DAG: -fuse-ld=gold
// LINUX_DYNLIB-x86_64-NOT: -pie
// LINUX_DYNLIB-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux]]
// LINUX_DYNLIB-x86_64: [[STDLIB_PATH]]{{/|\\\\}}x86_64{{/|\\\\}}swiftrt.o
// LINUX_DYNLIB-x86_64-DAG: [[OBJECTFILE]]
// LINUX_DYNLIB-x86_64-DAG: @[[AUTOLINKFILE]]
// LINUX_DYNLIB-x86_64-DAG: [[STDLIB_PATH]]
// LINUX_DYNLIB-x86_64-DAG: -lswiftCore
// LINUX_DYNLIB-x86_64-DAG: -L bar
// LINUX_DYNLIB-x86_64: -o dynlib.out
// IOS-linker-order: swift
// IOS-linker-order: -o [[OBJECTFILE:.*]]
// IOS-linker-order: {{(bin/)?}}ld{{"? }}
// IOS-linker-order: -rpath [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)iphonesimulator]]
// IOS-linker-order: -L foo
// IOS-linker-order: -rpath customrpath
// IOS-linker-order: -o {{.*}}
// LINUX-linker-order: swift
// LINUX-linker-order: -o [[OBJECTFILE:.*]]
// LINUX-linker-order: clang++{{(\.exe)?"? }}
// LINUX-linker-order: -Xlinker -rpath -Xlinker {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux}}
// LINUX-linker-order: -L foo
// LINUX-linker-order: -Xlinker -rpath -Xlinker customrpath
// LINUX-linker-order: -o {{.*}}
// LINUX-clang-linker-order: swift
// LINUX-clang-linker-order: -o [[OBJECTFILE:.*]]
// LINUX-clang-linker-order: clang++{{"? }}
// LINUX-clang-linker-order: -foo foopath
// LINUX-clang-linker-order: -o {{.*}}
// WINDOWS-clang-linker-order: swift
// WINDOWS-clang-linker-order: -o [[OBJECTFILE:.*]]
// WINDOWS-clang-linker-order: clang++{{"? }}
// WINDOWS-clang-linker-order: -foo foopath
// WINDOWS-clang-linker-order: -o {{.*}}
// DEBUG: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// DEBUG-NEXT: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// DEBUG-NEXT: {{(bin/)?}}ld{{"? }}
// DEBUG: -add_ast_path {{.*(/|\\\\)[^/]+}}.swiftmodule
// DEBUG: -o linker
// DEBUG-NEXT: bin{{/|\\\\}}dsymutil
// DEBUG: linker
// DEBUG: -o linker.dSYM
// LINK-SWIFTMODULES: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// LINK-SWIFTMODULES-NEXT: {{(bin/)?}}ld{{"? }}
// LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/a.swiftmodule
// LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/b.swiftmodule
// LINK-SWIFTMODULES-SAME: -o linker
// COMPILE_AND_LINK: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK: linker.swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK-NEXT: {{(bin/)?}}ld{{"? }}
// COMPILE_AND_LINK-DAG: /a.o
// COMPILE_AND_LINK-DAG: .o
// COMPILE_AND_LINK: -o linker
// FILELIST: {{(bin/)?}}ld{{"? }}
// FILELIST-NOT: .o{{"? }}
// FILELIST: -filelist {{"?[^-]}}
// FILELIST-NOT: .o{{"? }}
// FILELIST: /a.o{{"? }}
// FILELIST-NOT: .o{{"? }}
// FILELIST: -o linker
// INFERRED_NAME_DARWIN: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// INFERRED_NAME_DARWIN: -module-name LINKER
// INFERRED_NAME_DARWIN: {{(bin/)?}}ld{{"? }}
// INFERRED_NAME_DARWIN: -o libLINKER.dylib
// INFERRED_NAME_LINUX: -o libLINKER.so
// INFERRED_NAME_WINDOWS: -o LINKER.dll
// Test ld detection. We use hard links to make sure
// the Swift driver really thinks it's been moved.
// RUN: rm -rf %t
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/bin)
// RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc)
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE-LINKER %s
// RELATIVE-LINKER: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}swift
// RELATIVE-LINKER: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}ld
// RELATIVE-LINKER: -o {{[^ ]+}}
// Also test arclite detection. This uses xcrun to find arclite when it's not
// next to Swift.
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/bin)
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc)
// RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=XCRUN_ARCLITE %s
// XCRUN_ARCLITE: bin{{/|\\\\}}ld
// XCRUN_ARCLITE: {{/|\\\\}}ANOTHER-DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}lib{{/|\\\\}}arc{{/|\\\\}}libarclite_macosx.a
// XCRUN_ARCLITE: -o {{[^ ]+}}
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/lib/arc)
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE_ARCLITE %s
// RELATIVE_ARCLITE: bin{{/|\\\\}}ld
// RELATIVE_ARCLITE: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}lib{{/|\\\\}}arc{{/|\\\\}}libarclite_macosx.a
// RELATIVE_ARCLITE: -o {{[^ ]+}}
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
| 42.73253 | 262 | 0.663979 |
f56defe82f33fe3f5481f3b58479057109fcc251 | 1,637 | //
// GlideSceneDelegate.swift
// glide
//
// Copyright (c) 2019 cocoatoucher user on github.com (https://github.com/cocoatoucher/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public protocol GlideSceneDelegate: class {
/// Called when the paused states of the scene changes.
func glideScene(_ scene: GlideScene, didChangePaused paused: Bool)
/// Called when it is desired to end this scene with a predefined reason or with a custom context.
func glideSceneDidEnd(_ scene: GlideScene, reason: GlideScene.EndReason?, context: [String: Any]?)
}
| 45.472222 | 102 | 0.747709 |
c1161194f8098d60f85d078e0ad05a3963edaa07 | 2,366 | //
// SceneDelegate.swift
// Sample App
//
// Created by Jelzon WORK on 4/3/20.
// Copyright © 2020 LiveLike. All rights reserved.
//
import UIKit
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.814815 | 147 | 0.712172 |
21b418fedb87ebeb2c2f9217fb8a595ec2dc412f | 4,949 | //
// Environment.swift
// AppToolkit
//
// Created by Vasily Kolosovsky on 10/17/17.
// Copyright © 2017 Jibo Inc. All rights reserved.
//
import Foundation
/**
:nodoc:
*/
public enum Environment: String {
case production
case staging
case development
case preprod
case custom
}
//MARK: - Configuration
/// :nodoc:
struct Configuration: Equatable {
fileprivate var baseUrl: String?
var name: String?
var redirectURI: String?
var environment: Environment
init(_ configuration: String) {
if let env = Environment(rawValue: configuration) {
environment = env
} else {
environment = .custom
}
if let params = configurationParams(configuration) {
name = params["name"] as? String
baseUrl = params["baseUrl"] as? String
redirectURI = params["redirectURI"] as? String
}
}
private func configurationParams(_ name: String) -> Dictionary<String, Any>? {
switch environment {
case .custom:
return customConfigurationParams(name)
default:
return defaultConfigurationParams(name)
}
}
private func defaultConfigurationParams(_ name: String) -> Dictionary<String, Any>? {
if let plistPath = Bundle(for: EnvironmentSwitcher.self).path(forResource: name, ofType: "plist", inDirectory: "environments") {
return NSDictionary(contentsOfFile: plistPath) as? Dictionary<String, Any>
} else if let plistPath = Bundle(for: EnvironmentSwitcher.self).path(forResource: name, ofType: "plist") {
return NSDictionary(contentsOfFile: plistPath) as? Dictionary<String, Any>
}
return nil
}
private func customConfigurationParams(_ name: String) -> Dictionary<String, Any>? {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, [.userDomainMask], true)[0]
let environmentsPath = (documentsPath as NSString).appendingPathComponent("/environments")
createEnvironmentsDirectoryIfNeeded(environmentsPath)
if let plistPath = Bundle(for: EnvironmentSwitcher.self).path(forResource: name, ofType: "plist", inDirectory: "environments") {
return NSDictionary(contentsOfFile: plistPath) as? Dictionary<String, Any>
} else if let plistPath = Bundle(for: EnvironmentSwitcher.self).path(forResource: name, ofType: "plist") {
return NSDictionary(contentsOfFile: plistPath) as? Dictionary<String, Any>
}
return nil
}
private func createEnvironmentsDirectoryIfNeeded(_ path: String) {
if !FileManager.default.fileExists(atPath: path) {
try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false)
}
}
static func ==(lhs: Configuration, rhs: Configuration) -> Bool {
return lhs.name == rhs.name
}
}
/// :nodoc:
extension Configuration {
var authUrl: String? {
guard let url = baseUrl else { return nil }
return url + "/login"
}
var tokenUrl: String? {
guard let url = baseUrl else { return nil }
return url + "/token"
}
var userInfoUrl: String? {
guard let url = baseUrl else { return nil }
return url + "/rom/v1/info"
}
var robotsListUrl: String? {
guard let url = baseUrl else { return nil }
return url + "/rom/v1/robots/"
}
var certificatesCreationUrl: String? {
guard let url = baseUrl else { return nil }
return url + "/rom/v1/certificates/"
}
var certificatesRetrievalUrl: String? {
guard let url = baseUrl else { return nil }
return url + "/rom/v1/certificates/client"
}
}
//MARK: - Environment switcher
/// :nodoc:
fileprivate let EnvironmentID = "EnvironmentID"
/// :nodoc:
class EnvironmentSwitcher {
var currentEnvironment: Environment {
get {
return currentConfiguration.environment
}
set {
//TODO: add custom configurations creation support
guard newValue != .custom else { return }
let configName = newValue.rawValue
currentConfiguration = Configuration(configName)
UserDefaults.standard.set(configName, forKey:EnvironmentID)
}
}
var currentConfiguration: Configuration
class func shared() -> EnvironmentSwitcher {
return sharedEnvironmentSwitcher
}
private static var sharedEnvironmentSwitcher: EnvironmentSwitcher = {
let switcher = EnvironmentSwitcher()
return switcher
}()
private init() {
if let env = UserDefaults.standard.string(forKey: EnvironmentID) {
currentConfiguration = Configuration(env)
} else {
currentConfiguration = Configuration(Environment.staging.rawValue)
}
}
}
| 29.813253 | 136 | 0.637907 |
61939b20679bd0cf156417c241eddf988f39850d | 427 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{{{}}{let f{func a{let a{(){
| 42.7 | 79 | 0.735363 |
bf15b32868fd5241a3824e45180a2714f66e935c | 2,179 | //
// AppDelegate.swift
// InstagramAPI
//
// Created by anovoselskyi on 05/06/2020.
// Copyright (c) 2020 anovoselskyi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47.369565 | 285 | 0.755851 |
9b93b03fed7442a760696db5206dce21b6b5362a | 3,309 | //
// ViewController.swift
// SerialGateDemo
//
// Created by Takuto Nakamura on 2019/02/13.
// Copyright © 2019 Takuto Nakamura. All rights reserved.
//
import Cocoa
import SerialGate
// with Test_for_SerialGate Arduino Program
class ViewController: NSViewController {
@IBOutlet weak var portsPopUp: NSPopUpButton!
@IBOutlet weak var textField: NSTextField!
@IBOutlet var textView: NSTextView!
private let manager = SGPortManager.shared
private var portList = [SGPort]()
private var port: SGPort? = nil
override func viewDidLoad() {
super.viewDidLoad()
manager.updatedAvailablePortsHandler = { [weak self] in
self?.updatedAvailablePorts()
}
portList = manager.availablePorts
portsPopUp.removeAllItems()
portList.forEach { (port) in
portsPopUp.addItem(withTitle: port.name)
}
port = portList.first
}
override func viewWillDisappear() {
port?.close()
}
@IBAction func selectPort(_ sender: NSPopUpButton) {
port = portList[sender.indexOfSelectedItem]
}
@IBAction func pushButton(_ sender: NSButton) {
if sender.tag == 0 { // open
port?.baudRate = B9600
port?.portOpenedHandler = { [weak self] (port) in
self?.portWasOpened(port)
}
port?.portClosedHandler = { [weak self] (port) in
self?.portWasClosed(port)
}
port?.portClosedHandler = { [weak self] (port) in
self?.portWasClosed(port)
}
port?.receivedHandler = { [weak self] (text) in
self?.received(text)
}
port?.failureOpenHandler = { (port) in
Swift.print("Failure Open Port \(port.name)")
}
port?.open()
portsPopUp.isEnabled = false
textView.string = ""
} else if sender.tag == 1 { // close
port?.close()
portsPopUp.isEnabled = true
} else { // send
let text = textField.stringValue
if text.count > 0 {
port?.send(text)
}
}
}
// MARK: ★★ SGPortManager Handler ★★
func updatedAvailablePorts() {
portList = manager.availablePorts
portsPopUp.removeAllItems()
portList.forEach { (port) in
portsPopUp.addItem(withTitle: port.name)
}
if portList.contains(where: { (portInList) -> Bool in
return portInList.name == port!.name
}) {
portsPopUp.selectItem(withTitle: port!.name)
} else {
portsPopUp.isEnabled = true
port = portList.first
}
}
// MARK: ★★ SGPortDelegate ★★
func received(_ text: String) {
DispatchQueue.main.async {
self.textView.string += text
self.textView.scrollToEndOfDocument(nil)
}
}
func portWasOpened(_ port: SGPort) {
Swift.print("Port: \(port.name) Opend")
}
func portWasClosed(_ port: SGPort) {
Swift.print("Port: \(port.name) Closed")
}
func portWasRemoved(_ port: SGPort) {
Swift.print("Port: \(port.name) Removed")
}
}
| 28.773913 | 63 | 0.557872 |
bbfa808369ad52f02f306b4f2801524e2fe08335 | 1,670 | //
// RealNetworkRequest.swift
// TemplateSwift3
//
// Created by Hipolito Arias on 17/08/2017.
// Copyright © 2017 Hipolito Arias. All rights reserved.
//
import Alamofire
class Network: HARequestable, HAResponsable {
var manager: NetworkSessionManager
init(session: NetworkSessionManager) {
self.manager = session
}
func request(router: URLRequestConvertible, completion: @escaping (Result<Json, NetworkError>) -> Void) -> Request {
return self.request(router: router, adapter: nil, completion: completion)
}
func request(router: URLRequestConvertible, adapter: RequestAdapter?, completion: @escaping (Result<Json, NetworkError>) -> Void) -> Request {
manager.sessionManager.adapter = adapter
return manager.sessionManager
.request(router)
.validate(statusCode: 200..<300)
.responseJSON(completionHandler: { [weak self] (response) in
self?.parseResponseServer(response: response, completion: completion)
})
}
func request(_ url: URL, method: HTTPMethod, parameters: [String : Any]?, headers: [String : String]?, completion: @escaping (Result<Json, NetworkError>) -> Void) -> Request {
return manager.sessionManager
.request(url,
method: method,
parameters: parameters,
encoding: URLEncoding.default,
headers: headers)
.responseJSON(completionHandler: { [weak self] (response) in
self?.parseResponseServer(response: response, completion: completion)
})
}
}
| 36.304348 | 179 | 0.626946 |
72f583835ba727aa091c0afa7eac7097d5f5da79 | 1,568 | //
// NSStatusItem+Helper.swift
// MacTemplet
//
// Created by Bin Shang on 2019/11/23.
// Copyright © 2019 Bin Shang. All rights reserved.
//
import Cocoa
@objc public extension NSStatusItem {
// MARK: -chain
func lengthChain(_ length: CGFloat) -> Self {
self.length = length
return self
}
func menuChain(_ menu: NSMenu?) -> Self {
self.menu = menu
return self
}
@available(macOS 10.12, *)
func behaviorChain(_ behavior: NSStatusItem.Behavior) -> Self {
self.behavior = behavior
return self
}
@available(macOS 10.12, *)
func isVisibleChain(_ isVisible: Bool) -> Self {
self.isVisible = isVisible
return self
}
@available(macOS 10.12, *)
func autosaveNameChain(_ autosaveName: NSStatusItem.AutosaveName!) -> Self {
self.autosaveName = autosaveName
return self
}
// MARK: -funtions
static func create(imageName: String?) -> NSStatusItem {
var image = NSApplication.appIcon.resize(CGSize(width: 40, height: 30), isPixels: true);
if let imageName = imageName, let newImage = NSImage(named: imageName) {
image = newImage
}
let statusItem: NSStatusItem = {
let item = NSStatusBar.system.statusItem(withLength: -2)
item.button?.cell?.isHighlighted = false;
item.button?.image = image;
item.button?.toolTip = NSApplication.appName;
return item;
}()
return statusItem;
}
}
| 25.704918 | 96 | 0.596301 |
ac7869c0e1cfe73b21fa79c3a06cc661a865e65c | 5,621 | //
// MasterCardBrandTest.swift
// FrameworkTests
//
// Created by Vitalii Obertynskyi on 06.04.2020.
// Copyright © 2020 VGS. All rights reserved.
//
import XCTest
@testable import VGSCollectSDK
class CardBrandTest: XCTestCase {
var storage: VGSCollect!
var cardTextField: VGSTextField!
override func setUp() {
storage = VGSCollect(id: "123")
cardTextField = VGSTextField()
let config = VGSConfiguration(collector: storage, fieldName: "cardNum")
config.type = .cardNumber
config.formatPattern = nil
cardTextField.configuration = config
}
override func tearDown() {
storage = nil
cardTextField = nil
}
func testCardBrandDetectionReturnsTrue() {
let allBrands = SwiftLuhn.CardType.allCases
allBrands.forEach { brand in
let numbers = brand.cardNumbers
numbers.forEach { number in
cardTextField.textField.secureText = number
guard let state = cardTextField.state as? CardState else {
XCTFail("Guard fail")
return
}
XCTAssert(state.cardBrand == brand, "Card number \(number) for brand \(brand) fail")
}
}
}
func testCardBrandDetectionByFirstDigitsReturnsTrue() {
let allBrands = SwiftLuhn.CardType.allCases
allBrands.forEach { brand in
let numbers = brand.cardNumbers
numbers.forEach { number in
let startIndex = (brand == .mastercard || brand == .maestro) ? 7 : 4
let digitsCount = Int.random(in: startIndex...11)
let input = String(number.prefix(digitsCount))
cardTextField.textField.secureText = input
guard let state = cardTextField.state as? CardState else {
XCTFail("Guard fail")
return
}
XCTAssert(state.cardBrand == brand, "Card number \(number), first digits \(input), for brand \(brand) fail")
}
}
}
func testValidCardsValidationReturnsTrue() {
let allBrands = SwiftLuhn.CardType.allCases
allBrands.forEach { brand in
let numbers = brand.cardNumbers
numbers.forEach { number in
cardTextField.textField.secureText = number
guard let state = cardTextField.state as? CardState else {
XCTFail("Guard fail")
return
}
XCTAssert(state.isValid == true, "Card number \(number) for brand \(brand) fail")
}
}
}
func testNotFullCardsValidationReturnsFalse() {
let allBrands = SwiftLuhn.CardType.allCases
allBrands.forEach { brand in
let numbers = brand.cardNumbers
for number in numbers {
/// there are 19 digits numbers that detected as valid by Luhn algorithms when there are 16-19 digits
if number.count > 16 {
continue
}
let input = String(number.prefix(number.count - 1))
cardTextField.textField.secureText = input
guard let state = cardTextField.state as? CardState else {
XCTFail("Guard fail")
return
}
XCTAssert(state.isValid == false, "Card number \(number), first digits \(input), for brand \(brand) fail")
}
}
}
func testNotValidCardsValidationReturnsFalse() {
let allBrands = SwiftLuhn.CardType.allCases
allBrands.forEach { brand in
let numbers = brand.cardNumbers
numbers.forEach { number in
/// replace rendom number in card. We skip first digits that detect brand since brand used for validation too.
let lastIndex = number.count > 16 ? 16 : number.count
let replaceCharIndex = Int.random(in: 7...lastIndex)
let prefix = number.prefix(replaceCharIndex)
let numToChange = Int(String(prefix.last!))!
var randomNums = Array(0...9)
randomNums.remove(at: numToChange)
let newNum = randomNums.randomElement()!
let input = number.prefix(replaceCharIndex - 1) + "\(newNum)" + number.dropFirst(replaceCharIndex)
cardTextField.textField.secureText = String(input)
guard let state = cardTextField.state as? CardState else {
XCTFail("Guard fail")
return
}
XCTAssert(state.isValid == false, "Not Valid Card number \(number), first digits \(input), for brand \(brand) fail")
}
}
}
func testSpecificNotValidCardsValidationReturnsFalse() {
let numbers = SwiftLuhn.specificNotValidCardNumbers
numbers.forEach { number in
cardTextField.textField.secureText = number
guard let state = cardTextField.state as? CardState else {
XCTFail("Guard fail")
return
}
XCTAssert(state.isValid == false, "Specific Not Valid Card number \(number) validation fail")
XCTAssert(state.last4.isEmpty == true, "Specific Not Valid Card number \(number), state.last4.isEmpty == true fail")
XCTAssert(state.bin.isEmpty == true, "Specific Not Valid Card number \(number), tate.bin.isEmpty == true fail")
}
}
}
| 40.438849 | 132 | 0.571251 |
deaa9dabfb9795122ede7d044f592f0544d7b74b | 3,974 | // The MIT License (MIT)
//
// Copyright (c) 2019 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
class DropdownPresentationController: UIPresentationController {
private let dropDownHeight: CGFloat = 200
private let backgroundView = UIView()
private var dropDownOffset: CGFloat = 0
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
dropDownOffset = window?.safeAreaInsets.top ?? 0.0
dropDownOffset += UINavigationController().navigationBar.frame.size.height
}
backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
backgroundView.backgroundColor = .clear
backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backgroundTapped(_:))))
}
@objc func backgroundTapped(_ recognizer: UIGestureRecognizer) {
presentingViewController.dismiss(animated: true)
}
override func presentationTransitionWillBegin() {
guard let containerView = containerView else { return }
containerView.insertSubview(backgroundView, at: 0)
backgroundView.frame = containerView.bounds
}
override func containerViewWillLayoutSubviews() {
presentedView?.frame = frameOfPresentedViewInContainerView
}
override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
return CGSize(width: parentSize.width, height: parentSize.height - dropDownOffset)
}
override var frameOfPresentedViewInContainerView: CGRect {
guard let containerView = containerView,
let presentingView = presentingViewController.view else { return .zero }
let size = self.size(forChildContentContainer: presentedViewController,
withParentContainerSize: presentingView.bounds.size)
let position: CGPoint
if let navigationBar = (presentingViewController as? UINavigationController)?.navigationBar {
// We can't use the frame directly since iOS 13 new modal presentation style
let navigationRect = navigationBar.convert(navigationBar.bounds, to: nil)
let presentingRect = presentingView.convert(presentingView.frame, to: containerView)
position = CGPoint(x: presentingRect.origin.x, y: navigationRect.maxY)
// Match color with navigation bar
presentedViewController.view.backgroundColor = navigationBar.barTintColor
} else {
position = .zero
}
return CGRect(origin: position, size: size)
}
}
| 46.209302 | 134 | 0.722949 |
c1a925ade235775ab51c4ca68c4739b4ad9bf200 | 1,487 | //
// CustomerTests.swift
// SendInvitesTests
//
// Created by Oluwadamisi Pikuda on 09/05/2020.
// Copyright © 2020 Damisi Pikuda. All rights reserved.
//
import XCTest
@testable import SendInvites
final class CustomerTests: XCTestCase {
func test_location() {
let latitude = 52.986375
let longitude = -6.043701
let christina = Customer(id: 12, name: "Christina McArdle", latitude: latitude, longitude: longitude)
XCTAssertEqual(christina.location, SILocation(latitude: latitude, longitude: longitude))
}
func test_distanceFromOffice() {
let latitude = 52.986375
let longitude = -6.043701
let christina = Customer(id: 12, name: "Christina McArdle", latitude: latitude, longitude: longitude)
XCTAssertEqual(christina.distanceFromOffice.rounded(.up), 42)
}
func test_isToBeInvited() {
let latitude = 52.986375
let longitude = -6.043701
let christina = Customer(id: 12, name: "Christina McArdle", latitude: latitude, longitude: longitude)
XCTAssertTrue(christina.isToBeInvited)
}
func test_equatable() {
let latitude = 52.986375
let longitude = -6.043701
let christina = Customer(id: 12, name: "Christina McArdle", latitude: latitude, longitude: longitude)
let christina2 = Customer(id: 12, name: "Christina McArdle", latitude: latitude, longitude: longitude)
XCTAssertEqual(christina, christina2)
}
}
| 28.596154 | 110 | 0.675185 |
168d0e3c7a30a6efbd5fdd1237a86af951387e82 | 2,594 | import KsApi
import Library
import Prelude
import UIKit
internal final class CommentsDataSource: ValueCellDataSource {
internal enum Section: Int {
case comments
case empty
case error
}
internal func load(comments: [Comment], project: Project, shouldShowErrorState: Bool) {
guard !shouldShowErrorState else {
self.clearValues()
self.appendRow(
value: (),
cellClass: CommentsErrorCell.self,
toSection: Section.error.rawValue
)
return
}
let section = !comments.isEmpty ? Section.comments.rawValue : Section.empty.rawValue
self.clearValues()
guard !comments.isEmpty else {
self.appendRow(
value: (),
cellClass: EmptyCommentsCell.self,
toSection: section
)
return
}
comments.forEach { comment in
guard comment.isDeleted == false else {
self.appendRow(
value: comment,
cellClass: CommentRemovedCell.self,
toSection: section
)
return
}
switch comment.status {
case .failed, .retrying:
self.appendRow(
value: comment,
cellClass: CommentPostFailedCell.self,
toSection: section
)
case .success, .retrySuccess:
self.appendRow(value: (comment, project), cellClass: CommentCell.self, toSection: section)
case .unknown:
assertionFailure("Comments that have not had their state set should not be added to the data source.")
}
}
}
internal override func configureCell(tableCell cell: UITableViewCell, withValue value: Any) {
switch (cell, value) {
case let (cell as CommentCell, value as (Comment, Project)):
cell.configureWith(value: value)
case let (cell as CommentPostFailedCell, value as Comment):
cell.configureWith(value: value)
case let (cell as CommentRemovedCell, value as Comment):
cell.configureWith(value: value)
case let (cell as EmptyCommentsCell, _):
cell.configureWith(value: ())
case let (cell as CommentsErrorCell, _):
cell.configureWith(value: ())
default:
assertionFailure("Unrecognized combo: \(cell), \(value).")
}
}
public func comment(at indexPath: IndexPath) -> Comment? {
let value = self[indexPath]
switch value {
case let value as Comment: return value
case let value as (comment: Comment, project: Project): return value.comment
default: return nil
}
}
func isInErrorState(indexPath: IndexPath) -> Bool {
return indexPath.section == Section.error.rawValue
}
}
| 27.595745 | 110 | 0.65266 |
72dcf8f6875dcc3a790ab70177be202dc1e383fb | 8,521 | //
// VideoTableViewCell.swift
// OfficeChat
//
// Created by Asim on 18/07/18.
// Copyright © 2018 Fugu-Click Labs Pvt. Ltd. All rights reserved.
//
import UIKit
import AVFoundation
class VideoTableViewCell: MessageTableViewCell {
// MARK: - IBOutlets
@IBOutlet weak var viewFrameImageView: UIImageView!
@IBOutlet weak var messageBackgroundView: UIView!
@IBOutlet weak var downloadButton: UIButton!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var downloadActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var bottomDistanceOfMessageBgView: NSLayoutConstraint!
@IBOutlet weak var sizeLabel: UILabel!
// MARK: - Properties
weak var delegate: VideoTableViewCellDelegate?
//MARK: - View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
viewFrameImageView.contentMode = .scaleAspectFill
timeLabel.text = ""
timeLabel.font = HippoConfig.shared.theme.dateTimeFontSize
timeLabel.textAlignment = .right
timeLabel.textColor = HippoConfig.shared.theme.dateTimeTextColor
messageBackgroundView.layer.cornerRadius = HippoConfig.shared.theme.chatBoxCornerRadius
messageBackgroundView.backgroundColor = HippoConfig.shared.theme.outgoingChatBoxColor
messageBackgroundView.layer.borderWidth = HippoConfig.shared.theme.chatBoxBorderWidth
messageBackgroundView.layer.borderColor = HippoConfig.shared.theme.chatBoxBorderColor.cgColor
addNotificationObservers()
}
func addNotificationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(fileDownloadCompleted(_:)), name: Notification.Name.fileDownloadCompleted, object: nil)
}
@objc func fileDownloadCompleted(_ notification: Notification) {
guard let url = notification.userInfo?[DownloadManager.urlUserInfoKey] as? String else {
return
}
if message?.fileUrl == url {
setDownloadView()
}
}
// MARK: - IBAction
@IBAction func downloadButtonPressed() {
guard let unwrappedMessage = message else {
print("-------ERROR\nCannot download, Message is nil\n-------")
return
}
delegate?.downloadFileIn(message: unwrappedMessage)
setDownloadView()
}
@IBAction func playVideoButtonPressed() {
guard let unwrappedMessage = message else {
print("-------ERROR\nCannot play, Message is nil\n-------")
return
}
if message?.type == .embeddedVideoUrl{
delegate?.openFileIn(message: unwrappedMessage)
}else{
delegate?.openFileIn(message: unwrappedMessage)
setDownloadView()
}
}
// MARK: - Methods
func setBottomDistance() {
let bottomDistance: CGFloat = 2
guard let _ = message else {
return
}
bottomDistanceOfMessageBgView.constant = bottomDistance
}
func setDisplayView() {
if message?.type == .embeddedVideoUrl{
if let videoLinkStr = message?.customAction?.videoLink, let _ = URL(string: videoLinkStr) {
//Other method to get video ID using extension
print(videoLinkStr.youtubeID as Any)
//genarateThumbnailFromYouTubeID(youTubeID: youTubeID)
//getThumbnailFromVideoUrl(urlString: url)
if let youTubeID = videoLinkStr.youtubeID{
if let img = genarateThumbnailFromYouTubeID(youTubeID: youTubeID){
viewFrameImageView.image = img
self.showPlayButtonForEmbeddedVideoUrl()
}else{
viewFrameImageView.image = HippoConfig.shared.theme.placeHolderImage
self.hidePlayButtonForEmbeddedVideoUrl()
}
}else{
if let img = getThumbnailFromVideoUrl(urlString: videoLinkStr){
viewFrameImageView.image = img
self.showPlayButtonForEmbeddedVideoUrl()
}else{
viewFrameImageView.image = HippoConfig.shared.theme.placeHolderImage
self.hidePlayButtonForEmbeddedVideoUrl()
}
}
} else {
viewFrameImageView.image = HippoConfig.shared.theme.placeHolderImage
self.hidePlayButtonForEmbeddedVideoUrl()
}
}else{
if let imageThumbnailURL = message?.thumbnailUrl, let url = URL(string: imageThumbnailURL) {
viewFrameImageView.kf.setImage(with: url, placeholder: HippoConfig.shared.theme.placeHolderImage)
} else {
viewFrameImageView.image = HippoConfig.shared.theme.placeHolderImage
}
}
setTime()
sizeLabel.text = message?.fileSize ?? nil
}
//MARK:- Generate Thumbnail Functions
func genarateThumbnailFromYouTubeID(youTubeID: String) -> UIImage? {
let urlString = "http://img.youtube.com/vi/\(youTubeID)/1.jpg"
let image = try! (UIImage(withContentsOfUrl: urlString))!
return image
}
func getThumbnailFromVideoUrl(urlString: String) -> UIImage? {
// DispatchQueue.global().async {
let asset = AVAsset(url: URL(string: urlString)!)
let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMake(value: 1, timescale: 20)
let img = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil)
if img != nil {
let frameImg = UIImage(cgImage: img!)
// DispatchQueue.main.async(execute: {
// // assign your image to UIImageView
// })
return frameImg
}else{
return nil
}
// }
}
func showPlayButtonForEmbeddedVideoUrl(){
playButton.isHidden = false
downloadButton.isHidden = true
downloadActivityIndicator.isHidden = true
}
func hidePlayButtonForEmbeddedVideoUrl(){
playButton.isHidden = true
downloadButton.isHidden = true
downloadActivityIndicator.isHidden = true
}
func setDownloadView() {
if message?.type == .embeddedVideoUrl{
}else{
guard let unwrappedMessage = message else {
hideDownloadView()
return
}
let readyToDownload = !unwrappedMessage.isSentByMe() || unwrappedMessage.status != .none
guard let fileURL = unwrappedMessage.fileUrl else {
hideDownloadView()
return
}
guard (readyToDownload ? unwrappedMessage.fileUrl != nil : true) else {
print("ERROR------\nNo URL Found to download Video\n--------")
return
}
let isDownloading = DownloadManager.shared.isFileBeingDownloadedWith(url: fileURL)
let isDownloaded = DownloadManager.shared.isFileDownloadedWith(url: fileURL)
switch (isDownloading, isDownloaded) {
case (false, false):
playButton.isHidden = true
downloadButton.isHidden = false
downloadActivityIndicator.isHidden = true
case (true, _):
playButton.isHidden = true
downloadButton.isHidden = true
downloadActivityIndicator.startAnimating()
downloadActivityIndicator.isHidden = false
case (_, true):
playButton.isHidden = false
downloadButton.isHidden = true
downloadActivityIndicator.isHidden = true
}
}
}
func hideDownloadView() {
downloadButton.isHidden = true
playButton.isHidden = true
downloadActivityIndicator.isHidden = true
}
}
extension UIImage {
convenience init?(withContentsOfUrl imageUrlString: String) throws {
let imageUrl = URL(string: imageUrlString)!
let imageData = try Data(contentsOf: imageUrl)
self.init(data: imageData)
}
}
extension String {
var youtubeID: String? {
let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)"
let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: count)
guard let result = regex?.firstMatch(in: self, range: range) else {
return nil
}
return (self as NSString).substring(with: result.range)
}
}
| 36.105932 | 158 | 0.630795 |
e93e95938ec25a1b65aa667bc170f31caf9223ff | 1,971 | //
// URLRequestExtensions.swift
// EVPulse
//
// Created by Nikolas Konstantakopoulos on 28/1/22.
//
import Foundation
// MARK: - Helper types
extension URLRequest {
public enum HTTPMethod: String {
case get = "GET"
case put = "PUT"
case patch = "PATCH"
case post = "POST"
case delete = "DELETE"
}
public enum ContentType: String {
case json = "application/json"
case url = "application/x-www-form-urlencoded"
case urlUtf8 = "application/x-www-form-urlencoded; charset=utf-8"
}
public enum HeaderType {
case authorisation (auth: String)
case accept (type: ContentType)
case content (type: ContentType)
public var name: String {
switch self {
case .authorisation : return "Authorization"
case .accept : return "Accept"
case .content : return "Content-Type"
}
}
public var value: String {
switch self {
case .authorisation(let token) : return token
case .accept (let type) : return type.rawValue
case .content (let type) : return type.rawValue
}
}
}
}
// MARK: - Request constructing utilities
extension URLRequest {
public mutating func add(header: HeaderType) {
addValue(header.value, forHTTPHeaderField: header.name)
}
public func adding(header: HeaderType) -> URLRequest {
var request = self
request.add(header: header)
return request
}
}
// MARK: - Request method utilities
extension URLRequest {
public var method: HTTPMethod? {
get { .init(rawValue: httpMethod ?? "") }
set { httpMethod = newValue?.rawValue }
}
public static func get(path: String) -> URLRequest {
URLRequest(url: URL(string: path)!)
}
}
| 24.036585 | 73 | 0.564181 |
e6a5feecb13df78262bd681eccce9608d6ccc8d8 | 313 | //
// CellRepresentable.swift
// mvvm
//
// Created by Thomas Degry on 12/16/16.
// Copyright © 2016 Thomas Degry. All rights reserved.
//
import UIKit
protocol CellRepresentable {
var rowHeight: CGFloat { get }
func cellInstance(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell
}
| 20.866667 | 88 | 0.71246 |
dbfecb4c8c4593af0d137b2826f787e3da676442 | 587 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
protocol a {
var d = e(Any, y: C {
class A {
}
}
protocol a {
func a
class B = Int) {
return """
let g : l) {
i() -> T] {
}
}
protocol c {
}
typealias e : d = d, T -> String {
}
}
func d: a(t: R
| 20.964286 | 78 | 0.667802 |
4a61e07b11deec5513f4ee6d8f5f088f992b4be4 | 40,564 | //
// Statistics library written in Swift.
//
// https://github.com/evgenyneu/SigmaSwiftStatistics
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// StandardErrorOfTheMean.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 18/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Computes standard error of the mean.
http://en.wikipedia.org/wiki/Standard_error
- parameter values: Array of decimal numbers.
- returns: Standard error of the mean. Returns nil when the array is empty or contains a single value.
Formula:
SE = s / sqrt(n)
Where:
s is the sample standard deviation.
n is the sample size.
Example:
Sigma.standardErrorOfTheMean([1, 12, 19.5, -5, 3, 8]) // 3.5412254627
*/
static func standardErrorOfTheMean(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
guard let stdev = standardDeviationSample(values) else { return nil }
return stdev / sqrt(count)
}
}
// ----------------------------
//
// Kurtosis.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 19/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Computes kurtosis of a series of numbers. This implementation is the same as the SKEW function in Excel and Google Docs Sheets.
https://en.wikipedia.org/wiki/Kurtosis
- parameter values: Array of decimal numbers.
- returns: Kurtosis. Returns nil if the dataset contains less than 4 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
rac{n(n + 1)}{(n - 1)(n - 2)(n - 3)}\sum_{i=1}^{n} \Bigg( rac{x_i - ar{x}}{s} \Bigg)^4 - rac{3(n - 1)^2}{(n - 2)(n - 3)}
Example:
Sigma.kurtosisA([2, 1, 3, 4.1, 19, 1.5]) // 5.4570693277
*/
static func kurtosisA(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count < 4 { return nil }
guard let averageVal = average(values) else { return nil }
guard let stdev = standardDeviationSample(values) else { return nil }
var result = values.reduce(0.0) { sum, value in
let value = (value - averageVal) / stdev
return sum + pow(value, 4)
}
result *= (count * (count + 1) / ((count - 1) * (count - 2) * (count - 3)))
result -= 3 * pow(count - 1, 2) / ((count - 2) * (count - 3))
return result
}
/**
Computes kurtosis of a series of numbers. This implementation is the same as in Wolfram Alpha and "moments" R package.
https://en.wikipedia.org/wiki/Kurtosis
- parameter values: Array of decimal numbers.
- returns: Kurtosis. Returns nil if the dataset contains less than 2 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
rac{\mu_4}{\mu^2_2}
Example:
Sigma.kurtosisB([2, 1, 3, 4.1, 19, 1.5]) // 4.0138523409
*/
static func kurtosisB(_ values: [Double]) -> Double? {
if values.isEmpty { return nil }
guard let moment4 = centralMoment(values, order: 4) else { return nil }
guard let moment2 = centralMoment(values, order: 2) else { return nil }
if moment2 == 0 { return nil }
return (moment4 / pow(moment2, 2))
}
}
// ----------------------------
//
// Rank.swift
//
// ----------------------------
//
// Ranks.swift
// SigmaSwiftStatistics
//
// Created by Alan James Salmoni on 21/01/2017.
// Copyright © 2017 Evgenii Neumerzhitckii. All rights reserved.
//
import Foundation
public extension Sigma {
/// Determines how the ranks for the equal values ('ties') are calculated.
enum RankTieMethod {
/**
Calculates the average rank:
Sigma.average([100, 100, 100, 100], ties: .average) // [2.5, 2.5, 2.5, 2.5]
*/
case average
/**
Uses the mininum rank:
Sigma.rank([100, 100, 100, 100], ties: .min) // [1, 1, 1, 1]
*/
case min
/**
Uses the maximum rank:
Sigma.rank([100, 100, 100, 100], ties: .max) // [4, 4, 4, 4]
*/
case max
/**
Ranks are incremented:
Sigma.rank([100, 100, 100, 100], ties: .first) // [1, 2, 3, 4]
*/
case first
/**
Ranks are decremented:
Sigma.rank([100, 100, 100, 100], ties: .last) // [4, 3, 2, 1]
*/
case last
}
/**
Returns the ranks of the values in the array.
- parameter values: Array of decimal numbers.
- parameter ties: determines how the ranks for the equal values ('ties') are calculated. Default: .average.
- returns: Returns the ranks of the values in the array.
Examples:
Sigma.rank([2, 3, 6, 5, 3]) // [1.0, 2.5, 5.0, 4.0, 2.5]
*/
static func rank(_ values: [Double], ties: RankTieMethod = .average) -> [Double] {
var rank: Double
let start = 1.0
switch ties {
case .average:
rank = start - 0.5
default:
rank = start - 1.0
}
var increment: Double
var tinyIncrement: Double
let frequencies = Sigma.frequencies(values)
var ranks = [Double](repeating: 0, count: values.count)
for value in frequencies.keys.sorted() {
increment = Double(frequencies[value] ?? 1)
tinyIncrement = 1.0
for index in 0...(values.count - 1) {
if value == values[index] {
switch ties {
case .average:
ranks[index] = rank + (increment / 2.0)
case .min:
ranks[index] = rank + 1
case .max:
ranks[index] = rank + increment
case .first:
ranks[index] = rank + tinyIncrement
tinyIncrement += 1
case .last:
ranks[index] = rank + increment - tinyIncrement + 1.0
tinyIncrement += 1
}
}
}
rank += increment
}
return ranks
}
}
// ----------------------------
//
// Quantiles.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 21/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
The class contains nine functions that calculate sample quantiles corresponding to the given probability. The implementation is the same as in R. This is an implementation of the algorithms described in the Hyndman and Fan paper, 1996:
https://www.jstor.org/stable/2684934
https://www.amherst.edu/media/view/129116/original/Sample+Quantiles.pdf
The documentation of the functions is based on R and Wikipedia:
https://en.wikipedia.org/wiki/Quantile
http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html
*/
static let quantiles = SigmaQuantiles()
}
public class SigmaQuantiles {
/*
This method calculates quantiles using the inverse of the empirical distribution function.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method1(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let k = Int((probability * count))
let g = (probability * count) - Double(k)
var new_probability = 1.0
if g == 0.0 { new_probability = 0.0 }
return qDef(data, k: k, probability: new_probability)
}
/**
This method uses inverted empirical distribution function with averaging.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method2(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let k = Int(probability * count)
let g = (probability * count) - Double(k)
var new_probability = 1.0
if g == 0.0 { new_probability = 0.5 }
return qDef(data, k: k, probability: new_probability)
}
/**
The 3rd sample quantile method from Hyndman and Fan paper (1996).
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method3(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = -0.5
let k = Int((probability * count) + m)
let g = (probability * count) + m - Double(k)
var new_probability = 1.0
if g <= 0 && k % 2 == 0 { new_probability = 0.0 }
return qDef(data, k: k, probability: new_probability)
}
/**
It uses linear interpolation of the empirical distribution function.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method4(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = 0.0
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
This method uses a piecewise linear function where the knots are the values midway through the steps of the empirical distribution function.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method5(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = 0.5
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
This method is implemented in Microsoft Excel (PERCENTILE.EXC), Minitab and SPSS. It uses linear interpolation of the expectations for the order statistics for the uniform distribution on [0,1].
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method6(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = probability
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
This method is implemented in S, Microsoft Excel (PERCENTILE or PERCENTILE.INC) and Google Docs Sheets (PERCENTILE). It uses linear interpolation of the modes for the order statistics for the uniform distribution on [0, 1].
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method7(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = 1.0 - probability
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
The quantiles returned by the method are approximately median-unbiased regardless of the distribution of x.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method8(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = (probability + 1.0) / 3.0
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
The quantiles returned by this method are approximately unbiased for the expected order statistics if x is normally distributed.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method9(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = (0.25 * probability) + (3.0 / 8.0)
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
Shared function for all quantile methods.
- parameter data: Array of decimal numbers.
- parameter k: the position of the element in the dataset.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
private func qDef(_ data: [Double], k: Int, probability: Double) -> Double? {
if data.isEmpty { return nil }
if k < 1 { return data[0] }
if k >= data.count { return data.last }
return ((1.0 - probability) * data[k - 1]) + (probability * data[k])
}
}
// ----------------------------
//
// StandardDeviation.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Computes standard deviation based on a sample.
http://en.wikipedia.org/wiki/Standard_deviation
- parameter values: Array of decimal numbers.
- returns: Standard deviation of a sample. Returns nil when the array is empty or contains a single value.
Formula:
s = sqrt( Σ( (x - m)^2 ) / (n - 1) )
Where:
m is the sample mean.
n is the sample size.
Example:
Sigma.standardDeviationSample([1, 12, 19.5, -5, 3, 8]) // 8.674195447801869
*/
static func standardDeviationSample(_ values: [Double]) -> Double? {
if let varianceSample = varianceSample(values) {
return sqrt(varianceSample)
}
return nil
}
/**
Computes standard deviation of entire population.
http://en.wikipedia.org/wiki/Standard_deviation
- parameter values: Array of decimal numbers.
- returns: Standard deviation of entire population. Returns nil for an empty array.
Formula:
σ = sqrt( Σ( (x - m)^2 ) / n )
Where:
m is the population mean.
n is the population size.
Example:
Sigma.standardDeviationPopulation([1, 12, 19.5, -5, 3, 8]) // 8.67419544780187
*/
static func standardDeviationPopulation(_ values: [Double]) -> Double? {
if let variancePopulation = variancePopulation(values) {
return sqrt(variancePopulation)
}
return nil
}
}
// ----------------------------
//
// Normal.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Returns the normal distribution for the given values of x, μ and σ. The returned value is the area under the normal curve to the left of the value x.
https://en.wikipedia.org/wiki/Normal_distribution
- parameter x: The input value.
- parameter μ: The mean. Default: 0.
- parameter σ: The standard deviation. Default: 1.
- returns: The value of the normal distribution. The returned value is the area under the normal curve to the left of the value x. Returns nil if σ is zero or negative.
Example:
Sigma.normalDistribution(x: -1, μ: 0, σ: 1) // 0.1586552539314570
*/
static func normalDistribution(x: Double, μ: Double = 0, σ: Double = 1) -> Double? {
if σ <= 0 { return nil }
let z = (x - μ) / σ
return 0.5 * erfc(-z * 0.5.squareRoot())
}
/**
Returns the value of the normal density function.
https://en.wikipedia.org/wiki/Normal_distribution
- parameter x: The input value of the normal density function.
- parameter μ: The mean. Default: 0.
- parameter σ: The standard deviation. Default: 1.
- returns: The value of the normal density function. Returns nil if σ is zero or negative.
Formula (LaTeX):
rac{1}{\sqrt{2 \sigma^2 \pi}} e^{ - rac{(x - \mu)^2}{2 \sigma^2} }
Where:
x is the input value of the normal density function.
μ is the mean.
σ is the standard deviation.
Example:
Sigma.normalDensity(x: 0, μ: 0, σ: 1) // 0.3989422804014327
*/
static func normalDensity(x: Double, μ: Double = 0, σ: Double = 1) -> Double? {
if σ <= 0 { return nil }
return (1 / sqrt(2 * pow(σ,2) * Double.pi)) * pow(exp(1.0), (-( pow(x - μ, 2) / (2 * pow(σ, 2)) )))
}
/**
Returns the quantile function for the normal distribution.
https://en.wikipedia.org/wiki/Normal_distribution
- parameter p: The probability (area under the normal curve to the left of the returned value).
- parameter μ: The mean. Default: 0.
- parameter σ: The standard deviation. Default: 1.
- returns: The quantile function for the normal distribution. Returns nil if σ is zero or negative. Returns nil if p is negative or greater than one. Returns (-Double.infinity) if p is zero. Returns Double.infinity if p is one.
Example:
Sigma.normalQuantile(p: 0.025, μ: 0, σ: 1) // -1.9599639845400538
*/
static func normalQuantile(p: Double, μ: Double = 0, σ: Double = 1) -> Double? {
return qnorm(p: p, mu: μ, sigma: σ)
}
// MARK: - Protected functionality
/*
*
* Mathlib : A C Library of Special Functions
* Copyright (C) 1998 Ross Ihaka
* Copyright (C) 2000--2005 The R Core Team
* based on AS 111 (C) 1977 Royal Statistical Society
* and on AS 241 (C) 1988 Royal Statistical Society
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.R-project.org/Licenses/
*
* DESCRIPTION
*
* Compute the quantile function for the normal distribution.
*
* For small to moderate probabilities, algorithm referenced
* below is used to obtain an initial approximation which is
* polished with a final Newton step.
*
* For very large arguments, an algorithm of Wichura is used.
*
* REFERENCE
*
* Beasley, J. D. and S. G. Springer (1977).
* Algorithm AS 111: The percentage points of the normal distribution,
* Applied Statistics, 26, 118-121.
*
* Wichura, M.J. (1988).
* Algorithm AS 241: The Percentage Points of the Normal Distribution.
* Applied Statistics, 37, 477-484.
*/
/**
Computes the quantile function for the normal distribution.
Adapted from: https://svn.r-project.org/R/trunk/src/nmath/qnorm.c
- parameter p: The probability.
- parameter μ: The mean.
- parameter σ: The standard deviation.
- returns: The quantile function for the normal distribution. Returns nil if σ is zero or negative. Returns nil if p is negative or greater than one. Returns (-Double.infinity) if p is zero. Returns Double.infinity if p is one.
*/
static func qnorm(p: Double, mu: Double, sigma: Double) -> Double? {
if (p < 0 || p > 1) { return nil }
if (p == 0) { return -Double.infinity }
if (p == 1) { return Double.infinity }
if (sigma <= 0) { return nil }
let q = p - 0.5
var val: Double = 0, r: Double = 0
if (abs(q) <= 0.425) // 0.075 <= p <= 0.925
{
r = 0.180625 - q * q;
val = q * (((((((r * 2509.0809287301226727 +
33430.575583588128105) * r + 67265.770927008700853) * r +
45921.953931549871457) * r + 13731.693765509461125) * r +
1971.5909503065514427) * r + 133.14166789178437745) * r +
3.387132872796366608)
/ (((((((r * 5226.495278852854561 +
28729.085735721942674) * r + 39307.89580009271061) * r +
21213.794301586595867) * r + 5394.1960214247511077) * r +
687.1870074920579083) * r + 42.313330701600911252) * r + 1.0);
} else /* closer than 0.075 from {0,1} boundary */
{
r = q > 0 ? 1 - p : p;
r = sqrt(-log(r))
if (r <= 5) // <==> min(p,1-p) >= exp(-25) ~= 1.3888e-11
{
r -= 1.6;
val = (((((((r * 7.7454501427834140764e-4 +
0.0227238449892691845833) * r + 0.24178072517745061177) *
r + 1.27045825245236838258) * r +
3.64784832476320460504) * r + 5.7694972214606914055) *
r + 4.6303378461565452959) * r +
1.42343711074968357734)
/ (((((((r *
1.05075007164441684324e-9 + 5.475938084995344946e-4) *
r + 0.0151986665636164571966) * r +
0.14810397642748007459) * r + 0.68976733498510000455) *
r + 1.6763848301838038494) * r +
2.05319162663775882187) * r + 1.0);
}
else // very close to 0 or 1
{
r -= 5.0;
val = (((((((r * 2.01033439929228813265e-7 +
2.71155556874348757815e-5) * r +
0.0012426609473880784386) * r + 0.026532189526576123093) *
r + 0.29656057182850489123) * r +
1.7848265399172913358) * r + 5.4637849111641143699) *
r + 6.6579046435011037772)
/ (((((((r *
2.04426310338993978564e-15 + 1.4215117583164458887e-7) *
r + 1.8463183175100546818e-5) * r +
7.868691311456132591e-4) * r + 0.0148753612908506148525)
* r + 0.13692988092273580531) * r +
0.59983220655588793769) * r + 1.0);
}
if (q < 0.0) { val = -val; }
}
return (mu + sigma * val)
}
}
// ----------------------------
//
// CentralMoment.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 19/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Computes central moment of the dataset.
https://en.wikipedia.org/wiki/Central_moment
- parameter values: Array of decimal numbers.
- parameter order: The order of the moment (0, 1, 2, 3 etc.).
- returns: Central moment. Returns nil when the array is empty.
Formula:
Σ(x - m)^k / n
Where:
m is the sample mean.
k is the order of the moment (0, 1, 2, 3, ...).
n is the sample size.
Example:
Sigma.centralMoment([3, -1, 1, 4.1, 4.1, 0.7], order: 3) // -1.5999259259
*/
static func centralMoment(_ values: [Double], order: Int) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
guard let averageVal = average(values) else { return nil }
let total = values.reduce(0) { sum, value in
sum + pow((value - averageVal), Double(order))
}
return total / count
}
}
// ----------------------------
//
// Covariance.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Computes covariance of a sample between two variables: x and y.
http://en.wikipedia.org/wiki/Sample_mean_and_sample_covariance
- parameter x: Array of decimal numbers for the first variable.
- parameter y: Array of decimal numbers for the second variable.
- returns: Covariance of a sample between two variables: x and y. Returns nil if arrays x and y have different number of values. Returns nil for empty arrays or arrays containing a single element.
Formula:
cov(x,y) = Σ(x - mx)(y - my) / (n - 1)
Where:
mx is the sample mean of the first variable.
my is the sample mean of the second variable.
n is the total number of values.
Example:
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 1, 2.1, 3.4, 3.4, 4]
Sigma.covarianceSample(x: x, y: y) // 5.03
*/
static func covarianceSample(x: [Double], y: [Double]) -> Double? {
let xCount = Double(x.count)
let yCount = Double(y.count)
if xCount < 2 { return nil }
if xCount != yCount { return nil }
if let xMean = average(x),
let yMean = average(y) {
var sum:Double = 0
for (index, xElement) in x.enumerated() {
let yElement = y[index]
sum += (xElement - xMean) * (yElement - yMean)
}
return sum / (xCount - 1)
}
return nil
}
/**
Computes covariance for entire population between two variables: x and y.
http://en.wikipedia.org/wiki/Covariance
- parameter x: Array of decimal numbers for the first variable.
- parameter y: Array of decimal numbers for the second variable.
- returns: Covariance for entire population between two variables: x and y. Returns nil if arrays x and y have different number of values. Returns nil for empty arrays.
Formula:
cov(x,y) = Σ(x - mx)(y - my) / n
Where:
mx is the population mean of the first variable.
my is the population mean of the second variable.
n is the total number of values.
Example:
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 1, 2.1, 3.4, 3.4, 4]
Sigma.covariancePopulation(x: x, y: y) // 4.19166666666667
*/
static func covariancePopulation(x: [Double], y: [Double]) -> Double? {
let xCount = Double(x.count)
let yCount = Double(y.count)
if xCount == 0 { return nil }
if xCount != yCount { return nil }
if let xMean = average(x),
let yMean = average(y) {
var sum:Double = 0
for (index, xElement) in x.enumerated() {
let yElement = y[index]
sum += (xElement - xMean) * (yElement - yMean)
}
return sum / xCount
}
return nil
}
}
// ----------------------------
//
// Variance.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Computes variance based on a sample.
http://en.wikipedia.org/wiki/Variance
- parameter values: Array of decimal numbers.
- returns: Variance based on a sample. Returns nil when the array is empty or contains a single value.
Formula:
s^2 = Σ( (x - m)^2 ) / (n - 1)
Where:
m is the sample mean.
n is the sample size.
Example:
Sigma.varianceSample([1, 12, 19.5, -5, 3, 8]) // 75.24166667
*/
static func varianceSample(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count < 2 { return nil }
if let avgerageValue = average(values) {
let numerator = values.reduce(0) { total, value in
total + pow(avgerageValue - value, 2)
}
return numerator / (count - 1)
}
return nil
}
/**
Computes variance of entire population.
http://en.wikipedia.org/wiki/Variance
- parameter values: Array of decimal numbers.
- returns: Population variance. Returns nil when the array is empty.
Formula:
σ^2 = Σ( (x - m)^2 ) / n
Where:
m is the population mean.
n is the population size.
Example:
Sigma.variancePopulation([1, 12, 19.5, -5, 3, 8]) // 62.70138889
*/
static func variancePopulation(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
if let avgerageValue = average(values) {
let numerator = values.reduce(0) { total, value in
total + pow(avgerageValue - value, 2)
}
return numerator / count
}
return nil
}
}
// ----------------------------
//
// Pearson.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Calculates the Pearson product-moment correlation coefficient between two variables: x and y.
http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient
- parameter x: Array of decimal numbers for the first variable.
- parameter y: Array of decimal numbers for the second variable.
- returns: The Pearson product-moment correlation coefficient between two variables: x and y. Returns nil if arrays x and y have different number of values. Returns nil for empty arrays.
Formula:
p(x,y) = cov(x,y) / (σx * σy)
Where:
cov is the population covariance.
σx is the population standard deviation of x.
Example:
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 1, 2.1, 3.4, 3.4, 4]
Sigma.pearson(x: x, y: y) // 0.843760859352745
*/
static func pearson(x: [Double], y: [Double]) -> Double? {
if let cov = Sigma.covariancePopulation(x: x, y: y),
let σx = Sigma.standardDeviationPopulation(x),
let σy = Sigma.standardDeviationPopulation(y) {
if σx == 0 || σy == 0 { return nil }
return cov / (σx * σy)
}
return nil
}
}
// ----------------------------
//
// CoefficientVariation.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 21/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Computes coefficient of variation based on a sample.
https://en.wikipedia.org/wiki/Coefficient_of_variation
- parameter values: Array of decimal numbers.
- returns: Coefficient of variation of a sample. Returns nil when the array is empty or contains a single value. Returns Double.infinity if the mean is zero.
Formula:
CV = s / m
Where:
s is the sample standard deviation.
m is the mean.
Example:
Sigma.coefficientOfVariationSample([1, 12, 19.5, -5, 3, 8]) // 1.3518226672
*/
static func coefficientOfVariationSample(_ values: [Double]) -> Double? {
if values.count < 2 { return nil }
guard let stdDev = Sigma.standardDeviationSample(values) else { return nil }
guard let avg = average(values) else { return nil }
if avg == 0 { return stdDev >= 0 ? Double.infinity : -Double.infinity }
return stdDev / avg
}
}
// ----------------------------
//
// Median.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Returns the central value from the array after it is sorted.
http://en.wikipedia.org/wiki/Median
- parameter values: Array of decimal numbers.
- returns: The median value from the array. Returns nil for an empty array. Returns the mean of the two middle values if there is an even number of items in the array.
Example:
Sigma.median([1, 12, 19.5, 3, -5]) // 3
*/
static func median(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
let sorted = Sigma.sort(values)
if count.truncatingRemainder(dividingBy: 2) == 0 {
// Even number of items - return the mean of two middle values
let leftIndex = Int(count / 2 - 1)
let leftValue = sorted[leftIndex]
let rightValue = sorted[leftIndex + 1]
return (leftValue + rightValue) / 2
} else {
// Odd number of items - take the middle item.
return sorted[Int(count / 2)]
}
}
/**
Returns the central value from the array after it is sorted.
http://en.wikipedia.org/wiki/Median
- parameter values: Array of decimal numbers.
- returns: The median value from the array. Returns nil for an empty array. Returns the smaller of the two middle values if there is an even number of items in the array.
Example:
Sigma.medianLow([1, 12, 19.5, 10, 3, -5]) // 3
*/
static func medianLow(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
let sorted = values.sorted { $0 < $1 }
if count.truncatingRemainder(dividingBy: 2) == 0 {
// Even number of items - return the lower of the two middle values
return sorted[Int(count / 2) - 1]
} else {
// Odd number of items - take the middle item.
return sorted[Int(count / 2)]
}
}
/**
Returns the central value from the array after it is sorted.
http://en.wikipedia.org/wiki/Median
- parameter values: Array of decimal numbers.
- returns: The median value from the array. Returns nil for an empty array. Returns the greater of the two middle values if there is an even number of items in the array.
Example:
Sigma.medianHigh([1, 12, 19.5, 10, 3, -5]) // 10
*/
static func medianHigh(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
let sorted = values.sorted { $0 < $1 }
return sorted[Int(count / 2)]
}
}
// ----------------------------
//
// Frequencies.swift
//
// ----------------------------
//
// Frequencies.swift
// SigmaSwiftStatistics
//
// Created by Alan James Salmoni on 21/01/2017.
// Copyright © 2017 Evgenii Neumerzhitckii. All rights reserved.
//
import Foundation
public extension Sigma {
/*
Returns a dictionary with the keys containing the numbers from the input array and the values corresponding to the frequencies of those numbers.
- parameter values: Array of decimal numbers.
- returns: dictionary with the keys containing numbers from the input array and the values corresponding to the frequency of those numbers.
Example:
Sigma.frequencies([1, 2, 3, 4, 5, 4, 4, 3, 5]) // [2:1, 3:2, 4:3, 5:2, 1:1]
*/
static func frequencies(_ values: [Double]) -> ([Double: Int]) {
var counts: [Double: Int] = [:]
for item in values {
counts[item] = (counts[item] ?? 0) + 1
}
return counts
}
}
// ----------------------------
//
// Skewness.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 19/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Returns the skewness of the dataset. This implementation is the same as the SKEW function in Excel and Google Docs Sheets.
https://en.wikipedia.org/wiki/Skewness
- parameter values: Array of decimal numbers.
- returns: Skewness based on a sample. Returns nil if the dataset contains less than 3 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
rac{n}{(n-1)(n-2)}\sum_{i=1}^{n} rac{(x_i - ar{x})^3}{s^3}
Example:
Sigma.skewnessA([4, 2.1, 8, 21, 1]) // 1.6994131524
*/
static func skewnessA(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count < 3 { return nil }
guard let moment3 = centralMoment(values, order: 3) else { return nil }
guard let stdDev = standardDeviationSample(values) else { return nil }
if stdDev == 0 { return nil }
return pow(count, 2) / ((count - 1) * (count - 2)) * moment3 / pow(stdDev, 3)
}
/**
Returns the skewness of the dataset. This implementation is the same as in Wolfram Alpha, SKEW.P in Microsoft Excel and `skewness` function in "moments" R package..
https://en.wikipedia.org/wiki/Skewness
- parameter values: Array of decimal numbers.
- returns: Skewness based on a sample. Returns nil if the dataset contains less than 3 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
rac{1}{n}\sum_{i=1}^{n} rac{(x_i - ar{x})^3}{\sigma^3}
Example:
Sigma.skewnessB([4, 2.1, 8, 21, 1]) // 1.1400009992
*/
static func skewnessB(_ values: [Double]) -> Double? {
if values.count < 3 { return nil }
guard let stdDev = standardDeviationPopulation(values) else { return nil }
if stdDev == 0 { return nil }
guard let moment3 = centralMoment(values, order: 3) else { return nil }
return moment3 / pow(stdDev, 3)
}
}
// ----------------------------
//
// Sigma.swift
//
// ----------------------------
import Foundation
/**
Collection of functions for statistical calculation.
Project home: https://github.com/evgenyneu/SigmaSwiftStatistics
*/
public struct Sigma {
/**
Calculates the maximum value in the array.
- parameter values: Array of decimal numbers.
- returns: The maximum value in the array. Returns nil for an empty array.
Example:
Sigma.max([3, 10, 6]) // 10
*/
public static func max(_ values: [Double]) -> Double? {
if let maxValue = values.max() {
return maxValue
}
return nil
}
/**
Calculates the mimimum value in the array.
- parameter values: Array of decimal numbers.
- returns: The mimimum value in the array. Returns nil for an empty array.
Example:
Sigma.min([5, 3, 10]) // -> 3
*/
public static func min(_ values: [Double]) -> Double? {
if let minValue = values.min() {
return minValue
}
return nil
}
/**
Computes the sum of array values.
- parameter values: Array of decimal numbers.
- returns: The sum of array values.
Example:
Sigma.sum([1, 3, 10]) // 14
*/
public static func sum(_ values: [Double]) -> Double {
return values.reduce(0, +)
}
/**
Computes arithmetic mean of values in the array.
http://en.wikipedia.org/wiki/Arithmetic_mean
- parameter values: Array of decimal numbers.
- returns: Arithmetic mean of values in the array. Returns nil for an empty array.
Formula:
A = Σ(x) / n
Where n is the number of values.
Example:
Sigma.average([1, 12, 19.5, -5, 3, 8]) // 6.416666666666667
*/
public static func average(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
return sum(values) / count
}
// MARK: - Protected functionality
static func sort(_ values: [Double]) -> [Double] {
return values.sorted { $0 < $1 }
}
}
// ----------------------------
//
// Percentile.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Calculates Percentile value for the given dataset. This method is used same in Microsoft Excel (PERCENTILE or PERCENTILE.INC) and Google Docs Sheets (PERCENTILE). Same as the 7th sample quantile method from the Hyndman and Fan paper (1996).
https://en.wikipedia.org/wiki/Percentile
- parameter data: Array of decimal numbers in the dataset.
- parameter percentile: percentile between 0 and 1 inclusive. For example, value 0.4 corresponds to 40th percentile.
- returns: the percentile value.
Algorithm:
https://github.com/evgenyneu/SigmaSwiftStatistics/wiki/Percentile-1-method
Example:
Sigma.percentile1(values: [35, 20, 50, 40, 15], percentile: 0.4) // Result: 29
*/
static func percentile(_ data: [Double], percentile: Double) -> Double? {
return Sigma.quantiles.method7(data, probability: percentile)
}
}
// ----------------------------
//
// UniqueValues.swift
//
// ----------------------------
//
// UniqueValues.swift
// SigmaSwiftStatistics
//
// Created by Alan James Salmoni on 21/01/2017.
// Copyright © 2017 Evgenii Neumerzhitckii. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Returns an unsorted array containing all values that occur within the input array without the duplicates.
- parameter values: Array of numbers.
- returns: An unsorted array containing all values that occur within the input array without the duplicates.
Example:
Sigma.uniqueValues([2, 1, 3, 4, 5, 4, 3, 5]) // [2, 3, 4, 5, 1]
*/
static func uniqueValues(_ values: [Double]) -> [Double] {
return Array(Set(values))
}
}
| 26.374512 | 242 | 0.614979 |
fe52c3aa824cb66c3b47e99def4cf928a0a23b2e | 4,750 | //
// 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 {
func locationsPickedLocation(controller: LocationsViewController, latitude: NSNumber, longitude: NSNumber) {
let locationCoordinate = CLLocationCoordinate2D(latitude: latitude as! CLLocationDegrees, longitude: longitude as! CLLocationDegrees)
let annotation = MKPointAnnotation()
annotation.coordinate = locationCoordinate
annotation.title = "\(locationCoordinate.latitude)"
mapView.addAnnotation(annotation)
self.navigationController?.popToViewController(self, animated: true)
}
@IBOutlet weak var mapView: MKMapView!
var image: UIImage!
var imageToFull: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
//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)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTapTakePhoto(_ sender: Any) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = false
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 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
annotationView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
imageView.image = image ?? UIImage(named: "camera")
return annotationView
}
func mapView(_ mapView: MKMapView,
annotationView view: MKAnnotationView,
calloutAccessoryControlTapped control: UIControl) {
let imageView = view.leftCalloutAccessoryView as! UIImageView
imageToFull = imageView.image
self.performSegue(withIdentifier: "fullImageSegue", sender: nil)
}
@objc func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
// Get the image captured by the UIImagePickerController
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
image = chosenImage
// Dismiss UIImagePickerController to go back to your original view controller
dismiss(animated: true, completion: showLocationViewController)
}
func showLocationViewController() -> Void {
self.performSegue(withIdentifier: "tagSegue", sender: Any?.self)
}
// 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.
if segue.identifier == "tagSegue" {
let destination = segue.destination as! LocationsViewController
destination.delegate = self
}
if segue.identifier == "fullImageSegue" {
let destination = segue.destination as! FullImageViewController
destination.image = imageToFull
}
}
}
| 38.934426 | 165 | 0.665263 |
5b5580d3167830f119bda140aacbaaec077d032e | 5,898 | //
// Asset.swift
// AnyImageKit
//
// Created by 刘栋 on 2019/9/16.
// Copyright © 2019-2021 AnyImageProject.org. All rights reserved.
//
import UIKit
import Photos
public class Asset: IdentifiableResource {
/// 对应的 PHAsset
public let phAsset: PHAsset
/// 媒体类型
public let mediaType: MediaType
var _images: [ImageKey: UIImage] = [:]
var videoDidDownload: Bool = false
var idx: Int
var state: State = .unchecked
var selectedNum: Int = 1
public var identifier: String {
return phAsset.localIdentifier
}
init(idx: Int, asset: PHAsset, selectOptions: PickerSelectOption) {
self.idx = idx
self.phAsset = asset
self.mediaType = MediaType(asset: asset, selectOptions: selectOptions)
}
}
extension Asset {
/// 输出图像
public var image: UIImage {
return _image ?? .init()
}
var _image: UIImage? {
return (_images[.output] ?? _images[.edited]) ?? _images[.initial]
}
var duration: TimeInterval {
return phAsset.duration
}
var durationDescription: String {
let time = Int(duration)
let min = time / 60
let sec = time % 60
return String(format: "%02ld:%02ld", min, sec)
}
var isReady: Bool {
switch mediaType {
case .photo, .photoGIF, .photoLive:
return _image != nil
case .video:
return videoDidDownload
}
}
var isCamera: Bool {
return idx == Asset.cameraItemIdx
}
static let cameraItemIdx: Int = -1
}
extension Asset: CustomStringConvertible {
public var description: String {
return "<Asset> \(identifier) mediaType=\(mediaType) image=\(image)"
}
}
// MARK: - State
extension Asset {
enum State: Equatable {
case unchecked
case normal
case selected
case disable(AssetDisableCheckRule)
static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.unchecked, unchecked):
return true
case (.normal, normal):
return true
case (.selected, selected):
return true
case (.disable, disable):
return true
default:
return false
}
}
}
var isUnchecked: Bool {
return state == .unchecked
}
var isSelected: Bool {
get {
return state == .selected
}
set {
state = newValue ? .selected : .normal
}
}
var isDisable: Bool {
switch state {
case .disable(_):
return true
default:
return false
}
}
}
// MARK: - Disable Check
extension Asset {
func check(disable rules: [AssetDisableCheckRule]) {
guard isUnchecked else { return }
for rule in rules {
if rule.isDisable(for: self) {
state = .disable(rule)
return
}
}
state = .normal
}
}
// MARK: - Original Photo
extension Asset {
/// Fetch Photo Data 获取原图数据
/// - Note: Only for `MediaType` Photo, GIF, LivePhoto 仅用于媒体类型为照片、GIF、实况
/// - Parameter options: Photo Data Fetch Options 原图获取选项
/// - Parameter completion: Photo Data Fetch Completion 原图获取结果回调
@discardableResult
public func fetchPhotoData(options: PhotoDataFetchOptions = .init(), completion: @escaping PhotoDataFetchCompletion) -> PHImageRequestID {
guard phAsset.mediaType == .image else {
completion(.failure(.invalidMediaType), 0)
return 0
}
return ExportTool.requestPhotoData(for: phAsset, options: options, completion: completion)
}
/// Fetch Photo URL 获取原图路径
/// - Note: Only for `MediaType` Photo, PhotoGIF 仅用于媒体类型为照片、GIF
/// - Parameter options: Photo URL Fetch Options 原图路径获取选项
/// - Parameter completion: Photo URL Fetch Completion 原图路径获取结果回调
@discardableResult
public func fetchPhotoURL(options: PhotoURLFetchOptions = .init(), completion: @escaping PhotoURLFetchCompletion) -> PHImageRequestID {
guard phAsset.mediaType == .image else {
completion(.failure(.invalidMediaType), 0)
return 0
}
return ExportTool.requestPhotoURL(for: phAsset, options: options, completion: completion)
}
}
// MARK: - Video
extension Asset {
/// Fetch Video 获取视频,用于播放
/// - Note: Only for `MediaType` Video 仅用于媒体类型为视频
/// - Parameter options: Video Fetch Options 视频获取选项
/// - Parameter completion: Video Fetch Completion 视频获取结果回调
@discardableResult
public func fetchVideo(options: VideoFetchOptions = .init(), completion: @escaping VideoFetchCompletion) -> PHImageRequestID {
guard phAsset.mediaType == .video else {
completion(.failure(.invalidMediaType), 0)
return 0
}
return ExportTool.requestVideo(for: phAsset, options: options, completion: completion)
}
/// Fetch Video URL 获取视频路径,用于传输
/// - Note: Only for `MediaType` Video 仅用于媒体类型为视频
/// - Parameter options: Video URL Fetch Options 视频路径获取选项
/// - Parameter completion: Video URL Fetch Completion 视频路径获取结果回调
@discardableResult
public func fetchVideoURL(options: VideoURLFetchOptions = .init(), completion: @escaping VideoURLFetchCompletion) -> PHImageRequestID {
guard phAsset.mediaType == .video else {
completion(.failure(.invalidMediaType), 0)
return 0
}
return ExportTool.requestVideoURL(for: phAsset, options: options, completion: completion)
}
}
extension Asset {
enum ImageKey: String, Hashable {
case initial
case edited
case output
}
}
| 27.560748 | 142 | 0.594778 |
1808dcc63f8cfda2cd08e53f304647f4f97a3123 | 842 | //
// LaunchScreenViewController.swift
// AlbumMarvel
//
// Created by Gabriel Souza de Araujo on 18/08/21.
//
import UIKit
class FirstLoadAPIViewController: UIViewController {
var canRefresh:Bool = false
@IBOutlet var activityIndicator: UIActivityIndicatorView!
@IBOutlet var funnyLoadingLabel: UILabel!
override func viewDidLoad() {
self.funnyLoadingLabel.text = funnySentences[0]
//Change sentence
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { _ in
self.funnyLoadingLabel.text = funnySentences.randomElement()
}
let storyboard = UIStoryboard(name: "Menu", bundle: nil)
let mainVC = storyboard.instantiateViewController(withIdentifier: "MenuViewController")
self.searchCharacter(thenPresent: mainVC)
}
}
| 22.756757 | 95 | 0.687648 |
ef1b6d2753318408bfce70cbed24769204ef671d | 281 | import CoreMedia
extension CMSampleTimingInfo {
init(sampleBuffer: CMSampleBuffer) {
self.init()
duration = sampleBuffer.duration
decodeTimeStamp = sampleBuffer.decodeTimeStamp
presentationTimeStamp = sampleBuffer.presentationTimeStamp
}
}
| 25.545455 | 66 | 0.725979 |
33a219526f30b07d8f3806dcac7ab786b396d0f6 | 3,219 | // MIT License
//
// Copyright (c) 2017-present qazyn951230 [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
public enum JSONParseError: Error {
case valueInvalid
case invalidEncoding
case missQuotationMark
case stringEscapeInvalid
case stringUnicodeSurrogateInvalid
case stringUnicodeEscapeInvalidHex
case objectMissName
case objectMissColon
case objectMissCommaOrCurlyBracket
case arrayMissCommaOrSquareBracket
case numberMissFraction
case numberTooBig
case numberMissExponent
static func create(status: JSONParseStatus) -> JSONParseError {
switch status {
case JSONParseStatus.valueInvalid:
return JSONParseError.valueInvalid
case JSONParseStatus.invalidEncoding:
return JSONParseError.invalidEncoding
case JSONParseStatus.missQuotationMark:
return JSONParseError.missQuotationMark
case JSONParseStatus.stringEscapeInvalid:
return JSONParseError.stringEscapeInvalid
case JSONParseStatus.stringUnicodeSurrogateInvalid:
return JSONParseError.stringUnicodeSurrogateInvalid
case JSONParseStatus.stringUnicodeEscapeInvalidHex:
return JSONParseError.stringUnicodeEscapeInvalidHex
case JSONParseStatus.objectMissName:
return JSONParseError.objectMissName
case JSONParseStatus.objectMissColon:
return JSONParseError.objectMissColon
case JSONParseStatus.objectMissCommaOrCurlyBracket:
return JSONParseError.objectMissCommaOrCurlyBracket
case JSONParseStatus.arrayMissCommaOrSquareBracket:
return JSONParseError.arrayMissCommaOrSquareBracket
case JSONParseStatus.numberMissFraction:
return JSONParseError.numberMissFraction
case JSONParseStatus.numberTooBig:
return JSONParseError.numberTooBig
case JSONParseStatus.numberMissExponent:
return JSONParseError.numberMissExponent
case JSONParseStatus.success:
return JSONParseError.valueInvalid
@unknown default:
return JSONParseError.valueInvalid
}
}
}
| 44.09589 | 81 | 0.74868 |
4b08a9e50912783d565ce12feb57a1f78f5a20d2 | 958 | //
// ASAttributedLabelNode_Demo_Tests.swift
// ASAttributedLabelNode-Demo-Tests
//
// Created by Alex Studnicka on 05/01/15.
// Copyright (c) 2015 astudnicka. All rights reserved.
//
import UIKit
import XCTest
class ASAttributedLabelNode_Demo_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.891892 | 111 | 0.635699 |
fe45249b295fbeaa3473c960adffb74ded6defff | 396 | //
// ActivitySummaryType.swift
// Sportskanone
//
// Created by Fabian Pahl on 29.03.17.
// Copyright © 2017 21st digital GmbH. All rights reserved.
//
import Foundation
protocol ActivitySummaryType {
associatedtype User: UserType
typealias Calories = Int
var date: Date { get }
var updatedAt: Date? { get }
var activeEnergyBurned: Calories { get }
var user: User { get }
}
| 18 | 60 | 0.69697 |
7996eab0ca6508086ea349f1b599e371feb4ed3f | 535 | //
// Created by Arnon Keereena on 2019-02-14.
// Copyright (c) 2019 AMOS Thailand. All rights reserved.
//
#if !(TARGET_OS_SIMUATOR || TARGET_OS_iOS)
// If the target is OS simulator or iOS then it is built with cocoapods
// and is using subspecs where module dependencies is not required.
import AlgebraFx
#endif
import Foundation
import SwiftExpansion
import RxSwiftExpansion
import RxSwift
import RxCocoa
extension DriverType {
public static func |>>(left: E, right: Self) -> Driver<E> {
return right.startWith(left)
}
}
| 24.318182 | 71 | 0.749533 |
0a267a9bf298b9c8f0cb9a5ff031963756ee4fa2 | 11,768 | //
// DemoBaseViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-03.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
enum Option {
case toggleValues
case toggleIcons
case toggleHighlight
case animateX
case animateY
case animateXY
case saveToGallery
case togglePinchZoom
case toggleAutoScaleMinMax
case toggleData
case toggleBarBorders
// CandleChart
case toggleShadowColorSameAsCandle
case toggleShowCandleBar
// CombinedChart
case toggleLineValues
case toggleBarValues
case removeDataSet
// CubicLineSampleFillFormatter
case toggleFilled
case toggleCircles
case toggleCubic
case toggleHorizontalCubic
case toggleStepped
// HalfPieChartController
case toggleXValues
case togglePercent
case toggleHole
case spin
case drawCenter
// RadarChart
case toggleXLabels
case toggleYLabels
case toggleRotate
case toggleHighlightCircle
var label: String {
switch self {
case .toggleValues: return "Toggle Y-Values"
case .toggleIcons: return "Toggle Icons"
case .toggleHighlight: return "Toggle Highlight"
case .animateX: return "Animate X"
case .animateY: return "Animate Y"
case .animateXY: return "Animate XY"
case .saveToGallery: return "Save to Camera Roll"
case .togglePinchZoom: return "Toggle PinchZoom"
case .toggleAutoScaleMinMax: return "Toggle auto scale min/max"
case .toggleData: return "Toggle Data"
case .toggleBarBorders: return "Toggle Bar Borders"
// CandleChart
case .toggleShadowColorSameAsCandle: return "Toggle shadow same color"
case .toggleShowCandleBar: return "Toggle show candle bar"
// CombinedChart
case .toggleLineValues: return "Toggle Line Values"
case .toggleBarValues: return "Toggle Bar Values"
case .removeDataSet: return "Remove Random Set"
// CubicLineSampleFillFormatter
case .toggleFilled: return "Toggle Filled"
case .toggleCircles: return "Toggle Circles"
case .toggleCubic: return "Toggle Cubic"
case .toggleHorizontalCubic: return "Toggle Horizontal Cubic"
case .toggleStepped: return "Toggle Stepped"
// HalfPieChartController
case .toggleXValues: return "Toggle X-Values"
case .togglePercent: return "Toggle Percent"
case .toggleHole: return "Toggle Hole"
case .spin: return "Spin"
case .drawCenter: return "Draw CenterText"
// RadarChart
case .toggleXLabels: return "Toggle X-Labels"
case .toggleYLabels: return "Toggle Y-Labels"
case .toggleRotate: return "Toggle Rotate"
case .toggleHighlightCircle: return "Toggle highlight circle"
}
}
}
class DemoBaseViewController: UIViewController, ChartViewDelegate {
private var optionsTableView: UITableView? = nil
let parties = ["Party A", "Party B", "Party C", "Party D", "Party E", "Party F",
"Party G", "Party H", "Party I", "Party J", "Party K", "Party L",
"Party M", "Party N", "Party O", "Party P", "Party Q", "Party R",
"Party S", "Party T", "Party U", "Party V", "Party W", "Party X",
"Party Y", "Party Z"]
@IBOutlet weak var optionsButton: UIButton!
var options: [Option]!
var shouldHideData: Bool = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initialize()
}
private func initialize() {
self.edgesForExtendedLayout = []
}
func optionTapped(_ option: Option) {}
func handleOption(_ option: Option, forChartView chartView: ChartViewBase) {
switch option {
case .toggleValues:
for set in chartView.data!.dataSets {
set.drawValuesEnabled = !set.drawValuesEnabled
}
chartView.setNeedsDisplay()
case .toggleIcons:
for set in chartView.data!.dataSets {
set.drawIconsEnabled = !set.drawIconsEnabled
}
chartView.setNeedsDisplay()
case .toggleHighlight:
chartView.data!.highlightEnabled = !chartView.data!.isHighlightEnabled
chartView.setNeedsDisplay()
case .animateX:
chartView.animate(xAxisDuration: 3)
case .animateY:
chartView.animate(yAxisDuration: 3)
case .animateXY:
chartView.animate(xAxisDuration: 3, yAxisDuration: 3)
case .saveToGallery:
UIImageWriteToSavedPhotosAlbum(chartView.getChartImage(transparent: false)!, nil, nil, nil)
case .togglePinchZoom:
let barLineChart = chartView as! BarLineChartViewBase
barLineChart.pinchZoomEnabled = !barLineChart.pinchZoomEnabled
chartView.setNeedsDisplay()
case .toggleAutoScaleMinMax:
let barLineChart = chartView as! BarLineChartViewBase
barLineChart.autoScaleMinMaxEnabled = !barLineChart.isAutoScaleMinMaxEnabled
chartView.notifyDataSetChanged()
case .toggleData:
shouldHideData = !shouldHideData
updateChartData()
case .toggleBarBorders:
for set in chartView.data!.dataSets {
if let set = set as? BarChartDataSet {
set.barBorderWidth = set.barBorderWidth == 1.0 ? 0.0 : 1.0
}
}
chartView.setNeedsDisplay()
default:
break
}
}
@IBAction func optionsButtonTapped(_ sender: Any) {
if let optionsTableView = self.optionsTableView {
optionsTableView.removeFromSuperview()
self.optionsTableView = nil
return
}
let optionsTableView = UITableView()
optionsTableView.backgroundColor = UIColor(white: 0, alpha: 0.9)
optionsTableView.delegate = self
optionsTableView.dataSource = self
optionsTableView.translatesAutoresizingMaskIntoConstraints = false
self.optionsTableView = optionsTableView
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: optionsTableView,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1,
constant: 40))
constraints.append(NSLayoutConstraint(item: optionsTableView,
attribute: .trailing,
relatedBy: .equal,
toItem: sender as! UIView,
attribute: .trailing,
multiplier: 1,
constant: 0))
constraints.append(NSLayoutConstraint(item: optionsTableView,
attribute: .top,
relatedBy: .equal,
toItem: sender,
attribute: .bottom,
multiplier: 1,
constant: 5))
self.view.addSubview(optionsTableView)
constraints.forEach { $0.isActive = true }
let constraint = NSLayoutConstraint(item: optionsTableView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: 220)
constraint.isActive = true
}
func updateChartData() {
fatalError("updateChartData not overridden")
}
func setup(pieChartView chartView: PieChartView) {
chartView.usePercentValuesEnabled = true
chartView.drawSlicesUnderHoleEnabled = false
chartView.holeRadiusPercent = 0.58
chartView.transparentCircleRadiusPercent = 0.61
chartView.chartDescription?.enabled = false
chartView.setExtraOffsets(left: 5, top: 10, right: 5, bottom: 5)
chartView.drawCenterTextEnabled = false
chartView.drawHoleEnabled = true
chartView.rotationAngle = 0
chartView.rotationEnabled = false
chartView.highlightPerTapEnabled = false
}
func setup(radarChartView chartView: RadarChartView) {
chartView.chartDescription?.enabled = false
}
func setup(barLineChartView chartView: BarLineChartViewBase) {
chartView.chartDescription?.enabled = false
chartView.dragEnabled = true
chartView.setScaleEnabled(true)
chartView.pinchZoomEnabled = false
// ChartYAxis *leftAxis = chartView.leftAxis;
let xAxis = chartView.xAxis
xAxis.labelPosition = .bottom
chartView.rightAxis.enabled = false
}
// TODO: Cannot override from extensions
//extension DemoBaseViewController: ChartViewDelegate {
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
NSLog("chartValueSelected");
}
func chartValueNothingSelected(_ chartView: ChartViewBase) {
NSLog("chartValueNothingSelected");
}
func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
}
func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
}
}
extension DemoBaseViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if optionsTableView != nil {
return 1
}
return 0
}
@available(iOS 2.0, *)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if optionsTableView != nil {
return options.count
}
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if optionsTableView != nil {
return 40.0;
}
return 44.0;
}
@available(iOS 2.0, *)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell?.backgroundView = nil
cell?.backgroundColor = .clear
cell?.textLabel?.textColor = .white
}
cell?.textLabel?.text = self.options[indexPath.row].label
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if optionsTableView != nil {
tableView.deselectRow(at: indexPath, animated: true)
optionsTableView?.removeFromSuperview()
self.optionsTableView = nil
self.optionTapped(self.options[indexPath.row])
}
}
}
| 34.110145 | 103 | 0.593899 |
8f649ec159a3c406538d3eb68a00a8bf5484b7b7 | 429 | //
// Node+CoreDataProperties.swift
// weToExplore
//
// Created by Daniel Tan on 8/12/16.
// Copyright © 2016 Gnodnate. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Node {
@NSManaged var name: String?
@NSManaged var title: String?
}
| 20.428571 | 76 | 0.72028 |
917af686067808194275c5d67d12f6d52762e57d | 2,013 | //
// RootCoordinator.swift
// HealiosTest
//
// Created by Eugenio on 10/10/2020.
// Copyright © 2020 Eugenio Barquín. All rights reserved.
//
import UIKit
final class RootCoordinator: Coordinator {
private unowned let navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
override func start() {
let viewController = setupViewController()
navigationController.pushViewController(viewController, animated: true)
}
private func setupViewController() -> UIViewController {
let viewController = RootViewController.initFromStoryboard()
let commentRepository = CommentRepositoryDefault()
let userRepository = UserRepositoryDefault()
let postRepository = PostRepositoryDefault()
let eventManager = EventManager.shared
let coreDataStack = CoreDataStack()
let postCoreDataService = PostCoreDataService(context: coreDataStack.context, coreDataStack: coreDataStack)
let userCoreDataService = UserCoreDataService(context: coreDataStack.context, coreDataStack: coreDataStack)
let commentCoreDataService = CommentCoreDataService(context: coreDataStack.context, coreDataStack: coreDataStack)
let viewModel = RootViewModel(commentRepository: commentRepository, userRepository: userRepository, postRepository: postRepository, eventManager: eventManager, coreDataManager: coreDataStack, postCoreDataService: postCoreDataService, userCoreDataService: userCoreDataService, commentCoreDataService: commentCoreDataService)
viewController.viewModel = viewModel
viewController.navigateToDetail = navigateToDetail
return viewController
}
private func navigateToDetail(post: Post) {
let coordinator = DetailCoordinator(navigationController: navigationController, post: post)
add(child: coordinator)
coordinator.start()
}
}
| 43.76087 | 331 | 0.753602 |
231f3aab07329a4ef21baced8b3d311ded5814eb | 653 | //
// AppDelegate.swift
// AutoLayoutKeyPaths
//
// Created by Andres Rojas on 5/11/19.
// Copyright © 2019 Andres Rojas. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window : UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = .white
self.window?.rootViewController = ViewController()
self.window?.makeKeyAndVisible()
return true
}
}
| 23.321429 | 145 | 0.709035 |
39b1d218e587d7735149c2446fe0bcf55bbff28f | 478 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol b {
protocol a {
typealias g: start, g> {
}
}
}
func a<T) {
class a: b
| 28.117647 | 79 | 0.728033 |
d71c1c716d617ecaff1b6fdff95c6534c9df58fc | 2,097 | import Foundation
import TuistCore
import XCTest
/// A stub clock that can be primed with
/// multiple dates and timers.
public class StubClock: Clock {
/// Returns primed dates in the order they
/// were added to `primedDates`.
///
/// In the event there are no primed dates, `Date.distantPast`
/// is returned.
public var now: Date {
if let first = primedDates.first {
primedDates.removeFirst()
return first
}
return .distantPast
}
/// The dates to return when calling `now`
/// in the order they are specified.
public var primedDates: [Date] = []
/// The time intervals to return from timers
/// obtained when calling `startTimer()` in the
/// order they are specified.
public var primedTimers: [TimeInterval] = []
/// Asserts when the stub methods are called
/// while there is no more stubbed data
public var assertOnUnexpectedCalls: Bool = false
public init() {}
/// Returns stub timers that are primed with time intervals in the
/// the order they were defined in `primedTimers`.
///
/// In the event there are no primed time intervals, A stub timer
/// with a time interval of `0` is returned.
public func startTimer() -> ClockTimer {
if let first = primedTimers.first {
primedTimers.removeFirst()
return Timer(timeInterval: first)
}
if assertOnUnexpectedCalls {
XCTFail("Trying to get more timers than the ones stubbed")
}
return Timer(timeInterval: 0.0)
}
private class Timer: ClockTimer {
private let timeInterval: TimeInterval
private var stopCount = 0
fileprivate init(timeInterval: TimeInterval) {
self.timeInterval = timeInterval
}
func stop() -> TimeInterval {
defer {
stopCount += 1
}
if stopCount >= 1 {
XCTFail("Attempting to stop a timer more than once")
}
return timeInterval
}
}
}
| 29.125 | 70 | 0.602289 |
4a6da1750a84e96da944e64e4a70394623c04a02 | 2,096 | //
// MoviesTabBarController.swift
// Cineaste
//
// Created by Felizia Bernutz on 01.01.18.
// Copyright © 2018 notimeforthat.org. All rights reserved.
//
import UIKit
class MoviesTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let storageManager = MovieStorageManager()
let watchlistVC = MoviesViewController.instantiate()
watchlistVC.category = .watchlist
watchlistVC.tabBarItem = UITabBarItem(title: String.watchlist,
image: MovieListCategory.watchlist.image,
tag: 0)
watchlistVC.tabBarItem.accessibilityIdentifier = "WatchlistTab"
watchlistVC.storageManager = storageManager
let watchlistVCWithNavi = OrangeNavigationController(rootViewController: watchlistVC)
let seenVC = MoviesViewController.instantiate()
seenVC.category = .seen
seenVC.tabBarItem = UITabBarItem(title: String.seen,
image: MovieListCategory.seen.image,
tag: 1)
seenVC.tabBarItem.accessibilityIdentifier = "SeenTab"
seenVC.storageManager = storageManager
let seenVCWithNavi = OrangeNavigationController(rootViewController: seenVC)
let settingsVC = SettingsViewController.instantiate()
settingsVC.tabBarItem = UITabBarItem(title: String.settingsTitle,
image: UIImage.settingsIcon,
tag: 2)
settingsVC.tabBarItem.accessibilityIdentifier = "SettingsTab"
settingsVC.storageManager = storageManager
let settingsVCWithNavi = OrangeNavigationController(rootViewController: settingsVC)
viewControllers = [watchlistVCWithNavi, seenVCWithNavi, settingsVCWithNavi]
}
}
extension MoviesTabBarController: Instantiable {
static var storyboard: Storyboard { return .main }
static var storyboardID: String? { return "MoviesTabBarController" }
}
| 40.307692 | 93 | 0.650763 |
fbb7919f2958504d1e2f675bce7f22dede1a6fca | 4,523 | //
// Copyright 2021 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 SwiftUI
import DesignKit
@available(iOS, introduced: 14.0, deprecated: 15.0, message: "Use Text with an AttributedString instead.")
/// A `Text` view that renders attributed strings with their `.font` and `.foregroundColor` attributes.
/// This view is a workaround for iOS 13/14 not supporting `AttributedString`.
struct StyledText: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme
/// A string with a bold property.
private struct StringComponent {
let string: String
var font: Font? = nil
var color: Color? = nil
}
/// Internal representation of the string as composable parts.
private let components: [StringComponent]
// MARK: - Setup
/// Creates a `StyledText` using the supplied attributed string.
/// - Parameter attributedString: The attributed string to display.
init(_ attributedString: NSAttributedString) {
var components = [StringComponent]()
let range = NSRange(location: 0, length: attributedString.length)
let string = attributedString.string as NSString
attributedString.enumerateAttributes(in: range, options: []) { attributes, range, stop in
let font = attributes[.font] as? UIFont
let color = attributes[.foregroundColor] as? UIColor
let component = StringComponent(
string: string.substring(with: range),
font: font.map { Font($0) },
color: color.map { Color($0) }
)
components.append(component)
}
self.components = components
}
/// Creates a `StyledText` using a plain string.
/// - Parameter string: The plain string to display
init(_ string: String) {
self.components = [StringComponent(string: string, font: nil)]
}
// MARK: - Views
var body: some View {
components.reduce(Text("")) { lastValue, component in
lastValue + Text(component.string)
.font(component.font)
.foregroundColor(component.color)
}
}
}
@available(iOS 14.0, *)
struct StyledText_Previews: PreviewProvider {
static func prettyText() -> NSAttributedString {
let string = NSMutableAttributedString(string: "T", attributes: [
.font: UIFont.boldSystemFont(ofSize: 12),
.foregroundColor: UIColor.red
])
string.append(NSAttributedString(string: "e", attributes: [
.font: UIFont.boldSystemFont(ofSize: 14),
.foregroundColor: UIColor.orange
]))
string.append(NSAttributedString(string: "s", attributes: [
.font: UIFont.boldSystemFont(ofSize: 13),
.foregroundColor: UIColor.yellow
]))
string.append(NSAttributedString(string: "t", attributes: [
.font: UIFont.boldSystemFont(ofSize: 15),
.foregroundColor: UIColor.green
]))
string.append(NSAttributedString(string: "i", attributes: [
.font: UIFont.boldSystemFont(ofSize: 11),
.foregroundColor: UIColor.cyan
]))
string.append(NSAttributedString(string: "n", attributes: [
.font: UIFont.boldSystemFont(ofSize: 16),
.foregroundColor: UIColor.blue
]))
string.append(NSAttributedString(string: "g", attributes: [
.font: UIFont.boldSystemFont(ofSize: 14),
.foregroundColor: UIColor.purple
]))
return string
}
static var previews: some View {
VStack(spacing: 8) {
StyledText("Hello, World!")
StyledText(NSAttributedString(string: "Testing",
attributes: [.font: UIFont.boldSystemFont(ofSize: 64)]))
StyledText(prettyText())
}
}
}
| 35.614173 | 106 | 0.616405 |
8f403c82168a251d87ae90187dd23ca5ffb01729 | 6,253 | // License: http://creativecommons.org/publicdomain/zero/1.0/
// Import the required libraries
import CGLFW3
import SwiftGL
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
// Window dimensions
let WIDTH:GLsizei = 800, HEIGHT:GLsizei = 600
// Shaders
let vertexShaderSource = "#version 330 core\n" +
"layout (location = 0) in vec3 position;\n" +
"layout (location = 1) in vec3 color;\n" +
"out vec4 vertexColor;\n" +
"void main()\n" +
"{\n" +
"gl_Position = vec4(position, 1.0);\n" +
"vertexColor = vec4(0.5f, 0.0f, 0.0f, 1.0f);\n" +
"}\n"
let fragmentShaderSource = "#version 330 core\n" +
"out vec4 color;\n" +
"in vec4 vertexColor;\n" +
"uniform vec4 ourColor;\n" +
"void main()\n" +
"{\n" +
"color = ourColor;\n" +
"}\n"
// The *main* function; where our program begins running
func main()
{
print("Starting GLFW context, OpenGL 3.3")
// Init GLFW
glfwInit()
// Terminate GLFW when this function ends
defer { glfwTerminate() }
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE)
// Create a GLFWwindow object that we can use for GLFW's functions
let window = glfwCreateWindow(WIDTH, HEIGHT, "LearnSwiftGL", nil, nil)
glfwMakeContextCurrent(window)
guard window != nil else
{
print("Failed to create GLFW window")
return
}
// Set the required callback functions
glfwSetKeyCallback(window, keyCallback)
// Define the viewport dimensions
glViewport(x: 0, y: 0, width: WIDTH, height: HEIGHT)
// Build and compile our shader program
// Vertex shader
let vertexShader = glCreateShader(type: GL_VERTEX_SHADER)
vertexShaderSource.withCString {
var s = [$0]
glShaderSource(shader: vertexShader, count: 1, string: &s, length: nil)
}
glCompileShader(vertexShader)
// Check for compile time errors
var success:GLint = 0
var infoLog = [GLchar](repeating: 0, count: 512)
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success)
guard success == GL_TRUE else
{
glGetShaderInfoLog(vertexShader, 512, nil, &infoLog)
fatalError(String(cString:infoLog))
}
// Fragment shader
let fragmentShader = glCreateShader(type: GL_FRAGMENT_SHADER)
fragmentShaderSource.withCString {
var s = [$0]
glShaderSource(shader: fragmentShader, count: 1, string: &s, length: nil)
}
glCompileShader(fragmentShader)
// Check for compile time errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success)
guard success == GL_TRUE else
{
glGetProgramInfoLog(fragmentShader, 512, nil, &infoLog)
fatalError(String(cString:infoLog))
}
// Link shaders
let shaderProgram = glCreateProgram()
defer { glDeleteProgram(shaderProgram) }
glAttachShader(shaderProgram, vertexShader)
glAttachShader(shaderProgram, fragmentShader)
glLinkProgram(shaderProgram)
// Check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success)
guard success == GL_TRUE else
{
glGetShaderInfoLog(shaderProgram, 512, nil, &infoLog)
fatalError(String(cString:infoLog))
}
// We no longer need these since they are in the shader program
glDeleteShader(vertexShader)
glDeleteShader(fragmentShader)
// Set up vertex data
let vertices:[GLfloat] = [
0.5, -0.5, 0.0, // Bottom Right
-0.5, -0.5, 0.0, // Bottom Left
0.0, 0.5, 0.0 // Top
]
var VBO:GLuint=0, VAO:GLuint=0
glGenVertexArrays(n: 1, arrays: &VAO)
defer { glDeleteVertexArrays(1, &VAO) }
glGenBuffers(n: 1, buffers: &VBO)
defer { glDeleteBuffers(1, &VBO) }
// Bind the Vertex Array Object first, then bind and set
// vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO)
glBindBuffer(target: GL_ARRAY_BUFFER, buffer: VBO)
glBufferData(target: GL_ARRAY_BUFFER,
size: MemoryLayout<GLfloat>.stride * vertices.count,
data: vertices, usage: GL_STATIC_DRAW)
glVertexAttribPointer(index: 0, size: 3, type: GL_FLOAT,
normalized: false, stride: GLsizei(MemoryLayout<GLfloat>.stride * 3), pointer: nil)
glEnableVertexAttribArray(0)
glBindBuffer(target: GL_ARRAY_BUFFER, buffer: 0) // Note that this is allowed,
// the call to glVertexAttribPointer registered VBO as the currently bound
// vertex buffer object so afterwards we can safely unbind.
glBindVertexArray(0) // Unbind VAO; it's always a good thing to
// unbind any buffer/array to prevent strange bugs.
// remember: do NOT unbind the EBO, keep it bound to this VAO.
// Game loop
while glfwWindowShouldClose(window) == GL_FALSE
{
// Check if any events have been activated
// (key pressed, mouse moved etc.) and call
// the corresponding response functions
glfwPollEvents()
// Render
// Clear the colorbuffer
glClearColor(red: 0.2, green: 0.3, blue: 0.3, alpha: 1.0)
glClear(GL_COLOR_BUFFER_BIT)
// Draw our first triangle
glUseProgram(shaderProgram)
// Update the uniform color
let timeValue = glfwGetTime()
let greenValue = (sin(timeValue) / 2) + 0.5
let vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor")
glUniform4f(vertexColorLocation, 0.0, Float(greenValue), 0.0, 1.0)
glBindVertexArray(VAO)
glDrawArrays(GL_TRIANGLES, 0, 3)
glBindVertexArray(0)
// Swap the screen buffers
glfwSwapBuffers(window)
}
}
// called whenever a key is pressed/released via GLFW
func keyCallback(window: OpaquePointer!, key: Int32, scancode: Int32, action: Int32, mode: Int32)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE)
}
}
// Start the program with function main()
main()
| 33.084656 | 97 | 0.661762 |
f5768f4712bf1c9b4cebf6886555cbb9123765fa | 2,172 | //
// AppDelegate.swift
// BigFloat
//
// Created by primetimer on 10/28/2017.
// Copyright (c) 2017 primetimer. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.212766 | 285 | 0.754604 |
466877a52aeff2ff50dbf91d32f9c4dc20b9ed7d | 503 | import Foundation
@testable import RestLikeKit
extension ResourceRequest {
func expectedRequestBodyData() -> Data? {
if parameters is Empty {
return nil
} else {
return try! JSONEncoder.standard.encode(parameters)
}
}
func expectedResponseBodyData<T: Encodable>(response: T) -> Data? {
if response is Empty {
return nil
} else {
return try! JSONEncoder.standard.encode(response)
}
}
}
| 23.952381 | 71 | 0.586481 |
d6bc6cea9b291190f1c6bab7bbf5afd2fd1fece2 | 1,649 | //
// RidersVC.swift
// E-Ticketing
//
// Created by Muhammad Naveed on 24/08/2020.
// Copyright © 2020 technerds. All rights reserved.
//
import UIKit
class RidersVC: UIViewController {
//MARK:- outllets
@IBOutlet private weak var tableView: UITableView!
//MARK:- variables
var userList: [UserModel] = []
private var userManager = UserManager()
//MARK:- life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Select Rider"
self.userList = userManager.getUsers()
}
}
//MARK:- tableView datasource
extension RidersVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "MyTableViewCell")
let item = userList[indexPath.row]
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = item.userType
cell.detailTextLabel?.text = item.subtext
return cell
}
}
//MARK:- tableView daelegate
extension RidersVC: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let user = userList[indexPath.row]
let storyboard = UIStoryboard.get(.main)
let vc = storyboard.instantiateViewController(identifier: FaresVC.className) as! FaresVC
vc.user = user
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 27.949153 | 100 | 0.681019 |
ffbf69a06617f31034478b982d9b3f7fc4773d9e | 1,259 | /*
* Copyright (c) 2021 Natan Zalkin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import Foundation
public protocol Action {
associatedtype Dispatcher
func execute(with dispatcher: Dispatcher) async
}
| 39.34375 | 81 | 0.755361 |
ac1710221dfcc3def1b737e30bb76cd1ddc70125 | 2,245 | // swift-tools-version:5.3
//
// Hall
//
// Copyright (c) 2020 Wellington Marthas
//
// 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 PackageDescription
let package = Package(
name: "Hall",
platforms: [
.iOS(.v11), .macOS(.v10_13), .watchOS(.v4)
],
products: [
.library(
name: "Hall",
type: .static,
targets: ["Hall"])
],
dependencies: [
.package(name: "Adrenaline", url: "https://github.com/wellmart/adrenaline.git", .branch("master")),
.package(name: "ConcurrentKit", url: "https://github.com/wellmart/concurrentkit.git", .branch("master")),
.package(name: "SQLCipher", url: "https://github.com/wellmart/sqlcipher.git", .branch("master"))
],
targets: [
.target(
name: "Hall",
dependencies: [
"Adrenaline",
"ConcurrentKit",
"SQLCipher"
],
path: "Sources",
cSettings: [
.define("SQLITE_HAS_CODEC", to: "1")
],
swiftSettings: [
.define("SQLITE_HAS_CODEC")
])
],
swiftLanguageVersions: [.v5]
)
| 35.634921 | 113 | 0.625835 |
7653255f84eb5a21948f1506ee5599f2d8f56d68 | 1,734 | //
// Copyright © 2021 DHSC. All rights reserved.
//
import XCTest
@testable import CodeAnalyzer
final class LocalizableStringKeyParserTests: XCTestCase {
private var localizableStringKeyParser: LocalizableStringKeyParser!
override func setUpWithError() throws {
try super.setUpWithError()
try localizableStringKeyParser = LocalizableStringKeyParser(file: MockFile.localizableString.url)
}
func testKeys() {
let expected: Set<LocalizableKey> = [
LocalizableKey(
key: "key_one",
keyWithSuffix: "key_one_wls"
),
LocalizableKey(
key: "key_one_%@",
keyWithSuffix: nil
),
]
XCTAssertEqual(localizableStringKeyParser.keys, expected)
}
}
// MARK: - Helper methods
enum MockFile {
case stringLocalizationKey
case localizableString
case localizableStringDict
case swiftFileUsingKeys
var url: URL {
let resourceFilesDirectory = URL(fileURLWithPath: #file).deletingLastPathComponent().appendingPathComponent("ResourceFiles")
switch self {
case .stringLocalizationKey:
return resourceFilesDirectory.appendingPathComponent("StringLocalizationKey.swift")
case .localizableString:
return resourceFilesDirectory.appendingPathComponent("Localizable.strings")
case .localizableStringDict:
return resourceFilesDirectory.appendingPathComponent("Localizable.stringsdict")
case .swiftFileUsingKeys:
return resourceFilesDirectory.appendingPathComponent("SwiftFileUsingLocalizableKeys.swift")
}
}
}
| 30.421053 | 132 | 0.662053 |
9bee305e0de3214cef3d5df4866294b13866fe2c | 702 | //
// String+LineSpacing.swift
//
//
// Created by Mahshid Sharif on 9/19/21.
//
import UIKit
public extension String {
func withLineSpacing(_ spacing: CGFloat) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.lineSpacing = spacing
attributedString.addAttribute(.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: self.count))
return NSAttributedString(attributedString: attributedString)
}
}
| 31.909091 | 86 | 0.648148 |
de926f089757602207d3b553c85603fc01ff8fb2 | 69,284 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that iterates over a collection using its indices.
///
/// The `IndexingIterator` type is the default iterator for any collection that
/// doesn't declare its own. It acts as an iterator by using a collection's
/// indices to step over each value in the collection. Most collections in the
/// standard library use `IndexingIterator` as their iterator.
///
/// By default, any custom collection type you create will inherit a
/// `makeIterator()` method that returns an `IndexingIterator` instance,
/// making it unnecessary to declare your own. When creating a custom
/// collection type, add the minimal requirements of the `Collection`
/// protocol: starting and ending indices and a subscript for accessing
/// elements. With those elements defined, the inherited `makeIterator()`
/// method satisfies the requirements of the `Sequence` protocol.
///
/// Here's an example of a type that declares the minimal requirements for a
/// collection. The `CollectionOfTwo` structure is a fixed-size collection
/// that always holds two elements of a specific type.
///
/// struct CollectionOfTwo<Element>: Collection {
/// let elements: (Element, Element)
///
/// init(_ first: Element, _ second: Element) {
/// self.elements = (first, second)
/// }
///
/// var startIndex: Int { return 0 }
/// var endIndex: Int { return 2 }
///
/// subscript(index: Int) -> Element {
/// switch index {
/// case 0: return elements.0
/// case 1: return elements.1
/// default: fatalError("Index out of bounds.")
/// }
/// }
///
/// func index(after i: Int) -> Int {
/// precondition(i < endIndex, "Can't advance beyond endIndex")
/// return i + 1
/// }
/// }
///
/// Because `CollectionOfTwo` doesn't define its own `makeIterator()`
/// method or `Iterator` associated type, it uses the default iterator type,
/// `IndexingIterator`. This example shows how a `CollectionOfTwo` instance
/// can be created holding the values of a point, and then iterated over
/// using a `for`-`in` loop.
///
/// let point = CollectionOfTwo(15.0, 20.0)
/// for element in point {
/// print(element)
/// }
/// // Prints "15.0"
/// // Prints "20.0"
@_fixed_layout
public struct IndexingIterator<Elements : Collection> {
@usableFromInline
internal let _elements: Elements
@usableFromInline
internal var _position: Elements.Index
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements) {
self._elements = _elements
self._position = _elements.startIndex
}
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements, _position: Elements.Index) {
self._elements = _elements
self._position = _position
}
}
extension IndexingIterator: IteratorProtocol, Sequence {
public typealias Element = Elements.Element
public typealias Iterator = IndexingIterator<Elements>
public typealias SubSequence = AnySequence<Element>
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns all the elements of the underlying
/// sequence in order. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// This example shows how an iterator can be used explicitly to emulate a
/// `for`-`in` loop. First, retrieve a sequence's iterator, and then call
/// the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
@inlinable
@inline(__always)
public mutating func next() -> Elements.Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
}
/// A sequence whose elements can be traversed multiple times,
/// nondestructively, and accessed by an indexed subscript.
///
/// Collections are used extensively throughout the standard library. When you
/// use arrays, dictionaries, and other collections, you benefit from the
/// operations that the `Collection` protocol declares and implements. In
/// addition to the operations that collections inherit from the `Sequence`
/// protocol, you gain access to methods that depend on accessing an element
/// at a specific position in a collection.
///
/// For example, if you want to print only the first word in a string, you can
/// search for the index of the first space, and then create a substring up to
/// that position.
///
/// let text = "Buffalo buffalo buffalo buffalo."
/// if let firstSpace = text.firstIndex(of: " ") {
/// print(text[..<firstSpace])
/// }
/// // Prints "Buffalo"
///
/// The `firstSpace` constant is an index into the `text` string---the position
/// of the first space in the string. You can store indices in variables, and
/// pass them to collection algorithms or use them later to access the
/// corresponding element. In the example above, `firstSpace` is used to
/// extract the prefix that contains elements up to that index.
///
/// Accessing Individual Elements
/// =============================
///
/// You can access an element of a collection through its subscript by using
/// any valid index except the collection's `endIndex` property. This property
/// is a "past the end" index that does not correspond with any element of the
/// collection.
///
/// Here's an example of accessing the first character in a string through its
/// subscript:
///
/// let firstChar = text[text.startIndex]
/// print(firstChar)
/// // Prints "B"
///
/// The `Collection` protocol declares and provides default implementations for
/// many operations that depend on elements being accessible by their
/// subscript. For example, you can also access the first character of `text`
/// using the `first` property, which has the value of the first element of
/// the collection, or `nil` if the collection is empty.
///
/// print(text.first)
/// // Prints "Optional("B")"
///
/// You can pass only valid indices to collection operations. You can find a
/// complete set of a collection's valid indices by starting with the
/// collection's `startIndex` property and finding every successor up to, and
/// including, the `endIndex` property. All other values of the `Index` type,
/// such as the `startIndex` property of a different collection, are invalid
/// indices for this collection.
///
/// Saved indices may become invalid as a result of mutating operations. For
/// more information about index invalidation in mutable collections, see the
/// reference for the `MutableCollection` and `RangeReplaceableCollection`
/// protocols, as well as for the specific type you're using.
///
/// Accessing Slices of a Collection
/// ================================
///
/// You can access a slice of a collection through its ranged subscript or by
/// calling methods like `prefix(while:)` or `suffix(_:)`. A slice of a
/// collection can contain zero or more of the original collection's elements
/// and shares the original collection's semantics.
///
/// The following example creates a `firstWord` constant by using the
/// `prefix(while:)` method to get a slice of the `text` string.
///
/// let firstWord = text.prefix(while: { $0 != " " })
/// print(firstWord)
/// // Prints "Buffalo"
///
/// You can retrieve the same slice using the string's ranged subscript, which
/// takes a range expression.
///
/// if let firstSpace = text.firstIndex(of: " ") {
/// print(text[..<firstSpace]
/// // Prints "Buffalo"
/// }
///
/// The retrieved slice of `text` is equivalent in each of these cases.
///
/// Slices Share Indices
/// --------------------
///
/// A collection and its slices share the same indices. An element of a
/// collection is located under the same index in a slice as in the base
/// collection, as long as neither the collection nor the slice has been
/// mutated since the slice was created.
///
/// For example, suppose you have an array holding the number of absences from
/// each class during a session.
///
/// var absences = [0, 2, 0, 4, 0, 3, 1, 0]
///
/// You're tasked with finding the day with the most absences in the second
/// half of the session. To find the index of the day in question, follow
/// these steps:
///
/// 1) Create a slice of the `absences` array that holds the second half of the
/// days.
/// 2) Use the `max(by:)` method to determine the index of the day with the
/// most absences.
/// 3) Print the result using the index found in step 2 on the original
/// `absences` array.
///
/// Here's an implementation of those steps:
///
/// let secondHalf = absences.suffix(absences.count / 2)
/// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) {
/// print("Highest second-half absences: \(absences[i])")
/// }
/// // Prints "Highest second-half absences: 3"
///
/// Slices Inherit Collection Semantics
/// -----------------------------------
///
/// A slice inherits the value or reference semantics of its base collection.
/// That is, when working with a slice of a mutable collection that has value
/// semantics, such as an array, mutating the original collection triggers a
/// copy of that collection and does not affect the contents of the slice.
///
/// For example, if you update the last element of the `absences` array from
/// `0` to `2`, the `secondHalf` slice is unchanged.
///
/// absences[7] = 2
/// print(absences)
/// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]"
/// print(secondHalf)
/// // Prints "[0, 3, 1, 0]"
///
/// Traversing a Collection
/// =======================
///
/// Although a sequence can be consumed as it is traversed, a collection is
/// guaranteed to be *multipass*: Any element can be repeatedly accessed by
/// saving its index. Moreover, a collection's indices form a finite range of
/// the positions of the collection's elements. The fact that all collections
/// are finite guarantees the safety of many sequence operations, such as
/// using the `contains(_:)` method to test whether a collection includes an
/// element.
///
/// Iterating over the elements of a collection by their positions yields the
/// same elements in the same order as iterating over that collection using
/// its iterator. This example demonstrates that the `characters` view of a
/// string returns the same characters in the same order whether the view's
/// indices or the view itself is being iterated.
///
/// let word = "Swift"
/// for character in word {
/// print(character)
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// for i in word.indices {
/// print(word[i])
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// Conforming to the Collection Protocol
/// =====================================
///
/// If you create a custom sequence that can provide repeated access to its
/// elements, make sure that its type conforms to the `Collection` protocol in
/// order to give a more useful and more efficient interface for sequence and
/// collection operations. To add `Collection` conformance to your type, you
/// must declare at least the following requirements:
///
/// - The `startIndex` and `endIndex` properties
/// - A subscript that provides at least read-only access to your type's
/// elements
/// - The `index(after:)` method for advancing an index into your collection
///
/// Expected Performance
/// ====================
///
/// Types that conform to `Collection` are expected to provide the `startIndex`
/// and `endIndex` properties and subscript access to elements as O(1)
/// operations. Types that are not able to guarantee this performance must
/// document the departure, because many collection operations depend on O(1)
/// subscripting performance for their own performance guarantees.
///
/// The performance of some collection operations depends on the type of index
/// that the collection provides. For example, a random-access collection,
/// which can measure the distance between two indices in O(1) time, can
/// calculate its `count` property in O(1) time. Conversely, because a forward
/// or bidirectional collection must traverse the entire collection to count
/// the number of contained elements, accessing its `count` property is an
/// O(*n*) operation.
public protocol Collection: Sequence where SubSequence: Collection {
// FIXME: ideally this would be in MigrationSupport.swift, but it needs
// to be on the protocol instead of as an extension
@available(*, deprecated/*, obsoleted: 5.0*/, message: "all index distances are now of type Int")
typealias IndexDistance = Int
// FIXME(ABI): Associated type inference requires this.
associatedtype Element
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
associatedtype Index : Comparable
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
var startIndex: Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.firstIndex(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
var endIndex: Index { get }
/// A type that provides the collection's iteration interface and
/// encapsulates its iteration state.
///
/// By default, a collection conforms to the `Sequence` protocol by
/// supplying `IndexingIterator` as its associated `Iterator`
/// type.
associatedtype Iterator = IndexingIterator<Self>
// FIXME(ABI)#179 (Type checker): Needed here so that the `Iterator` is properly deduced from
// a custom `makeIterator()` function. Otherwise we get an
// `IndexingIterator`. <rdar://problem/21539115>
/// Returns an iterator over the elements of the collection.
func makeIterator() -> Iterator
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
associatedtype SubSequence = Slice<Self> where SubSequence.Index == Index
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
///
/// - Complexity: O(1)
subscript(position: Index) -> Element { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// For example, using a `PartialRangeFrom` range expression with an array
/// accesses the subrange from the start of the range expression until the
/// end of the array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2..<5]
/// print(streetsSlice)
/// // ["Channing", "Douglas", "Evarts"]
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. This example searches `streetsSlice` for one of the
/// strings in the slice, and then uses that index in the original array.
///
/// let index = streetsSlice.firstIndex(of: "Evarts")! // 4
/// print(streets[index])
/// // "Evarts"
///
/// Always use the slice's `startIndex` property instead of assuming that its
/// indices start at a particular value. Attempting to access an element by
/// using an index outside the bounds of the slice may result in a runtime
/// error, even if that index is valid for the original collection.
///
/// print(streetsSlice.startIndex)
/// // 2
/// print(streetsSlice[2])
/// // "Channing"
///
/// print(streetsSlice[0])
/// // error: Index out of bounds
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
subscript(bounds: Range<Index>) -> SubSequence { get }
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : Collection = DefaultIndices<Self>
where Indices.Element == Index,
Indices.Index == Index,
Indices.SubSequence == Indices
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// Using the `prefix(upTo:)` method is equivalent to using a partial
/// half-open range as the collection's subscript. The subscript notation is
/// preferred over `prefix(upTo:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[..<i])
/// }
/// // Prints "[10, 20, 30]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
__consuming func prefix(upTo end: Index) -> SubSequence
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// Using the `suffix(from:)` method is equivalent to using a partial range
/// from the index as the collection's subscript. The subscript notation is
/// preferred over `suffix(from:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[i...])
/// }
/// // Prints "[40, 50, 60]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
__consuming func suffix(from start: Index) -> SubSequence
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// Using the `prefix(through:)` method is equivalent to using a partial
/// closed range as the collection's subscript. The subscript notation is
/// preferred over `prefix(through:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[...i])
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
__consuming func prefix(through position: Index) -> SubSequence
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!"
///
/// - Complexity: O(1)
var isEmpty: Bool { get }
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
var count: Int { get }
// The following requirements enable dispatching for firstIndex(of:) and
// lastIndex(of:) when the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found
/// or `Optional(nil)` if an element was determined to be missing;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*)
func _customIndexOfEquatableElement(_ element: Element) -> Index??
/// Customization point for `Collection.lastIndex(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: Hopefully less than O(`count`).
func _customLastIndexOfEquatableElement(_ element: Element) -> Index??
// FIXME(move-only types): `first` might not be implementable by collections
// with move-only elements, since they would need to be able to somehow form
// a temporary `Optional<Element>` value from a non-optional Element without
// modifying the collection.
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
var first: Element? { get }
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: Int) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index?
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> Int
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)
func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.lowerBound) ||
/// range.lowerBound == bounds.upperBound)
/// precondition(
/// bounds.contains(range.upperBound) ||
/// range.upperBound == bounds.upperBound)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)
/// Returns the position immediately after the given index.
///
/// The successor of an index must be well defined. For an index `i` into a
/// collection `c`, calling `c.index(after: i)` returns the same index every
/// time.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Index) -> Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
func formIndex(after i: inout Index)
}
/// Default implementation for forward collections.
extension Collection {
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inlinable // protocol-only
@inline(__always)
public func formIndex(after i: inout Index) {
i = index(after: i)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"Out of bounds: index < startIndex")
_precondition(
index < bounds.upperBound,
"Out of bounds: index >= endIndex")
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"Out of bounds: index < startIndex")
_precondition(
index <= bounds.upperBound,
"Out of bounds: index > endIndex")
}
@inlinable
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= range.lowerBound,
"Out of bounds: range begins before startIndex")
_precondition(
range.lowerBound <= bounds.upperBound,
"Out of bounds: range ends after endIndex")
_precondition(
bounds.lowerBound <= range.upperBound,
"Out of bounds: range ends before bounds.lowerBound")
_precondition(
range.upperBound <= bounds.upperBound,
"Out of bounds: range begins after bounds.upperBound")
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return self._advanceForward(i, by: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return self._advanceForward(i, by: n, limitedBy: limit)
}
/// Offsets the given index by the specified distance.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func formIndex(_ i: inout Index, offsetBy n: Int) {
i = index(i, offsetBy: n)
}
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func formIndex(
_ i: inout Index, offsetBy n: Int, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
var start = start
var count = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
/// Returns a random element of the collection, using the given generator as
/// a source for randomness.
///
/// Call `randomElement(using:)` to select a random element from an array or
/// another collection when you are using a custom random number generator.
/// This example picks a name at random from an array:
///
/// let names = ["Zoey", "Chloe", "Amani", "Amaia"]
/// let randomName = names.randomElement(using: &myGenerator)!
/// // randomName == "Amani"
///
/// - Parameter generator: The random number generator to use when choosing
/// a random element.
/// - Returns: A random element from the collection. If the collection is
/// empty, the method returns `nil`.
@inlinable
public func randomElement<T: RandomNumberGenerator>(
using generator: inout T
) -> Element? {
guard !isEmpty else { return nil }
let random = generator.next(upperBound: UInt(count))
let index = self.index(
startIndex,
offsetBy: numericCast(random)
)
return self[index]
}
/// Returns a random element of the collection.
///
/// Call `randomElement()` to select a random element from an array or
/// another collection. This example picks a name at random from an array:
///
/// let names = ["Zoey", "Chloe", "Amani", "Amaia"]
/// let randomName = names.randomElement()!
/// // randomName == "Amani"
///
/// This method uses the default random generator, `Random.default`. The call
/// to `names.randomElement()` above is equivalent to calling
/// `names.randomElement(using: &Random.default)`.
///
/// - Returns: A random element from the collection. If the collection is
/// empty, the method returns `nil`.
@inlinable
public func randomElement() -> Element? {
return randomElement(using: &Random.default)
}
/// Do not use this method directly; call advanced(by: n) instead.
@inlinable
@inline(__always)
internal func _advanceForward(_ i: Index, by n: Int) -> Index {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
formIndex(after: &i)
}
return i
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@inlinable
@inline(__always)
internal func _advanceForward(
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
if i == limit {
return nil
}
formIndex(after: &i)
}
return i
}
}
/// Supply the default `makeIterator()` method for `Collection` models
/// that accept the default associated `Iterator`,
/// `IndexingIterator<Self>`.
extension Collection where Iterator == IndexingIterator<Self> {
/// Returns an iterator over the elements of the collection.
@inlinable // trivial-implementation
@inline(__always)
public func makeIterator() -> IndexingIterator<Self> {
return IndexingIterator(_elements: self)
}
}
/// Supply the default "slicing" `subscript` for `Collection` models
/// that accept the default associated `SubSequence`, `Slice<Self>`.
extension Collection where SubSequence == Slice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.firstIndex(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
@inlinable
public subscript(bounds: Range<Index>) -> Slice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// - Returns: The first element of the collection if the collection is
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popFirst() -> Element? {
// TODO: swift-3-indexing-model - review the following
guard !isEmpty else { return nil }
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
}
/// Default implementations of core requirements
extension Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
@inlinable
public var isEmpty: Bool {
return startIndex == endIndex
}
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
@inlinable
public var first: Element? {
@inline(__always)
get {
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
// so instead of testing `isEmpty` and then returning the first element,
// we'll just rely on the fact that the iterator always yields the
// first element first.
var i = makeIterator()
return i.next()
}
}
// TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?)
/// Returns the first element of `self`, or `nil` if `self` is empty.
///
/// - Complexity: O(1)
// public var first: Element? {
// return isEmpty ? nil : self[startIndex]
// }
/// A value less than or equal to the number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return count
}
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public var count: Int {
return distance(from: startIndex, to: endIndex)
}
// TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)?
/// Customization point for `Collection.firstIndex(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: Hopefully less than O(`count`).
@inlinable
public // dispatching
func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? {
return nil
}
/// Customization point for `Collection.lastIndex(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: Hopefully less than O(`count`).
@inlinable
public // dispatching
func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {
return nil
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Collection
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercased() }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
@inlinable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
// TODO: swift-3-indexing-model - review the following
let n = self.count
if n == 0 {
return []
}
var result = ContiguousArray<T>()
result.reserveCapacity(n)
var i = self.startIndex
for _ in 0..<n {
result.append(try transform(self[i]))
formIndex(after: &i)
}
_expectEnd(of: self, is: i)
return Array(result)
}
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the collection.
@inlinable
public func dropFirst(_ n: Int) -> SubSequence {
_precondition(n >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex,
offsetBy: n, limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off the specified number of elements
/// at the end.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let amount = Swift.max(0, count - n)
let end = index(startIndex,
offsetBy: amount, limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence by skipping elements while `predicate` returns
/// `true` and returning the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be skipped or `false` if it should be included. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func drop(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
var start = startIndex
while try start != endIndex && predicate(self[start]) {
formIndex(after: &start)
}
return self[start..<endIndex]
}
/// Returns a subsequence, up to the specified maximum length, containing
/// the initial elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this collection
/// with at most `maxLength` elements.
@inlinable
public func prefix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a prefix of negative length from a collection")
let end = index(startIndex,
offsetBy: maxLength, limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence containing the initial elements until `predicate`
/// returns `false` and skipping the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be included or `false` if it should be excluded. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
var end = startIndex
while try end != endIndex && predicate(self[end]) {
formIndex(after: &end)
}
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let amount = Swift.max(0, count - maxLength)
let start = index(startIndex,
offsetBy: amount, limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// Using the `prefix(upTo:)` method is equivalent to using a partial
/// half-open range as the collection's subscript. The subscript notation is
/// preferred over `prefix(upTo:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[..<i])
/// }
/// // Prints "[10, 20, 30]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
@inlinable
public func prefix(upTo end: Index) -> SubSequence {
return self[startIndex..<end]
}
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// Using the `suffix(from:)` method is equivalent to using a partial range
/// from the index as the collection's subscript. The subscript notation is
/// preferred over `suffix(from:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[i...])
/// }
/// // Prints "[40, 50, 60]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
@inlinable
public func suffix(from start: Index) -> SubSequence {
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// Using the `prefix(through:)` method is equivalent to using a partial
/// closed range as the collection's subscript. The subscript notation is
/// preferred over `prefix(through:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[...i])
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
@inlinable
public func prefix(through position: Index) -> SubSequence {
return prefix(upTo: index(after: position))
}
/// Returns the longest possible subsequences of the collection, in order,
/// that don't contain elements satisfying the given predicate.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the collection satisfying the `isSeparator`
/// predicate. The default value is `true`.
/// - isSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the collection should be
/// split at that element.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@inlinable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [SubSequence] = []
var subSequenceStart: Index = startIndex
func appendSubsequence(end: Index) -> Bool {
if subSequenceStart == end && omittingEmptySubsequences {
return false
}
result.append(self[subSequenceStart..<end])
return true
}
if maxSplits == 0 || isEmpty {
_ = appendSubsequence(end: endIndex)
return result
}
var subSequenceEnd = subSequenceStart
let cachedEndIndex = endIndex
while subSequenceEnd != cachedEndIndex {
if try isSeparator(self[subSequenceEnd]) {
let didAppend = appendSubsequence(end: subSequenceEnd)
formIndex(after: &subSequenceEnd)
subSequenceStart = subSequenceEnd
if didAppend && result.count == maxSplits {
break
}
continue
}
formIndex(after: &subSequenceEnd)
}
if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences {
result.append(self[subSequenceStart..<cachedEndIndex])
}
return result
}
}
extension Collection where Element : Equatable {
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the collection are not returned as part
/// of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(separator: " "))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(separator: " ", maxSplits: 1))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(separator: " ", omittingEmptySubsequences: false))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the collection and for each instance of `separator` at
/// the start or end of the collection. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@inlinable
public func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
// TODO: swift-3-indexing-model - review the following
_precondition(!isEmpty, "Can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater than
/// or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*).
@inlinable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= n,
"Can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: n)..<endIndex]
}
}
extension Collection {
@inlinable
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try preprocess()
}
}
| 39.07727 | 112 | 0.641707 |
e0deb7fbf11db3bd282869707adf2fcd1305731b | 16,036 | //
// LinterCacheTests.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/27/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
@testable import SwiftLintFramework
import XCTest
private struct CacheTestHelper {
fileprivate let configuration: Configuration
private let ruleList: RuleList
private let ruleDescription: RuleDescription
private let cache: LinterCache
private var fileManager: TestFileManager {
// swiftlint:disable:next force_cast
return cache.fileManager as! TestFileManager
}
fileprivate init(dict: [String: Any], cache: LinterCache) {
ruleList = RuleList(rules: RuleWithLevelsMock.self)
ruleDescription = ruleList.list.values.first!.description
configuration = Configuration(dict: dict, ruleList: ruleList)!
self.cache = cache
}
fileprivate func makeViolations(file: String) -> [StyleViolation] {
touch(file: file)
return [
StyleViolation(ruleDescription: ruleDescription,
severity: .warning,
location: Location(file: file, line: 10, character: 2),
reason: "Something is not right."),
StyleViolation(ruleDescription: ruleDescription,
severity: .error,
location: Location(file: file, line: 5, character: nil),
reason: "Something is wrong.")
]
}
fileprivate func makeConfig(dict: [String: Any]) -> Configuration {
return Configuration(dict: dict, ruleList: ruleList)!
}
fileprivate func touch(file: String) {
fileManager.stubbedModificationDateByPath[file] = Date()
}
fileprivate func remove(file: String) {
fileManager.stubbedModificationDateByPath[file] = nil
}
fileprivate func fileCount() -> Int {
return fileManager.stubbedModificationDateByPath.count
}
}
private class TestFileManager: LintableFileManager {
fileprivate func filesToLint(inPath: String, rootDirectory: String? = nil) -> [String] {
return []
}
fileprivate var stubbedModificationDateByPath = [String: Date]()
fileprivate func modificationDate(forFileAtPath path: String) -> Date? {
return stubbedModificationDateByPath[path]
}
}
class LinterCacheTests: XCTestCase {
// MARK: Test Helpers
private var cache = LinterCache(fileManager: TestFileManager())
private func makeCacheTestHelper(dict: [String: Any]) -> CacheTestHelper {
return CacheTestHelper(dict: dict, cache: cache)
}
private func cacheAndValidate(violations: [StyleViolation], forFile: String, configuration: Configuration,
file: StaticString = #file, line: UInt = #line) {
cache.cache(violations: violations, forFile: forFile, configuration: configuration)
cache = cache.flushed()
XCTAssertEqual(cache.violations(forFile: forFile, configuration: configuration)!,
violations, file: file, line: line)
}
private func cacheAndValidateNoViolationsTwoFiles(configuration: Configuration,
file: StaticString = #file, line: UInt = #line) {
let (file1, file2) = ("file1.swift", "file2.swift")
// swiftlint:disable:next force_cast
let fileManager = cache.fileManager as! TestFileManager
fileManager.stubbedModificationDateByPath = [file1: Date(), file2: Date()]
cacheAndValidate(violations: [], forFile: file1, configuration: configuration, file: file, line: line)
cacheAndValidate(violations: [], forFile: file2, configuration: configuration, file: file, line: line)
}
private func validateNewConfigDoesntHitCache(dict: [String: Any], initialConfig: Configuration,
file: StaticString = #file, line: UInt = #line) {
let newConfig = Configuration(dict: dict)!
let (file1, file2) = ("file1.swift", "file2.swift")
XCTAssertNil(cache.violations(forFile: file1, configuration: newConfig), file: file, line: line)
XCTAssertNil(cache.violations(forFile: file2, configuration: newConfig), file: file, line: line)
XCTAssertEqual(cache.violations(forFile: file1, configuration: initialConfig)!, [], file: file, line: line)
XCTAssertEqual(cache.violations(forFile: file2, configuration: initialConfig)!, [], file: file, line: line)
}
// MARK: Cache Initialization
func testInitThrowsWhenUsingInvalidCacheFormat() {
let cache = [["version": "0.1.0"]]
checkError(LinterCacheError.invalidFormat) {
_ = try LinterCache(cache: cache)
}
}
func testSaveThrowsWithNoLocation() throws {
let cache = try LinterCache(cache: [:])
checkError(LinterCacheError.noLocation) {
try cache.save()
}
}
func testInitSucceeds() {
XCTAssertNotNil(try? LinterCache(cache: [:]))
}
// MARK: Cache Reuse
// Two subsequent lints with no changes reuses cache
func testUnchangedFilesReusesCache() {
let helper = makeCacheTestHelper(dict: ["whitelist_rules": ["mock"]])
let file = "foo.swift"
let violations = helper.makeViolations(file: file)
cacheAndValidate(violations: violations, forFile: file, configuration: helper.configuration)
helper.touch(file: file)
XCTAssertNil(cache.violations(forFile: file, configuration: helper.configuration))
}
func testConfigFileReorderedReusesCache() {
let helper = makeCacheTestHelper(dict: ["whitelist_rules": ["mock"], "disabled_rules": []])
let file = "foo.swift"
let violations = helper.makeViolations(file: file)
cacheAndValidate(violations: violations, forFile: file, configuration: helper.configuration)
let configuration2 = helper.makeConfig(dict: ["disabled_rules": [], "whitelist_rules": ["mock"]])
XCTAssertEqual(cache.violations(forFile: file, configuration: configuration2)!, violations)
}
func testConfigFileWhitespaceAndCommentsChangedOrAddedOrRemovedReusesCache() throws {
let helper = makeCacheTestHelper(dict: try YamlParser.parse("whitelist_rules:\n - mock"))
let file = "foo.swift"
let violations = helper.makeViolations(file: file)
cacheAndValidate(violations: violations, forFile: file, configuration: helper.configuration)
let configuration2 = helper.makeConfig(dict: ["disabled_rules": [], "whitelist_rules": ["mock"]])
XCTAssertEqual(cache.violations(forFile: file, configuration: configuration2)!, violations)
let configYamlWithComment = try YamlParser.parse("# comment1\nwhitelist_rules:\n - mock # comment2")
let configuration3 = helper.makeConfig(dict: configYamlWithComment)
XCTAssertEqual(cache.violations(forFile: file, configuration: configuration3)!, violations)
XCTAssertEqual(cache.violations(forFile: file, configuration: helper.configuration)!, violations)
}
func testConfigFileUnrelatedKeysChangedOrAddedOrRemovedReusesCache() {
let helper = makeCacheTestHelper(dict: ["whitelist_rules": ["mock"], "reporter": "json"])
let file = "foo.swift"
let violations = helper.makeViolations(file: file)
cacheAndValidate(violations: violations, forFile: file, configuration: helper.configuration)
let configuration2 = helper.makeConfig(dict: ["whitelist_rules": ["mock"], "reporter": "xcode"])
XCTAssertEqual(cache.violations(forFile: file, configuration: configuration2)!, violations)
let configuration3 = helper.makeConfig(dict: ["whitelist_rules": ["mock"]])
XCTAssertEqual(cache.violations(forFile: file, configuration: configuration3)!, violations)
}
// MARK: Sing-File Cache Invalidation
// Two subsequent lints with a file touch in between causes just that one
// file to be re-linted, with the cache used for all other files
func testChangedFileCausesJustThatFileToBeLintWithCacheUsedForAllOthers() {
let helper = makeCacheTestHelper(dict: ["whitelist_rules": ["mock"], "reporter": "json"])
let (file1, file2) = ("file1.swift", "file2.swift")
let violations1 = helper.makeViolations(file: file1)
let violations2 = helper.makeViolations(file: file2)
cacheAndValidate(violations: violations1, forFile: file1, configuration: helper.configuration)
cacheAndValidate(violations: violations2, forFile: file2, configuration: helper.configuration)
helper.touch(file: file2)
XCTAssertEqual(cache.violations(forFile: file1, configuration: helper.configuration)!, violations1)
XCTAssertNil(cache.violations(forFile: file2, configuration: helper.configuration))
}
func testFileRemovedPreservesThatFileInTheCacheAndDoesntCauseAnyOtherFilesToBeLinted() {
let helper = makeCacheTestHelper(dict: ["whitelist_rules": ["mock"], "reporter": "json"])
let (file1, file2) = ("file1.swift", "file2.swift")
let violations1 = helper.makeViolations(file: file1)
let violations2 = helper.makeViolations(file: file2)
cacheAndValidate(violations: violations1, forFile: file1, configuration: helper.configuration)
cacheAndValidate(violations: violations2, forFile: file2, configuration: helper.configuration)
XCTAssertEqual(helper.fileCount(), 2)
helper.remove(file: file2)
XCTAssertEqual(cache.violations(forFile: file1, configuration: helper.configuration)!, violations1)
XCTAssertEqual(helper.fileCount(), 1)
}
// MARK: All-File Cache Invalidation
func testCustomRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted() {
let initialConfig = Configuration(
dict: [
"whitelist_rules": ["custom_rules", "rule1"],
"custom_rules": ["rule1": ["regex": "([n,N]inja)"]]
],
ruleList: RuleList(rules: CustomRules.self)
)!
cacheAndValidateNoViolationsTwoFiles(configuration: initialConfig)
// Change
validateNewConfigDoesntHitCache(
dict: [
"whitelist_rules": ["custom_rules", "rule1"],
"custom_rules": ["rule1": ["regex": "([n,N]injas)"]]
],
initialConfig: initialConfig
)
// Addition
validateNewConfigDoesntHitCache(
dict: [
"whitelist_rules": ["custom_rules", "rule1"],
"custom_rules": ["rule1": ["regex": "([n,N]injas)"], "rule2": ["regex": "([k,K]ittens)"]]
],
initialConfig: initialConfig
)
// Removal
validateNewConfigDoesntHitCache(dict: ["whitelist_rules": ["custom_rules"]], initialConfig: initialConfig)
}
func testDisabledRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted() {
let initialConfig = Configuration(dict: ["disabled_rules": ["nesting"]])!
cacheAndValidateNoViolationsTwoFiles(configuration: initialConfig)
// Change
validateNewConfigDoesntHitCache(dict: ["disabled_rules": ["todo"]], initialConfig: initialConfig)
// Addition
validateNewConfigDoesntHitCache(dict: ["disabled_rules": ["nesting", "todo"]], initialConfig: initialConfig)
// Removal
validateNewConfigDoesntHitCache(dict: ["disabled_rules": []], initialConfig: initialConfig)
}
func testOptInRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted() {
let initialConfig = Configuration(dict: ["opt_in_rules": ["attributes"]])!
cacheAndValidateNoViolationsTwoFiles(configuration: initialConfig)
// Change
validateNewConfigDoesntHitCache(dict: ["opt_in_rules": ["empty_count"]], initialConfig: initialConfig)
// Rules addition
validateNewConfigDoesntHitCache(dict: ["opt_in_rules": ["attributes", "empty_count"]],
initialConfig: initialConfig)
// Removal
validateNewConfigDoesntHitCache(dict: ["opt_in_rules": []], initialConfig: initialConfig)
}
func testEnabledRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted() {
let initialConfig = Configuration(dict: ["enabled_rules": ["attributes"]])!
cacheAndValidateNoViolationsTwoFiles(configuration: initialConfig)
// Change
validateNewConfigDoesntHitCache(dict: ["enabled_rules": ["empty_count"]], initialConfig: initialConfig)
// Addition
validateNewConfigDoesntHitCache(dict: ["enabled_rules": ["attributes", "empty_count"]],
initialConfig: initialConfig)
// Removal
validateNewConfigDoesntHitCache(dict: ["enabled_rules": []], initialConfig: initialConfig)
}
func testWhitelistRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted() {
let initialConfig = Configuration(dict: ["whitelist_rules": ["nesting"]])!
cacheAndValidateNoViolationsTwoFiles(configuration: initialConfig)
// Change
validateNewConfigDoesntHitCache(dict: ["whitelist_rules": ["todo"]], initialConfig: initialConfig)
// Addition
validateNewConfigDoesntHitCache(dict: ["whitelist_rules": ["nesting", "todo"]], initialConfig: initialConfig)
// Removal
validateNewConfigDoesntHitCache(dict: ["whitelist_rules": []], initialConfig: initialConfig)
}
func testRuleConfigurationChangedOrAddedOrRemovedCausesAllFilesToBeReLinted() {
let initialConfig = Configuration(dict: ["line_length": 120])!
cacheAndValidateNoViolationsTwoFiles(configuration: initialConfig)
// Change
validateNewConfigDoesntHitCache(dict: ["line_length": 100], initialConfig: initialConfig)
// Addition
validateNewConfigDoesntHitCache(dict: ["line_length": 100, "number_separator": ["minimum_length": 5]],
initialConfig: initialConfig)
// Removal
validateNewConfigDoesntHitCache(dict: [:], initialConfig: initialConfig)
}
func testSwiftVersionChangedRemovedCausesAllFilesToBeReLinted() {
let fileManager = TestFileManager()
cache = LinterCache(fileManager: fileManager)
let helper = makeCacheTestHelper(dict: [:])
let file = "foo.swift"
let violations = helper.makeViolations(file: file)
cacheAndValidate(violations: violations, forFile: file, configuration: helper.configuration)
let thisSwiftVersionCache = cache
let differentSwiftVersion: SwiftVersion = (SwiftVersion.current >= .four) ? .three : .four
cache = LinterCache(fileManager: fileManager, swiftVersion: differentSwiftVersion)
XCTAssertNotNil(thisSwiftVersionCache.violations(forFile: file, configuration: helper.configuration))
XCTAssertNil(cache.violations(forFile: file, configuration: helper.configuration))
}
func testDetectSwiftVersion() {
#if swift(>=4.1.0)
let version = "4.1.0"
#elseif swift(>=4.0.3)
let version = "4.0.3"
#elseif swift(>=4.0.2)
let version = "4.0.2"
#elseif swift(>=4.0.1)
let version = "4.0.1"
#elseif swift(>=4.0.0)
let version = "4.0.0"
#elseif swift(>=3.2.3)
let version = "4.0.3" // Since we can't pass SWIFT_VERSION=3 to sourcekit, it returns 4.0.3
#elseif swift(>=3.2.2)
let version = "4.0.2" // Since we can't pass SWIFT_VERSION=3 to sourcekit, it returns 4.0.2
#elseif swift(>=3.2.1)
let version = "4.0.1" // Since we can't pass SWIFT_VERSION=3 to sourcekit, it returns 4.0.1
#else // if swift(>=3.2.0)
let version = "4.0.0" // Since we can't pass SWIFT_VERSION=3 to sourcekit, it returns 4.0.0
#endif
XCTAssertEqual(SwiftVersion.current.rawValue, version)
}
}
| 45.299435 | 117 | 0.666376 |
2682deb6c02a9bb80b6f6fe4f86b69c465d0b7ab | 4,530 | // Corona-Warn-App
//
// SAP SE 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 UIKit
final class HomeHighRiskCellConfigurator: HomeRiskLevelCellConfigurator {
private var numberRiskContacts: Int
private var daysSinceLastExposure: Int?
// MARK: Creating a Home Risk Cell Configurator
init(
isLoading: Bool,
numberRiskContacts: Int,
daysSinceLastExposure: Int?,
lastUpdateDate: Date?,
manualExposureDetectionState: ManualExposureDetectionState?,
detectionMode: DetectionMode,
detectionInterval: Int
) {
self.numberRiskContacts = numberRiskContacts
self.daysSinceLastExposure = daysSinceLastExposure
super.init(
isLoading: isLoading,
isButtonEnabled: manualExposureDetectionState == .possible,
isButtonHidden: detectionMode == .automatic,
detectionIntervalLabelHidden: detectionMode != .automatic,
lastUpdateDate: lastUpdateDate,
detectionInterval: detectionInterval
)
}
// MARK: Configuration
override func configure(cell: RiskLevelCollectionViewCell) {
cell.delegate = self
let title: String = isLoading ? AppStrings.Home.riskCardStatusCheckTitle : AppStrings.Home.riskCardHighTitle
let titleColor: UIColor = .enaColor(for: .textContrast)
cell.configureTitle(title: title, titleColor: titleColor)
cell.configureBody(text: "", bodyColor: titleColor, isHidden: true)
let color: UIColor = .enaColor(for: .riskHigh)
let separatorColor: UIColor = .enaColor(for: .hairlineContrast)
var itemCellConfigurators: [HomeRiskViewConfiguratorAny] = []
if isLoading {
let isLoadingItem = HomeRiskLoadingItemViewConfigurator(title: AppStrings.Home.riskCardStatusCheckBody, titleColor: titleColor, isLoading: true, color: color, separatorColor: separatorColor)
itemCellConfigurators.append(isLoadingItem)
} else {
let numberOfDaysSinceLastExposure = daysSinceLastExposure ?? 0
let numberContactsTitle = String(format: AppStrings.Home.riskCardNumberContactsItemTitle, numberRiskContacts)
let item1 = HomeRiskImageItemViewConfigurator(title: numberContactsTitle, titleColor: titleColor, iconImageName: "Icons_RisikoBegegnung", iconTintColor: titleColor, color: color, separatorColor: separatorColor)
let lastContactTitle = String(format: AppStrings.Home.riskCardLastContactItemTitle, numberOfDaysSinceLastExposure)
let item2 = HomeRiskImageItemViewConfigurator(title: lastContactTitle, titleColor: titleColor, iconImageName: "Icons_Calendar", iconTintColor: titleColor, color: color, separatorColor: separatorColor)
let dateTitle = String(format: AppStrings.Home.riskCardDateItemTitle, lastUpdateDateString)
let item3 = HomeRiskImageItemViewConfigurator(title: dateTitle, titleColor: titleColor, iconImageName: "Icons_Aktualisiert", iconTintColor: titleColor, color: color, separatorColor: separatorColor)
itemCellConfigurators.append(contentsOf: [item1, item2, item3])
}
cell.configureRiskViews(cellConfigurators: itemCellConfigurators)
cell.configureBackgroundColor(color: color)
let intervalTitle = String(format: AppStrings.Home.riskCardIntervalUpdateTitle, "\(detectionInterval)")
cell.configureDetectionIntervalLabel(
text: intervalTitle,
isHidden: detectionIntervalLabelHidden
)
configureButton(for: cell)
setupAccessibility(cell)
}
// MARK: Hashable
override func hash(into hasher: inout Swift.Hasher) {
super.hash(into: &hasher)
hasher.combine(numberRiskContacts)
hasher.combine(daysSinceLastExposure)
}
static func == (lhs: HomeHighRiskCellConfigurator, rhs: HomeHighRiskCellConfigurator) -> Bool {
lhs.isLoading == rhs.isLoading &&
lhs.isButtonEnabled == rhs.isButtonEnabled &&
lhs.isButtonHidden == rhs.isButtonHidden &&
lhs.detectionIntervalLabelHidden == rhs.detectionIntervalLabelHidden &&
lhs.lastUpdateDate == rhs.lastUpdateDate &&
lhs.numberRiskContacts == rhs.numberRiskContacts &&
lhs.daysSinceLastExposure == rhs.daysSinceLastExposure &&
lhs.detectionInterval == rhs.detectionInterval
}
}
| 42.735849 | 213 | 0.79117 |
5d330612aa13826227abe3ef688902234302f097 | 3,321 | //
// YelpClient.swift
// Yelp
//
// Created by Timothy Lee on 9/19/14.
// Copyright (c) 2014 Timothy Lee. All rights reserved.
//
import UIKit
import AFNetworking
import BDBOAuth1Manager
// You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys
let yelpConsumerKey = "vxKwwcR_NMQ7WaEiQBK_CA"
let yelpConsumerSecret = "33QCvh5bIF5jIHR5klQr7RtBDhQ"
let yelpToken = "uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV"
let yelpTokenSecret = "mqtKIxMIR4iBtBPZCmCLEb-Dz3Y"
enum YelpSortMode: Int {
case BestMatched = 0, Distance, HighestRated
}
class YelpClient: BDBOAuth1RequestOperationManager {
var accessToken: String!
var accessSecret: String!
class var sharedInstance : YelpClient {
struct Static {
static var token : dispatch_once_t = 0
static var instance : YelpClient? = nil
}
dispatch_once(&Static.token) {
Static.instance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret)
}
return Static.instance!
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) {
self.accessToken = accessToken
self.accessSecret = accessSecret
let baseUrl = NSURL(string: "https://api.yelp.com/v2/")
super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret);
let token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil)
self.requestSerializer.saveAccessToken(token)
}
func searchWithTerm(offset: Int, term: String, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
return searchWithTerm(offset, term: term, sort: nil, categories: nil, deals: nil, completion: completion)
}
func searchWithTerm(offset: Int, term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
// For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api
// Default the location to San Francisco
var parameters: [String : AnyObject] = ["term": term, "ll": "37.785771,-122.406165"]
parameters["offset"] = offset
if sort != nil {
parameters["sort"] = sort!.rawValue
}
if categories != nil && categories!.count > 0 {
parameters["category_filter"] = (categories!).joinWithSeparator(",")
}
if deals != nil {
parameters["deals_filter"] = deals!
}
print(parameters)
return self.GET("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
let dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
}
}, failure: { (operation: AFHTTPRequestOperation?, error: NSError!) -> Void in
completion(nil, error)
})!
}
}
| 36.9 | 181 | 0.646191 |
21de093cd795acce526c7865c727924f016cc21a | 3,275 | import Foundation
import Speech
import NaturalLanguage
final class SpeechRecognizer {
private var speechRecognizer: SFSpeechRecognizer
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var recognitionTask: SFSpeechRecognitionTask?
let url: URL
init(url: URL, locale: Locale = .current) {
self.url = url
self.speechRecognizer = SFSpeechRecognizer(locale: locale)!
}
func startRecognize(completion: @escaping (Result<String, Error>) -> Void) {
let authStatus = SFSpeechRecognizer.authorizationStatus()
guard authStatus == .authorized else {
if authStatus == .notDetermined {
SFSpeechRecognizer.requestAuthorization { [weak self] status in
if status == .authorized {
self?.recognize(completion: completion)
} else {
completion(.failure(SpeechRecognizerErrors.authenticationFailed))
}
}
} else {
completion(.failure(SpeechRecognizerErrors.authenticationFailed))
}
return
}
guard recognitionTask == nil, self.recognitionRequest == nil else {
stopRecognize()
recognize(completion: completion)
return
}
recognize(completion: completion)
}
private func recognize(completion: @escaping (Result<String, Error>) -> Void) {
let recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
self.recognitionRequest = recognitionRequest
recognitionRequest.shouldReportPartialResults = false
recognitionRequest.requiresOnDeviceRecognition = true
speechRecognizer.queue = OperationQueue()
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { [weak self] result, error in
guard let self = self else { return }
if let error = error {
self.stopRecognize()
completion(.failure(error))
return
}
guard let result = result else {
completion(.failure(SpeechRecognizerErrors.unknown))
return
}
if result.isFinal {
self.stopRecognize()
completion(.success(result.bestTranscription.formattedString))
}
}
do {
let audioFile = try AVAudioFile(forReading: url)
let frameCount = AVAudioFrameCount(audioFile.length)
if let pcmBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: frameCount) {
try audioFile.read(into: pcmBuffer)
recognitionRequest.append(pcmBuffer)
recognitionRequest.endAudio()
} else {
throw SpeechRecognizerErrors.invalidAudioFormat
}
} catch {
completion(.failure(error))
}
}
func stopRecognize() {
recognitionTask?.cancel()
recognitionTask?.finish()
recognitionRequest?.endAudio()
recognitionRequest = nil
recognitionTask = nil
}
}
| 35.597826 | 115 | 0.594198 |
ab9caeacff3b835f884ea566933f347ddca17e32 | 5,301 | //
// SearchHeaderView.swift
// Circle
//
// Created by Ravi Rani on 12/24/14.
// Copyright (c) 2014 RH Labs Inc. All rights reserved.
//
import UIKit
protocol SearchHeaderViewDelegate {
func didCancel(sender: UIView)
func didSelectTag()
}
class SearchHeaderView: UIView {
let searchFieldLeftViewDefaultWidth = CGFloat(30.0)
@IBOutlet weak private(set) var cancelButton: UIButton!
@IBOutlet weak private(set) var searchTextField: CircleTextField!
@IBOutlet weak private(set) var searchTextFieldHeightConstraint: NSLayoutConstraint!
@IBOutlet weak private(set) var searchTextFieldTrailingSpaceConstraint: NSLayoutConstraint!
var containerBackgroundColor = UIColor.appViewBackgroundColor()
var delegate: SearchHeaderViewDelegate?
var searchFieldBackgroundColor = UIColor.appSearchTextFieldBackground()
var searchFieldTextColor = UIColor.appPrimaryTextColor()
var searchFieldTintColor = UIColor.appHighlightColor()
var searchFieldLeftView = UIView()
weak var searchFieldTagView: UIView?
private var leftViewImageView: UIImageView!
class var height: CGFloat {
return 44.0
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
customizeSearchField()
hideCancelButton()
}
// MARK: - Configuration
private func customizeSearchField() {
searchFieldLeftView.frame = CGRectMake(0.0, 0.0, searchFieldLeftViewDefaultWidth, searchTextField.frame.height)
searchFieldLeftView.backgroundColor = UIColor.clearColor()
leftViewImageView = UIImageView(image: UIImage(named: "searchbar_search")?.imageWithRenderingMode(.AlwaysTemplate))
leftViewImageView.contentMode = .Center
leftViewImageView.frame = CGRectMake(0.0, (searchTextField.frame.height - 16.0)/2.0, 16.0, 16.0)
leftViewImageView.tintColor = UIColor.appSearchIconTintColor()
searchFieldLeftView.addSubview(leftViewImageView)
searchTextField.leftViewMode = .Always
searchTextField.leftView = searchFieldLeftView
searchTextField.clearButtonMode = .WhileEditing
searchFieldBackgroundColor = UIColor.whiteColor()
containerBackgroundColor = UIColor.whiteColor()
updateView()
}
func updateView() {
searchTextField.backgroundColor = searchFieldBackgroundColor
searchTextField.textColor = searchFieldTextColor
searchTextField.tintColor = searchFieldTintColor
searchTextField.superview?.backgroundColor = containerBackgroundColor
cancelButton.setTitleColor(UIColor.appHighlightColor(), forState: .Normal)
}
// MARK: - Tag View
func showTagWithTitle(title: String) {
searchFieldTagView?.removeFromSuperview()
let tag = UIButton()
tag.backgroundColor = UIColor.appHighlightColor()
tag.contentEdgeInsets = UIEdgeInsetsMake(9.0, 14.0, 9.0, 14.0)
tag.setAttributedTitle(NSAttributedString(string: title, attributes: [NSFontAttributeName: UIFont.boldFont(11.0), NSKernAttributeName: 1.0, NSForegroundColorAttributeName: UIColor.whiteColor()]), forState: .Normal)
tag.sizeToFit()
tag.layer.cornerRadius = 3.0
if let searchHeaderViewDelegate = delegate as? AnyObject {
tag.addTarget(searchHeaderViewDelegate, action: "didSelectTag", forControlEvents: .TouchUpInside)
}
let tagPadding = CGFloat(8.0)
searchFieldLeftView.frameWidth = searchFieldLeftViewDefaultWidth + tag.frameWidth
tag.frame = CGRectMake(leftViewImageView.frameRight + tagPadding, floor((searchFieldLeftView.frameHeight - tag.frameHeight) / 2), tag.frameWidth, tag.frameHeight)
searchFieldLeftView.addSubview(tag)
searchFieldTagView = tag
searchTextField.placeholder = nil
}
func hideTag() {
searchFieldTagView?.removeFromSuperview()
searchFieldLeftView.frameWidth = searchFieldLeftViewDefaultWidth
}
// MARK: - CancelButtonState
func showCancelButton() {
searchTextFieldTrailingSpaceConstraint.constant = frame.width - cancelButton.frame.origin.x + 10.0
searchTextField.setNeedsUpdateConstraints()
UIView.animateWithDuration(
0.2,
animations: { () -> Void in
self.searchTextField.layoutIfNeeded()
self.cancelButton.alpha = 1.0
},
completion: nil
)
}
func hideCancelButton() {
searchTextFieldTrailingSpaceConstraint.constant = 0.0
searchTextField.setNeedsUpdateConstraints()
UIView.animateWithDuration(
0.2,
animations: { () -> Void in
self.searchTextField.layoutIfNeeded()
self.cancelButton.alpha = 0.0
},
completion: nil
)
}
func removeFocusFromSearchField() {
searchTextField.resignFirstResponder()
}
// MARK: - IBActions
@IBAction func cancelButtonTapped(sender: AnyObject!) {
hideCancelButton()
searchTextField.text = ""
searchTextField.resignFirstResponder()
self.delegate?.didCancel(self)
}
}
| 36.308219 | 222 | 0.683267 |
7627874c1e3c59929e0f21e68571fcffe342656e | 1,048 | //
// CryptoSwift
//
// Copyright (C) 2014-2021 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
import Foundation
#if !_runtime(_ObjC)
extension Error {
var localizedDescription: String {
"\(self)"
}
}
#endif
| 40.307692 | 217 | 0.749046 |
b9fd5861d9e0a4a9094a990250842e5d919b43e2 | 1,617 | import Foundation
typealias SymbolManifest = [ScannedSymbol]
struct SymbolManifestParser {
private struct Plist: Decodable {
enum CodingKeys: String, CodingKey {
case symbols
case yearToReleaseMapping = "year_to_release"
}
var symbols: [String: String]
var yearToReleaseMapping: [String: [String: String]]
}
static func parse(availabilityFileData: Data?) -> SymbolManifest? {
guard
let data = availabilityFileData,
let plist = try? PropertyListDecoder().decode(Plist.self, from: data)
else {
return nil
}
var availabilityFile: SymbolManifest = []
let availabilities = plist.yearToReleaseMapping.compactMap { key, value in
Availability(iOS: value["iOS"]!, tvOS: value["tvOS"]!, watchOS: value["watchOS"]!, macOS: value["macOS"]!, year: key)
}
for (key, value) in plist.symbols {
guard let availability = (availabilities.first { $0.year == value }) else {
// Cancel on single failure
return nil
}
availabilityFile.append(ScannedSymbol(name: key, availability: availability))
}
// Unfortunately, the data is inconsistent and for some symbols there are conflicting availability dates
// We just remove those symbols completely
availabilityFile = availabilityFile.filter { scannedSymbol in !availabilityFile.contains { $0.name == scannedSymbol.name && $0.availability != scannedSymbol.availability } }
return availabilityFile
}
}
| 36.75 | 181 | 0.633271 |
64e8986ea754fa4363c6d6a003089d027b28b724 | 2,665 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 937. Reorder Data in Log Files
// You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.
// There are two types of logs:
// Letter-logs: All words (except the identifier) consist of lowercase English letters.
// Digit-logs: All words (except the identifier) consist of digits.
// Reorder these logs so that:
// The letter-logs come before all digit-logs.
// The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
// The digit-logs maintain their relative ordering.
// Return the final order of the logs.
// Example 1:
// Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
// Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
// Explanation:
// The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".
// The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".
// Example 2:
// Input: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
// Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
// Constraints:
// 1 <= logs.length <= 100
// 3 <= logs[i].length <= 100
// All the tokens of logs[i] are separated by a single space.
// logs[i] is guaranteed to have an identifier and at least one word after the identifier.
// - Complexity:
// - time: O(n)
// - space: O(n)
func reorderLogFiles(_ logs: [String]) -> [String] {
guard !logs.isEmpty else { return [] }
var orderedDigits = [String]()
var orderedLetters = [String]()
var letters = [(key: String, value: String)]()
for log in logs {
guard let spaceIndex = log.firstIndex(of: " ") else { fatalError() }
let startValueIndex = log.index(after: spaceIndex)
let key = String(log[..<spaceIndex])
let value = String(log[startValueIndex...])
if value.first!.isLetter {
letters.append((key, value))
} else {
orderedDigits.append(log)
}
}
letters.sort { $0.value <= $1.value } // only letter-logs's values(ignore id) need to be ordered lexicographically
for letter in letters { orderedLetters.append(letter.key + " " + letter.value) }
return orderedLetters + orderedDigits
}
} | 42.983871 | 157 | 0.613508 |
0ef804f1d50e4968768965bbb6f3ace06c9d86dc | 7,079 | //===--- Semaphore.swift ----------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Foundation3
import Boilerplate
public protocol SemaphoreType {
init()
init(value: Int)
func wait() -> Bool
func wait(until:NSDate) -> Bool
func wait(timeout: Timeout) -> Bool
func signal() -> Int
}
public extension SemaphoreType {
public static var defaultValue:Int {
get {
return 0
}
}
}
public extension SemaphoreType {
/// Performs the wait operation on this semaphore until the timeout
/// Returns true if the semaphore was signalled before the timeout occurred
/// or false if the timeout occurred.
public func wait(timeout: Timeout) -> Bool {
switch timeout {
case .Infinity:
return wait()
default:
return wait(timeout.timeSinceNow())
}
}
}
private extension NSCondition {
func waitWithConditionalEnd(date:NSDate?) -> Bool {
guard let date = date else {
self.wait()
return true
}
return self.wait(until: date)
}
}
/// A wrapper around NSCondition
public class BlockingSemaphore : SemaphoreType {
/// The underlying NSCondition
private(set) public var underlyingSemaphore: NSCondition
private(set) public var value: Int
/// Creates a new semaphore with the given initial value
/// See NSCondition and https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW13
public required init(value: Int) {
self.underlyingSemaphore = NSCondition()
self.value = value
}
/// Creates a new semaphore with initial value 0
/// This kind of semaphores is useful to protect a critical section
public convenience required init() {
self.init(value: BlockingSemaphore.defaultValue)
}
//TODO: optimise with atomics for value. Will allow to run not-blocked sema faster
private func waitWithConditionalDate(until:NSDate?) -> Bool {
underlyingSemaphore.lock()
defer {
underlyingSemaphore.unlock()
}
value -= 1
var signaled:Bool = true
if value < 0 {
signaled = underlyingSemaphore.waitWithConditionalEnd(until)
}
return signaled
}
public func wait() -> Bool {
return waitWithConditionalDate(nil)
}
/// returns true on success (false if timeout expired)
/// if nil is passed - waits forever
public func wait(until:NSDate) -> Bool {
return waitWithConditionalDate(until)
}
/// Performs the signal operation on this semaphore
public func signal() -> Int {
underlyingSemaphore.lock()
defer {
underlyingSemaphore.unlock()
}
value += 1
underlyingSemaphore.signal()
return value
}
}
class HashableAnyContainer<T> : AnyContainer<T>, Hashable {
let guid = NSUUID()
let hashValue: Int
override init(_ item: T) {
hashValue = self.guid.hashValue
super.init(item)
}
}
func ==<T>(lhs:HashableAnyContainer<T>, rhs:HashableAnyContainer<T>) -> Bool {
return lhs.guid == rhs.guid
}
private enum Wakeable {
case Loop(loop:RunnableRunLoopType)
case Sema(loop:RunLoopType, sema:SemaphoreType)
}
private extension Wakeable {
init(loop:RunLoopType) {
if let loop = loop as? RunnableRunLoopType {
self = .Loop(loop: loop)
} else {
self = .Sema(loop:loop, sema: loop.semaphore())
}
}
func waitWithConditionalDate(until:NSDate?) -> Bool {
switch self {
case .Loop(let loop):
if let until = until {
return loop.run(Timeout(until: until))
} else {
return loop.run()
}
case .Sema(_, let sema):
if let until = until {
return sema.wait(until)
} else {
return sema.wait()
}
}
}
func wake(task:SafeTask) {
switch self {
case .Loop(let loop):
loop.execute {
task()
loop.stop()
}
case .Sema(let loop, let sema):
loop.execute {
task()
sema.signal()
}
}
}
}
public class RunLoopSemaphore : SemaphoreType {
private var signals:[SafeTask]
private let lock:NSLock
private var value:Int
private var signaled:ThreadLocal<Bool>
public required convenience init() {
self.init(value: 0)
}
public required init(value: Int) {
self.value = value
signals = Array()
lock = NSLock()
signaled = try! ThreadLocal()
}
//TODO: optimise with atomics for value. Will allow to run non-blocked sema faster
private func waitWithConditionalDate(until:NSDate?) -> Bool {
lock.lock()
defer {
lock.unlock()
}
value -= 1
if value >= 0 {
return true
}
var signaled = false
var timedout = false
let loop = RunLoop.current
let wakeable:Wakeable = Wakeable(loop: loop)
let signal = {
wakeable.wake {
self.signaled.value = true
}
}
signals.append(signal)
if value < 0 {
lock.unlock()
//defer {
// lock.lock()
//}
while !signaled && !timedout {
timedout = wakeable.waitWithConditionalDate(until)
signaled = self.signaled.value ?? false
}
self.signaled.value = false
lock.lock()
}
return signaled
}
public func wait() -> Bool {
return waitWithConditionalDate(nil)
}
public func wait(until:NSDate) -> Bool {
return waitWithConditionalDate(until)
}
public func signal() -> Int {
lock.lock()
value += 1
let signal:SafeTask? = signals.isEmpty ? nil : signals.removeLast()
lock.unlock()
signal?()
return 1
}
} | 27.332046 | 194 | 0.566605 |
0107de2b89700c64ea409d22f60c95268bf69e0b | 2,346 | import Foundation
import TSCBasic
import struct TSCUtility.Version
import TuistSupport
protocol VersionsControlling: AnyObject {
typealias Installation = (AbsolutePath) throws -> Void
func install(version: String, installation: Installation) throws
func uninstall(version: String) throws
func path(version: String) -> AbsolutePath
func versions() -> [InstalledVersion]
func semverVersions() -> [Version]
}
enum InstalledVersion: CustomStringConvertible, Equatable {
case semver(Version)
case reference(String)
var description: String {
switch self {
case let .reference(value): return value
case let .semver(value): return value.description
}
}
}
class VersionsController: VersionsControlling {
// MARK: - VersionsControlling
func install(version: String, installation: Installation) throws {
try withTemporaryDirectory { tmpDir in
try installation(tmpDir)
// Copy only if there's file in the folder
if !tmpDir.glob("*").isEmpty {
let dstPath = path(version: version)
if FileHandler.shared.exists(dstPath) {
try FileHandler.shared.delete(dstPath)
}
try FileHandler.shared.copy(from: tmpDir, to: dstPath)
}
}
}
func uninstall(version: String) throws {
let path = self.path(version: version)
if FileHandler.shared.exists(path) {
try FileHandler.shared.delete(path)
}
}
func path(version: String) -> AbsolutePath {
Environment.shared.versionsDirectory.appending(component: version)
}
func versions() -> [InstalledVersion] {
Environment.shared.versionsDirectory.glob("*").map { path in
let versionStringValue = path.components.last!
if let version = Version(string: versionStringValue) {
return InstalledVersion.semver(version)
} else {
return InstalledVersion.reference(versionStringValue)
}
}
}
func semverVersions() -> [Version] {
versions().compactMap { version in
if case let InstalledVersion.semver(semver) = version {
return semver
}
return nil
}.sorted()
}
}
| 30.467532 | 74 | 0.621057 |
23b6637011b00f8ab8f252d352b1289b2a517f33 | 2,616 | //
// Random_Extentsion.swift
// ShenZhouDaDiXing
//
// Created by spectator Mr.Z on 2016/10/23.
// Copyright © 2016年 ZZC WORKSPACE. All rights reserved.
//
import UIKit
let randomContentArr = ["0","1","2","3","4","5","6","7","8","9"]
class Random_Extentsion: NSObject {
func UUIDByNumber() -> String {
var uuid = ""
for _ in 0..<32 {
let subscri = Int(arc4random()%10)
let str = randomContentArr[subscri]
uuid = uuid + str
}
UserDefaults.standard.set(uuid, forKey: "uuid")
UserDefaults.standard.synchronize()
return uuid
}
func getDateString(start: Int, end: Int) -> String {
let date = Date()
var dateValue = date.timeIntervalSince1970
dateValue = dateValue * 1000
let dateStr = String(format: "%.0f", dateValue)
// let starBound = dateStr.index(dateStr.startIndex, offsetBy: start)
// let endBound = dateStr.index(dateStr.startIndex, offsetBy: end)
// let resultStr = dateStr.substring(with: Range(uncheckedBounds: (starBound, endBound)))
// let resultStr = dateStr.substring(star: start, end: end)
let resultStr = dateStr[safe: start..<end] ?? ""
return resultStr
}
func getBillNumber() -> String {
var uuid = ""
if let onlyID = UserDefaults.standard.value(forKey: "uuid") {
uuid = onlyID as! String
} else {
uuid = UUIDByNumber()
}
SNLog("random \(uuid)")
let uuidIndex = uuid.index(uuid.startIndex, offsetBy: 3)
// let first = uuid.substring(to: uuidIndex)
let first = uuid.prefix(upTo: uuidIndex)
let timeStamp = getDateString(start: 2, end: 9)
let uuids = first + "\(arc4random()%10)" + timeStamp + "\(arc4random()%10)"
return uuids
}
func getCartBatchNumber() -> String {
var uuid = ""
if let onlyID = UserDefaults.standard.value(forKey: "uuid") {
uuid = onlyID as! String
} else {
uuid = UUIDByNumber()
}
SNLog("random \(uuid)")
let uuidIndex = uuid.index(uuid.startIndex, offsetBy: 5)
// let first = uuid.substring(to: uuidIndex)
let first = uuid.prefix(upTo: uuidIndex)
let timeStamp = getDateString(start: 8, end: 13)
return "VR" + first + timeStamp + "\(arc4random()%10)" + "\(arc4random()%10)"
}
}
| 28.434783 | 96 | 0.541667 |
6725f7aa144e9478ef2800534776291e67cb66ef | 1,862 | //
// RxUtils.swift
// Core
//
// Created by Socratis Michaelides on 08/11/2018.
// Copyright © 2018 Socratis Michaelides. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
infix operator >>>: AdditionPrecedence
public func >>> (lhs: Disposable?, rhs: DisposeBag) {
lhs?.disposed(by: rhs)
}
infix operator <->: AdditionPrecedence
public func <-> <T> (property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
let bindToUIDisposable = variable.asObservable().debug("Variable values in bind")
.bind(to: property)
let bindToVariable = property
.debug("Property values in bind")
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
public protocol Optionable {
associatedtype WrappedType
func unwrap() -> WrappedType
func isEmpty() -> Bool
}
extension Optional : Optionable {
public typealias WrappedType = Wrapped
public func unwrap() -> WrappedType {
return self!
}
public func isEmpty() -> Bool {
return self == nil
}
}
extension ObservableType where E : Optionable {
public func unwrap() -> Observable<E.WrappedType> {
return self.filter({ !$0.isEmpty() }).map({ $0.unwrap() })
}
public func onNil() -> Observable<Void> {
return self.filter({ $0.isEmpty() }).map({ _ -> Void in })
}
}
extension SharedSequence where S == DriverSharingStrategy, E : Optionable {
public func unwrap() -> SharedSequence<S, E.WrappedType> {
return self.filter({ !$0.isEmpty() }).map({ $0.unwrap() })
}
public func onNil() -> SharedSequence<S, Void> {
return self.filter({ $0.isEmpty() }).map({ _ -> Void in })
}
}
extension ObservableType {
public func asVoid() -> Observable<Void> {
return self.map { _ in }
}
}
| 24.5 | 89 | 0.665414 |
e8b74119ef288c9c9ecf7978d00d655fb432959e | 538 | //
// Dragging.View.Contract.swift
// SnapAlignment
//
// Created by Haider Khan on 3/11/20.
// Copyright © 2020 zkhaider. All rights reserved.
//
import AppKit
public protocol DraggingViewContract: class {
func startedDrag(
for view: ShapeView,
in superview: NSView,
event: NSEvent
)
func dragging(
for view: ShapeView,
in superview: NSView,
event: NSEvent
)
func endDrag(
for view: ShapeView,
in superview: NSView,
event: NSEvent
)
}
| 19.214286 | 51 | 0.605948 |
89e9abd8cb25d97917d642ee7f818c80420e88c2 | 253 | //
// QuizAnswer.swift
// QuizArcTouch
//
// Created by Débora Oliveira on 16/11/19.
// Copyright © 2019 Débora Oliveira. All rights reserved.
//
import Foundation
struct QuizAnswer: Codable {
let question: String?
let answer: [String]?
}
| 16.866667 | 58 | 0.683794 |
c1c49ac3a252467212e6cc24b5c4e013bf8dd509 | 21,397 | //
// pointeger.swift
// pons
//
// Created by Dan Kogai on 2/4/16.
// Copyright © 2016 Dan Kogai. All rights reserved.
//
public typealias POSwiftInteger = IntegerType
///
/// Protocol-oriented integer, signed or unsigned.
///
/// For the sake of protocol-oriented programming,
/// consider extend this protocol first before extending each integer type.
///
public protocol POInteger : POComparableNumber,
RandomAccessIndexType, IntegerLiteralConvertible, _BuiltinIntegerLiteralConvertible
{
// from IntegerArithmeticType
static func addWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool)
static func subtractWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool)
static func multiplyWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool)
static func divideWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool)
static func remainderWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool)
func %(lhs: Self, rhs: Self) -> Self
// from BitwiseOperationsType
func &(lhs: Self, rhs: Self) -> Self
func |(lhs: Self, rhs: Self) -> Self
func ^(lhs: Self, rhs: Self) -> Self
prefix func ~(x: Self) -> Self
// strangely they did not exist
func <<(_:Self,_:Self)->Self
func >>(_:Self,_:Self)->Self
// init?(_:String, radix:Int)
func toDouble()->Double
static var precision:Int { get }
// the most significant bit
var msbAt:Int { get }
//
var asUInt64:UInt64? { get }
var asUInt32:UInt32? { get }
var asUInt16:UInt16? { get }
var asUInt8:UInt8? { get }
var asUInt:UInt? { get }
var asInt64:Int64? { get }
var asInt32:Int32? { get }
var asInt16:Int16? { get }
var asInt8:Int8? { get }
var asInt:Int? { get }
}
// give away arithmetic operators
public func +<I:POInteger>(lhs:I, rhs:I)->I {
let (result, overflow) = I.addWithOverflow(lhs, rhs)
if overflow { fatalError("overflow: \(lhs) + \(rhs)") }
return result
}
public func -<I:POInteger>(lhs:I, rhs:I)->I {
let (result, overflow) = I.subtractWithOverflow(lhs, rhs)
if overflow { fatalError("overflow: \(lhs) - \(rhs)") }
return result
}
public func *<I:POInteger>(lhs:I, rhs:I)->I {
let (result, overflow) = I.multiplyWithOverflow(lhs, rhs)
if overflow { fatalError("overflow: \(lhs) * \(rhs)") }
return result
}
public func /<I:POInteger>(lhs:I, rhs:I)->I {
let (result, overflow) = I.divideWithOverflow(lhs, rhs)
if overflow { fatalError("overflow: \(lhs) / \(rhs)") }
return result
}
public func %<I:POInteger>(lhs:I, rhs:I)->I {
let (result, overflow) = I.remainderWithOverflow(lhs, rhs)
if overflow { fatalError("overflow: \(lhs) % \(rhs)") }
return result
}
// give away &op
//public func &+<I:POInteger>(lhs:I, rhs:I)->I {
// return I.addWithOverflow(lhs, rhs).0
//}
//public func &-<I:POInteger>(lhs:I, rhs:I)->I {
// return I.subtractWithOverflow(lhs, rhs).0
//}
//public func &*<I:POInteger>(lhs:I, rhs:I)->I {
// return I.multiplyWithOverflow(lhs, rhs).0
//}
// give away op=
public func %=<I:POInteger>(inout lhs:I, rhs:I) {
lhs = lhs % rhs
}
public func &=<I:POInteger>(inout lhs:I, rhs:I) {
lhs = lhs & rhs
}
public func |=<I:POInteger>(inout lhs:I, rhs:I) {
lhs = lhs | rhs
}
public func ^=<I:POInteger>(inout lhs:I, rhs:I) {
lhs = lhs ^ rhs
}
public func <<=<I:POInteger>(inout lhs:I, rhs:I) {
lhs = lhs << rhs
}
public func >>=<I:POInteger>(inout lhs:I, rhs:I) {
lhs = lhs >> rhs
}
public extension POInteger {
/// IntegerLiteralConvertible by Default
public init(integerLiteral:Int) {
self.init(integerLiteral)
}
/// _BuiltinIntegerLiteralConvertible by Default
public init(_builtinIntegerLiteral:_MaxBuiltinIntegerType) {
self.init(Int(_builtinIntegerLiteral: _builtinIntegerLiteral))
}
// from BitwiseOperationsType
public static var allZeros: Self { return 0 }
// RandomAccessIndexType by default
public func successor() -> Self {
return self + 1
}
public func predecessor() -> Self {
return self - 1
}
public func advancedBy(n: Int) -> Self {
return self + Self(n)
}
//
public init(_ v:UInt64) { self.init(v.asInt!) }
public init(_ v:UInt32) { self.init(v.asInt!) }
public init(_ v:UInt16) { self.init(v.asInt!) }
public init(_ v:UInt8) { self.init(v.asInt!) }
public init(_ v:Int64) { self.init(v.asInt!) }
public init(_ v:Int32) { self.init(v.asInt!) }
public init(_ v:Int16) { self.init(v.asInt!) }
public init(_ v:Int8) { self.init(v.asInt!) }
public init(_ d:Double) { self.init(Int(d)) }
public var asDouble:Double? { return self.toDouble() }
public var asFloat:Float? { return Float(self.toDouble()) }
//
/// default implementation. you should override it
public static func divmod(lhs:Self, _ rhs:Self)->(Self, Self) {
return (lhs / rhs, lhs % rhs)
}
///
/// Generalized power func
///
/// the end result is the same as `(1..<n).reduce(lhs, combine:op)`
/// but it is faster by [exponentiation by squaring].
///
/// power(2, 3){ $0 + $1 } // 2 + 2 + 2 == 6
/// power("Swift", 3){ $0 + $1 } // "SwiftSwiftSwift"
///
/// In exchange for efficiency, `op` must be commutable.
/// That is, `op(x, y) == op(y, x)` is true for all `(x, y)`
///
/// [exponentiation by squaring]: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
public static func power<L>(lhs:L, _ rhs:Self, op:(L,L)->L)->L {
if rhs < Self(1) {
fatalError("negative exponent unsupported")
}
var r = lhs
var t = lhs, n = rhs - Self(1)
while n > Self(0) {
if n & Self(1) == Self(1) {
r = op(r, t)
}
n >>= Self(1)
t = op(t, t)
}
return r
}
/// Integer square root
public static func sqrt(n:Self)->Self {
if n == 0 { return 0 }
if n == 1 { return 1 }
var xk = n >> Self(n.msbAt / 2)
repeat {
let xk1 = (xk + n / xk) >> 1 // /2
if xk1 >= xk { return xk }
xk = xk1
} while true
}
}
public typealias POSwiftUInt = UnsignedIntegerType
///
/// Protocol-oriented unsigned integer. All built-ins already conform to this.
///
/// For the sake of protocol-oriented programming,
/// consider extend this protocol first before extending each unsigned integer type.
///
public protocol POUInt: POInteger, StringLiteralConvertible, CustomDebugStringConvertible {
init (_:UInt)
init (_:UIntMax)
func toUIntMax()->UIntMax
associatedtype IntType:POSignedNumber // its correspoinding singed type
//init(_:IntType) // must be capable of initializing from it
var asSigned:IntType? { get }
var asBigUInt:BigUInt? { get }
init(_:BigUInt)
}
public extension POUInt {
public init(_ v:UInt64) { self.init(v.toUIntMax()) }
public init(_ v:UInt32) { self.init(v.toUIntMax()) }
public init(_ v:UInt16) { self.init(v.toUIntMax()) }
public init(_ v:UInt8) { self.init(v.toUIntMax()) }
public init(_ bu:BigUInt) {
self.init(bu.asUInt64!)
}
public var asBigUInt:BigUInt? {
// print("\(__LINE__):\(__FILE__):self=\(self)")
return BigUInt(self.asUInt64!)
}
/// number of significant bits == sizeof(Self) * 8
public static var precision:Int {
return sizeof(Self) * 8
}
///
/// Returns the index of the most significant bit of `self`
/// or `-1` if `self == 0`
public var msbAt:Int { return self.toUIntMax().msbAt }
//
// from IntegerArithmeticType
public static func addWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = UInt.addWithOverflow(lhs.asUInt!, rhs.asUInt!)
return (Self(result), overflow)
}
public static func subtractWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = UInt.subtractWithOverflow(lhs.asUInt!, rhs.asUInt!)
return (Self(result), overflow)
}
public static func multiplyWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = UInt.multiplyWithOverflow(lhs.asUInt!, rhs.asUInt!)
return (Self(result), overflow)
}
public static func divideWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = UInt.divideWithOverflow(lhs.asUInt!, rhs.asUInt!)
return (Self(result), overflow)
}
public static func remainderWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = UInt.remainderWithOverflow(lhs.asUInt!, rhs.asUInt!)
return (Self(result), overflow)
}
// POInteger conformance
public var asUInt64:UInt64? { return UInt64(self.toUIntMax()) }
public var asUInt32:UInt32? { return UInt32(self.toUIntMax()) }
public var asUInt16:UInt16? { return UInt16(self.toUIntMax()) }
public var asUInt8:UInt8? { return UInt8(self.toUIntMax()) }
public var asUInt:UInt? { return UInt(self.toUIntMax()) }
public var asInt64:Int64? {
let ux = self.toUIntMax()
return UInt64(Int64.max) < ux ? nil : Int64(ux)
}
public var asInt32:Int32? {
let ux = self.toUIntMax()
return UInt64(Int32.max) < ux ? nil : Int32(ux)
}
public var asInt16:Int16? {
let ux = self.toUIntMax()
return UInt64(Int16.max) < ux ? nil : Int16(ux)
}
public var asInt8:Int8? {
let ux = self.toUIntMax()
return UInt64(Int8.max) < ux ? nil : Int8(ux)
}
public var asInt:Int? {
let ux = self.toUIntMax()
return UInt64(Int.max) < ux ? nil : Int(ux)
}
public func toDouble()->Double { return Double(self.toUIntMax()) }
///
/// `self.toString()` uses this to extract digits
///
public static func divmod8(lhs:Self, _ rhs:Int8)->(Self, Int) {
let denom = Self(rhs.asInt!)
return (lhs / denom, (lhs % denom).asInt!)
}
/// returns quotient and remainder all at once.
///
/// we give you the default you should override this for efficiency
public static func divmod8(lhs:Self, _ rhs:Self)->(Self, Self) {
return (lhs / rhs, lhs % rhs)
}
///
/// Stringifies `self` with base `radix` which defaults to `10`
///
public func toString(base:Int = 10)-> String {
guard 2 <= base && base <= 36 else {
fatalError("base out of range. \(base) is not within 2...36")
}
var v = self
var digits = [Int]()
repeat {
var r:Int
(v, r) = Self.divmod8(v, Int8(base))
digits.append(r)
} while v != 0
return digits.reverse().map{"\(POUtil.int2char[$0])"}.joinWithSeparator("")
}
// automagically CustomStringConvertible by defalut
public var description:String {
return self.toString()
}
// automagically CustomDebugStringConvertible
public var debugDescription:String {
return "0x" + self.toString(16)
}
public static func fromString(s: String, radix:Int = 10)->Self? {
var (ss, b) = (s, radix)
let si = s.startIndex
if s[si] == "0" {
let sis = si.successor()
if s[sis] == "x" || s[sis] == "o" || s[sis] == "b" {
ss = s[sis.successor()..<s.endIndex]
b = s[sis] == "x" ? 16 : s[sis] == "o" ? 8 : 2
}
}
var result = Self(0)
for c in ss.lowercaseString.characters {
if let d = POUtil.char2int[c] {
result *= Self(b)
result += Self(d)
} else {
if c != "_" { return nil }
}
}
return result
}
/// init() with String. Handles `0x`, `0b`, and `0o`
///
/// ought to be `init?` but that makes Swift 2.1 irate :-(
public init(_ s:String, radix:Int = 10) {
self.init(Self.fromString(s, radix:radix)!)
}
public var hashValue : Int { // slow but steady
return self.debugDescription.hashValue
}
/// StringLiteralConvertible by Default
public init(stringLiteral: String) {
self.init(stringLiteral)
}
public init(unicodeScalarLiteral: String) {
self.init(stringLiteral: "\(unicodeScalarLiteral)")
}
public init(extendedGraphemeClusterLiteral: String) {
self.init(stringLiteral: extendedGraphemeClusterLiteral)
}
///
/// * `lhs ** rhs`
/// * `lhs ** rhs % mod` if `mod !=` (aka `modpow` or `powmod`)
///
/// note only `rhs` must be an integer.
///
public static func pow<L:POUInt>(lhs:L, _ rhs:Self)->L {
return rhs < Self(1) ? L(1) : power(lhs, rhs){ L.multiplyWithOverflow($0, $1).0 }
}
/// true if self is power of 2
public var isPowerOf2:Bool {
return self != 0 && self & (self - 1) == 0
}
}
//
//public func &<U:POUInt>(lhs:U, rhs:U)->U {
// return U(lhs.toUIntMax() & rhs.toUIntMax())
//}
//public func |<U:POUInt>(lhs:U, rhs:U)->U {
// return U(lhs.toUIntMax() | rhs.toUIntMax())
//}
//public func ^<U:POUInt>(lhs:U, rhs:U)->U {
// return U(lhs.toUIntMax() ^ rhs.toUIntMax())
//}
//public func << <U:POUInt>(lhs:U, rhs:U)->U {
// return U(lhs.toUIntMax() << rhs.toUIntMax())
//}
//public func >> <U:POUInt>(lhs:U, rhs:U)->U {
// return U(lhs.toUIntMax() << rhs.toUIntMax())
//}
//
extension UInt64: POUInt {
public typealias IntType = Int64
public var msbAt:Int {
return self <= UInt64(UInt32.max)
? UInt32(self).msbAt
: UInt32(self >> 32).msbAt + 32
}
public var asSigned:IntType? { return UInt64(Int64.max) < self ? nil : IntType(self) }
}
extension UInt32: POUInt {
public typealias IntType = Int32
public var msbAt:Int {
return Double.frexp(Double(self)).1 - 1
}
public var asSigned:IntType? { return UInt32(Int32.max) < self ? nil : IntType(self) }
}
extension UInt16: POUInt {
public typealias IntType = Int16
public var asSigned:IntType? { return UInt16(Int16.max) < self ? nil : IntType(self) }
}
extension UInt8: POUInt {
public typealias IntType = Int8
public var asSigned:IntType? { return UInt8(Int8.max) < self ? nil : IntType(self) }
}
extension UInt: POUInt {
public typealias IntType = Int
public var asSigned:IntType? { return UInt(Int.max) < self ? nil : IntType(self) }
}
public typealias POSwiftInt = SignedIntegerType
///
/// Protocol-oriented signed integer. All built-ins already conform to this.
///
/// For the sake of protocol-oriented programming,
/// consider extend this protocol first before extending each signed integer types.
///
public protocol POInt: POInteger, POSignedNumber, StringLiteralConvertible, CustomDebugStringConvertible {
init(_:IntMax)
///
/// The unsigned version of `self`
///
associatedtype UIntType:POUInt // its corresponding unsinged type
init(_:UIntType) // capable of initializing from it
var asUnsigned:UIntType? { get } // able to convert to unsigned
var asBigInt:BigInt? { get }
}
public extension POInt {
/// number of significant bits == sizeof(Self) * 8 - 1
public static var precision:Int {
return sizeof(Self) * 8 - 1
}
public static func addWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = Int.addWithOverflow(lhs.asInt!, rhs.asInt!)
return (Self(result), overflow)
}
public static func subtractWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = Int.subtractWithOverflow(lhs.asInt!, rhs.asInt!)
return (Self(result), overflow)
}
public static func multiplyWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = Int.multiplyWithOverflow(lhs.asInt!, rhs.asInt!)
return (Self(result), overflow)
}
public static func divideWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = Int.divideWithOverflow(lhs.asInt!, rhs.asInt!)
return (Self(result), overflow)
}
public static func remainderWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) {
let (result, overflow) = Int.remainderWithOverflow(lhs.asInt!, rhs.asInt!)
return (Self(result), overflow)
}
/// Default isSignMinus
public var isSignMinus:Bool {
return self < 0
}
/// Default toUIntMax
public func toUIntMax()->UIntMax {
return UIntMax(self.toIntMax())
}
// POInteger conformance
public var asUInt64:UInt64? {
let ix = self.toIntMax()
return ix < 0 ? nil : UInt64(ix)
}
public var asUInt32:UInt32? {
let ix = self.toIntMax()
return ix < 0 ? nil : UInt32(ix)
}
public var asUInt16:UInt16? {
let ix = self.toIntMax()
return ix < 0 ? nil : UInt16(ix)
}
public var asUInt8:UInt8? {
let ix = self.toIntMax()
return ix < 0 ? nil : UInt8(ix)
}
public var asUInt:UInt? {
let ix = self.toIntMax()
return ix < 0 ? nil : UInt(ix)
}
public var asBigInt:BigInt? {
return BigInt(self.toIntMax())
}
public var asInt64:Int64? { return Int64(self.toIntMax()) }
public var asInt32:Int32? { return Int32(self.toIntMax()) }
public var asInt16:Int16? { return Int16(self.toIntMax()) }
public var asInt8:Int8? { return Int8(self.toIntMax()) }
public var asInt:Int? { return Int(self.toIntMax()) }
public func toDouble()->Double { return Double(self.toIntMax()) }
///
/// Returns the index of the most significant bit of `self`
/// or `-1` if `self == 0`
public var msbAt:Int {
return self < 0 ? sizeof(Self) * 8 - 1 : self.toUIntMax().msbAt
}
///
/// Stringifies `self` with base `radix` which defaults to `10`
///
public func toString(radix:Int = 10)-> String {
return (self < 0 ? "-" : "") + self.abs.asUnsigned!.toString(radix)
}
// automagically CustomStringConvertible by defalut
public var description:String {
return self.toString()
}
// automagically CustomDebugStringConvertible
public var debugDescription:String {
return (self < 0 ? "-" : "+") + self.abs.asUInt64.debugDescription
}
/// init() with String. Handles `0x`, `0b`, and `0o`
///
/// ought to be `init?` but that makes Swift 2.1 irate :-(
public init(_ s:String, radix:Int = 10) {
let si = s.startIndex
let u = s[si] == "-" || s[si] == "+"
? UIntType(s[si.successor()..<s.endIndex], radix:radix)
: UIntType(s, radix:radix)
self.init(s[si] == "-" ? -Self(u) : +Self(u))
}
///
/// StringLiteralConvertible by Default
public init(stringLiteral: String) {
self.init(stringLiteral)
}
public init(unicodeScalarLiteral: String) {
self.init(stringLiteral: "\(unicodeScalarLiteral)")
}
public init(extendedGraphemeClusterLiteral: String) {
self.init(stringLiteral: extendedGraphemeClusterLiteral)
}
/// - returns:
/// `lhs ** rhs` or `lhs ** rhs % mod` if `mod != 1` (aka `modpow` or `powmod`)
///
/// note only `rhs` must be an integer.
/// also note it unconditinally returns `1` if `rhs < 1`
/// for negative exponent, make lhs noninteger
///
/// pow(2, -2) // 1
/// pow(2.0, -2) // 0.25
public static func pow<L:POInt>(lhs:L, _ rhs:Self)->L {
return rhs < 1 ? 1 : power(lhs, rhs){ L.multiplyWithOverflow($0, $1).0 }
}
/// - returns: `lhs ** rhs`
public static func pow<L:POReal>(lhs:L, _ rhs:Self)->L {
return L.pow(lhs, L(rhs.toDouble()))
}
/// true if self is power of 2
public var isPowerOf2:Bool {
return self.abs.asUnsigned!.isPowerOf2
}
}
//
//public func &<I:POInt>(lhs:I, rhs:I)->I {
// return I(lhs.toIntMax() & rhs.toIntMax())
//}
//public func |<I:POInt>(lhs:I, rhs:I)->I {
// return I(lhs.toIntMax() | rhs.toIntMax())
//}
//public func ^<I:POInt>(lhs:I, rhs:I)->I {
// return I(lhs.toIntMax() ^ rhs.toIntMax())
//}
//public func << <I:POInt>(lhs:I, rhs:I)->I {
// return I(lhs.toIntMax() << rhs.toIntMax())
//}
//public func >> <I:POInt>(lhs:I, rhs:I)->I {
// return I(lhs.toIntMax() << rhs.toIntMax())
//}
//
extension Int64: POInt {
public typealias UIntType = UInt64
public var asUnsigned:UIntType? { return self < 0 ? nil : UIntType(self) }
}
extension Int32: POInt {
public typealias UIntType = UInt32
public var asUnsigned:UIntType? { return self < 0 ? nil : UIntType(self) }
}
extension Int16: POInt {
public typealias UIntType = UInt16
public var asUnsigned:UIntType? { return self < 0 ? nil : UIntType(self) }
}
extension Int8: POInt {
public typealias UIntType = UInt8
public var asUnsigned:UIntType? { return self < 0 ? nil : UIntType(self) }
}
extension Int: POInt {
public typealias UIntType = UInt
public var asUnsigned:UIntType? { return self < 0 ? nil : UIntType(self) }
}
| 36.143581 | 106 | 0.600271 |
ed9059511c00cb800add1e7acf2b955f1faf7c19 | 3,985 | //
// Copyright © 2016 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
@objc(UBSDKUpfrontFare) public class UpfrontFare: NSObject, Codable {
/// A unique upfront fare identifier.
@objc public private(set) var fareID: String
/// The total upfront fare value.
@objc public private(set) var value: Double
/// ISO 4217 currency code.
@objc public private(set) var currencyCode: String
/// Formatted string of estimate in local currency.
@objc public private(set) var display: String
/// The upfront fare expiration time
@objc public private(set) var expiresAt: Date
/// The components that make up the upfront fare
@objc public private(set) var breakdown: [UpfrontFareComponent]
enum CodingKeys: String, CodingKey {
case fareID = "fare_id"
case value = "value"
case currencyCode = "currency_code"
case display = "display"
case expiresAt = "expires_at"
case breakdown = "breakdown"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
fareID = try container.decode(String.self, forKey: .fareID)
value = try container.decode(Double.self, forKey: .value)
currencyCode = try container.decode(String.self, forKey: .currencyCode)
display = try container.decode(String.self, forKey: .display)
expiresAt = try container.decode(Date.self, forKey: .expiresAt)
breakdown = try container.decode([UpfrontFareComponent].self, forKey: .breakdown)
}
}
@objc(UBSDKUpfrontFareComponent) public class UpfrontFareComponent: NSObject, Codable {
/// Upfront fare type
@objc public private(set) var type: UpfrontFareComponentType
/// Value of the upfront fare component
@objc public private(set) var value: Double
/// A string that can be displayed to the user representing this portion of the fare
@objc public private(set) var name: String
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(UpfrontFareComponentType.self, forKey: .type)
value = try container.decode(Double.self, forKey: .value)
name = try container.decode(String.self, forKey: .name)
}
}
@objc(UBSDKUpfrontFareComponentType) public enum UpfrontFareComponentType: Int, Codable {
/// Base fare
case baseFare
/// Promotion adjustment
case promotion
/// Unknown case.
case unknown
public init(from decoder: Decoder) throws {
let string = try decoder.singleValueContainer().decode(String.self).lowercased()
switch string.lowercased() {
case "base_fare":
self = .baseFare
case "promotion":
self = .promotion
default:
self = .unknown
}
}
}
| 40.252525 | 89 | 0.698871 |
f8f4b0fe433987d08a0f074dc14f8d0c11d9b7bf | 1,818 | //
// NSControl+RxTests.swift
// Tests
//
// Created by mrahmiao on 1/1/16.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
import Cocoa
import XCTest
final class NSControlTests : RxTest {
}
extension NSControlTests {
func test_controlEvent() {
let control = NSControl(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
var numberOfTimesReceivedValue = 0
let d1 = control.rx.controlEvent.subscribe(onNext: { numberOfTimesReceivedValue += 1 })
let d2 = control.rx.controlEvent.subscribe(onNext: { numberOfTimesReceivedValue += 1 })
XCTAssertEqual(numberOfTimesReceivedValue, 0)
if let target = control.target, let action = control.action {
_ = target.perform(action, with: target)
}
XCTAssertEqual(numberOfTimesReceivedValue, 2)
d1.dispose()
d2.dispose()
_ = control.rx.controlEvent.subscribe(onNext: { numberOfTimesReceivedValue += 1 })
_ = control.rx.controlEvent.subscribe(onNext: { numberOfTimesReceivedValue += 1 })
XCTAssertEqual(numberOfTimesReceivedValue, 2)
if let target = control.target, let action = control.action {
_ = target.perform(action, with: target)
}
XCTAssertEqual(numberOfTimesReceivedValue, 4)
}
func testEnabled_False() {
let subject = NSButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
Observable.just(false).subscribe(subject.rx.isEnabled).dispose()
XCTAssertTrue(subject.isEnabled == false)
}
func testEnabled_True() {
let subject = NSButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
Observable.just(true).subscribe(subject.rx.isEnabled).dispose()
XCTAssertTrue(subject.isEnabled == true)
}
}
| 28.40625 | 95 | 0.657866 |
e5099387caab45eace834980190dd3bb30e4bdcd | 13,111 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
import Foundation
extension MarketplaceMetering {
// MARK: Enums
public enum UsageRecordResultStatus: String, CustomStringConvertible, Codable {
case success = "Success"
case customernotsubscribed = "CustomerNotSubscribed"
case duplicaterecord = "DuplicateRecord"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct BatchMeterUsageRequest: AWSEncodableShape {
/// Product code is used to uniquely identify a product in AWS Marketplace. The product code should be the same as the one used during the publishing of a new product.
public let productCode: String
/// The set of UsageRecords to submit. BatchMeterUsage accepts up to 25 UsageRecords at a time.
public let usageRecords: [UsageRecord]
public init(productCode: String, usageRecords: [UsageRecord]) {
self.productCode = productCode
self.usageRecords = usageRecords
}
public func validate(name: String) throws {
try validate(self.productCode, name: "productCode", parent: name, max: 255)
try validate(self.productCode, name: "productCode", parent: name, min: 1)
try self.usageRecords.forEach {
try $0.validate(name: "\(name).usageRecords[]")
}
try validate(self.usageRecords, name: "usageRecords", parent: name, max: 25)
try validate(self.usageRecords, name: "usageRecords", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case productCode = "ProductCode"
case usageRecords = "UsageRecords"
}
}
public struct BatchMeterUsageResult: AWSDecodableShape {
/// Contains all UsageRecords processed by BatchMeterUsage. These records were either honored by AWS Marketplace Metering Service or were invalid.
public let results: [UsageRecordResult]?
/// Contains all UsageRecords that were not processed by BatchMeterUsage. This is a list of UsageRecords. You can retry the failed request by making another BatchMeterUsage call with this list as input in the BatchMeterUsageRequest.
public let unprocessedRecords: [UsageRecord]?
public init(results: [UsageRecordResult]? = nil, unprocessedRecords: [UsageRecord]? = nil) {
self.results = results
self.unprocessedRecords = unprocessedRecords
}
private enum CodingKeys: String, CodingKey {
case results = "Results"
case unprocessedRecords = "UnprocessedRecords"
}
}
public struct MeterUsageRequest: AWSEncodableShape {
/// Checks whether you have the permissions required for the action, but does not make the request. If you have the permissions, the request returns DryRunOperation; otherwise, it returns UnauthorizedException. Defaults to false if not specified.
public let dryRun: Bool?
/// Product code is used to uniquely identify a product in AWS Marketplace. The product code should be the same as the one used during the publishing of a new product.
public let productCode: String
/// Timestamp, in UTC, for which the usage is being reported. Your application can meter usage for up to one hour in the past. Make sure the timestamp value is not before the start of the software usage.
public let timestamp: TimeStamp
/// It will be one of the fcp dimension name provided during the publishing of the product.
public let usageDimension: String
/// Consumption value for the hour. Defaults to 0 if not specified.
public let usageQuantity: Int?
public init(dryRun: Bool? = nil, productCode: String, timestamp: TimeStamp, usageDimension: String, usageQuantity: Int? = nil) {
self.dryRun = dryRun
self.productCode = productCode
self.timestamp = timestamp
self.usageDimension = usageDimension
self.usageQuantity = usageQuantity
}
public func validate(name: String) throws {
try validate(self.productCode, name: "productCode", parent: name, max: 255)
try validate(self.productCode, name: "productCode", parent: name, min: 1)
try validate(self.usageDimension, name: "usageDimension", parent: name, max: 255)
try validate(self.usageDimension, name: "usageDimension", parent: name, min: 1)
try validate(self.usageQuantity, name: "usageQuantity", parent: name, max: 2147483647)
try validate(self.usageQuantity, name: "usageQuantity", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case dryRun = "DryRun"
case productCode = "ProductCode"
case timestamp = "Timestamp"
case usageDimension = "UsageDimension"
case usageQuantity = "UsageQuantity"
}
}
public struct MeterUsageResult: AWSDecodableShape {
/// Metering record id.
public let meteringRecordId: String?
public init(meteringRecordId: String? = nil) {
self.meteringRecordId = meteringRecordId
}
private enum CodingKeys: String, CodingKey {
case meteringRecordId = "MeteringRecordId"
}
}
public struct RegisterUsageRequest: AWSEncodableShape {
/// (Optional) To scope down the registration to a specific running software instance and guard against replay attacks.
public let nonce: String?
/// Product code is used to uniquely identify a product in AWS Marketplace. The product code should be the same as the one used during the publishing of a new product.
public let productCode: String
/// Public Key Version provided by AWS Marketplace
public let publicKeyVersion: Int
public init(nonce: String? = nil, productCode: String, publicKeyVersion: Int) {
self.nonce = nonce
self.productCode = productCode
self.publicKeyVersion = publicKeyVersion
}
public func validate(name: String) throws {
try validate(self.nonce, name: "nonce", parent: name, max: 255)
try validate(self.productCode, name: "productCode", parent: name, max: 255)
try validate(self.productCode, name: "productCode", parent: name, min: 1)
try validate(self.publicKeyVersion, name: "publicKeyVersion", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case nonce = "Nonce"
case productCode = "ProductCode"
case publicKeyVersion = "PublicKeyVersion"
}
}
public struct RegisterUsageResult: AWSDecodableShape {
/// (Optional) Only included when public key version has expired
public let publicKeyRotationTimestamp: TimeStamp?
/// JWT Token
public let signature: String?
public init(publicKeyRotationTimestamp: TimeStamp? = nil, signature: String? = nil) {
self.publicKeyRotationTimestamp = publicKeyRotationTimestamp
self.signature = signature
}
private enum CodingKeys: String, CodingKey {
case publicKeyRotationTimestamp = "PublicKeyRotationTimestamp"
case signature = "Signature"
}
}
public struct ResolveCustomerRequest: AWSEncodableShape {
/// When a buyer visits your website during the registration process, the buyer submits a registration token through the browser. The registration token is resolved to obtain a CustomerIdentifier and product code.
public let registrationToken: String
public init(registrationToken: String) {
self.registrationToken = registrationToken
}
public func validate(name: String) throws {
try validate(self.registrationToken, name: "registrationToken", parent: name, pattern: "\\S+")
}
private enum CodingKeys: String, CodingKey {
case registrationToken = "RegistrationToken"
}
}
public struct ResolveCustomerResult: AWSDecodableShape {
/// The CustomerIdentifier is used to identify an individual customer in your application. Calls to BatchMeterUsage require CustomerIdentifiers for each UsageRecord.
public let customerIdentifier: String?
/// The product code is returned to confirm that the buyer is registering for your product. Subsequent BatchMeterUsage calls should be made using this product code.
public let productCode: String?
public init(customerIdentifier: String? = nil, productCode: String? = nil) {
self.customerIdentifier = customerIdentifier
self.productCode = productCode
}
private enum CodingKeys: String, CodingKey {
case customerIdentifier = "CustomerIdentifier"
case productCode = "ProductCode"
}
}
public struct UsageRecord: AWSEncodableShape & AWSDecodableShape {
/// The CustomerIdentifier is obtained through the ResolveCustomer operation and represents an individual buyer in your application.
public let customerIdentifier: String
/// During the process of registering a product on AWS Marketplace, up to eight dimensions are specified. These represent different units of value in your application.
public let dimension: String
/// The quantity of usage consumed by the customer for the given dimension and time. Defaults to 0 if not specified.
public let quantity: Int?
/// Timestamp, in UTC, for which the usage is being reported. Your application can meter usage for up to one hour in the past. Make sure the timestamp value is not before the start of the software usage.
public let timestamp: TimeStamp
public init(customerIdentifier: String, dimension: String, quantity: Int? = nil, timestamp: TimeStamp) {
self.customerIdentifier = customerIdentifier
self.dimension = dimension
self.quantity = quantity
self.timestamp = timestamp
}
public func validate(name: String) throws {
try validate(self.customerIdentifier, name: "customerIdentifier", parent: name, max: 255)
try validate(self.customerIdentifier, name: "customerIdentifier", parent: name, min: 1)
try validate(self.dimension, name: "dimension", parent: name, max: 255)
try validate(self.dimension, name: "dimension", parent: name, min: 1)
try validate(self.quantity, name: "quantity", parent: name, max: 2147483647)
try validate(self.quantity, name: "quantity", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case customerIdentifier = "CustomerIdentifier"
case dimension = "Dimension"
case quantity = "Quantity"
case timestamp = "Timestamp"
}
}
public struct UsageRecordResult: AWSDecodableShape {
/// The MeteringRecordId is a unique identifier for this metering event.
public let meteringRecordId: String?
/// The UsageRecordResult Status indicates the status of an individual UsageRecord processed by BatchMeterUsage. Success- The UsageRecord was accepted and honored by BatchMeterUsage. CustomerNotSubscribed- The CustomerIdentifier specified is not subscribed to your product. The UsageRecord was not honored. Future UsageRecords for this customer will fail until the customer subscribes to your product. DuplicateRecord- Indicates that the UsageRecord was invalid and not honored. A previously metered UsageRecord had the same customer, dimension, and time, but a different quantity.
public let status: UsageRecordResultStatus?
/// The UsageRecord that was part of the BatchMeterUsage request.
public let usageRecord: UsageRecord?
public init(meteringRecordId: String? = nil, status: UsageRecordResultStatus? = nil, usageRecord: UsageRecord? = nil) {
self.meteringRecordId = meteringRecordId
self.status = status
self.usageRecord = usageRecord
}
private enum CodingKeys: String, CodingKey {
case meteringRecordId = "MeteringRecordId"
case status = "Status"
case usageRecord = "UsageRecord"
}
}
}
| 48.380074 | 600 | 0.670963 |
912d7caf903679c6a1dd472abc1bc2386a0d6e84 | 436 | //
// UserDefaultsManager.swift
// NaADae
//
// Created by Lee on 2020/06/20.
// Copyright © 2020 Kira. All rights reserved.
//
import Foundation
class UserDefaultsManager {
enum Key: String, CaseIterable {
case nickname
}
static var nickname: String? {
get { UserDefaults.standard.string(forKey: Key.nickname.rawValue) }
set { UserDefaults.standard.set(newValue, forKey: Key.nickname.rawValue) }
}
}
| 18.956522 | 78 | 0.68578 |
4a670b15ec40d01bafda40bcc0f9c6b768a8adfc | 2,412 | // Copyright SIX DAY LLC. All rights reserved.
import Foundation
import UIKit
import StatefulViewController
class TransactionsEmptyView: UIView {
private let titleLabel = UILabel()
private let imageView = UIImageView()
private let button = Button(size: .normal, style: .solid)
private let insets: UIEdgeInsets
private var onRetry: (() -> Void)? = .none
private let viewModel = StateViewModel()
init(
title: String = R.string.localizable.transactionsNoTransactionsLabelTitle(),
image: UIImage? = R.image.no_transactions_vlx(),
insets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0),
onRetry: (() -> Void)? = .none
) {
self.insets = insets
self.onRetry = onRetry
super.init(frame: .zero)
backgroundColor = .white
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.text = title
titleLabel.font = viewModel.descriptionFont
titleLabel.textColor = viewModel.descriptionTextColor
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = image
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(R.string.localizable.refresh(), for: .normal)
button.addTarget(self, action: #selector(retry), for: .touchUpInside)
let stackView = [
imageView,
titleLabel,
].asStackView(axis: .vertical, spacing: 30, alignment: .center)
stackView.translatesAutoresizingMaskIntoConstraints = false
if onRetry != nil {
stackView.addArrangedSubview(button)
}
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: centerYAnchor),
button.widthAnchor.constraint(equalToConstant: 180),
])
}
@objc func retry() {
onRetry?()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TransactionsEmptyView: StatefulPlaceholderView {
func placeholderViewInsets() -> UIEdgeInsets {
return insets
}
}
| 32.594595 | 84 | 0.66874 |
ac7afc98350dee97d31f326d796101279a45ce35 | 4,894 | //
// GameScene.swift
//
// Created by MARK BROWNSWORD on 24/7/16.
// Copyright © 2016 MARK BROWNSWORD. All rights reserved.
//
import SpriteKit
import GameplayKit
class LandingScene: GameSceneBase, TileMapScene {
// MARK: Public Properties
var entities = [GKEntity]()
var graphs = [String : GKGraph]()
var backgroundLayer: SKTileMapNode!
var gridLayer: SKTileMapNode!
var selectionLayer: SKTileMapNode!
var currentSelectionlocation: CGPoint?
var gameCamera: SKCameraNode! {
return self.camera
}
var gameScene: SKScene! {
return self
}
var gameScaleMode: SKSceneScaleMode! {
get {
return self.scaleMode
}
set {
self.scaleMode = newValue
}
}
private var lastUpdateTime : TimeInterval = 0
// MARK: Override Functions
override func sceneDidLoad() {
self.lastUpdateTime = 0
}
override func didMove(to view: SKView) {
guard let backgroundLayer = childNode(withName: "background") as? SKTileMapNode else {
fatalError("Background node not loaded")
}
guard let gridLayer = childNode(withName: "grid") as? SKTileMapNode else {
fatalError("Grid node not loaded")
}
guard let selectionLayer = childNode(withName: "selection") as? SKTileMapNode else {
fatalError("Selection node not loaded")
}
guard let camera = self.childNode(withName: "gameCamera") as? SKCameraNode else {
fatalError("Camera node not loaded")
}
self.backgroundLayer = backgroundLayer
self.gridLayer = gridLayer
self.selectionLayer = selectionLayer
self.camera = camera
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePanFrom(recognizer:)))
panGestureRecognizer.maximumNumberOfTouches = 1
view.addGestureRecognizer(panGestureRecognizer)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleTapFrom(recognizer:)))
tapGestureRecognizer.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGestureRecognizer)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongPressFrom(recognizer:)))
longPressRecognizer.minimumPressDuration = 1
view.addGestureRecognizer(longPressRecognizer)
// Add the grid tile to GridLayer
self.floodFillGrid()
}
override func update(_ currentTime: TimeInterval) {
// Initialize _lastUpdateTime if it has not already been
if (self.lastUpdateTime == 0) {
self.lastUpdateTime = currentTime
}
// Calculate time since last update
let dt = currentTime - self.lastUpdateTime
// Update entities
for entity in self.entities {
entity.update(deltaTime: dt)
}
self.lastUpdateTime = currentTime
}
// MARK: GestureRecognizer functions
@objc
func handlePanFrom(recognizer: UIPanGestureRecognizer) {
if recognizer.state != .changed {
return
}
// Get touch delta
let translation = recognizer.translation(in: recognizer.view!)
// Move camera
self.camera?.position.x -= translation.x
self.camera?.position.y += translation.y
// Reset
recognizer.setTranslation(CGPoint.zero, in: recognizer.view)
}
@objc
func handleTapFrom(recognizer: UITapGestureRecognizer) {
if recognizer.state != .ended {
return
}
let location = recognizer.location(in: recognizer.view!)
let targetLocation = self.convertPoint(fromView: location)
// Don't allow selection of obstacle tiles
if self.isObstacleAt(targetLocation: targetLocation) {
return
}
// Show the selection tile at the current location
// Update the currently selected location
self.currentSelectionlocation = self.setSelectionTileAt(targetLocation: targetLocation)
}
@objc
func handleLongPressFrom(recognizer: UILongPressGestureRecognizer) {
if recognizer.state != .began {
return
}
// Toggle visibility of gridLayer
self.gridLayer.isHidden = !self.gridLayer.isHidden
}
// MARK: Private functions
private func isObstacleAt(targetLocation: CGPoint) -> Bool {
let isObstacle = self.backgroundLayer.getUserData(forKey: "isObstacle", location: targetLocation) as? Int
return isObstacle == 1
}
}
| 30.02454 | 134 | 0.620964 |
645898348c878a59d953a5c183523a7e664a66ad | 2,988 | //
// SNSTests.swift
// written by Adam Fowler
// SNS tests
//
import XCTest
import Foundation
@testable import AWSSNS
enum SNSTestsError : Error {
case noTopicArn
}
// testing query service
class SNSTests: XCTestCase {
let client = SNS(
accessKeyId: "key",
secretAccessKey: "secret",
region: .useast1,
endpoint: ProcessInfo.processInfo.environment["SNS_ENDPOINT"] ?? "http://localhost:4575"
)
class TestData {
var client: SNS
var topicName: String
var topicArn: String
init(_ testName: String, client: SNS) throws {
let testName = testName.lowercased().filter { return $0.isLetter }
self.client = client
self.topicName = "\(testName)-topic"
let request = SNS.CreateTopicInput(name: topicName)
let response = try client.createTopic(request).wait()
guard let topicArn = response.topicArn else {throw SNSTestsError.noTopicArn}
self.topicArn = topicArn
}
deinit {
attempt {
// disabled until we get valid topic arn's returned from Localstack
#if false
let request = SNS.DeleteTopicInput(topicArn: self.topicArn)
_ = try client.deleteTopic(request).wait()
#endif
}
}
}
//MARK: TESTS
func testCreateDelete() {
attempt {
_ = try TestData(#function, client: client)
}
}
func testListTopics() {
attempt {
let testData = try TestData(#function, client: client)
let request = SNS.ListTopicsInput()
let response = try client.listTopics(request).wait()
let topic = response.topics?.first {$0.topicArn == testData.topicArn }
XCTAssertNotNil(topic)
}
}
// disabled until we get valid topic arn's returned from Localstack
#if false
func testSetTopicAttributes() {
attempt {
let testData = try TestData(#function, client: client)
let setTopicAttributesInput = SNS.SetTopicAttributesInput(attributeName:"DisplayName", attributeValue: "aws-test topic", topicArn: testData.topicArn)
try client.setTopicAttributes(setTopicAttributesInput).wait()
let getTopicAttributesInput = SNS.GetTopicAttributesInput(topicArn: testData.topicArn)
let getTopicAttributesResponse = try client.getTopicAttributes(getTopicAttributesInput).wait()
XCTAssertEqual(getTopicAttributesResponse.attributes?["DisplayName"], "aws-test topic")
}
}
#endif
static var allTests : [(String, (SNSTests) -> () throws -> Void)] {
return [
("testCreateDelete", testCreateDelete),
("testListTopics", testListTopics),
// ("testSetTopicAttributes", testSetTopicAttributes),
]
}
}
| 30.181818 | 161 | 0.599063 |
207fe64977145087f13d81447cc622585e7981c0 | 1,502 | //
// UIButton++.swift
// SayTheirNames
//
// Copyright (c) 2020 Say Their Names Team (https://github.com/Say-Their-Name)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Custom tap gesture that accepts a return value
class STNTapGestureRecognizer: UITapGestureRecognizer {
var value: String?
}
extension UIButton {
convenience init(image: UIImage?) {
self.init(frame: .zero)
setImage(image, for: .normal)
}
}
| 40.594595 | 81 | 0.736352 |
9c7ab537c5063d5da9524abeab32ee900e49aac2 | 899 | //
// BasicInfoSectionFactory.swift
// RIBsReactorKit
//
// Created by Elon on 2020/10/04.
// Copyright © 2020 Elon. All rights reserved.
//
import Foundation
import UIKit.UIImage
struct BasicInfoSectionFactory: UserInfoSectionFactory {
let factories: [UserInfoSectionItemFactory] = [
GenderSctionItemFactory(),
BirthdaySctionItemFactory(),
AgeSctionItemFactory()
]
func makeSection(from userModel: UserModel) -> UserInfoSectionModel {
let headerViewModel: UserInfoSectionHeaderViewModel = UserInfoSectionHeaderViewModelImpl(
title: Strings.UserInfoTitle.basicInfo
)
let items = factories.enumerated().map {
$0.element.makeSectionItem(from: userModel, isLastItem: $0.offset == factories.endIndex)
}
let section = UserInfoSectionModel(
header: headerViewModel,
hasFooter: true,
items: items
)
return section
}
}
| 24.297297 | 94 | 0.723026 |
5dddc5c30dd19f2b4e35492572db537242cc8107 | 649 | //
// AnimalBehaviors.swift
// Generics
//
// Created by Hesham Salman on 1/30/17.
// Copyright © 2017 View The Space. All rights reserved.
//
import Foundation
public protocol Slitherable { }
public protocol Flyable { }
public protocol Swimmable { }
public protocol WaterBreathable: Swimmable { }
public protocol Carnivorous { }
public protocol Herbivorous { }
public protocol Omnivorous { }
extension Carnivorous where Self: Animal {
public func eat(food: Meat) { }
}
extension Omnivorous where Self: Animal {
public func eat(food: AnyFood) { }
}
extension Herbivorous where Self: Animal {
public func eat(food: Grass) { }
}
| 20.935484 | 57 | 0.718028 |
Subsets and Splits