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
|
---|---|---|---|---|---|
036f16db801e83db5e67700caa3e2da805cd3ad1 | 516 | // REQUIRES: objc_interop
// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -F %S/mock-sdk -api-diff-data-file %S/Inputs/API.json -emit-migrated-file-path %t/member.swift.result -emit-remap-file-path %t/member.swift.remap -o /dev/null
// RUN: diff -u %S/member.swift.expected %t/member.swift.result
import Bar
func foo(_ b: BarForwardDeclaredClass, _ s: SomeItemSet) -> Int32 {
let _ = s.theSimpleOldName
let _ = s.theSimpleOldNameNotToRename
return barGlobalVariable
}
| 43 | 246 | 0.734496 |
bfd664324741a48e6400220627f10d898f820014 | 814 | //
// SHMediaSATChannel.swift
// Smart-Bus
//
// Created by Mark Liu on 2017/11/7.
// Copyright © 2018 SmartHome. All rights reserved.
//
import UIKit
@objcMembers class SHMediaSATChannel: NSObject {
/// 分类ID
var categoryID: UInt = 0
/// 通道ID
var channelID: UInt = 0
/// 通道编号(与通道ID相同)
var channelNo: UInt = 0
/// 通道名称
var channelName: String?
/// 通道图片名称
var iconName: String?
/// 场景号
var sequenceNo: UInt = 0
/// 区域号(没有什么用,保留旧版本的代码)
var zoneID: UInt = 0
override init() {
super.init()
}
init(dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| 16.28 | 72 | 0.534398 |
03f7202312f1ec6ac9be4c4829b45d6576ed9008 | 3,164 | //
// DuplicationDetector.swift
// SwiftConstCore
//
// Created by Yusuke Kita on 03/03/19.
//
import Foundation
import SwiftSyntax
public struct DuplicationDetector {
let paths: [String]
let minimumLength: Int
let duplicationThreshold: Int
let ignoreHidden: Bool
let ignoreTest: Bool
let ignorePaths: [String]
let ignorePatterns: [String]
public init(
paths: [String],
minimumLength: Int,
duplicationThreshold: Int,
ignoreHidden: Bool,
ignoreTest: Bool,
ignorePaths: [String],
ignorePatterns: [String]
) {
self.paths = paths
self.minimumLength = minimumLength
self.duplicationThreshold = duplicationThreshold
self.ignoreHidden = ignoreHidden
self.ignoreTest = ignoreTest
self.ignorePaths = ignorePaths
self.ignorePatterns = ignorePatterns
}
public func detect() throws -> [SwiftConstString] {
let sourceFilePathIterator = SourceFilePathIterator(
paths: paths,
ignoreHidden: ignoreHidden,
ignoreTest: ignoreTest,
ignorePaths: ignorePaths
)
return try sourceFilePathIterator
.flatMap { filePath -> [SwiftConstString] in
let parser = SourceFileParser(filePath: filePath)
let syntax = try parser.parse()
let dataStore = DataStore()
var visitor = StringVisitor(
filePath: filePath,
minimumLength: minimumLength,
ignorePatterns: ignorePatterns,
syntax: syntax,
dataStore: dataStore
)
syntax.walk(&visitor)
return dataStore.strings
}
.filteredDuplicatedStrings(with: duplicationThreshold)
}
}
extension Array where Element == SwiftConstString {
fileprivate func filteredDuplicatedStrings(with threshold: Int) -> [Element] {
let sortedStrings = self.sorted(by: { $0.value < $1.value })
var previousString = ""
var duplicatedStrings: [Element] = []
for string in sortedStrings {
// if there is already same string in duplicatedStrings, append it immidiately
guard !duplicatedStrings.contains(where: { $0.value == string.value }) else {
duplicatedStrings.append(string)
continue
}
// if there is no same string in the array, but same string from previous one,
// that means duplication count was less than threshold, so let's skip
guard string.value != previousString else {
continue
}
// check if duplication count is eaqual or greater than threshold
let duplicationCount = sortedStrings.filter { $0.value == string.value }.count
if duplicationCount >= threshold {
duplicatedStrings.append(string)
}
previousString = string.value
}
return duplicatedStrings
}
}
| 32.618557 | 90 | 0.586599 |
7afe0f72b44a885bfdeba430d796aa3c38e54b35 | 610 | /*
Setting.swift
This source file is part of the Workspace open source project.
Diese Quelldatei ist Teil des quelloffenen Arbeitsbereich‐Projekt.
https://github.com/SDGGiesbrecht/Workspace#workspace
Copyright ©2020–2021 Jeremy David Giesbrecht and the Workspace project contributors.
Urheberrecht ©2020–2021 Jeremy David Giesbrecht und die Mitwirkenden des Arbeitsbereich‐Projekts.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
internal enum Setting {
case library
case topLevel
case unknown
}
| 27.727273 | 98 | 0.791803 |
9ba88e65af63ecbaa5fc820929a1cdd8559013ab | 5,281 | // YoutubeWithLabelExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// 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 XLPagerTabStrip
class YoutubeWithLabelExampleViewController: BaseButtonBarPagerTabStripViewController<YoutubeIconWithLabelCell> {
let redColor = UIColor(red: 221/255.0, green: 0/255.0, blue: 19/255.0, alpha: 1.0)
let unselectedIconColor = UIColor(red: 73/255.0, green: 8/255.0, blue: 10/255.0, alpha: 1.0)
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
buttonBarItemSpec = ButtonBarItemSpec.nibFile(nibName: "YoutubeIconWithLabelCell", bundle: Bundle(for: YoutubeIconWithLabelCell.self), width: { _ in
return 70.0
})
}
override func viewDidLoad() {
// change selected bar color
settings.style.buttonBarBackgroundColor = redColor
settings.style.buttonBarItemBackgroundColor = .clear
settings.style.selectedBarBackgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1.0)
settings.style.selectedBarHeight = 4.0
settings.style.buttonBarMinimumLineSpacing = 0
settings.style.buttonBarItemTitleColor = .black
settings.style.buttonBarItemsShouldFillAvailableWidth = true
settings.style.buttonBarLeftContentInset = 0
settings.style.buttonBarRightContentInset = 0
changeCurrentIndexProgressive = { [weak self] (oldCell: YoutubeIconWithLabelCell?, newCell: YoutubeIconWithLabelCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
guard changeCurrentIndex == true else { return }
oldCell?.iconImage.tintColor = self?.unselectedIconColor
oldCell?.iconLabel.textColor = self?.unselectedIconColor
newCell?.iconImage.tintColor = .white
newCell?.iconLabel.textColor = .white
}
super.viewDidLoad()
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let child_1 = TableChildExampleViewController(style: .plain, itemInfo: IndicatorInfo(title: " HOME", image: UIImage(named: "home")))
let child_2 = TableChildExampleViewController(style: .plain, itemInfo: IndicatorInfo(title: " TRENDING", image: UIImage(named: "trending")))
let child_3 = ChildExampleViewController(itemInfo: IndicatorInfo(title: " ACCOUNT", image: UIImage(named: "profile")))
return [child_1, child_2, child_3]
}
override func configure(cell: YoutubeIconWithLabelCell, for indicatorInfo: IndicatorInfo) {
cell.iconImage.image = indicatorInfo.image?.withRenderingMode(.alwaysTemplate)
cell.iconLabel.text = indicatorInfo.title?.trimmingCharacters(in: .whitespacesAndNewlines)
}
override func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
super.updateIndicator(for: viewController, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: progressPercentage, indexWasChanged: indexWasChanged)
if indexWasChanged && toIndex > -1 && toIndex < viewControllers.count {
let child = viewControllers[toIndex] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
UIView.performWithoutAnimation({ [weak self] () -> Void in
guard let me = self else { return }
me.navigationItem.leftBarButtonItem?.title = child.indicatorInfo(for: me, state: pagerTabStates[toIndex]).title
})
}
}
// MARK: - Actions
@IBAction func closeAction(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| 52.81 | 208 | 0.72562 |
edeb5d6fdc3abadc12c6c400968cb7900a2e4d13 | 3,548 | //
// PaymentMethodSelectionHeaderCollectionReusableView.swift
// StashCore
//
// Created by Robert on 21.03.19.
// Copyright © 2019 MobiLab Solutions GmbH. All rights reserved.
//
import UIKit
class PaymentMethodSelectionHeaderCollectionReusableView: UICollectionReusableView {
private static let titleFontSize: CGFloat = 24
private static let subtitleFontSize: CGFloat = 14
private let subtitleLabelBottomOffset: CGFloat = 46
private let subtitleLabelHorizontalOffset: CGFloat = 16
private let titleSubtitleVerticalDistance: CGFloat = 8
private let bottomInset: CGFloat = 14
private let subtitleAlpha: CGFloat = 0.79
private let titleLabel: UILabel = {
let label = UILabel()
label.font = UIConstants.defaultFont(of: PaymentMethodSelectionHeaderCollectionReusableView.titleFontSize, type: .regular)
label.textColor = .white
label.attributedText = NSAttributedString(string: "Payment Method", attributes: [.kern: 1.9])
return label
}()
private let subtitleLabel: UILabel = {
let label = UILabel()
label.font = UIConstants.defaultFont(of: PaymentMethodSelectionHeaderCollectionReusableView.subtitleFontSize, type: .regular)
label.textColor = .white
label.text = "Choose a payment method"
return label
}()
private let backgroundImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleToFill
imageView.image = UIConstants.paymentSelectionIllustrationImage
return imageView
}()
var configuration: PaymentMethodUIConfiguration? {
didSet {
self.titleLabel.textColor = configuration?.lightTextColor ?? self.titleLabel.textColor
self.subtitleLabel.textColor = configuration?.lightTextColor.withAlphaComponent(subtitleAlpha) ?? self.subtitleLabel.textColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.sharedInit()
}
private func sharedInit() {
self.backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
self.titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(self.backgroundImageView)
addSubview(self.titleLabel)
addSubview(self.subtitleLabel)
NSLayoutConstraint.activate([
subtitleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -subtitleLabelBottomOffset),
subtitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: subtitleLabelHorizontalOffset),
subtitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -subtitleLabelHorizontalOffset),
titleLabel.leadingAnchor.constraint(equalTo: subtitleLabel.leadingAnchor),
titleLabel.trailingAnchor.constraint(equalTo: subtitleLabel.trailingAnchor),
titleLabel.bottomAnchor.constraint(equalTo: subtitleLabel.topAnchor, constant: -titleSubtitleVerticalDistance),
backgroundImageView.topAnchor.constraint(equalTo: topAnchor),
backgroundImageView.leftAnchor.constraint(equalTo: leftAnchor),
backgroundImageView.rightAnchor.constraint(equalTo: rightAnchor),
backgroundImageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -bottomInset),
])
}
}
| 42.746988 | 138 | 0.725479 |
e2063f4e87fb91f48db66229ce19ccd238411811 | 3,088 | //
// Callback.swift
// Milkshake
//
// Created by Dean Liu on 1/12/18.
// Copyright © 2018 Dean Liu. All rights reserved.
//
// Callback from API requests to create array of MusicItems
// Resultant array of MusicItems is then used to create ResultsViewController
//
import Cocoa
class Callback: NSObject {
static func callbackArtist(results: [String: AnyObject]) -> [MusicItem] {
var items: [MusicItem] = []
let artistLatestRelease = Util.artistLatestRelease(catalog: results)
let artistTopTracks = Util.artistTopTracks(catalog: results)
let artistAlbumsRelease = Util.artistAlbumsRelease(catalog: results)
let artistSimilarArtists = Util.artistSimilarArtists(catalog: results)
let artistDetailsItem = Util.artistDetails(catalog: results)
artistDetailsItem.isHeader = true
// Set the artist name based on top track. If blank, set based on album
artistDetailsItem.name = artistTopTracks.count > 0 ? artistTopTracks[0].artistName : nil
if (artistAlbumsRelease.count > 0 && artistDetailsItem.name == nil) {
artistDetailsItem.name = artistAlbumsRelease[0].artistName
}
let artistKey = Util.artistKey(catalog: results)
artistDetailsItem.pandoraId = results[artistKey]!["pandoraId"] as? String
artistDetailsItem.artistId = artistDetailsItem.pandoraId
items.append(artistDetailsItem)
let latestHeader = MusicItem()
latestHeader.name = "LATEST RELEASE"
latestHeader.isHeader = true
items.append(latestHeader)
items = items + artistLatestRelease
let topHeader = MusicItem()
topHeader.name = "TOP SONGS"
topHeader.isHeader = true
items.append(topHeader)
items = items + artistTopTracks
let albumHeader = MusicItem()
albumHeader.name = "ALBUMS"
albumHeader.isHeader = true
items.append(albumHeader)
items = items + artistAlbumsRelease
let artistsHeader = MusicItem()
artistsHeader.name = "SIMILAR ARTISTS"
artistsHeader.isHeader = true
items.append(artistsHeader)
items = items + artistSimilarArtists
return items
}
static func callbackStationsList(results: [String: AnyObject]) -> [MusicItem] {
var stationResults = Util.parseStationSearchIntoItems(stationResult: results)
let stationsHeader = MusicItem()
stationsHeader.name = "STATIONS"
stationsHeader.isHeader = true
stationResults.insert(stationsHeader, at: 0)
return stationResults
}
static func callbackPlaylistList(results: [String: AnyObject]) -> [MusicItem] {
var playlistResults = Util.parsePlaylistSearchIntoItems(playlistSearchResult: results)
let playlistHeader = MusicItem()
playlistHeader.name = "PLAYLISTS"
playlistHeader.isHeader = true
playlistResults.insert(playlistHeader, at: 0)
return playlistResults
}
}
| 37.658537 | 96 | 0.664832 |
e8203d06392c6fbd2b9ee5dbf226edba8371baac | 3,823 | //
// DebuggingExtensions.swift
// BNRunCore
//
// Created by hsoi on 9/7/17.
// Copyright © 2017 Big Nerd Ranch, LLC. All rights reserved.
//
import Foundation
import Intents
import IntentsUI
extension INInteraction {
public func dump() {
print("\n** INInteraction dump start:")
print("interaction.intent: \(String(describing:intent))")
var responseString = "none"
if let response = intentResponse {
responseString = String(describing:response)
}
print("interaction.intentResponse: \(responseString))")
print("interaction.intentHandlingStatus: \(String(describing:intentHandlingStatus))")
print("interaction.direction: \(String(describing:direction))")
print("** INInteraction dump end\n")
}
}
extension INIntentHandlingStatus: CustomStringConvertible {
public var description: String {
switch self {
case .unspecified:
return "unspecified"
case .ready:
return "ready"
case .inProgress:
return "in progress"
case .success:
return "success"
case .failure:
return "failure"
case .deferredToApplication:
return "deferred to application"
}
}
}
extension INInteractionDirection: CustomStringConvertible {
public var description: String {
switch self {
case .unspecified:
return "unspecified"
case .outgoing:
return "outgoing"
case .incoming:
return "incoming"
}
}
}
extension INStartWorkoutIntentResponseCode: CustomStringConvertible {
public var description: String {
switch self {
case .continueInApp:
return "continue in app"
case .failure:
return "failure"
case .failureNoMatchingWorkout:
return "failure, no matching workout"
case .failureOngoingWorkout:
return "failure, ongoing workout"
case .failureRequiringAppLaunch:
return "failure, requiring app launch"
case .handleInApp:
return "handle in app"
case .ready:
return "ready"
case .success:
return "success"
case .unspecified:
return "unspecified"
}
}
}
extension INEndWorkoutIntentResponseCode: CustomStringConvertible {
public var description: String {
switch self {
case .continueInApp:
return "continue in app"
case .failure:
return "failure"
case .failureNoMatchingWorkout:
return "failure, no matching workout"
case .failureRequiringAppLaunch:
return "failure, requiring app launch"
case .handleInApp:
return "handle in app"
case .ready:
return "ready"
case .success:
return "success"
case .unspecified:
return "unspecified"
}
}
}
@available(iOS 11.0, *)
extension INParameter {
public func dump() {
print(String(describing: self))
}
}
@available(iOS 11.0, *)
extension Set where Element == INParameter {
public func dump() {
print("\n** Set<INParameter> dump start:")
print("parameters count: \(count)")
forEach { print(String(describing: $0)) }
print("** Set<INParameter> dump end\n")
}
}
@available(iOS 11.0, *)
extension INUIInteractiveBehavior: CustomStringConvertible {
public var description: String {
switch self {
case .genericAction:
return "generic action"
case .launch:
return "launch"
case .nextView:
return "next view"
case .none:
return "none"
}
}
}
| 24.664516 | 93 | 0.588805 |
d9fb9db4eb053249f1d2ec6eb12272e5fbc560a6 | 180 | //
// NetworkingLogLevel.swift
//
//
// Created by Sacha DSO on 30/01/2020.
//
import Foundation
public enum NetworkingLogLevel {
case off
case info
case debug
}
| 12 | 39 | 0.655556 |
4b7c4268cf71c9752866a6b4113a62e7802b8bfc | 766 | //
// KikurageStateHelper.swift
// Kikurage
//
// Created by Shusuke Ota on 2020/10/22.
// Copyright © 2020 shusuke. All rights reserved.
//
import UIKit
struct KikurageStateHelper {
private init() {}
/// きくらげの状態によって表情を変える
/// - Parameter type: きくらげの状態(Firestoreより取得する文字列)
static func setStateImage(type: KikurageStateType) -> [UIImage] {
var kikurageStateImages: [UIImage] = []
let beforeImage = UIImage(named: "\(type.rawValue)_01")! // swiftlint:disable:this force_unwrapping
let afterImage = UIImage(named: "\(type.rawValue)_02")! // swiftlint:disable:this force_unwrapping
kikurageStateImages.append(beforeImage)
kikurageStateImages.append(afterImage)
return kikurageStateImages
}
}
| 28.37037 | 107 | 0.690601 |
1dd92da23157f2ad0e5c8f0baf45477da7280e47 | 4,930 | //import Result
//import ReactiveSwift
//
///// Used to represent the ReactorFlow. A typical flow consists of loading from persistence,
///// making a network request and finally saving it to persistence. All three flows are
///// public on purpose, so they can be manually replaced or extended.
/////
///// At very least a `NetworkFlow` must be provided, at initialization.
//public struct ReactorFlow<T> {
//
// public typealias NetworkFlow = (Resource) -> SignalProducer<T, ReactorError>
// public typealias LoadFromPersistenceFlow = () -> SignalProducer<T, ReactorError>
// public typealias SaveToPersistenceFlow = (T) -> SignalProducer<T, ReactorError>
//
// public var networkFlow: NetworkFlow
// public var loadFromPersistenceFlow: LoadFromPersistenceFlow
// public var saveToPersistenceFlow: SaveToPersistenceFlow
//
// /// If `loadFromPersistenceFlow` is not passed, the `Reactor` will bailout and hit the network
// /// If `saveToPersistenceFlow` is not passed, the `Reactor` will persist anything
// init(networkFlow: @escaping NetworkFlow, loadFromPersistenceFlow: @escaping LoadFromPersistenceFlow = {SignalProducer(error: .persistence("Persistence bailout"))}, saveToPersistenceFlow: @escaping SaveToPersistenceFlow = SignalProducer.identity) {
//
// self.networkFlow = networkFlow
// self.loadFromPersistenceFlow = loadFromPersistenceFlow
// self.saveToPersistenceFlow = saveToPersistenceFlow
// }
//}
//
///// Used as a factory to create a `ReactorFlow` for a single `T: Mappable`
//public func createFlow<T>(_ connection: Connection, configuration: FlowConfigurable = FlowConfiguration(persistenceConfiguration: .disabled)) -> ReactorFlow<T> where T: Mappable {
//
// let parser: (Data) -> SignalProducer<T, ReactorError> = parse
// let networkFlow: (Resource) -> SignalProducer<T, ReactorError> = { resource in connection.makeRequest(resource).map { $0.0}.flatMapLatest(parser) }
//
// switch configuration.persistenceConfiguration {
// case .disabled:
// return ReactorFlow(networkFlow: networkFlow)
//
// case .enabled(let persistencePath):
// let persistenceHandler = InDiskPersistenceHandler<T>(persistenceFilePath: persistencePath)
// let loadFromPersistence = persistenceHandler.load
// let saveToPersistence = persistenceHandler.save
//
// return ReactorFlow(networkFlow: networkFlow, loadFromPersistenceFlow: loadFromPersistence, saveToPersistenceFlow: saveToPersistence)
// }
//}
//
///// Used as a factory to create a `ReactorFlow` for a single `T: Mappable`
//public func createFlow<T>(_ baseURL: URL, configuration: FlowConfigurable = FlowConfiguration(persistenceConfiguration: .disabled)) -> ReactorFlow<T> where T: Mappable {
//
// let connection = createConnection(baseURL, shouldCheckReachability: configuration.shouldCheckReachability)
// return createFlow(connection, configuration: configuration)
//}
//
///// Used as a factory to create a `ReactorFlow` for a `SequenceType` of `T: Mappable`
//public func createFlow<T>(_ connection: Connection, configuration: FlowConfigurable = FlowConfiguration(persistenceConfiguration: .disabled)) -> ReactorFlow<T> where T: Sequence, T.Iterator.Element: Mappable {
//
// let parser: (Data) -> SignalProducer<T, ReactorError> = configuration.shouldPrune ? prunedParse : strictParse
// let networkFlow: (Resource) -> SignalProducer<T, ReactorError> = { resource in connection.makeRequest(resource).map { $0.0}.flatMapLatest(parser) }
//
// switch configuration.persistenceConfiguration {
// case .disabled:
// return ReactorFlow(networkFlow: networkFlow)
//
// case .enabled(let persistencePath):
// let persistenceHandler = InDiskPersistenceHandler<T>(persistenceFilePath: persistencePath)
// let loadFromPersistence = persistenceHandler.load
// let saveToPersistence = persistenceHandler.save
//
// return ReactorFlow(networkFlow: networkFlow, loadFromPersistenceFlow: loadFromPersistence, saveToPersistenceFlow: saveToPersistence)
// }
//}
//
///// Used as a factory to create a `ReactorFlow` for a `SequenceType` of `T: Mappable`
//public func createFlow<T>(_ baseURL: URL, configuration: FlowConfigurable = FlowConfiguration(persistenceConfiguration: .disabled)) -> ReactorFlow<T> where T: Sequence, T.Iterator.Element: Mappable {
//
// let connection = createConnection(baseURL, shouldCheckReachability: configuration.shouldCheckReachability)
// return createFlow(connection, configuration: configuration)
//}
//
//private func createConnection(_ baseURL: URL, shouldCheckReachability: Bool) -> Connection {
//
// if shouldCheckReachability {
// return Network(baseURL: baseURL)
// }
// else {
// return Network(baseURL: baseURL, reachability: AlwaysReachable())
// }
//}
| 54.777778 | 253 | 0.726978 |
6ab90f89b77656d56969642f5409333a73a0672f | 2,295 | //
// SceneDelegate.swift
// Tip Calculator
//
// Created by Wasif Khan on 1/23/22.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.301887 | 147 | 0.712418 |
01be985b438b555d455ca571430fd289b272b798 | 1,300 | //
// OpenProjectView.swift
// LocalizationHelper
//
// Created by Chung Tran on 24/07/2021.
//
import SwiftUI
struct OpenProjectView: View {
// MARK: - Nested type
enum ProjectType: String {
case `default`
case tuist
}
// MARK: - State
@State private var projectType = ProjectType.default
let handler: OpenProjectHandler
// MARK: - Body
var body: some View {
Group {
Picker("", selection: $projectType) {
Text("Default project").tag(ProjectType.default)
Text("Tuist project").tag(ProjectType.tuist)
}
.pickerStyle(SegmentedPickerStyle())
.padding()
content
.padding()
Spacer()
}
}
var content: AnyView {
switch projectType {
case .default:
return AnyView(DefaultProjectView(handler: handler))
case .tuist:
return AnyView(TuistProjectView(handler: handler))
}
}
}
#if DEBUG
struct OpenProjectView_Previews: PreviewProvider {
static var previews: some View {
OpenProjectView(handler: OpenProjectHandler_Preview())
.frame(width: 500, height: 500)
}
}
#endif
| 22.807018 | 64 | 0.553846 |
ac4e2ab77778b00dd44a05c2a1292b7722b392b4 | 443 | //
// WrappedURIParser.swift
// secant-testnet
//
// Created by Lukáš Korba on 17.05.2022.
//
import Foundation
struct WrappedURIParser {
let isValidURI: (String) throws -> Bool
}
extension WrappedURIParser {
static func live(uriParser: URIParser = URIParser(derivationTool: .live())) -> Self {
Self(
isValidURI: { uri in
try uriParser.isValidURI(uri)
}
)
}
}
| 18.458333 | 89 | 0.591422 |
3936f1ac00e0b1cca30e8bc863b80998664ad81e | 3,093 | //
// STPPaymentMethodAUBECSDebitTests.swift
// StripeiOS Tests
//
// Created by Cameron Sabol on 3/4/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
@testable import Stripe
private var kAUBECSDebitPaymentIntentClientSecret =
"pi_1GaRLjF7QokQdxByYgFPQEi0_secret_z76otRQH2jjOIEQYsA9vxhuKn"
class STPPaymentMethodAUBECSDebitTests: XCTestCase {
private(set) var auBECSDebitJSON: [AnyHashable: Any]?
func _retrieveAUBECSDebitJSON(_ completion: @escaping ([AnyHashable: Any]?) -> Void) {
if let auBECSDebitJSON = auBECSDebitJSON {
completion(auBECSDebitJSON)
} else {
let client = STPAPIClient(publishableKey: STPTestingAUPublishableKey)
client.retrievePaymentIntent(
withClientSecret: kAUBECSDebitPaymentIntentClientSecret,
expand: ["payment_method"]
) { [self] paymentIntent, _ in
auBECSDebitJSON = paymentIntent?.paymentMethod?.auBECSDebit?.allResponseFields
completion(auBECSDebitJSON ?? [:])
}
}
}
func testCorrectParsing() {
let retrieveJSON = XCTestExpectation(description: "Retrieve JSON")
_retrieveAUBECSDebitJSON({ json in
let auBECSDebit = STPPaymentMethodAUBECSDebit.decodedObject(fromAPIResponse: json)
XCTAssertNotNil(auBECSDebit, "Failed to decode JSON")
retrieveJSON.fulfill()
})
wait(for: [retrieveJSON], timeout: STPTestingNetworkRequestTimeout)
}
func testFailWithoutRequired() {
var retrieveJSON = XCTestExpectation(description: "Retrieve JSON")
_retrieveAUBECSDebitJSON({ json in
var auBECSDebitJSON = json
auBECSDebitJSON?["bsb_number"] = nil
XCTAssertNil(
STPPaymentMethodAUBECSDebit.decodedObject(fromAPIResponse: auBECSDebitJSON),
"Should not intialize with missing `bsb_number`")
retrieveJSON.fulfill()
})
wait(for: [retrieveJSON], timeout: STPTestingNetworkRequestTimeout)
retrieveJSON = XCTestExpectation(description: "Retrieve JSON")
_retrieveAUBECSDebitJSON({ json in
var auBECSDebitJSON = json
auBECSDebitJSON?["last4"] = nil
XCTAssertNil(
STPPaymentMethodAUBECSDebit.decodedObject(fromAPIResponse: auBECSDebitJSON),
"Should not intialize with missing `last4`")
retrieveJSON.fulfill()
})
wait(for: [retrieveJSON], timeout: STPTestingNetworkRequestTimeout)
retrieveJSON = XCTestExpectation(description: "Retrieve JSON")
_retrieveAUBECSDebitJSON({ json in
var auBECSDebitJSON = json
auBECSDebitJSON?["fingerprint"] = nil
XCTAssertNil(
STPPaymentMethodAUBECSDebit.decodedObject(fromAPIResponse: auBECSDebitJSON),
"Should not intialize with missing `fingerprint`")
retrieveJSON.fulfill()
})
wait(for: [retrieveJSON], timeout: STPTestingNetworkRequestTimeout)
}
}
| 40.697368 | 94 | 0.661494 |
4b07360e60e6c45c8e5667e25573f376a7aaf105 | 635 | //
// GravityPuttScreenshots_iOS.swift
// GravityPuttScreenshots-iOS
//
// Created by Andrew Finke on 4/14/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import XCTest
class GravityPuttScreenshots_iOS: XCTestCase {
let app = XCUIApplication()
override func setUpWithError() throws {
setupSnapshot(app)
app.launch()
continueAfterFailure = false
}
func testScreenshots() throws {
XCUIDevice.shared.orientation = .landscapeLeft
sleep(0)
snapshot("0")
sleep(2)
snapshot("1")
sleep(3)
snapshot("2")
}
}
| 19.84375 | 55 | 0.614173 |
391bfb3c0aa3f4e47e461ba5d787cea08cb2fccb | 2,896 | /**
The result of a classification request.
Given a query and a set of labeled examples,
the model will predict the most likely label for the query.
Useful as a drop-in replacement for any ML classification or text-to-label task.
*/
public struct Classification: Hashable {
/// A classification example.
public struct Example: Hashable {
/// The source of an example.
public enum Source: Hashable {
/// A document identified by its position.
case document(Int)
/// A file
case file(File.ID)
}
/// The source of the example.
public let source: Source
/// The classification label for the example.
public let label: String
/// The text of the example.
public let text: String
}
/// The completion for the classification.
public let completion: String
/// The classification label assigned by the model.
public let label: String
/// The engine used to perform classification.
public let engine: Engine.ID
/// The engine used for searching.
public let searchEngine: Engine.ID
/// The examples selected by the model in making its classification determination.
public let selectedExamples: [Example]
}
// MARK: - Codable
extension Classification: Codable {
private enum CodingKeys: String, CodingKey {
case completion
case label
case engine = "model"
case searchEngine = "search_model"
case selectedExamples = "selected_examples"
}
}
extension Classification.Example: Codable {
private enum CodingKeys: String, CodingKey {
case document, file
case label
case text
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let document = try? container.decode(Int.self, forKey: .document) {
self.source = .document(document)
} else if let file = try? container.decode(File.ID.self, forKey: .file) {
self.source = .file(file)
} else {
let context = DecodingError.Context(codingPath: [], debugDescription: "unable to decode document or file")
throw DecodingError.dataCorrupted(context)
}
self.label = try container.decode(String.self, forKey: .label)
self.text = try container.decode(String.self, forKey: .text)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch source {
case .document(let document):
try container.encode(document, forKey: .document)
case .file(let file):
try container.encode(file, forKey: .file)
}
try container.encode(label, forKey: .label)
try container.encode(text, forKey: .text)
}
}
| 30.808511 | 118 | 0.639848 |
e41f72ab4fdcde284224350841ac6b0b65876238 | 1,093 | //
// LNDecodePaymentRequestResponse.swift
// DropBit
//
// Created by Ben Winters on 7/24/19.
// Copyright © 2019 Coin Ninja, LLC. All rights reserved.
//
import Moya
struct LNDecodePaymentRequestResponse: LNResponseDecodable {
let numSatoshis: Int?
var description: String?
let isExpired: Bool
let expiresAt: Date
static var sampleJSON: String {
return """
{
"num_satoshis" : 2000,
"destination" : "0357b3bb3fdedb369d2bdb429b6c397b207169bc8933e6f37e926e18b2f6c560f1",
"expiry" : 3600,
"fallback_addr" : "",
"route_hints" : nil,
"description_hash" : "",
"cltv_expiry" : 40,
"description" : "Test request generated at: 2019-07-31 14:17:04 +0000",
"timestamp" : "2019-07-31T14:17:04.000000Z",
"payment_hash" : "59da58f1b9ab6bb1b89659bfb5bd48a0221c40ddd2b5dcea3b25fb5843b58d9c"
}
"""
}
static var requiredStringKeys: [KeyPath<LNDecodePaymentRequestResponse, String>] {
return []
}
static var optionalStringKeys: [WritableKeyPath<LNDecodePaymentRequestResponse, String?>] {
return [\.description]
}
}
| 24.840909 | 93 | 0.698079 |
09ee2d48c0025e754f8180a6166dabd4062cd8e4 | 9,887 | //
// JCAreaPickerView.swift
// JChat
//
// Created by deng on 2017/5/3.
// Copyright © 2017年 dengyonghao. All rights reserved.
//
import UIKit
let stateKey = "state"
let citiesKey = "cities"
let cityKey = "city"
let areasKey = "areas"
enum JCAreaPickerType: Int {
case province
case city
case area
}
@objc public protocol JCAreaPickerViewDelegate: NSObjectProtocol {
@objc optional func areaPickerView(_ areaPickerView: JCAreaPickerView, didSelect button: UIButton, selectLocate locate: JCLocation)
@objc optional func areaPickerView(_ areaPickerView: JCAreaPickerView, cancleSelect button: UIButton)
}
@objc(JCAreaPickerView)
public class JCAreaPickerView: UIView {
weak var delegate: JCAreaPickerViewDelegate?
fileprivate var cities = [[String: AnyObject]]()
fileprivate var areas = [String]()
fileprivate var pickerView: UIPickerView!
override init(frame: CGRect) {
super.init(frame: frame)
let toolView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 40))
toolView.backgroundColor = .white
let line = UILabel(frame: CGRect(x: 0, y: toolView.frame.size.height - 0.5 , width: toolView.frame.size.width, height: toolView.frame.size.height - 0.5))
line.backgroundColor = UIColor(netHex: 0x999999)
toolView.addSubview(line)
let cancelButton = UIButton(frame: CGRect(x: 15, y: 0, width: 50, height: 39.5))
cancelButton.setTitle("取消", for: .normal)
cancelButton.setTitleColor(.black, for: .normal)
cancelButton.addTarget(self, action: #selector(_areaPickerCancel), for: .touchUpInside)
let sureButton = UIButton(frame: CGRect(x: toolView.frame.size.width - 50 - 15, y: 0, width: 50, height: 39.5))
sureButton.setTitle("确定", for: .normal)
sureButton.setTitleColor(.black, for: .normal)
sureButton.addTarget(self, action: #selector(_areaPickerSure), for: .touchUpInside)
toolView.addSubview(cancelButton)
toolView.addSubview(sureButton)
addSubview(toolView)
pickerView = UIPickerView(frame: CGRect(x: 0, y: 40, width: frame.size.width, height: frame.size.height - 40))
pickerView.backgroundColor = .white
pickerView.delegate = self
pickerView.dataSource = self
addSubview(pickerView)
cities = provinces[0][citiesKey] as! [[String : AnyObject]]!
if let province = provinces[0][stateKey] as? String {
locate.province = province
}
if let city = cities[0][cityKey] as? String {
locate.city = city
}
areas = cities[0][areasKey] as! [String]!
if areas.count > 0 {
locate.area = areas[0]
} else {
locate.area = ""
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func _areaPickerCancel(_ sender: UIButton) {
delegate?.areaPickerView?(self, cancleSelect: sender)
}
@objc func _areaPickerSure(_ sender: UIButton) {
delegate?.areaPickerView?(self, didSelect: sender, selectLocate: locate)
}
func shouldSelected(proName: String, cityName: String, areaName: String?) {
for index in 0..<provinces.count {
let pro = provinces[index]
if pro[stateKey] as! String == proName {
cities = provinces[index][citiesKey] as! [[String : AnyObject]]!
if let province = provinces[index][stateKey] as? String {
locate.province = province
}
pickerView.selectRow(index, inComponent: JCAreaPickerType.province.rawValue, animated: false)
break
}
}
for index in 0..<cities.count {
let city = cities[index]
if city[cityKey] as! String == cityName {
if let city = cities[index][cityKey] as? String {
locate.city = city
}
areas = cities[index][areasKey] as! [String]!
pickerView.selectRow(index, inComponent: JCAreaPickerType.city.rawValue, animated: false)
break
}
}
if areaName != nil {
for (index, name) in areas.enumerated() {
if name == areaName! {
locate.area = areas[index]
pickerView.reloadAllComponents()
pickerView.selectRow(index, inComponent: JCAreaPickerType.area.rawValue, animated: false)
break
}
}
}
}
func setCode(provinceName: String, cityName: String, areaName: String?){
let url = Bundle.main.url(forResource: "addressCode", withExtension: nil)
let data = try! Data(contentsOf: url!)
let dict = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
let provinces = dict["p"] as! [[String: AnyObject]]
for pro in provinces {
if pro["n"] as! String == provinceName {
if let proCode = pro["v"] as? String {
locate.provinceCode = proCode //找到省编号
}
var foundCity = false
for city in pro["c"] as! [[String: AnyObject]] {
if city["n"] as! String == cityName {
if let cityCode = city["v"] as? String {
locate.cityCode = cityCode //找到城市编码
}
for area in city["d"] as! [[String: String]] {
if area["n"] == areaName {
locate.areaCode = area["v"]!
}
}
foundCity = true
}
}
//如果第二层没有找到相应的城市.那就是直辖市了,要重新找
if !foundCity {
for city in pro["c"] as! [[String: AnyObject]] {
let areas = city["d"] as! [[String: String]] //直接查找三级区域
for area in areas {
if area["n"] == cityName {
locate.areaCode = area["v"]!
if let cityCode = city["v"] as? String {
locate.cityCode = cityCode
}
break
}
}
}
}
}
}
}
// MARK: - lazy
lazy var provinces: [[String: AnyObject]] = {
let path = Bundle.main.path(forResource: "area", ofType: "plist")
return NSArray(contentsOfFile: path!) as! [[String: AnyObject]]
}()
lazy var locate: JCLocation = {
return JCLocation()
}()
}
extension JCAreaPickerView: UIPickerViewDelegate, UIPickerViewDataSource {
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
let pickerType = JCAreaPickerType(rawValue: component)!
switch pickerType {
case .province:
return provinces.count
case .city:
return cities.count
case .area:
return areas.count
}
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let pickerType = JCAreaPickerType(rawValue: component)!
switch pickerType {
case .province:
return provinces[row][stateKey] as! String?
case .city:
return cities[row][cityKey] as! String?
case .area:
if areas.count > 0 {
return areas[row]
} else {
return ""
}
}
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let pickerType = JCAreaPickerType(rawValue: component)!
switch pickerType {
case .province:
cities = provinces[row][citiesKey] as! [[String : AnyObject]]!
pickerView.reloadComponent(JCAreaPickerType.city.rawValue)
pickerView.selectRow(0, inComponent: JCAreaPickerType.city.rawValue, animated: true)
reloadAreaComponent(pickerView: pickerView, row: 0)
if let province = provinces[row][stateKey] as? String {
locate.province = province
}
case .city:
reloadAreaComponent(pickerView: pickerView, row: row)
case .area:
if areas.count > 0 {
locate.area = areas[row]
} else {
locate.area = ""
}
}
setCode(provinceName: locate.province, cityName: locate.city, areaName: locate.area)
}
func reloadAreaComponent(pickerView: UIPickerView, row: Int) {
guard row <= cities.count - 1 else {
return
}
areas = cities[row][areasKey] as! [String]!
pickerView.reloadComponent(JCAreaPickerType.area.rawValue)
pickerView.selectRow(0, inComponent: JCAreaPickerType.area.rawValue, animated: true)
if let city = cities[row][cityKey] as? String {
locate.city = city
}
if areas.count > 0 {
locate.area = areas[0]
} else {
locate.area = ""
}
}
}
| 35.952727 | 161 | 0.543542 |
8fe6f6e2fd573ea0ecccc86fd48eef5f7aa29fe4 | 4,453 |
import Glibc
import CSua
import Sua
class SocketAll {
let serverSocket: ServerSocket
var buffer = [UInt8](repeating: 0, count: 1024)
init(hostName: String, port: UInt16) throws {
serverSocket = try ServerSocket(hostName: hostName, port: port)
}
func close() {
serverSocket.close()
}
func runThreaded() throws {
while true {
if let socket = serverSocket.accept() {
var tb = Thread() {
defer {
socket.close()
}
var buffer = [UInt8](repeating: 0, count: 1024)
var _ = socket.read(buffer: &buffer, maxBytes: buffer.count)
let _ = socket.write(string: "Hello World\n")
}
let _ = try tb.join()
}
}
}
func runForked() throws {
while true {
try serverSocket.spawnAccept() { socket in
self.answer(socket: socket)
}
}
}
func runSingle() {
while true {
if let socket = serverSocket.accept() {
answer(socket: socket)
}
}
}
func answer(socket: Socket) {
defer {
socket.close()
}
let _ = socket.read(buffer: &buffer, maxBytes: buffer.count)
let _ = socket.write(string: "Hello World\n")
}
}
enum SocketAllType {
case Single
case Threaded
case Forked
}
struct SocketAllOptions {
var port: UInt16 = 9123
var hostName = "127.0.0.1"
var type: SocketAllType = .Single
}
func printUsage() {
print("SocketAll: SocketAll -type (s|t|f) [-port #]\n" +
"Usage: run SocketAll by giving it at least the type parameter.\n" +
" -type s | t | f s for single; t for threaded; f for forked.\n" +
" -port 9123 port, which defaults to 9123. Range from 0 to" +
" 65535.\n" +
"E.g.\n" +
" > SocketAll -type s\n" +
" > SocketAll -type s -port 9123\n")
}
func processArguments() -> SocketAllOptions? {
let args = Process.arguments
var i = 1
let len = args.count
var stream = ByteStream()
var type: SocketAllType?
var port: UInt16?
func error(_ ti: Int = -1) {
type = nil
let t = args[ti < 0 ? i : ti]
print("\u{1b}[1m\u{1b}[31mError:\u{1b}[0m Error while parsing the " +
"command-line options: ^\(t)\n")
printUsage()
}
func eatPortDigits() -> Bool {
if stream.eatWhileDigit() {
let s = stream.collectTokenString()
let _ = stream.eatSpace()
if stream.isEol {
let n = Int(s!)!
if n >= 0 && n <= 65535 {
port = UInt16(n)
return true
}
}
}
return false
}
while i < len {
switch args[i] {
case "-type":
i += 1
if i < len {
switch args[i] {
case "s":
type = .Single
case "t":
type = .Threaded
case "f":
type = .Forked
default:
error()
break
}
} else {
error(i - 1)
break
}
case "-types":
type = .Single
case "-typet":
type = .Threaded
case "-typef":
type = .Forked
case "-port":
i += 1
if i < len {
stream.bytes = Array(args[i].utf8)
if !eatPortDigits() {
error()
break
}
} else {
error(i - 1)
break
}
default:
stream.bytes = Array(args[i].utf8)
if stream.eatString(string: "-port") {
stream.startIndex = stream.currentIndex
if !eatPortDigits() {
error()
break
}
} else {
error()
break
}
}
i += 1
}
if type != nil {
var o = SocketAllOptions()
o.type = type!
if port != nil {
o.port = port!
}
return o
}
if len == 1 {
printUsage()
}
return nil
}
if let opt = processArguments() {
print("Starting the server on \(opt.hostName):\(opt.port)")
var sa = try SocketAll(hostName: opt.hostName, port: opt.port)
switch opt.type {
case .Single:
print("Server type: Single. Single process, single thread.")
sa.runSingle()
case .Threaded:
print("Server type: Threaded. Multiple threads on a single process.")
try sa.runThreaded()
case .Forked:
print("Server type: Forked. Multiple forked processes with single " +
"thread.")
try sa.runForked()
}
}
| 21.935961 | 82 | 0.515832 |
724ecff346708db725943fc982790ed029dbfe61 | 1,646 | //
// PalmTreeFoliage.swift
//
// Created by Zack Brown on 21/06/2021.
//
import SwiftUI
class PalmTreeFoliage: Codable, Hashable, ObservableObject {
static let `default`: PalmTreeFoliage = PalmTreeFoliage(fronds: 7)
enum CodingKeys: CodingKey {
case crown
case frond
case fronds
}
@Published var fronds: Int
@Published var crown: PalmTreeChonk
@Published var frond: PalmTreeFrond
init(fronds: Int) {
self.fronds = fronds
self.crown = .crown
self.frond = .default
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
fronds = try container.decode(Int.self, forKey: .fronds)
crown = try container.decode(PalmTreeChonk.self, forKey: .crown)
frond = try container.decode(PalmTreeFrond.self, forKey: .frond)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(fronds, forKey: .fronds)
try container.encode(crown, forKey: .crown)
try container.encode(frond, forKey: .frond)
}
func hash(into hasher: inout Hasher) {
hasher.combine(fronds)
hasher.combine(crown)
hasher.combine(frond)
}
static func == (lhs: PalmTreeFoliage, rhs: PalmTreeFoliage) -> Bool {
return lhs.fronds == rhs.fronds &&
lhs.crown == rhs.crown &&
lhs.frond == rhs.frond
}
}
| 24.939394 | 73 | 0.585662 |
0a9f8bd7d3bf8d21383a35eb916c8c916991ad8d | 180 | //
// 🦠 Corona-Warn-App
//
import Foundation
class StatisticsProvidingFake: StatisticsProviding {
func statistics() -> AnyPublisher<SAP_Internal_Stats_Statistics, Error> {
}
}
| 16.363636 | 74 | 0.755556 |
f9fe6f842467b8bc8d609a7b7c7bbc4e5ed47065 | 1,284 | //
// AHMainViewController.swift
// Gank
//
// Created by CoderAhuan on 2016/12/7.
// Copyright © 2016年 CoderAhuan. All rights reserved.
//
import UIKit
class AHMainViewController: BaseViewController {
lazy var tabBarVC: TabBarController = {
let tabBarVC = TabBarController()
tabBarVC.delegate = self
return tabBarVC
}()
lazy var LaunchVC: AHLaunchViewController = {
let LaunchVC = AHLaunchViewController(showTime: 3)
LaunchVC.launchComplete = { [unowned self] in
self.view.addSubview(self.tabBarVC.view)
self.addChildViewController(self.tabBarVC)
}
return LaunchVC
}()
override func viewDidLoad() {
super.viewDidLoad()
setupLaunchVC()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupLaunchVC() {
addChildViewController(LaunchVC)
view.addSubview(LaunchVC.view)
}
}
extension AHMainViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
NotificationCenter.default.post(name: NSNotification.Name.AHTabBarDidSelectNotification, object: nil)
}
}
| 26.75 | 111 | 0.67757 |
38fe285ba7fa0443a0a0bf1daa389b03c50df630 | 111 | import SwiftDoc
extension Symbol {
var isDocumented: Bool {
return !documentation.isEmpty
}
}
| 13.875 | 37 | 0.666667 |
f57743fa51f3ec23a2e6afc6b2c788868df05429 | 3,180 | //
// LeetCodeListView.swift
// Swift-Learning-Demo
//
// Created by yuan xiaodong on 2020/12/4.
// Copyright © 2020 yuan. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
import ObjectMapper
private let cellIdentifier = "cellIdentifier"
class LeetCodeViewController: BaseViewController{
var didSetupConstraints = false
override func viewDidLoad() {
super.viewDidLoad()
title = "LeetCode"
view.addSubview(self.tableView)
view.setNeedsUpdateConstraints()
}
override func updateViewConstraints() {
if !didSetupConstraints {
tableView.snp_makeConstraints { (maker) in
maker.edges.equalToSuperview()
}
didSetupConstraints = true
}
super.updateViewConstraints()
}
// MARK: - *********** 懒加载 ***********
lazy var dataArr : NSArray = {
let jsonData = dataForJson(fileName: "leetCode.json")
let jsonStr = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue)
let dicArr = getArrayFromJSONString(jsonString: jsonStr! as String)
//数组转模型
var modelArr = [YSListModel]()
for var item in dicArr{
let model = Mapper<YSListModel>().map(JSON: item as! [String : Any])
modelArr.append(model!)
}
return modelArr as NSArray
}()
lazy var tableView : UITableView = {
let table = UITableView.init()
table.delegate = self;
table.dataSource = self;
table.tableFooterView = UIView()
return table
}()
@objc func twoSum(){
let nums = [2, 7, 11, 15]
let taget = 9
let arr = Solution().twoSum(nums, taget);
print("twoSum的结果是\(arr)");
}
}
// MARK: - *********** UITableViewDelegate ***********
extension LeetCodeViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: YSTableViewCell? = nil
if cell != nil {
cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? YSTableViewCell
}else{
cell = YSTableViewCell.init(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: cellIdentifier)
}
let model = self.dataArr[indexPath.row] as? YSListModel
cell?.model = model
cell?.textLabel?.text = model?.title
cell?.detailTextLabel?.text = model?.subTitle
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = self.dataArr[indexPath.row] as? YSListModel
let selector = Selector(model!.event)
if self.responds(to:selector) {
self.perform(selector)
}else{
print("\(selector.description)方法不存在!!!")
}
}
}
| 30.576923 | 116 | 0.61195 |
9cb1291d45b03049c3a19653be50d782205f46d3 | 647 | //
// Int+RoundToNearest.swift
// DayDatePicker
//
// Created by Hugh Bellamy on 05/02/2018.
//
internal extension Int {
func round(toNearest: Int) -> Int{
let fractionNum = Double(self) / Double(toNearest)
let roundedNum = Int(floor(fractionNum))
return roundedNum * toNearest
}
var ordinalIndicatorString: String {
get {
switch self {
case 1, 21, 31:
return "st"
case 2, 22, 32:
return "nd"
case 3, 23, 33:
return "nd"
default:
return "th"
}
}
}
}
| 21.566667 | 58 | 0.486862 |
deb8e45870474baadd46861e8fc71cdc6ac1a38d | 1,029 | //
// CredentialsService.swift
// SmartSleep
//
// Created by Anders Borch on 23/02/2019.
// Copyright © 2019 Anders Borch. All rights reserved.
//
import Foundation
import KeychainAccess
struct Credentials: Codable {
var username: String
var password: String
}
class CredentialsService {
private let keychain = Keychain(service: "dk.ku.sund.smartsleep")
var credentials: Credentials? {
get {
let ud = UserDefaults()
guard let username: String = ud.valueFor(.username) else { return nil }
guard let password = keychain[username] else { return nil }
return Credentials(
username: username,
password: password
)
}
set(value) {
if let creds = value {
let ud = UserDefaults()
ud.setValueFor(.username, to: creds.username)
ud.synchronize()
keychain[creds.username] = creds.password
}
}
}
}
| 25.725 | 83 | 0.570457 |
71d9cac6c89a81287124cb7c49370f7a6ab56300 | 1,871 | //
// UIScrollView+Zoom.swift
// BoxPreviewSDK-iOS
//
// Created by Abel Osorio on 8/2/19.
// Copyright © 2019 Box. All rights reserved.
//
import UIKit
extension UIScrollView {
func zoom(to point: CGPoint, animated: Bool, forceZoomInMax: Bool = false) {
let currentScale = zoomScale
let minScale = minimumZoomScale
let maxScale = maximumZoomScale
if minScale == maxScale, minScale > 1 {
return
}
var finalScale: CGFloat
if forceZoomInMax {
finalScale = maxScale
} else {
finalScale = (currentScale == minScale) ? maxScale : minScale
}
let zoomRect = self.zoomRect(for: finalScale, withCenter: point)
zoom(to: zoomRect, animated: animated)
}
func move(to point: CGPoint, animated: Bool) {
var scale = zoomScale
if scale != maximumZoomScale {
scale = maximumZoomScale
}
let zoomRect = self.zoomRect(for: scale, withCenter: point)
zoom(to: zoomRect, animated: animated)
}
// The center should be in the imageView's coordinates
func zoomRect(for scale: CGFloat, withCenter center: CGPoint) -> CGRect {
var zoomRect = CGRect.zero
let bounds = self.bounds
// the zoom rect is in the content view's coordinates.
// At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
// As the zoom scale decreases, so more content is visible, the size of the rect grows.
zoomRect.size.width = bounds.size.width / scale
zoomRect.size.height = bounds.size.height / scale
// choose an origin so as to get the right center.
zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0)
return zoomRect
}
}
| 32.824561 | 95 | 0.623196 |
87ba06db3ac288370ac7c6e7d89dc27934222863 | 351 | //
// PlaceHolderClass.swift
// CuckooDemo
//
// Created by Andrei Nagy on 19/05/2019.
// Copyright © 2019 Andrei Nagy. All rights reserved.
//
// cuckoo: generate
import Foundation
class PlaceHolderClass: NSObject {
func method() -> Int {
return 13
}
func anotherMethod() -> String {
return "someValue"
}
}
| 16.714286 | 54 | 0.621083 |
eb9dfca1968dd6e236a36be35f1a92382f08da1c | 5,767 |
import UIKit
import Firebase
import AVFoundation
class ChatCell: UICollectionViewCell {
// MARK: - Properties
var bubbleWidthAnchor: NSLayoutConstraint?
var bubbleViewRightAnchor: NSLayoutConstraint?
var bubbleViewLeftAnchor: NSLayoutConstraint?
var delegate: ChatCellDelegate?
var playerLayer: AVPlayerLayer?
var player: AVPlayer?
var message: Message? {
didSet {
if let messageText = message?.messageText {
textView.text = messageText
}
guard let chatPartnerId = message?.getChatPartnerId() else { return }
Database.fetchUser(with: chatPartnerId) { (user) in
guard let profileImageUrl = user.profileImageUrl else { return }
self.profileImageView.loadImage(with: profileImageUrl)
}
}
}
let activityIndicatorView: UIActivityIndicatorView = {
let aiv = UIActivityIndicatorView(style: .whiteLarge)
aiv.translatesAutoresizingMaskIntoConstraints = false
aiv.hidesWhenStopped = true
return aiv
}()
lazy var playButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "play"), for: .normal)
button.tintColor = .white
button.addTarget(self, action: #selector(handlePlayVideo), for: .touchUpInside)
return button
}()
let bubbleView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.rgb(red: 0, green: 137, blue: 249)
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 16
view.layer.masksToBounds = true
return view
}()
let textView: UITextView = {
let tv = UITextView()
tv.font = UIFont.systemFont(ofSize: 16)
tv.backgroundColor = .clear
tv.textColor = .white
tv.translatesAutoresizingMaskIntoConstraints = false
tv.isEditable = false
return tv
}()
let profileImageView: CustomImageView = {
let iv = CustomImageView()
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
iv.backgroundColor = .lightGray
return iv
}()
let messageImageView: CustomImageView = {
let iv = CustomImageView()
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(bubbleView)
addSubview(textView)
addSubview(profileImageView)
bubbleView.addSubview(messageImageView)
messageImageView.anchor(top: bubbleView.topAnchor, left: bubbleView.leftAnchor, bottom: bubbleView.bottomAnchor, right: bubbleView.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
bubbleView.addSubview(playButton)
playButton.centerXAnchor.constraint(equalTo: bubbleView.centerXAnchor).isActive = true
playButton.centerYAnchor.constraint(equalTo: bubbleView.centerYAnchor).isActive = true
playButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
playButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
playButton.translatesAutoresizingMaskIntoConstraints = false
bubbleView.addSubview(activityIndicatorView)
activityIndicatorView.centerXAnchor.constraint(equalTo: bubbleView.centerXAnchor).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: bubbleView.centerYAnchor).isActive = true
activityIndicatorView.widthAnchor.constraint(equalToConstant: 50).isActive = true
activityIndicatorView.heightAnchor.constraint(equalToConstant: 50).isActive = true
profileImageView.anchor(top: nil, left: leftAnchor, bottom: bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 8, paddingBottom: -4, paddingRight: 0, width: 32, height: 32)
profileImageView.layer.cornerRadius = 32 / 2
// bubble view right anchor
bubbleViewRightAnchor = bubbleView.rightAnchor.constraint(equalTo: rightAnchor, constant: -8)
bubbleViewRightAnchor?.isActive = true
// bubble view left anchor
bubbleViewLeftAnchor = bubbleView.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8)
bubbleViewLeftAnchor?.isActive = false
// bubble view width and top anchor
bubbleView.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
bubbleWidthAnchor = bubbleView.widthAnchor.constraint(equalToConstant: 200)
bubbleWidthAnchor?.isActive = true
bubbleView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
// bubble view text view anchors
textView.leftAnchor.constraint(equalTo: bubbleView.leftAnchor, constant: 8).isActive = true
textView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
textView.rightAnchor.constraint(equalTo: bubbleView.rightAnchor).isActive = true
textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
override func prepareForReuse() {
super.prepareForReuse()
player?.pause()
activityIndicatorView.stopAnimating()
playerLayer?.removeFromSuperlayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Handlers
@objc func handlePlayVideo() {
delegate?.handlePlayVideo(for: self)
}
}
| 38.704698 | 238 | 0.667765 |
1866792e9131fff499a38819d0c58592782bb823 | 2,729 | import SourceKittenFramework
extension Structure {
var isClass: Bool {
return declarationKind == .class
}
var isExtension: Bool {
return declarationKind == .extension
}
var isFinalClass: Bool {
return isClass && attributes.contains("source.decl.attribute.final")
}
var isTestFunction: Bool {
return declarationKind == .functionMethodInstance && name?.hasPrefix("test") == true
}
var isAllTestsExtension: Bool {
return substructure
.compactMap { Structure(sourceKitResponse: $0) }
.contains(where: { $0.name == "allTests" })
}
func `extension`() -> Structure? {
return substructure
.compactMap { Structure(sourceKitResponse: $0) }
.first(where: { $0.isExtension })
}
func `class`(parentClasses: [String]) -> Structure? {
guard let firstClass = Structure.classInStructure(self) else {
return nil
}
if firstClass.inheritedTypes.contains(where: { parentClasses.contains($0) }) {
return firstClass
} else {
guard let nestedClass = Structure.classInStructure(firstClass) else {
return nil
}
guard nestedClass.inheritedTypes.contains(where: { parentClasses.contains($0) }) else {
return nil
}
guard let firstClassName = firstClass.name,
let nestedClassName = nestedClass.name else {
return nil
}
var nestedStructure = nestedClass.dictionary
nestedStructure["key.name"] = [firstClassName, nestedClassName].joined(separator: ".")
return Structure(sourceKitResponse: nestedStructure)
}
}
func scopes(parentClasses: [String]) -> [Structure] {
return Structure.scopesInStructure(self)
}
func testCases() -> [String] {
return substructure
.compactMap { Structure(sourceKitResponse: $0) }
.filter { $0.isTestFunction }
.compactMap { $0.name?.replacingOccurrences(of: "()", with: "") }
}
static func classInStructure(_ structure: Structure) -> Structure? {
return structure
.substructure
.compactMap { Structure(sourceKitResponse: $0) }
.first(where: { $0.isClass })
}
static func scopesInStructure(_ structure: Structure) -> [Structure] {
return structure
.substructure
.compactMap { Structure(sourceKitResponse: $0) }
.filter { $0.isClass || $0.isExtension }
}
}
| 31.011364 | 99 | 0.566508 |
d907f0ce6abb37c30902eeb95dbe7d443d4d984a | 2,354 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TensorFlow
final class TensorTests: XCTestCase {
func testSimpleCond() {
func selectValue(_ pred: Bool) -> Tensor<Int32> {
let a = Tensor<Int32>(0)
let b = Tensor<Int32>(1)
if pred {
return a
}
return b
}
XCTAssertEqual(selectValue(true).scalar, 0)
}
func testRankGetter() {
let vector = Tensor<Int32>([1])
let matrix = Tensor<Float>([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
let ones = Tensor<Int32>(ones: [1, 2, 2, 2, 2, 2, 1])
let tensor = Tensor<Int32>(shape: [3, 4, 5], scalars: Array(0..<60))
XCTAssertEqual(vector.rank, 1)
XCTAssertEqual(matrix.rank, 2)
XCTAssertEqual(ones.rank, 7)
XCTAssertEqual(tensor.rank, 3)
}
func testShapeGetter() {
let vector = Tensor<Int32>([1])
let matrix = Tensor<Float>([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
let ones = Tensor<Int32>(ones: [1, 2, 2, 2, 2, 2, 1])
let tensor = Tensor<Int32>(shape: [3, 4, 5], scalars: Array(0..<60))
XCTAssertEqual(vector.shape, [1])
XCTAssertEqual(matrix.shape, [2, 3])
XCTAssertEqual(ones.shape, [1, 2, 2, 2, 2, 2, 1])
XCTAssertEqual(tensor.shape, [3, 4, 5])
}
func testTensorShapeDescription() {
XCTAssertEqual(Tensor<Int32>(ones: [2, 2]).shape.description, "[2, 2]")
XCTAssertEqual(Tensor(1).shape.description, "[]")
}
static var allTests = [
("testSimpleCond", testSimpleCond),
("testRankGetter", testRankGetter),
("testShapeGetter", testShapeGetter),
("testTensorShapeDescription", testTensorShapeDescription)
]
}
| 36.215385 | 79 | 0.61215 |
67c56a10064348c5e847825c28240d53ddf0cf86 | 792 | // UILayoutPriorityExtensions.swift - Copyright 2020 SwifterSwift
#if os(iOS) || os(tvOS)
import UIKit
extension UILayoutPriority: ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
// MARK: - Initializers
/// SwifterSwift: Initialize `UILayoutPriority` with a float literal.
///
/// constraint.priority = 0.5
///
/// - Parameter value: The float value of the constraint.
public init(floatLiteral value: Float) {
self.init(rawValue: value)
}
/// SwifterSwift: Initialize `UILayoutPriority` with an integer literal.
///
/// constraint.priority = 5
///
/// - Parameter value: The integer value of the constraint.
public init(integerLiteral value: Int) {
self.init(rawValue: Float(value))
}
}
#endif
| 27.310345 | 84 | 0.665404 |
bf4cabd60f0ebf97e06ae0f47af93693bf6841e3 | 1,817 | //
// ViewController.swift
// MapKit Series Part 1
//
// Created by James Rea Taylor on 20/02/2019.
// Copyright © 2019 James Rea Taylor. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
let mapView = MKMapView()
override func viewDidLoad() {
super.viewDidLoad()
setupMap()
setupLayout()
}
func setupMap() {
let latitude: CLLocationDegrees = 51.481663
let longitude: CLLocationDegrees = -0.1931452
let latDelta: CLLocationDegrees = 0.02
let lonDelta: CLLocationDegrees = 0.02
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: coordinates, span: span)
let annotation: MKPointAnnotation = MKPointAnnotation()
annotation.coordinate = coordinates
annotation.title = "You are here"
annotation.subtitle = "Your coordinates are \n\(latitude)° N \n\(longitude)° W"
mapView.setRegion(region, animated: true)
mapView.addAnnotation(annotation)
}
func setupLayout() {
view.addSubview(mapView)
mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
mapView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
mapView.translatesAutoresizingMaskIntoConstraints = false
}
}
| 29.786885 | 90 | 0.643368 |
7907348b5cd2a55160bfa7f462a2c8dedf17b020 | 752 | import XCTest
import RoundCornerView
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.931034 | 111 | 0.603723 |
8fc7ad4d3c7c885081c96e2b1167e00d7a87b134 | 367 |
import UIKit
extension UIStoryboard {
func initViewController<T: UIViewController>() -> T {
let identifier = String(describing: T.self)
guard let obj = self.instantiateViewController(withIdentifier: identifier) as? T else {
fatalError("Can't find any class name with identifier: \(identifier)")
}
return obj
}
}
| 26.214286 | 95 | 0.653951 |
e65e58840b9686d1a8391c6851df934694075760 | 457 | //
// FullscreenWKWebView.swift
// KikkAR
//
// Created by Amelie Rosser on 06/10/2018.
// Copyright © 2018. All rights reserved.
//
import Foundation
import WebKit
// https://stackoverflow.com/questions/47244002/make-wkwebview-real-fullscreen-on-iphone-x-remove-safe-area-from-wkwebview
class FullScreenWKWebView: WKWebView {
override var safeAreaInsets: UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
| 22.85 | 122 | 0.722101 |
d5790a2930028e259ac5cf7f58840417427917cd | 11,073 | public struct BTree<Element: Comparable> {
fileprivate var root: Node
init(order: Int) {
self.root = Node(order: order)
}
}
extension BTree {
final class Node {
let order: Int
var mutationCount: Int64 = 0
var elements: [Element] = []
var children: [Node] = []
init(order: Int) {
self.order = order
}
}
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
let cacheSize: Int? = {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
var result: Int = 0
var size = MemoryLayout<Int>.size
let status = sysctlbyname("hw.l1dcachesize", &result, &size, nil, 0)
guard status != -1 else { return nil }
return result
#elseif os(Linux)
let result = sysconf(Int32(_SC_LEVEL1_DCACHE_SIZE))
guard result != -1 else { return nil }
return result
#else
return nil // Unknown platform
#endif
}()
extension BTree {
public init() {
let order = (cacheSize ?? 32768) / (4 * MemoryLayout<Element>.stride)
self.init(order: Swift.max(16, order))
}
}
extension BTree {
public func forEach(_ body: (Element) throws -> Void) rethrows {
try root.forEach(body)
}
}
extension BTree.Node {
func forEach(_ body: (Element) throws -> Void) rethrows {
if children.isEmpty {
try elements.forEach(body)
}
else {
for i in 0 ..< elements.count {
try children[i].forEach(body)
try body(elements[i])
}
try children[elements.count].forEach(body)
}
}
}
extension BTree.Node {
internal func slot(of element: Element) -> (match: Bool, index: Int) {
var start = 0
var end = elements.count
while start < end {
let mid = start + (end - start) / 2
if elements[mid] < element {
start = mid + 1
}
else {
end = mid
}
}
let match = start < elements.count && elements[start] == element
return (match, start)
}
}
extension BTree {
public func contains(_ element: Element) -> Bool {
return root.contains(element)
}
}
extension BTree.Node {
func contains(_ element: Element) -> Bool {
let slot = self.slot(of: element)
if slot.match { return true }
guard !children.isEmpty else { return false }
return children[slot.index].contains(element)
}
}
extension BTree {
fileprivate mutating func makeRootUnique() -> Node {
if isKnownUniquelyReferenced(&root) { return root }
root = root.clone()
return root
}
}
extension BTree.Node {
func clone() -> BTree<Element>.Node {
let clone = BTree<Element>.Node(order: order)
clone.elements = self.elements
clone.children = self.children
return clone
}
}
extension BTree.Node {
func makeChildUnique(at slot: Int) -> BTree<Element>.Node {
guard !isKnownUniquelyReferenced(&children[slot]) else {
return children[slot]
}
let clone = children[slot].clone()
children[slot] = clone
return clone
}
}
extension BTree.Node {
var isLeaf: Bool { return children.isEmpty }
var isTooLarge: Bool { return elements.count >= order }
}
extension BTree {
struct Splinter {
let separator: Element
let node: Node
}
}
extension BTree.Node {
func split() -> BTree<Element>.Splinter {
let count = self.elements.count
let middle = count / 2
let separator = self.elements[middle]
let node = BTree<Element>.Node(order: order)
node.elements.append(contentsOf: self.elements[middle + 1 ..< count])
self.elements.removeSubrange(middle ..< count)
if !isLeaf {
node.children.append(contentsOf: self.children[middle + 1 ..< count + 1])
self.children.removeSubrange(middle + 1 ..< count + 1)
}
return .init(separator: separator, node: node)
}
}
extension BTree.Node {
func insert(_ element: Element) -> (old: Element?, splinter: BTree<Element>.Splinter?) {
let slot = self.slot(of: element)
if slot.match {
// The element is already in the tree.
return (self.elements[slot.index], nil)
}
mutationCount += 1
if self.isLeaf {
elements.insert(element, at: slot.index)
return (nil, self.isTooLarge ? self.split() : nil)
}
let (old, splinter) = makeChildUnique(at: slot.index).insert(element)
guard let s = splinter else { return (old, nil) }
elements.insert(s.separator, at: slot.index)
children.insert(s.node, at: slot.index + 1)
return (nil, self.isTooLarge ? self.split() : nil)
}
}
extension BTree {
@discardableResult
public mutating func insert(_ element: Element) -> (inserted: Bool, memberAfterInsert: Element) {
let root = makeRootUnique()
let (old, splinter) = root.insert(element)
if let splinter = splinter {
let r = Node(order: root.order)
r.elements = [splinter.separator]
r.children = [root, splinter.node]
self.root = r
}
return (old == nil, old ?? element)
}
}
extension BTree {
struct UnsafePathElement {
unowned(unsafe) let node: Node
var slot: Int
init(_ node: Node, _ slot: Int) {
self.node = node
self.slot = slot
}
}
}
extension BTree.UnsafePathElement {
var value: Element? {
guard slot < node.elements.count else { return nil }
return node.elements[slot]
}
var child: BTree<Element>.Node {
return node.children[slot]
}
var isLeaf: Bool { return node.isLeaf }
var isAtEnd: Bool { return slot == node.elements.count }
}
extension BTree.UnsafePathElement: Equatable {
static func ==(left: BTree<Element>.UnsafePathElement, right: BTree<Element>.UnsafePathElement) -> Bool {
return left.node === right.node && left.slot == right.slot
}
}
extension BTree {
public struct Index {
fileprivate weak var root: Node?
fileprivate let mutationCount: Int64
fileprivate var path: [UnsafePathElement]
fileprivate var current: UnsafePathElement
init(startOf tree: BTree) {
self.root = tree.root
self.mutationCount = tree.root.mutationCount
self.path = []
self.current = UnsafePathElement(tree.root, 0)
while !current.isLeaf { push(0) }
}
init(endOf tree: BTree) {
self.root = tree.root
self.mutationCount = tree.root.mutationCount
self.path = []
self.current = UnsafePathElement(tree.root, tree.root.elements.count)
}
}
}
extension BTree.Index {
fileprivate func validate(for root: BTree<Element>.Node) {
precondition(self.root === root)
precondition(self.mutationCount == root.mutationCount)
}
fileprivate static func validate(_ left: BTree<Element>.Index, _ right: BTree<Element>.Index) {
precondition(left.root === right.root)
precondition(left.mutationCount == right.mutationCount)
precondition(left.root != nil)
precondition(left.mutationCount == left.root!.mutationCount)
}
}
extension BTree.Index {
fileprivate mutating func push(_ slot: Int) {
path.append(current)
let child = current.node.children[current.slot]
current = BTree<Element>.UnsafePathElement(child, slot)
}
fileprivate mutating func pop() {
current = self.path.removeLast()
}
}
extension BTree.Index {
fileprivate mutating func formSuccessor() {
precondition(!current.isAtEnd, "Cannot advance beyond endIndex")
current.slot += 1
if current.isLeaf {
// This loop will rarely execute even once.
while current.isAtEnd, current.node !== root {
// Ascend to the nearest ancestor that has further elements.
pop()
}
}
else {
// Descend to the start of the leftmost leaf node under us.
while !current.isLeaf {
push(0)
}
}
}
}
extension BTree.Index {
fileprivate mutating func formPredecessor() {
if current.isLeaf {
while current.slot == 0, current.node !== root {
pop()
}
precondition(current.slot > 0, "Cannot go below startIndex")
current.slot -= 1
}
else {
while !current.isLeaf {
let c = current.child
push(c.isLeaf ? c.elements.count - 1 : c.elements.count)
}
}
}
}
extension BTree.Index: Comparable {
public static func ==(left: BTree<Element>.Index, right: BTree<Element>.Index) -> Bool {
BTree<Element>.Index.validate(left, right)
return left.current == right.current
}
public static func <(left: BTree<Element>.Index, right: BTree<Element>.Index) -> Bool {
BTree<Element>.Index.validate(left, right)
switch (left.current.value, right.current.value) {
case let (a?, b?): return a < b
case (nil, _): return false
default: return true
}
}
}
extension BTree: SortedSet {
public var startIndex: Index { return Index(startOf: self) }
public var endIndex: Index { return Index(endOf: self) }
public subscript(index: Index) -> Element {
index.validate(for: root)
return index.current.value!
}
public func formIndex(after i: inout Index) {
i.validate(for: root)
i.formSuccessor()
}
public func formIndex(before i: inout Index) {
i.validate(for: root)
i.formPredecessor()
}
public func index(after i: Index) -> Index {
i.validate(for: root)
var i = i
i.formSuccessor()
return i
}
public func index(before i: Index) -> Index {
i.validate(for: root)
var i = i
i.formPredecessor()
return i
}
}
extension BTree {
public var count: Int {
return root.count
}
}
extension BTree.Node {
var count: Int {
return children.reduce(elements.count) { $0 + $1.count }
}
}
extension BTree {
public struct Iterator: IteratorProtocol {
let tree: BTree
var index: Index
init(_ tree: BTree) {
self.tree = tree
self.index = tree.startIndex
}
public mutating func next() -> Element? {
guard let result = index.current.value else { return nil }
index.formSuccessor()
return result
}
}
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
| 27.340741 | 109 | 0.577621 |
56e1ff2e9cd9dd3804b811a11157146058078e97 | 503 | //
// ViewController.swift
// TumblrApp
//
// Created by Seaon Shin on 5/20/18.
// Copyright © 2018 Seaon Shin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.346154 | 80 | 0.666004 |
fe69d4fa42b5c9d6e64eb8a47259eea74b5acd3d | 835 | //
// SettingViewController.swift
// Mah Income
//
// Created by Van Luu on 4/24/17.
// Copyright © 2017 Van Luu. All rights reserved.
//
import UIKit
class SettingViewController: 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 23.194444 | 105 | 0.691018 |
cc44e6ecd270416db7887b83b7f3feb630f21b1d | 1,245 | //
// SPLarkSettingsHeaderView.swift
// lark-controller
//
// Created by solo on 2021/5/8.
// Copyright © 2021 Ivan Vorobei. All rights reserved.
//
import UIKit
class SPLarkSettingsHeaderView: UICollectionReusableView {
let lblTitle = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.purple
// Customize here
// 为什么这种就可以直接添加 uistackview
// 如果用 xib 直接拖动的话,直接报错,missing constraints
// 当然这里也可以完全不用添加 uistackview,直接加 label 也可以的
let container = UIStackView()
self.addSubview(container)
container.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints([
container.topAnchor.constraint(equalTo: self.topAnchor),
container.bottomAnchor.constraint(equalTo: self.bottomAnchor),
container.leadingAnchor.constraint(equalTo: self.leadingAnchor),
container.trailingAnchor.constraint(equalTo: self.trailingAnchor),
])
lblTitle.textColor = UIColor.label
container.addArrangedSubview(lblTitle)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 28.953488 | 78 | 0.658635 |
d5888866c88aad5e63b9cc15f34fa8302cd3aba8 | 2,827 | //
// LogLineNamespace.swift
// HSTracker
//
// Created by Benjamin Michotte on 11/08/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
enum LogLineNamespace: String {
case achievements = "Achievements",
adTracking = "AdTracking",
all = "All",
arena = "Arena",
asset = "Asset",
biReport = "BIReport",
battleNet = "BattleNet",
becca = "Becca",
ben = "Ben",
bob = "Bob",
brian = "Brian",
bugReporter = "BugReporter",
cameron = "Cameron",
cardbackMgr = "CardbackMgr",
changedCards = "ChangedCards",
clientRequestManager = "ClientRequestManager",
configFile = "ConfigFile",
crafting = "Crafting",
dbfXml = "DbfXml",
deckHelper = "DeckHelper",
deckRuleset = "DeckRuleset",
deckTray = "DeckTray",
decks = "Decks",
derek = "Derek",
deviceEmulation = "DeviceEmulation",
downloader = "Downloader",
endOfGame = "EndOfGame",
eventTiming = "EventTiming",
faceDownCard = "FaceDownCard",
fullScreenFX = "FullScreenFX",
gameMgr = "GameMgr",
graphics = "Graphics",
hand = "Hand",
healthyGaming = "HealthyGaming",
henry = "Henry",
innKeepersSpecial = "InnKeepersSpecial",
jMac = "JMac",
jay = "Jay",
josh = "Josh",
kyle = "Kyle",
loadingScreen = "LoadingScreen",
mike = "Mike",
mikeH = "MikeH",
missingAssets = "MissingAssets",
net = "Net",
packet = "Packet",
party = "Party",
playErrors = "PlayErrors",
power = "Power",
raf = "RAF",
rachelle = "Rachelle",
reset = "Reset",
robin = "Robin",
ryan = "Ryan",
sound = "Sound",
spectator = "Spectator",
store = "Store",
updateManager = "UpdateManager",
userAttention = "UserAttention",
yim = "Yim",
zone = "Zone"
static func usedValues() -> [LogLineNamespace] {
return [.power, .rachelle, .arena, .loadingScreen, .decks, .fullScreenFX]
}
static func allValues() -> [LogLineNamespace] {
return [.achievements, .adTracking, .all, .arena, .asset, .biReport, .battleNet, .becca,
.ben, .bob, .brian, .bugReporter, .cameron, .cardbackMgr, .changedCards,
.clientRequestManager, .configFile, .crafting, .dbfXml, .deckHelper, .deckRuleset,
.deckTray, .derek, .deviceEmulation, .downloader, .endOfGame, .eventTiming,
.faceDownCard, .fullScreenFX, .gameMgr, .graphics, .hand, .healthyGaming, .henry,
.innKeepersSpecial, .jMac, .jay, .josh, .kyle, .loadingScreen, .mike, .mikeH,
.missingAssets, .net, .packet, .party, .playErrors, .power, .raf, .rachelle, .reset,
.robin, .ryan, .sound, .spectator, .store, .updateManager, .userAttention,
.yim, .zone]
}
}
| 31.411111 | 100 | 0.599222 |
d7b8d6788eba5dfb2fb318cdf6734a3d3d0584df | 526 | //
// Created by Przemysław Pająk on 14.01.2018.
// Copyright (c) 2018 FEARLESS SPIDER. All rights reserved.
//
import Foundation
import Alamofire
import Crashlytics
import SwiftyJSON
protocol HomeView: class {
}
protocol HomePresenter {
var router: HomeViewRouter { get }
}
class HomePresenterImplementation: HomePresenter {
fileprivate weak var view: HomeView?
let router: HomeViewRouter
init(view: HomeView, router: HomeViewRouter) {
self.view = view
self.router = router
}
} | 15.939394 | 59 | 0.709125 |
48d273d22c916693eceb892fb108d1806d8bd476 | 2,172 | //
// AppDelegate.swift
// tippy
//
// Created by Christopher Kim on 12/23/18.
// Copyright © 2018 Grace Liu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.212766 | 285 | 0.754604 |
183ed130bd27b5683697a77ea71568bd496255f7 | 885 | //
// PreworkTests.swift
// PreworkTests
//
// Created by Akku on 1/31/21.
//
import XCTest
@testable import Prework
class PreworkTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.029412 | 111 | 0.659887 |
3364068af45b8f6b46bd0e4dcc887fe94676e7ad | 485 | // 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
enum B : AnyObject, Any)):
struct Q<T where B : A.<S : b : a {
var _ = f(i: Int -> [""
| 40.416667 | 79 | 0.71134 |
ddb62f663c3113fad8b6f18e43f74181a64395da | 1,324 | //
// ItemRow.swift
// SimpleShoppingList
//
// Created by Jarek Dereszowski on 24/06/2019.
// Copyright © 2019 Jarek Dereszowski. All rights reserved.
//
import SwiftUI
struct ItemRow : View {
@State var item: Item
var body: some View {
Button(action: {
self.item.done.toggle()
}) {
HStack {
VStack(alignment: .leading) {
Text(self.item.name)
.font(.headline)
.strikethrough(self.item.done)
.foregroundColor(self.item.done ? .secondary : .primary)
Text("\(self.item.quantity)")
.font(.subheadline)
.strikethrough(self.item.done)
.foregroundColor(self.item.done ? .secondary : .primary)
}
Spacer()
if self.item.done {
Image(systemName: "checkmark.circle")
.foregroundColor(.secondary)
} else {
Image(systemName: "circle")
}
}
}
}
}
#if DEBUG
struct ItemRow_Previews : PreviewProvider {
static var previews: some View {
ItemRow(item: Item(name: "example", quantity: 2))
}
}
#endif
| 27.583333 | 80 | 0.481118 |
4bfb3b6bbdffec0ddd7af53353d3e23cf149833c | 363 | //
// Article.swift
// Medly
//
// Created by Vlad Z. on 3/23/21.
//
import Foundation
struct Country: Codable, Hashable {
let name: String
let alpha2Code: String
let capital: String
let population: Int
let timezones: [String]
var imageULR: URL {
URL(string: "https://www.countryflags.io/\(alpha2Code)/flat/64.png")!
}
}
| 17.285714 | 77 | 0.628099 |
e40bb5d79e90ee86a6bbc5ec7040314ccef67ce5 | 613 | //
// CCBorderRadius.swift
// clz
//
// Created by cc on 2021/8/5.
//
import UIKit
public func CC_ViewBorder(_ view: UIView, _ borderWidth: CGFloat, _ borderColor: UIColor) {
view.layer.borderWidth = borderWidth
view.layer.borderColor = borderColor.cgColor
}
public func CC_ViewRadius(_ view: UIView, _ radius: CGFloat) {
view.layer.cornerRadius = radius
view.layer.masksToBounds = true
}
public func CC_ViewBorderRadius(_ view: UIView, _ borderWidth: CGFloat, _ borderColor: UIColor, _ radius: CGFloat) {
CC_ViewRadius(view, radius)
CC_ViewBorder(view, borderWidth, borderColor)
}
| 25.541667 | 116 | 0.730832 |
224bdad19fa19faf1e8284cd4a1d1ce30123724b | 3,408 | //
// BDButton.swift
// Orbit Defense
//
// Created by jason kim on 8/16/18.
// Copyright © 2018 jason kim. All rights reserved.
//
import Foundation
import SpriteKit
class BDButton: SKNode {
var button: SKShapeNode
private var mask: SKShapeNode
//private var cropNode: SKCropNode
private var action: () -> Void
var isEnabled = true
init(buttonText: String, screenWidth: CGFloat, buttonAction: @escaping() -> Void, enabled: Bool){
button = SKShapeNode(rectOf: CGSize(width: screenWidth/4, height: scsize.height/14),cornerRadius: screenWidth/40)
button.fillColor = SKColor.white
let label = SKLabelNode(fontNamed: "AppleSDGothicNeo-Light")
label.text = buttonText
label.fontSize = screenWidth/40
label.fontColor = SKColor.black
label.position = CGPoint(x: 0, y: -scsize.height/140)
button.addChild(label)
mask = SKShapeNode(rectOf: CGSize(width: screenWidth/4, height: scsize.height/14),cornerRadius: screenWidth/40)
mask.fillColor = SKColor.black
mask.alpha = 0
mask.zPosition = 3
//cropNode = SKCropNode()
//cropNode.maskNode = button
//cropNode.zPosition = 3
//cropNode.addChild(mask)
action = buttonAction
super.init()
isUserInteractionEnabled = true
setupNode()
addNodes()
if(!enabled)
{
disable()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupNode() {
button.zPosition = 0
}
func addNodes() {
addChild(button)
//addChild(cropNode)
addChild(mask)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if isEnabled {
mask.alpha = 0.5
run(SKAction.scale(by: 1.05, duration: 0.05))
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if isEnabled {
for touch in touches {
let location: CGPoint = touch.location(in: self)
if button.contains(location) {
mask.alpha = 0.5
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if isEnabled {
for touch in touches {
let location: CGPoint = touch.location(in: self)
if button.contains(location) {
disable()
action()
run(SKAction.sequence([SKAction.wait(forDuration: 0.2), SKAction.run({
self.enable()
})]))
run(SKAction.scale(by: 1/1.05, duration: 0.05))
}
else{
mask.alpha = 0.0
run(SKAction.scale(by: 1/1.05, duration: 0.05))
}
}
}
}
func disable() {
isEnabled = false
mask.alpha = 0.0
button.alpha = 0.5
}
func enable() {
isEnabled = true
mask.alpha = 0.0
button.alpha = 1.0
}
deinit{
print("deinit bdbutton")
}
}
| 26.015267 | 121 | 0.519366 |
9c40487d98de2292304b4004e83b4d1407b83ac0 | 2,086 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// Applied to `HBRequest` before it is dealt with by the router. Middleware passes the processed request onto the next responder
/// (either the next middleware or the router) by calling `next.apply(to: request)`. If you want to shortcut the request you
/// can return a response immediately
///
/// Middleware is added to the application by calling `app.middleware.add(MyMiddleware()`.
///
/// Middleware allows you to process a request before it reaches your request handler and then process the response
/// returned by that handler.
/// ```
/// func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse> {
/// let request = processRequest(request)
/// return next.respond(to: request).map { response in
/// return processResponse(response)
/// }
/// }
/// ```
/// Middleware also allows you to shortcut the whole process and not pass on the request to the handler
/// ```
/// func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse> {
/// if request.method == .OPTIONS {
/// return request.success(HBResponse(status: .noContent))
/// } else {
/// return next.respond(to: request)
/// }
/// }
/// ```
public protocol HBMiddleware {
func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse>
}
struct MiddlewareResponder: HBResponder {
let middleware: HBMiddleware
let next: HBResponder
func respond(to request: HBRequest) -> EventLoopFuture<HBResponse> {
return self.middleware.apply(to: request, next: self.next)
}
}
| 37.927273 | 129 | 0.649569 |
7aa9e632d2be5f08a205907e73d978ed8080aca8 | 2,294 | //
// SceneDelegate.swift
// TicTacToe
//
// Created by Marcin Kessler on 14.01.21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.283019 | 147 | 0.713165 |
b90054c5cfdf7441bacb641a50b9f72e522e647c | 461 |
public func getVersion() -> Int {
#if BEFORE
return 0
#else
return 1
#endif
}
#if BEFORE
@_fixed_layout
public struct AddInitializer {
public var x: Int
// This could be @inlinable, but we want to force inlining to take place
// at -Onone to get better test coverage.
@_transparent
public init() {
self.x = 0
}
}
#else
@_fixed_layout
public struct AddInitializer {
public var x: Int = 0
@_transparent
public init() {}
}
#endif
| 13.171429 | 74 | 0.67462 |
208813bb6c118363f40729f7dbc3a33e08f57e68 | 660 | import Foundation
// https://www.europeandataportal.eu/data/en/dataset/stazioni-bikesharing-trentino
class TrentinoBikeStationServiceFactory {
private static let endpoints = [
"lavis",
"mezzocorona",
"mezzolombardo",
"pergine_valsugana",
"rovereto",
"sanmichelealladige",
"trento"
]
private static let baseEndpoint = "https://os.smartcommunitylab.it/core.mobility/bikesharing/"
static func get() -> [BikeStationService] {
return endpoints
.compactMap { URL(string: "\(baseEndpoint)\($0)") }
.compactMap { TrentinoBikeStationService(url: $0) }
}
}
| 26.4 | 98 | 0.636364 |
de9fd967c07c31817056c0112c46f70902007633 | 4,615 | //
// AppDelegate.swift
// CoreDataEntityFromCSV
//
// Created by Rahul Nair on 05/02/18.
// Copyright © 2018 Rahul Nair. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDataEntityFromCSV")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 49.095745 | 285 | 0.688624 |
8a5df6887187767edd6acb98bd823028d0e07710 | 379 | //
// Geometry.swift
// StellarJay
//
// Created by Stadelman, Stan on 8/15/18.
// Copyright © 2018 sstadelman. All rights reserved.
//
import Foundation
public class Geometry: GeoJSON {
enum CodingKeys: String, CodingKey {
case coordinates
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
| 18.047619 | 57 | 0.641161 |
fca4db4987dca3d88e9552f47af59a17fa7f2aa0 | 7,763 | //
// TLIEditTaskViewController.swift
// Tinylog
//
// Created by Spiros Gerokostas on 18/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
class TLIEditTaskViewController: UIViewController {
var indexPath:NSIndexPath?
var task:TLITask?
var textView:UITextView?
var keyboardRect:CGRect?
var delegate:TLIEditTaskViewControllerDelegate?
var tagsView:TLITagsView?
var saveOnClose:Bool = true
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Edit Task"
self.view.backgroundColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Close", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TLIEditTaskViewController.close(_:)))
let reminderButton:UIButton = UIButton(frame: CGRectMake(0.0, 0.0, 22.0, 22.0))
reminderButton.setBackgroundImage(UIImage(named: "728-clock-toolbar"), forState: UIControlState.Normal)
reminderButton.addTarget(self, action: #selector(TLIEditTaskViewController.displayReminder(_:)), forControlEvents: UIControlEvents.TouchUpInside)
let reminderBarButtonItem:UIBarButtonItem = UIBarButtonItem(customView: reminderButton)
let saveBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TLIEditTaskViewController.save(_:)))
self.navigationItem.rightBarButtonItems = [saveBarButtonItem, reminderBarButtonItem]
textView = UITextView(frame: CGRectZero)
textView?.autocorrectionType = UITextAutocorrectionType.Yes
textView?.bounces = true
textView?.alwaysBounceVertical = true
textView?.text = task?.displayLongText
textView?.textColor = UIColor.tinylogTextColor()
textView?.font = UIFont.tinylogFontOfSize(17.0)
self.view.addSubview(textView!)
let keyboardBar:TLIKeyboardBar = TLIKeyboardBar(frame: CGRectMake(0.0, 0.0, self.view.bounds.size.width, UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad ? 54.0 : 44.0))
keyboardBar.keyInputView = textView
textView?.inputAccessoryView = keyboardBar
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLIEditTaskViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLIEditTaskViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo!
keyboardRect = self.view.convertRect(userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)!.CGRectValue, fromView: nil)
let duration:Double = userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey)!.doubleValue
layoutTextView(duration)
}
func keyboardWillHide(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo!
keyboardRect = CGRectZero
let size:CGSize = self.view.bounds.size
var heightAdjust:CGFloat
if(UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
heightAdjust = 2.0
} else {
heightAdjust = keyboardRect!.size.height
}
let textViewHeight = size.height - heightAdjust //- 44.0
UIView.animateWithDuration(NSTimeInterval(userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey)!.floatValue), delay: NSTimeInterval(0.0), options: [UIViewAnimationOptions.CurveEaseInOut,UIViewAnimationOptions.AllowUserInteraction], animations: { () -> Void in
self.textView?.frame = CGRectMake(0.0, 0.0, size.width, textViewHeight)
return
}, completion: { (finished:Bool) -> Void in
})
}
func close(sender:UIButton) {
saveOnClose = false
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
func save(sender:UIButton) {
saveOnClose = true
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
UIView.animateWithDuration(duration, delay: 0.0,
options: .AllowUserInteraction, animations: {
self.layoutTextView(duration)
}, completion: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
keyboardRect = CGRectZero
layoutTextView(0.0)
textView?.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
hideKeyboard()
if saveOnClose {
task?.displayLongText = textView!.text
//Update notification
if let _ = task?.notification {
task!.notification!.displayText = task!.displayLongText
task!.notification!.fireDate = task!.reminder!
task!.notification!.updatedAt = NSDate()
}
let cdc:TLICDController = TLICDController.sharedInstance
let total:NSString = textView!.text
let words:NSArray = total.componentsSeparatedByString(" ")
for word in words {
let t = word as! NSString
if t.hasPrefix("#") {
let value:NSString = t.substringWithRange(NSMakeRange(1, t.length - 1))
let tagModel:TLITag = TLITag.existing(value, context: cdc.context!)!
let tags:NSMutableSet = task?.valueForKeyPath("tags") as! NSMutableSet
tags.addObject(tagModel)
} else if t.hasPrefix("@") {
let value:NSString = t.substringWithRange(NSMakeRange(1, t.length - 1))
let mention:TLIMention = TLIMention.existing(value, context: cdc.context!)!
let mentions:NSMutableSet = task?.valueForKeyPath("mentions") as! NSMutableSet
mentions.addObject(mention)
}
}
cdc.backgroundSaveContext()
delegate?.onClose(self, indexPath: indexPath!)
}
}
func layoutTextView(duration:NSTimeInterval) {
let size:CGSize = self.view.bounds.size
var heightAdjust:CGFloat
if(UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
heightAdjust = 2.0
} else {
heightAdjust = keyboardRect!.size.height
}
let textViewHeight = size.height - heightAdjust //- 44.0
UIView.animateWithDuration(NSTimeInterval(duration), delay: NSTimeInterval(0.0), options: [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.AllowUserInteraction], animations: { () -> Void in
self.textView?.frame = CGRectMake(0.0, 0.0, size.width, textViewHeight)
return
}, completion: { (finished:Bool) -> Void in
})
}
func hideKeyboard() {
self.view.endEditing(true)
}
func displayReminder(button:UIButton) {
let viewController:TLIReminderViewController = TLIReminderViewController()
viewController.task = task
self.navigationController?.pushViewController(viewController, animated: true)
}
}
| 44.107955 | 275 | 0.656834 |
feeb53ce9dd5ade75972a6d1683c8e6a2179c591 | 795 | import Foundation
public enum Error: Swift.Error {
case imageMapping(Response)
case jsonMapping(Response)
case stringMapping(Response)
case statusCode(Response)
case data(Response)
case underlying(Swift.Error)
case requestMapping(String)
}
public extension Moya.Error {
/// Depending on error type, returns a `Response` object.
var response: Moya.Response? {
switch self {
case .imageMapping(let response): return response
case .jsonMapping(let response): return response
case .stringMapping(let response): return response
case .statusCode(let response): return response
case .data(let response): return response
case .underlying: return nil
case .requestMapping: return nil
}
}
}
| 29.444444 | 61 | 0.683019 |
11769becb14056a3c0b8806f1b6e4bf8171ea1d7 | 1,574 | //
// Extensions.swift
// IngenicoConnectKit
//
// Created for Ingenico ePayments on 15/12/2016.
// Copyright © 2016 Global Collect Services. All rights reserved.
//
import Foundation
extension String {
subscript (i: Int) -> String {
return self[Range(i ..< i + 1)]
}
func substring(from: Int) -> String {
return self[Range(min(from, count) ..< count)]
}
func substring(to: Int) -> String {
return self[Range(0 ..< max(0, to))]
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(count, r.lowerBound)),
upper: min(count, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
public func base64URLDecode() -> Data {
let underscoreReplaced = self.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let modulo = self.count % 4
var paddingAdded = underscoreReplaced
if modulo == 2 {
paddingAdded += "=="
} else if modulo == 3 {
paddingAdded += "="
}
return self.decode(paddingAdded)
}
public func decode(_ string: String? = nil) -> Data {
if let str = string {
return Data(base64Encoded: str)!
}
return Data(base64Encoded: self)!
}
}
| 28.107143 | 85 | 0.547014 |
dddc5e8ae25fde175750c645c303d39a19b45727 | 4,625 | //
// AppDelegate.swift
// LoSelf
//
// Created by Dzy on 26/07/2017.
// Copyright © 2017 Dzy. All rights reserved.
//
import UIKit
import CoreData
@available(iOS 10.0, *)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "LoSelf")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 48.177083 | 285 | 0.684973 |
486b535a5b3ac504c227436fbe856bc357730020 | 3,392 | //
// Copyright © 2018 Frollo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class PropertyListPersistence: PreferencesPersistence {
private let preferencesPath: URL
private var lock = NSLock()
private var needsPersistence = false
private var preferencesData = [String: Any]()
init(path: URL) {
self.preferencesPath = path
loadPreferences()
}
internal subscript(key: String) -> Any? {
get {
defer { lock.unlock() }
lock.lock()
return preferencesData[key]
}
set {
setValue(newValue, for: key)
}
}
func setValue(_ value: Any?, for key: String) {
defer { lock.unlock() }
lock.lock()
if !needsPersistence {
needsPersistence = true
DispatchQueue.global(qos: .utility).async { [weak self] in
self?.synchroniseIfNeeded()
}
}
preferencesData[key] = value
}
internal func reset() {
resetPreferences()
}
internal func synchronise() {
savePreferences()
}
// MARK: - Monitoring Persistence
private func synchroniseIfNeeded() {
if needsPersistence {
savePreferences()
}
}
// MARK: - Persistence
private func loadPreferences() {
defer { lock.unlock() }
lock.lock()
do {
let data = try Data(contentsOf: preferencesPath)
if let prefData = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] {
preferencesData = prefData
} else {
preferencesData = [:]
}
} catch {
error.logError()
}
}
private func savePreferences() {
defer { lock.unlock() }
lock.lock()
needsPersistence = false
do {
let data = try PropertyListSerialization.data(fromPropertyList: preferencesData, format: .xml, options: 0)
do {
try data.write(to: preferencesPath)
} catch {
error.logError()
}
} catch {
error.logError()
}
}
private func resetPreferences() {
defer { lock.unlock() }
lock.lock()
preferencesData = [:]
if FileManager.default.fileExists(atPath: preferencesPath.path) {
do {
try FileManager.default.removeItem(at: preferencesPath)
} catch {
error.logError()
}
}
}
}
| 24.941176 | 130 | 0.528892 |
e03b0e51984e8fe6cf10fe3f88720ffac62d5a0f | 2,003 | //
// CarViewController.swift
// Demo
//
// Created by Dal Rupnik on 23/05/16.
// Copyright © 2016 Unified Sense. All rights reserved.
//
import UIKit
import ViewModelable
class CarViewController: ModelableViewController<CarViewModel> {
//
// MARK: - Outlets
//
@IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet private weak var topLabel: UILabel!
@IBOutlet private weak var bottomLabel: UILabel!
//
// MARK: - ViewModelObservable
//
override func viewModelDidSetup(viewModel: CarViewModel) {
super.viewModelDidSetup(viewModel: viewModel)
//
// Called once after viewDidLoad, view model will be in .setuped state.
//
print("[+] ViewModel: \(viewModel) did setup.")
update()
}
override func viewModelDidLoad(viewModel: CarViewModel) {
super.viewModelDidLoad(viewModel: viewModel)
//
// Can be called anytime after viewWillAppear (asychronously) and can be called multiple times.
//
print("[+] ViewModel: \(viewModel) did load.")
update()
}
override func viewModelDidUpdate(viewModel: CarViewModel, updates: [String : Any]) {
super.viewModelDidUpdate(viewModel: viewModel, updates: updates)
//
// Can be called anytime after viewModelDidLoad is called and can be called multiple times.
//
}
override func viewModelDidUnload(viewModel: CarViewModel) {
super.viewModelDidUnload(viewModel: viewModel)
//
// Will be called after viewWillDisappear, view model transitioned to .setuped state.
//
}
//
// MARK: Private Methods
//
func update() {
topLabel.text = viewModel.carDescription
bottomLabel.text = viewModel.engineDescription
activityIndicatorView.isHidden = !viewModel.loading
}
}
| 26.355263 | 103 | 0.622566 |
e87c260ec00021054bb2328b659b643fed81fec8 | 866 | // Copyright © 2019 Optimove. All rights reserved.
import Foundation
public struct NetworkResponse<Body> {
let statusCode: Int
let body: Body
}
public extension NetworkResponse where Body == Data? {
func decode<BodyType: Decodable>(to type: BodyType.Type) throws -> BodyType {
let data = try unwrap()
return try JSONDecoder().decode(BodyType.self, from: data)
}
func unwrap() throws -> Data {
guard let data = body else {
throw NetworkError.noData
}
return data
}
var description: String {
do {
let body = try unwrap()
guard let decodedBody = String(data: body, encoding: .utf8) else {
return "no body"
}
return decodedBody
} catch {
return error.localizedDescription
}
}
}
| 23.405405 | 81 | 0.578522 |
e983b5f9ce8dbaf1dcd2450019ab85be73fc6640 | 1,756 | //
// PasswordOps.swift
// ios-tester
//
// This is a Swift wrapper for the external C wrapper for the Rust static library.
// Making this a separate class allows for better error handling and isolation,
// as well as the ability to do automated testing.
//
import Foundation
enum PasswordError: Error {
case notFound
case notString(Data)
case unexpected(OSStatus)
}
class PasswordOps {
static func setPassword(service: String, user: String, password: String) throws {
let status = KeyringSetPassword(service as CFString, user as CFString, password as CFString)
guard status == errSecSuccess else {
throw PasswordError.unexpected(status)
}
}
static func getPassword(service: String, user: String) throws -> String {
var result: CFData?
let status = KeyringCopyPassword(service as CFString, user as CFString, &result)
switch status {
case errSecSuccess, errSecDecode:
let data = result! as Data
if let password = String.init(bytes: data, encoding: .utf8) {
return password
} else {
throw PasswordError.notString(data)
}
case errSecItemNotFound:
throw PasswordError.notFound
default:
throw PasswordError.unexpected(status)
}
}
static func deletePassword(service: String, user: String) throws {
let status = KeyringDeletePassword(service as CFString, user as CFString)
switch status {
case errSecSuccess:
return
case errSecItemNotFound:
throw PasswordError.notFound
default:
throw PasswordError.unexpected(status)
}
}
}
| 30.807018 | 100 | 0.634396 |
e438d3e061f6b8c252f78d09f9da21f526edc6c3 | 976 | //: ## TDD In Swift Playgrounds
//:
//: Wouldn’t it be really cool if somehow you could write your code in a Playground alongside the unit tests which validate the code. That way, once you’ve finished your class you could move the code and the tests back into your app, and get the best of both worlds!
//: First: make sure you import XCTest:
import XCTest
//: The actual unit tests look an awful lot like, well, unit tests. For instance, a standard XCTestCase subclass which contains a failing test:
class MyTests : XCTestCase {
func testShouldFail() {
XCTFail("You must fail to succeed!")
}
func testShouldPass() {
XCTAssertEqual(2+2, 4)
}
}
//: ### Failure Is Not An Option
//:
//: Call the runTests() function, passing in the test class you wish to run (in this case, 'My Tests'. If you wish to see the code for the TestRunner, it's in the Playground Sources directory
TestRunner().runTests(testClass: MyTests.self)
//: [Next](@next)
| 37.538462 | 266 | 0.710041 |
4a27617cb05451ade75d3e7a449bb59bf183160f | 2,881 | //
// KnobRenderer.swift
// KnobControl
//
// Created by dsadaoui on 28/09/2020.
//
import UIKit
class KnobRenderer {
var color: UIColor = .blue {
didSet {
trackLayer.strokeColor = color.cgColor
pointerLayer.strokeColor = color.cgColor
}
}
var lineWidth: CGFloat = 2 {
didSet {
trackLayer.lineWidth = lineWidth
pointerLayer.lineWidth = lineWidth
updateTrackLayerPath()
updatePointerLayerPath()
}
}
var startAngle: CGFloat = CGFloat(-Double.pi) * 11 / 8 {
didSet {
updateTrackLayerPath()
}
}
var endAngle: CGFloat = CGFloat(Double.pi) * 3 / 8 {
didSet {
updateTrackLayerPath()
}
}
var pointerLength: CGFloat = 6 {
didSet {
updateTrackLayerPath()
updatePointerLayerPath()
}
}
private (set) var pointerAngle: CGFloat = CGFloat(-Double.pi) * 11 / 8
func setPointerAngle(_ newPointerAngle: CGFloat, animated: Bool = false) {
CATransaction.begin()
CATransaction.setDisableActions(true)
pointerLayer.transform = CATransform3DMakeRotation(newPointerAngle, 0, 0, 1)
if animated {
let midAngleValue = (max(newPointerAngle, pointerAngle) - min(newPointerAngle, pointerAngle)) / 2 + min(newPointerAngle, pointerAngle)
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.values = [pointerAngle, midAngleValue, newPointerAngle]
animation.keyTimes = [0.0, 0.5, 1.0]
animation.timingFunctions = [CAMediaTimingFunction(name: .easeInEaseOut)]
pointerLayer.add(animation, forKey: nil)
}
CATransaction.commit()
pointerAngle = newPointerAngle
}
let trackLayer = CAShapeLayer()
let pointerLayer = CAShapeLayer()
init() {
trackLayer.fillColor = UIColor.clear.cgColor
pointerLayer.fillColor = UIColor.clear.cgColor
}
private func updateTrackLayerPath() {
let bounds = trackLayer.bounds
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let offset = max(pointerLength, lineWidth / 2)
let radius = min(bounds.width, bounds.height) / 2 - offset
let ring = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
trackLayer.path = ring.cgPath
}
private func updatePointerLayerPath() {
let bounds = trackLayer.bounds
let pointer = UIBezierPath()
pointer.move(to: CGPoint(x: bounds.width - CGFloat(pointerLength) - CGFloat(lineWidth) / 2, y: bounds.midY))
pointer.addLine(to: CGPoint(x: bounds.width, y: bounds.midY))
pointerLayer.path = pointer.cgPath
}
func updateBounds(_ bounds: CGRect) {
trackLayer.bounds = bounds
trackLayer.position = CGPoint(x: bounds.midX, y: bounds.midY)
updateTrackLayerPath()
pointerLayer.bounds = trackLayer.bounds
pointerLayer.position = trackLayer.position
updatePointerLayerPath()
}
}
| 27.438095 | 140 | 0.689691 |
cc5a1cd719c307d66a109cf03cd37582dc6132af | 2,183 | //
// Movie.swift
// movietime
//
// Created by Adilet on 6/2/20.
// Copyright © 2020 Adilet. All rights reserved.
//
import Foundation
struct Movie {
var id: Int?
var title: String?
var posterPath: String?
var backdropPath: String?
var rating: Double?
var duration: Int?
var genres: [String]?
var releaseDate: String?
var budget: Int?
var revenue: Int?
var description: String?
func getReleaseDate() -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd, yyyy"
if let relDate = releaseDate {
if let date = dateFormatterGet.date(from: relDate) {
return dateFormatterPrint.string(from: date)
}
}
return releaseDate!
}
func getGenresList() -> String {
var list = ""
if let glist = genres {
for g in glist {
list += g + " "
}
}
return list
}
var durationString: String {
var dur = ""
if let minutes = duration {
let hours = minutes / 60
let mins = minutes % 60
dur = "\(hours) hours \(mins) min"
}
return dur
}
func getMoney() -> [String] {
var br = [String]()
if let b = budget, let r = revenue {
let numberFormatter = NumberFormatter()
numberFormatter.groupingSeparator = ","
numberFormatter.groupingSize = 3
numberFormatter.usesGroupingSeparator = true
numberFormatter.decimalSeparator = "."
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 2
let b = numberFormatter.string(from: NSNumber(value: b))!
let r = numberFormatter.string(from: NSNumber(value: r))!
br.append("$ \(b)")
br.append("$ \(r)")
}
return br
}
}
| 24.52809 | 69 | 0.519469 |
1d87715ec6890282a0d526d82cb2ba3d13394df9 | 318 | //
// ListItemConfiguration.swift
// Pods
//
// Created by Jose Manuel Sánchez Peñarroja on 1/3/16.
//
//
import UIKit
public struct ListItemConfiguration<T: Equatable>: Equatable {
public var backgroundColor: UIColor?
public static var `default`: ListItemConfiguration {
return ListItemConfiguration()
}
}
| 17.666667 | 62 | 0.738994 |
ef5cfeea603cc4000e8c1048a01a1d520af321e0 | 5,023 | //
// TweetViewController.swift
// Graffiti Samples
//
// BSD License
// Copyright © 2018, M8 Labs (m8labs.com). All rights reserved.
//
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import UIKit
import Graffiti
/*
Code setup sample.
Code setup is useful because of easy detection of any API changes.
For clarity here raw strings are used, but for robustness always use #selector to get property names (see below).
TweetViewController.json contains an exact same setup. To check it, comment setup() method below
and set 'restorationIdentifier' of this view controller to 'TweetViewController' in the Interface Builder.
*/
class TweetViewController: ContentViewController {
@IBOutlet var tweetButton: UIBarButtonItem!
@IBOutlet var textView: UITextView!
}
extension TweetViewController {
// The rule for this setup is very simple - if you can't repeat it in IB or JSON, then don't write it.
override func setup() {
let tweetAction = BarButtonActionController()
tweetAction.serviceProvider = TwitterService.client
tweetAction.actionName = TwitterAction.tweet.name
tweetAction.form = (view as! FormDisplayView) // don't forget to set custom class for self.view to FormDisplayView
tweetAction.form!.mandatoryFields = [textView] // at least should be one mandatory field
tweetAction.sender = tweetButton
let tweetStatus = ActionStatusController()
tweetStatus.actionName = tweetAction.actionName
tweetStatus.alias = "tweetStatus" // alias to access this object in bindings
tweetStatus.elements = [tweetButton, textView] // these elements will be updated on status changes according to bindings
tweetStatus.errorMessage = NSLocalizedString("Tweet can't be tweeted so far.", comment: "") // show message in case of error
textView.gx_fieldName = "text" // this is form field name "$text" in action "tweet" (without $)
textView.gx.identifier = "\(#selector(getter: TweetViewController.textView))" // "textView", using #selector against typos and changes
// keep textView not editable while operation in progress
textView.gx.addBinding(dictionary: [ObjectAssistant.bindTo: "gx_readOnly", ObjectAssistant.bindFrom: "tweetStatus.inProgress"])
// reset textView value after operation succeeds, and re-assign its own value if isSuccess == 0 (during setup or when failed)
textView.gx.addBinding(dictionary: [BindingOption.predicateFormat.rawValue: "tweetStatus.isSuccess == 1",
BindingOption.valueIfTrue.rawValue: "",
BindingOption.valueIfFalse.rawValue: "$textView.text"])
// disable button while operation in progress
tweetButton.gx.addBinding(dictionary: [ObjectAssistant.bindTo: "gx_disabled", ObjectAssistant.bindFrom: "tweetStatus.inProgress"])
// dissmiss this view controller on success
self.gx.addBinding(dictionary: [ObjectAssistant.bindTo: "gx_dismissed", ObjectAssistant.bindFrom: "tweetStatus.isSuccess"])
self.objects = [tweetAction, tweetStatus]
super.setup() // Ready set Go!
}
}
extension TweetViewController {
// override func outlet(_ object: NSObject, addedTo: NSObject, propertyKey: String, outletKey: String) {
// print((addedTo.gx.identifier ?? "<unknown>") + "." + propertyKey + " = " + outletKey)
// }
//
// override func assigned(to target: NSObject, with identifier: String?, keyPath: String, source: NSObject, value: Any?, valueType: String, binding: NSObject) {
// print("\(identifier ?? "<unknown>").\(keyPath) = \(value ?? "nil")")
// }
}
| 52.322917 | 163 | 0.710532 |
ff7b27323ea3245d65f6beb2563ce898b44c3d5e | 1,963 | //
// Newspaper.swift
// Otec
//
// Copyright (c) 2016 Inaka - http://inaka.net/
//
// 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 Jayme
import SwiftyJSON
struct Newspaper: Identifiable {
let id: String
let newspaperDescription: String
}
extension Newspaper: DictionaryInitializable, DictionaryRepresentable {
init(dictionary: [String: AnyObject]) throws {
let json = JSON(dictionary)
guard let
id = json["name"].string,
description = json["description"].string
else { throw JaymeError.ParsingError }
self.id = id
self.newspaperDescription = description
}
var dictionaryValue: [String: AnyObject] {
return [
"name": self.id,
"description": self.newspaperDescription
]
}
}
extension String: CustomStringConvertible { public var description: String { return self } }
| 35.690909 | 92 | 0.709628 |
fb8871cb32227d6828eacbe0e3a5d5245d05d235 | 5,865 | /// The type of a path extension (e.g. 'txt' of 'file.txt').
public typealias PathExtension = String
/// A generic protocol around a path. Currently, there are two conformances, `AbsolutePath` and `RelativePath`.
/// It is strongly discouraged to declare new conformances to this protocol. They're not guaranteed to work as expected.
public protocol PathProtocol: Hashable {
/// The string reprensentation of the path this conformance represents.
var pathString: String { get }
/// The last component of this path.
var lastPathComponent: PathComponent? { get }
/// The extension of the last component of this path.
var lastPathExtension: PathExtension? { get }
/// Creates a new path by parsing the given string.
/// - Parameter pathString: The path string to parse into a path.
init(pathString: String)
/// Returns the current path.
static var current: Self { get }
/// Checks whether the receiver is a sub-path of the given absolute path.
/// - Parameter other: The absolute path, which should be checked for being a parent path of the receiver.
func isSubpath(of other: AbsolutePath) -> Bool
/// Checks whether the receiver is a sub-path of the given relative path.
/// - Parameter other: The relative path, which should be checked for being a parent path of the receiver.
func isSubpath(of other: RelativePath) -> Bool
/// Appends a relative path to the receiver.
/// - Parameter other: The relative path to append to the receiver.
mutating func append(_ other: RelativePath)
/// Returns a new path which has `other` appended to the receiver.
/// - Parameter other: The relative path to append to the reciever.
func appending(_ other: RelativePath) -> Self
/// Appends the path components, taken from each element of the sequence of path component convertible objects, to the receiver.
/// - Parameter pathComponents: The sequence of path component convertible objects, whose path components to append to the receiver.
mutating func append<Components>(pathComponents: Components) where Components: Sequence, Components.Element == PathComponentConvertible
/// Returns a new path by appending the path components, taken from each element of the sequence of path component convertible objects, to the receiver.
/// - Parameter pathComponents: The sequence of path component convertible objects, whose path components to append to the receiver and return.
func appending<Components>(pathComponents: Components) -> Self where Components: Sequence, Components.Element == PathComponentConvertible
/// Appends a path extension to the last component of the receiver.
/// - Parameter pathExtension: The extension to append to the last component of the receiver.
/// - Note: If the path has no components, this method does nothing.
mutating func append(pathExtension: PathExtension)
/// Returns a new path by appending the given path extension the last component of the receiver.
/// - Parameter pathExtension: The extension to append to the last component of the receiver.
/// - Note: If the path has no components, this method returns the unchanged receiver.
func appending(pathExtension: PathExtension) -> Self
/// Removes the last path component of the reciever.
mutating func removeLastPathComponent()
/// Returns a new path which has the last path component of the receiver removed.
func removingLastPathComponent() -> Self
/// Removes the last extension of the last component of the receiver.
mutating func removeLastPathExtension()
/// Returns a new path that has the last extension from the last component of the receiver removed.
func removingLastPathExtension() -> Self
}
extension PathProtocol where Self: CustomStringConvertible {
/// See `CustomStringConvertible.description`
@inlinable
public var description: String { pathString }
}
extension PathProtocol where Self: LosslessStringConvertible {
/// See `LosslessStringConvertible.init(_:)`
/// - Parameter description: See `LosslessStringConvertible.init(_:)`
@inlinable
public init?(_ description: String) {
self.init(pathString: description)
}
}
extension PathProtocol where Self: CustomDebugStringConvertible {
/// See `CustomDebugStringConvertible.debugDescription`
public var debugDescription: String { "[\(Self.self)]: \(pathString)" }
}
extension PathProtocol {
/// Appends the path components, taken from each element of the variadic list of path component convertible objects, to the receiver.
/// - Parameter pathComponents: The variadic list of path component convertible objects, whose path components to append to the receiver.
@inlinable
public mutating func append(pathComponents: PathComponentConvertible...) {
append(pathComponents: pathComponents)
}
/// Returns a new path by appending the path components, taken from each element of the variadic list of path component convertible objects, to the receiver.
/// - Parameter pathComponents: The variadic list of path component convertible objects, whose path components to append to the receiver and return.
@inlinable
public func appending(pathComponents: PathComponentConvertible...) -> Self {
appending(pathComponents: pathComponents)
}
}
extension PathProtocol {
/// Conveniently forms a path by appending the path component of a path component convertible object to an existing path.
/// - Parameters:
/// - lhs: The existing path to append the path component to.
/// - rhs: The path component convertible object to append the path component to.
@inlinable
public static func / <Component: PathComponentConvertible> (lhs: Self, rhs: Component) -> Self {
lhs.appending(pathComponents: rhs)
}
}
| 53.807339 | 161 | 0.736061 |
7ab84b9f2bc047b2b063f681eaf420d777f251c6 | 427 | //
// QrScannerViewModel.swift
// mamba
//
// Created by Armand Kamffer on 2020/08/21.
// Copyright © 2020 Armand Kamffer. All rights reserved.
//
import Foundation
class QrScannerViewModel: ObservableObject {
let scanInterval: Double = 1.0
@Published var torchIsOn: Bool = false
@Published var lastQrCode: String = ""
func onFoundQrCode(_ code: String) {
self.lastQrCode = code
}
}
| 20.333333 | 57 | 0.667447 |
fb3f10474fe9015d861e55b78148d635f5b2a942 | 1,539 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.github.io/JSQWebViewController
//
//
// GitHub
// https://github.com/jessesquires/JSQWebViewController
//
//
// License
// Copyright (c) 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
import JSQWebViewController
final class ViewController: UITableViewController {
let url = URL(string: "http://jessesquires.com")!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isTranslucent = true
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .automatic
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 2 {
return
}
let webVC = WebViewController(url: url)
switch indexPath.row {
case 0:
navigationController?.pushViewController(webVC, animated: true)
case 1:
let nav = UINavigationController(rootViewController: webVC)
present(nav, animated: true, completion: nil)
default: break
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let webViewController = segue.destination as? WebViewController
webViewController?.urlRequest = URLRequest(url: url)
}
}
| 25.65 | 92 | 0.65822 |
d56bd894f980bfcf936eff473ffeb6511bc1194c | 1,541 | //
// ViewController.swift
// Prework
//
// Created by Yong Seok Lee on 2/2/22.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billAmountTextField: UITextField!
@IBOutlet weak var tipAmountLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipSlider: UISlider!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var tipPercentage: UILabel!
@IBAction func calculateTip(_ sender: Any) {
let bill = Float(billAmountTextField.text!) ?? 0
let tipPercentages = tipSlider.value
tipPercentage.text = String(format: "%.0f%%", tipPercentages * 100)
let tip = bill * tipPercentages
let total = bill + tip
tipAmountLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
@IBAction func calculateTipSlider(_ sender: Any) {
let bill = Double(billAmountTextField.text!) ?? 0
let tipPercentages = [0.15, 0.18, 0.2]
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
tipAmountLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 23 | 75 | 0.580143 |
62bb03dd8ffd1aff6d1af29d59ca653240c5e20e | 5,704 | //
// SpinnerView.swift
// SpinnerView
//
// Created by Igor Kotkovets on 4/15/20.
//
import Foundation
import UIKit
import os.log
import RxSwift
import RxCocoa
@IBDesignable public class SpinnerView: UIView {
@IBInspectable dynamic public var lineColor: UIColor = UIColor.red {
didSet {
animatedLayer.strokeColor = lineColor.cgColor
}
}
@IBInspectable public var lineWidth: CGFloat = 4 {
didSet {
updateLayerPosition()
}
}
@IBInspectable public var animationDuration: CFTimeInterval = 4
private var isAnimatingInternal: Bool = false
@IBInspectable public var isAnimating: Bool {
get {
return isAnimatingInternal
}
set {
isAnimatingInternal = newValue
self.animatedLayer.isHidden = !isAnimatingInternal;
if isAnimatingInternal {
startAnimation()
}
else {
stopAnimation()
}
}
}
var angleRad: CGFloat = (330*2*CGFloat.pi/360)
var angleDegree: CGFloat = 330 {
didSet {
angleRad = 2*CGFloat.pi*angleDegree/360
updateLayerPosition()
}
}
var outLog = OSLog(subsystem: "SpinnerView", category: String(describing: self))
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
layer.isHidden = !isAnimatingInternal
}
override public class var layerClass: AnyClass {
return CAShapeLayer.self
}
override public func layoutSubviews() {
super.layoutSubviews()
updateLayerPosition()
}
public override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
updateLayerPosition()
}
override public func prepareForInterfaceBuilder() {
animatedLayer.path = UIBezierPath(ovalIn: circleFrame).cgPath
updateLayerPosition()
prepareLayerForAnimation()
}
var animatedLayer: CAShapeLayer {
return layer as! CAShapeLayer
}
var circleFrame: CGRect {
return bounds.insetBy(dx: lineWidth/2, dy: lineWidth/2)
}
func updateLayerPosition() {
let radius = (bounds.size.width-lineWidth)/2
let center = CGPoint(x: bounds.width/2, y: bounds.height/2)
let path = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: 0,
endAngle: angleRad,
clockwise: true)
animatedLayer.path = path.cgPath
}
func updateAnimationState() {
if isAnimating {
startAnimation()
}
}
let STROKE_ANIMATION_KEY = "animatingStrokeStart"
let ROTATION_ANIMATION_KEY = "animatingRotate"
func startAnimation() {
prepareLayerForAnimation()
if animatedLayer.animation(forKey: STROKE_ANIMATION_KEY) == nil {
forwardAnimation()
}
if animatedLayer.animation(forKey: ROTATION_ANIMATION_KEY) == nil {
rotateAnimation()
}
}
private func prepareLayerForAnimation() {
animatedLayer.fillColor = UIColor.clear.cgColor
animatedLayer.strokeStart = 0
animatedLayer.strokeColor = lineColor.cgColor
animatedLayer.lineWidth = lineWidth
}
func forwardAnimation() {
CATransaction.begin()
let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
strokeEnd.fromValue = 0
strokeEnd.toValue = 1
strokeEnd.duration = animationDuration/2
strokeEnd.fillMode = .forwards
strokeEnd.isRemovedOnCompletion = false
strokeEnd.timingFunction = CAMediaTimingFunction(name: .linear)
CATransaction.setCompletionBlock{ [weak self] in
guard self?.isAnimating == true else { return }
self?.reverseAnimation()
}
animatedLayer.add(strokeEnd, forKey: STROKE_ANIMATION_KEY)
CATransaction.commit()
}
fileprivate func rotateAnimation() {
CATransaction.begin()
let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
rotate.fromValue = 0
rotate.toValue = 2*CGFloat.pi
rotate.repeatCount = MAXFLOAT
rotate.autoreverses = false
rotate.duration = animationDuration/4
animatedLayer.add(rotate, forKey: ROTATION_ANIMATION_KEY)
CATransaction.commit()
}
func reverseAnimation() {
CATransaction.begin()
let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
strokeEnd.fromValue = animatedLayer.presentation()?.strokeEnd
strokeEnd.toValue = 0
strokeEnd.duration = animationDuration/2
strokeEnd.fillMode = .forwards
strokeEnd.isRemovedOnCompletion = false
strokeEnd.timingFunction = CAMediaTimingFunction(name: .easeIn)
CATransaction.setCompletionBlock{ [weak self] in
guard self?.isAnimating == true else { return }
self?.forwardAnimation()
}
animatedLayer.add(strokeEnd, forKey: STROKE_ANIMATION_KEY)
CATransaction.commit()
}
func stopAnimation() {
animatedLayer.removeAnimation(forKey: ROTATION_ANIMATION_KEY)
animatedLayer.removeAnimation(forKey: STROKE_ANIMATION_KEY)
}
}
extension Reactive where Base: SpinnerView {
public var isAnimating: Binder<Bool> {
return Binder(self.base) { view, isAnimating in
view.isAnimating = isAnimating
}
}
}
| 29.102041 | 84 | 0.624474 |
e0a796ec180634e59cc2e93a68cf3075e7a03cbf | 1,998 | //
// Example4ViewController.swift
// JHPlaceUIView-UIViewExtension
//
// Created by Jonathan Hoche on 02/02/2017.
// Copyright © 2017 Jonathan Hoche. All rights reserved.
//
import UIKit
class Example4ViewController: UIViewController {
@IBOutlet weak var orange: UIView!
@IBOutlet weak var white: UIView!
@IBOutlet weak var red: UIView!
@IBOutlet weak var yellow: UIView!
@IBOutlet weak var brown: UIView!
@IBOutlet weak var black1: UIView!
@IBOutlet weak var black2: UIView!
@IBOutlet weak var green: UIView!
@IBOutlet weak var blue: UIView!
@IBOutlet weak var pink: UIView!
override func viewDidLoad() {
super.viewDidLoad()
UIView.animate(withDuration: 3) {
self.orange.placeInCenterOfSuperView()
self.white.placeInCenter(of: self.orange)
self.red.placeInMidX(of: self.white)
self.red.placeInTop(of: self.white)
self.blue.placeInLeft(of: self.white)
self.blue.placeOnBottom(of: self.red)
self.black1.placeInRight(of: self.white)
self.black1.placeOnBottom(of: self.red)
self.yellow.placeOnLeft(of: self.black1)
self.yellow.placeOnBottom(of: self.red)
//
//
self.brown.placeOnRight(of: self.blue)
self.brown.placeInBottom(of: self.white)
self.black2.placeOnRight(of: self.blue)
self.black2.placeOnTop(of: self.brown)
self.pink.placeOnRight(of: self.black2)
self.pink.placeOnBottom(of: self.yellow)
self.green.placeOnRight(of: self.pink)
self.green.placeOnTop(of: self.brown)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 29.820896 | 58 | 0.59009 |
e4be37a6d011b483083405b317c5c3bff90a7cdd | 2,189 | //
// CustomImageCropperOverlayView.swift
// Demo
//
// Created by Artem Krachulov on 11/28/16.
// Copyright © 2016 Artem Krachulov. All rights reserved.
//
import Foundation
import AKImageCropperView
final class CustomImageCropperOverlayView: AKImageCropperOverlayView {
private func drawCycleInCornerView(_ view: UIView, inTouchView touchView: UIView, forState state: AKImageCropperCropViewTouchState) {
var color: UIColor
var width: CGFloat
if state == .normal {
color = configuraiton.corner.normalLineColor
width = configuraiton.corner.normalLineWidth
} else {
color = configuraiton.corner.highlightedLineColor
width = configuraiton.corner.highlightedLineWidth
}
let layer: CAShapeLayer = view.layer.sublayers!.first as! CAShapeLayer
let circlePath = UIBezierPath(
arcCenter: CGPoint(x: touchView.bounds.midX, y: touchView.bounds.midY),
radius: width,
startAngle: 0.0,
endAngle: CGFloat(Double.pi * 2),
clockwise: true)
layer.path = circlePath.cgPath
layer.fillColor = color.cgColor
layer.strokeColor = color.cgColor
}
override func layoutTopLeftCornerView(_ view: UIView, inTouchView touchView: UIView, forState state: AKImageCropperCropViewTouchState) {
drawCycleInCornerView(view, inTouchView: touchView, forState: state)
}
override func layoutTopRightCornerView(_ view: UIView, inTouchView touchView: UIView, forState state: AKImageCropperCropViewTouchState) {
drawCycleInCornerView(view, inTouchView: touchView, forState: state)
}
override func layoutBottomLeftCornerView(_ view: UIView, inTouchView touchView: UIView, forState state: AKImageCropperCropViewTouchState) {
drawCycleInCornerView(view, inTouchView: touchView, forState: state)
}
override func layoutBottomRightCornerView(_ view: UIView, inTouchView touchView: UIView, forState state: AKImageCropperCropViewTouchState) {
drawCycleInCornerView(view, inTouchView: touchView, forState: state)
}
}
| 39.089286 | 144 | 0.698492 |
bbcad0d4740d7dcf6b0392d2a9dbec5d3f4596ff | 1,714 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift
// RUN: %target-build-swift -module-name main -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s --color
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574
// UNSUPPORTED: OS=windows-msvc
import Distributed
import FakeDistributedActorSystems
typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem
distributed actor Greeter {
distributed func echo(name: String) -> String {
return "Echo: \(name)"
}
}
func test() async throws {
let system = DefaultDistributedActorSystem()
let local = Greeter(actorSystem: system)
let ref = try Greeter.resolve(id: local.id, using: system)
let reply = try await ref.echo(name: "Caplin")
// CHECK: >> remoteCall: on:main.Greeter, target:main.Greeter.echo(name:), invocation:FakeInvocationEncoder(genericSubs: [], arguments: ["Caplin"], returnType: Optional(Swift.String), errorType: nil), throwing:Swift.Never, returning:Swift.String
// CHECK: << remoteCall return: Echo: Caplin
print("reply: \(reply)")
// CHECK: reply: Echo: Caplin
}
@main struct Main {
static func main() async {
try! await test()
}
}
| 36.468085 | 247 | 0.745624 |
14d346aad130cae959b9c11df40f52549a43c2e1 | 917 | // Copyright (c) 2020 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
protocol PartitionedByDay {
var day: Date? { get set }
}
| 36.68 | 63 | 0.748092 |
1e9fddc4b6a2eddf7e7f4d6f5ac3727f7b989604 | 582 | import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let viewController = UIViewController()
viewController.view.backgroundColor = .white
window?.rootViewController = viewController
window?.makeKeyAndVisible()
return true
}
func hello() -> String {
"AppDelegate.hello()"
}
}
| 29.1 | 127 | 0.689003 |
710f6c8224c987917592abc71399e74d638476df | 1,015 | import UIKit
class BlueView: UIViewController {
var viewModel: BlueViewModelProtocol?
@IBOutlet weak var text: UILabel!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
@IBAction func buttonPressed(_ sender: Any) {
viewModel?.showYellowView()
}
}
// MARK: - View setup
extension BlueView {
func setupView() {
guard let viewModel = viewModel else {
return
}
title = viewModel.title
text.text = viewModel.text
button.setTitle(viewModel.buttonTitle, for: .normal)
view.backgroundColor = UIColor(
red: CGFloat(viewModel.color.red),
green: CGFloat(viewModel.color.green),
blue: CGFloat(viewModel.color.blue),
alpha: 255.0)
}
}
// MARK: - Creating instances
extension BlueView {
static func create() -> BlueView {
return BlueView(nibName: "BlueView", bundle: Bundle.main)
}
}
| 22.555556 | 65 | 0.615764 |
9c96fcbdadc334dd873d868bac67d60255aaee87 | 1,956 | //
// SliderCell.swift
// ControllerApp
//
// Created by Galvin on 2020/3/9.
// Copyright © 2020 GalvinLi. All rights reserved.
//
import Cocoa
class SliderCell: NSSliderCell {
override func drawKnob(_ knobRect: NSRect) {
let bg = NSBezierPath(roundedRect: knobRect,
xRadius: knobRect.width * 0.5,
yRadius: knobRect.height * 0.5)
let color = AppState.isDarkMode ? NSColor(0xfafeff) : NSColor(0x9f9f9f)
color.setFill()
bg.fill()
}
override func knobRect(flipped: Bool) -> NSRect {
let orgRect = super.knobRect(flipped: flipped)
let knobRadius: CGFloat = 4
let value = CGFloat((self.doubleValue - self.minValue) / (self.maxValue - self.minValue))
let rect = NSRect(x: (orgRect.minX + 3) + value * (orgRect.width - 12),
y: orgRect.midY - knobRadius,
width: knobRadius * 2,
height: knobRadius * 2)
return rect
}
override func drawBar(inside rect: NSRect, flipped: Bool) {
var rect = rect
rect.size.height = 4
rect.size.width += 2
let barRadius: CGFloat = 2
let value = CGFloat((self.doubleValue - self.minValue) / (self.maxValue - self.minValue))
let finalWidth: CGFloat = value * (self.controlView!.bounds.size.width - 12) + 4
var leftRect = rect
leftRect.size.width = finalWidth
let bg = NSBezierPath(roundedRect: rect, xRadius: barRadius, yRadius: barRadius)
let bgColor = AppState.isDarkMode ? NSColor(0x1c5773) : NSColor(0xe1e5e7)
bgColor.setFill()
bg.fill()
let active = NSBezierPath(roundedRect: leftRect, xRadius: barRadius, yRadius: barRadius)
let activeColor = AppState.isDarkMode ? NSColor(0x7ec3ec) : NSColor(0x0081bb)
activeColor.setFill()
active.fill()
}
}
| 36.222222 | 97 | 0.595092 |
d5d96caeac8e76d0d1c47aa555b7e775cf87d7b4 | 1,195 | //MIT License
//
//Copyright (c) 2017 Corey Schaf @ Rogue Bit Studios (roguebit.io)
//
//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
internal class Router {
}
| 42.678571 | 80 | 0.769874 |
ff8968261c2b07e5bec80d5a0a44c2a5e2ca7762 | 284 | internal class InternalClass {}
private struct PrivateStruct {}
// public var publicTuple: (first: InternalClass, second: PrivateStruct) = (InternalClass(), PrivateStruct())
private var privateTuple: (first: InternalClass, second: PrivateStruct) = (InternalClass(), PrivateStruct())
| 47.333333 | 109 | 0.774648 |
d9b098b354b6232740950a367dc9114e041c1ace | 2,319 | //
// MeetingView.swift
// ScrumDinger
//
// Created by Ronak Harkhani on 20/03/21.
//
import SwiftUI
import AVFoundation
struct MeetingView: View {
@Binding var scrum: DailyScrum
// StateObject means the view owns the source of truth for the object
// The objects lifecycle is tied to the view's lifecycle
@StateObject var scrumTimer = ScrumTimer()
private let speechRecognizer = SpeechRecognizer()
@State private var isRecording = false
@State private var transcript = ""
var player: AVPlayer {
return AVPlayer.sharedDingPlayer
}
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 16.0)
.fill(scrum.color)
VStack {
MeetingHeaderView(secondsElapsed: scrumTimer.secondsElapsed,
secondsRemaining: scrumTimer.secondsRemaining,
scrumColor: scrum.color)
MeetingTimerView(speakers: scrumTimer.speakers, isRecording: isRecording, scrumColor: scrum.color)
MeetingFooterView(speakers: scrumTimer.speakers, skipAction: scrumTimer.skipSpeaker)
}
}
.padding()
.foregroundColor(scrum.color.accessibleFontColor)
.onAppear {
scrumTimer.reset(lengthInMinutes: scrum.lengthInMinutes, attendees: scrum.attendees)
scrumTimer.speakerChangedAction = {
player.seek(to: .zero)
player.play()
}
speechRecognizer.record(to: $transcript)
isRecording = true
scrumTimer.startScrum()
}
.onDisappear {
scrumTimer.stopScrum()
speechRecognizer.stopRecording()
isRecording = false
let newHistory = History(attendees: scrum.attendees,
lengthInMinutes: scrumTimer.secondsElapsed / 60,
transcript: transcript)
scrum.history.insert(newHistory, at: 0)
}
}
}
struct MeetingView_Previews: PreviewProvider {
static var previews: some View {
MeetingView(scrum: .constant(DailyScrum.previewData[0]))
}
}
| 31.337838 | 114 | 0.576973 |
db92e12d05c7dec6c99199ec35648a215efa6000 | 4,797 | //
// Created on 07/11/2020.
// Copyright © 2020 Nanoray. All rights reserved.
//
#if canImport(Foundation)
import Foundation
import KokoroUtils
import ObjectiveC
public struct InMemoryCacheOptions {
public enum Validity {
public enum InvalidationOrder {
case byStorageDate, byAccessDate
}
case forever
case afterStorage(_ time: TimeInterval)
case afterAccess(_ time: TimeInterval)
public var invalidationOrder: InvalidationOrder {
switch self {
case .forever, .afterStorage:
return .byStorageDate
case .afterAccess:
return .byAccessDate
}
}
}
public var validity: Validity
public var entryCountLimit: Int?
public var totalSizeLimit: Int?
public init(validity: Validity = .forever, entryCountLimit: Int? = nil, totalSizeLimit: Int? = nil) {
self.validity = validity
self.entryCountLimit = entryCountLimit
self.totalSizeLimit = totalSizeLimit
}
}
public class InMemoryCache<Key: Hashable, Value>: Cache {
private class Entry {
let key: Key
let value: Value
let size: Int
var invalidationDate: Date?
init(key: Key, value: Value, size: Int, validUntil: Date?) {
self.key = key
self.value = value
self.size = size
invalidationDate = validUntil
}
}
public var options = InMemoryCacheOptions(
validity: .afterAccess(5 * 60), // 5 minutes
totalSizeLimit: Int(ProcessInfo.processInfo.physicalMemory / 4) // 25% of available RAM
)
private let scheduler: Scheduler
private let sizeFunction: (Value) -> Int
private let lock = ObjcLock()
private var entries = [Key: Entry]()
private var entriesSortedByInvalidationDate = SortedArray<Entry>(comparator: {
switch ($0.invalidationDate, $1.invalidationDate) {
case let (.some(lhs), .some(rhs)):
return lhs < rhs
case (.some, _):
return true
case (_, _):
return false
}
})
private var scheduledInvalidation: (key: Key, workItem: DispatchWorkItem)?
private var currentSize = 0
public init(scheduler: Scheduler = DispatchQueue.global(qos: .background), sizeFunction: @escaping (Value) -> Int) {
self.scheduler = scheduler
self.sizeFunction = sizeFunction
}
public func value(for key: Key) -> Value? {
return lock.acquireAndRun {
if let entry = entries[key] {
if case let .afterAccess(time) = options.validity {
if let index = entriesSortedByInvalidationDate.firstIndex(where: { $0.key == entry.key }) {
entriesSortedByInvalidationDate.remove(at: index)
}
entry.invalidationDate = scheduler.currentDate.addingTimeInterval(time)
entriesSortedByInvalidationDate.insert(entry)
scheduleInvalidation()
}
return entry.value
}
return nil
}
}
public func store(_ value: Value, for key: Key) {
lock.acquireAndRun {
invalidateValue(for: key)
let size = sizeFunction(value)
if let entryCountLimit = self.options.entryCountLimit, entries.count >= entryCountLimit {
invalidateValue(for: entriesSortedByInvalidationDate.first!.key)
}
if let totalSizeLimit = self.options.totalSizeLimit {
while !entries.isEmpty && currentSize + size > totalSizeLimit {
invalidateValue(for: entriesSortedByInvalidationDate.first!.key)
}
}
let invalidationDate: Date?
switch self.options.validity {
case .forever:
invalidationDate = nil
case let .afterAccess(time), let .afterStorage(time):
invalidationDate = scheduler.currentDate.addingTimeInterval(time)
}
let entry = Entry(key: key, value: value, size: size, validUntil: invalidationDate)
entries[key] = entry
entriesSortedByInvalidationDate.insert(entry)
currentSize += size
if entry.invalidationDate != nil {
scheduleInvalidation()
}
}
}
public func invalidateValue(for key: Key) {
lock.acquireAndRun {
if let entry = entries.removeValue(forKey: key) {
entriesSortedByInvalidationDate.remove(at: entriesSortedByInvalidationDate.firstIndex(where: { $0.key == key })!)
currentSize -= entry.size
}
scheduleInvalidation()
}
}
public func invalidateAllValues() {
lock.acquireAndRun {
entries.removeAll()
entriesSortedByInvalidationDate.removeAll()
currentSize = 0
scheduleInvalidation()
}
}
private func scheduleInvalidation() {
lock.acquireAndRun {
scheduledInvalidation?.workItem.cancel()
scheduledInvalidation = nil
guard let entry = entriesSortedByInvalidationDate.first, let invalidationDate = entry.invalidationDate else { return }
let workItem = DispatchWorkItem { [weak self, key = entry.key] in
self?.invalidateValue(for: key)
}
scheduledInvalidation = (key: entry.key, workItem: workItem)
scheduler.schedule(at: invalidationDate, execute: workItem)
}
}
public static func == (lhs: InMemoryCache<Key, Value>, rhs: InMemoryCache<Key, Value>) -> Bool {
return lhs === rhs
}
}
#endif
| 27.889535 | 121 | 0.719825 |
fee59026c96e45f0e34b5deae125480171762c81 | 4,509 | //
// AppDelegate.swift
// Game Detail
//
// Created by Andy Walters on 12/11/19.
// Copyright © 2019 Andy Walt. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
/* for checking font list
for family in UIFont.familyNames.sorted() {
let names = UIFont.fontNames(forFamilyName: family)
print("Family: \(family) Font names: \(names)")
} */
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.titleTextAttributes = [.font : UIFont(name: "PressStart2p", size: 20)!, .foregroundColor : UIColor(red: 248/255, green: 189/255, blue: 0/255, alpha: 1.0)]
navigationBarAppearace.largeTitleTextAttributes = [.font : UIFont(name: "PressStart2p", size: 20)!]
navigationBarAppearace.tintColor = UIColor(red: 248/255, green: 189/255, blue: 0/255, alpha: 1.0)
navigationBarAppearace.barTintColor = .black
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Game_Goals")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 44.643564 | 199 | 0.660013 |
5d5ba4e785d5294c424836165f8049a47e45f062 | 1,203 | //
// SafariView.swift
// Construct
//
// Created by Thomas Visser on 25/02/2020.
// Copyright © 2020 Thomas Visser. All rights reserved.
//
import Foundation
import SwiftUI
import SafariServices
import ComposableArchitecture
final class SafariView: UIViewControllerRepresentable {
let url: URL
init(url: URL) {
self.url = url
}
func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
return SFSafariViewController(url: url)
}
func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SafariView>) {
}
}
struct SafariViewState: Hashable, Codable, Identifiable {
let url: URL
var id: URL { url }
static let nullInstance = SafariViewState(url: URL(fileURLWithPath: "/"))
}
extension SafariViewState: NavigationStackItemState {
var navigationStackItemStateId: String {
"safariView:\(url.absoluteString)"
}
var navigationTitle: String {
"Safari"
}
}
extension SafariView {
convenience init(store: Store<SafariViewState, Void>) {
self.init(url: ViewStore(store).url)
}
}
| 22.698113 | 136 | 0.714048 |
d9d60647a327b2d4b38721e5b793baa36e3e32b4 | 4,031 | //
// TealInfo.swift
// WJRH
//
// Created by Eric Weber on 6/28/16.
// Copyright © 2016 Eric Weber. All rights reserved.
//
import Foundation
class TealInfo {
var currentSongName = ""
var currentArtist = ""
var currentShowName = ""
var currentDJName = ""
private var urlSession = NSURLSession.sharedSession()
var programs: [String: TealProgram] = [:]
init(imageLoadCallback: ((Void) -> Void)?) {
reloadCurrentMetaData()
let request = urlSession.dataTaskWithURL(NSURL(string: "https://api.teal.cool/organizations/wjrh/")!) { (data, response, error) -> Void in
do {
if let dataUnwrapped = data {
let resultAsJson = try NSJSONSerialization.JSONObjectWithData(dataUnwrapped, options: .AllowFragments)
for i in 0..<resultAsJson.count {
//print(resultAsJson[i]["name"]!!)
let showName = String(resultAsJson[i]["name"]!!)
let showShortName = String(resultAsJson[i]["shortname"]!!)
let showAuthor = String(resultAsJson[i]["author"]!!)
var showTime = ""
if let showTimeFromRequest = resultAsJson[i]["scheduled_time"]! {
showTime = String(showTimeFromRequest)
}
var showDescription = ""
if let showDescriptionFromRequest = resultAsJson[i]["description"]! {
showDescription = String(showDescriptionFromRequest)
}
let showImageUrl = String(resultAsJson[i]["image"]!!)
self.programs[showName] = TealProgram(name: showName, shortName: showShortName, author: showAuthor, time: showTime, description: showDescription, imageURL: showImageUrl, imageLoadCallback: imageLoadCallback, urlSession: self.urlSession)
}
}
} catch {
print("Error loading log.")
}
}
request.resume()
}
func reloadCurrentMetaData() {
let request = urlSession.dataTaskWithURL(NSURL(string: "https://api.teal.cool/organizations/wjrh/latest")!) { (data, response, error) -> Void in
do {
if let dataUnwrapped = data {
let resultAsJson = try NSJSONSerialization.JSONObjectWithData(dataUnwrapped, options: .AllowFragments)
if let event = resultAsJson["event"]! {
let eventString = String(event)
if eventString == "episode-start" {
self.currentShowName = String(resultAsJson["program"]!!["name"]!!)
self.currentDJName = String(resultAsJson["program"]!!["author"]!!)
self.currentSongName = ""
self.currentArtist = ""
} else if eventString == "track-log" {
//self.currentShowName = String(resultAsJson["program"]!!["name"]!!)
//self.currentDJName = String(resultAsJson["program"]!!["author"]!!)
self.currentSongName = String(resultAsJson["track"]!!["title"]!!)
self.currentArtist = String(resultAsJson["track"]!!["artist"]!!)
} else if eventString == "episode-end" {
self.currentShowName = "WJRH Playlist"
self.currentDJName = "WJRH Robo DJ"
self.currentSongName = ""
self.currentArtist = ""
}
}
}
} catch {
print("Error loading log.")
}
}
request.resume()
}
} | 45.806818 | 260 | 0.494914 |
db9f495a33175bfae723a6a135e649cac238eafa | 52,176 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// The type of all `channelInitializer` callbacks.
internal typealias ChannelInitializerCallback = (Channel) -> EventLoopFuture<Void>
/// Common functionality for all NIO on sockets bootstraps.
internal enum NIOOnSocketsBootstraps {
internal static func isCompatible(group: EventLoopGroup) -> Bool {
return group is SelectableEventLoop || group is MultiThreadedEventLoopGroup
}
}
/// A `ServerBootstrap` is an easy way to bootstrap a `ServerSocketChannel` when creating network servers.
///
/// Example:
///
/// ```swift
/// let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
/// defer {
/// try! group.syncShutdownGracefully()
/// }
/// let bootstrap = ServerBootstrap(group: group)
/// // Specify backlog and enable SO_REUSEADDR for the server itself
/// .serverChannelOption(ChannelOptions.backlog, value: 256)
/// .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
///
/// // Set the handlers that are applied to the accepted child `Channel`s.
/// .childChannelInitializer { channel in
/// // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
/// channel.pipeline.addHandler(BackPressureHandler()).flatMap { () in
/// // make sure to instantiate your `ChannelHandlers` inside of
/// // the closure as it will be invoked once per connection.
/// channel.pipeline.addHandler(MyChannelHandler())
/// }
/// }
///
/// // Enable SO_REUSEADDR for the accepted Channels
/// .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
/// .childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16)
/// .childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator())
/// let channel = try! bootstrap.bind(host: host, port: port).wait()
/// /* the server will now be accepting connections */
///
/// try! channel.closeFuture.wait() // wait forever as we never close the Channel
/// ```
///
/// The `EventLoopFuture` returned by `bind` will fire with a `ServerSocketChannel`. This is the channel that owns the listening socket.
/// Each time it accepts a new connection it will fire a `SocketChannel` through the `ChannelPipeline` via `fireChannelRead`: as a result,
/// the `ServerSocketChannel` operates on `Channel`s as inbound messages. Outbound messages are not supported on a `ServerSocketChannel`
/// which means that each write attempt will fail.
///
/// Accepted `SocketChannel`s operate on `ByteBuffer` as inbound data, and `IOData` as outbound data.
public final class ServerBootstrap {
private let group: EventLoopGroup
private let childGroup: EventLoopGroup
private var serverChannelInit: Optional<ChannelInitializerCallback>
private var childChannelInit: Optional<ChannelInitializerCallback>
@usableFromInline
internal var _serverChannelOptions: ChannelOptions.Storage
@usableFromInline
internal var _childChannelOptions: ChannelOptions.Storage
/// Create a `ServerBootstrap` on the `EventLoopGroup` `group`.
///
/// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `ServerBootstrap` is
/// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by
/// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:childGroup:)` for a fallible initializer for
/// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with.
public convenience init(group: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) else {
preconditionFailure("ServerBootstrap is only compatible with MultiThreadedEventLoopGroup and " +
"SelectableEventLoop. You tried constructing one with \(group) which is incompatible.")
}
self.init(validatingGroup: group, childGroup: group)!
}
/// Create a `ServerBootstrap` on the `EventLoopGroup` `group` which accepts `Channel`s on `childGroup`.
///
/// The `EventLoopGroup`s `group` and `childGroup` must be compatible, otherwise the program will crash.
/// `ServerBootstrap` is compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by
/// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:childGroup:)` for a fallible initializer for
/// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with.
/// - childGroup: The `EventLoopGroup` to run the accepted `SocketChannel`s on.
public convenience init(group: EventLoopGroup, childGroup: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) && NIOOnSocketsBootstraps.isCompatible(group: childGroup) else {
preconditionFailure("ServerBootstrap is only compatible with MultiThreadedEventLoopGroup and " +
"SelectableEventLoop. You tried constructing one with group: \(group) and " +
"childGroup: \(childGroup) at least one of which is incompatible.")
}
self.init(validatingGroup: group, childGroup: childGroup)!
}
/// Create a `ServerBootstrap` on the `EventLoopGroup` `group` which accepts `Channel`s on `childGroup`, validating
/// that the `EventLoopGroup`s are compatible with `ServerBootstrap`.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use for the `bind` of the `ServerSocketChannel` and to accept new `SocketChannel`s with.
/// - childGroup: The `EventLoopGroup` to run the accepted `SocketChannel`s on. If `nil`, `group` is used.
public init?(validatingGroup group: EventLoopGroup, childGroup: EventLoopGroup? = nil) {
let childGroup = childGroup ?? group
guard NIOOnSocketsBootstraps.isCompatible(group: group) && NIOOnSocketsBootstraps.isCompatible(group: childGroup) else {
return nil
}
self.group = group
self.childGroup = childGroup
self._serverChannelOptions = ChannelOptions.Storage()
self._childChannelOptions = ChannelOptions.Storage()
self.serverChannelInit = nil
self.childChannelInit = nil
self._serverChannelOptions.append(key: ChannelOptions.tcpOption(.tcp_nodelay), value: 1)
}
/// Initialize the `ServerSocketChannel` with `initializer`. The most common task in initializer is to add
/// `ChannelHandler`s to the `ChannelPipeline`.
///
/// The `ServerSocketChannel` uses the accepted `Channel`s as inbound messages.
///
/// - note: To set the initializer for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelInitializer`.
///
/// - parameters:
/// - initializer: A closure that initializes the provided `Channel`.
public func serverChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self {
self.serverChannelInit = initializer
return self
}
/// Initialize the accepted `SocketChannel`s with `initializer`. The most common task in initializer is to add
/// `ChannelHandler`s to the `ChannelPipeline`. Note that if the `initializer` fails then the error will be
/// fired in the *parent* channel.
///
/// - warning: The `initializer` will be invoked once for every accepted connection. Therefore it's usually the
/// right choice to instantiate stateful `ChannelHandler`s within the closure to make sure they are not
/// accidentally shared across `Channel`s. There are expert use-cases where stateful handler need to be
/// shared across `Channel`s in which case the user is responsible to synchronise the state access
/// appropriately.
///
/// The accepted `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages.
///
/// - parameters:
/// - initializer: A closure that initializes the provided `Channel`.
public func childChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self {
self.childChannelInit = initializer
return self
}
/// Specifies a `ChannelOption` to be applied to the `ServerSocketChannel`.
///
/// - note: To specify options for the accepted `SocketChannel`s, look at `ServerBootstrap.childChannelOption`.
///
/// - parameters:
/// - option: The option to be applied.
/// - value: The value for the option.
@inlinable
public func serverChannelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self {
self._serverChannelOptions.append(key: option, value: value)
return self
}
/// Specifies a `ChannelOption` to be applied to the accepted `SocketChannel`s.
///
/// - parameters:
/// - option: The option to be applied.
/// - value: The value for the option.
@inlinable
public func childChannelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self {
self._childChannelOptions.append(key: option, value: value)
return self
}
/// Specifies a timeout to apply to a bind attempt. Currently unsupported.
///
/// - parameters:
/// - timeout: The timeout that will apply to the bind attempt.
public func bindTimeout(_ timeout: TimeAmount) -> Self {
return self
}
/// Bind the `ServerSocketChannel` to `host` and `port`.
///
/// - parameters:
/// - host: The host to bind on.
/// - port: The port to bind on.
public func bind(host: String, port: Int) -> EventLoopFuture<Channel> {
return bind0 {
return try SocketAddress.makeAddressResolvingHost(host, port: port)
}
}
/// Bind the `ServerSocketChannel` to `address`.
///
/// - parameters:
/// - address: The `SocketAddress` to bind on.
public func bind(to address: SocketAddress) -> EventLoopFuture<Channel> {
return bind0 { address }
}
/// Bind the `ServerSocketChannel` to a UNIX Domain Socket.
///
/// - parameters:
/// - unixDomainSocketPath: The _Unix domain socket_ path to bind to. `unixDomainSocketPath` must not exist, it will be created by the system.
public func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel> {
return bind0 {
try SocketAddress(unixDomainSocketPath: unixDomainSocketPath)
}
}
/// Bind the `ServerSocketChannel` to a UNIX Domain Socket.
///
/// - parameters:
/// - unixDomainSocketPath: The _Unix domain socket_ path to bind to. `unixDomainSocketPath` must not exist, it will be created by the system.
/// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `path`.
public func bind(unixDomainSocketPath: String, cleanupExistingSocketFile: Bool) -> EventLoopFuture<Channel> {
if cleanupExistingSocketFile {
do {
try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath)
} catch {
return group.next().makeFailedFuture(error)
}
}
return self.bind(unixDomainSocketPath: unixDomainSocketPath)
}
#if !os(Windows)
/// Use the existing bound socket file descriptor.
///
/// - parameters:
/// - descriptor: The _Unix file descriptor_ representing the bound stream socket.
@available(*, deprecated, renamed: "ServerBootstrap.withBoundSocket(_:)")
public func withBoundSocket(descriptor: CInt) -> EventLoopFuture<Channel> {
return withBoundSocket(descriptor)
}
#endif
/// Use the existing bound socket file descriptor.
///
/// - parameters:
/// - descriptor: The _Unix file descriptor_ representing the bound stream socket.
public func withBoundSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
func makeChannel(_ eventLoop: SelectableEventLoop, _ childEventLoopGroup: EventLoopGroup) throws -> ServerSocketChannel {
return try ServerSocketChannel(socket: socket, eventLoop: eventLoop, group: childEventLoopGroup)
}
return bind0(makeServerChannel: makeChannel) { (eventLoop, serverChannel) in
let promise = eventLoop.makePromise(of: Void.self)
serverChannel.registerAlreadyConfigured0(promise: promise)
return promise.futureResult
}
}
private func bind0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> {
let address: SocketAddress
do {
address = try makeSocketAddress()
} catch {
return group.next().makeFailedFuture(error)
}
func makeChannel(_ eventLoop: SelectableEventLoop, _ childEventLoopGroup: EventLoopGroup) throws -> ServerSocketChannel {
return try ServerSocketChannel(eventLoop: eventLoop,
group: childEventLoopGroup,
protocolFamily: address.protocol)
}
return bind0(makeServerChannel: makeChannel) { (eventLoop, serverChannel) in
serverChannel.registerAndDoSynchronously { serverChannel in
serverChannel.bind(to: address)
}
}
}
private func bind0(makeServerChannel: (_ eventLoop: SelectableEventLoop, _ childGroup: EventLoopGroup) throws -> ServerSocketChannel, _ register: @escaping (EventLoop, ServerSocketChannel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> {
let eventLoop = self.group.next()
let childEventLoopGroup = self.childGroup
let serverChannelOptions = self._serverChannelOptions
let serverChannelInit = self.serverChannelInit ?? { _ in eventLoop.makeSucceededFuture(()) }
let childChannelInit = self.childChannelInit
let childChannelOptions = self._childChannelOptions
let serverChannel: ServerSocketChannel
do {
serverChannel = try makeServerChannel(eventLoop as! SelectableEventLoop, childEventLoopGroup)
} catch {
return eventLoop.makeFailedFuture(error)
}
return eventLoop.submit {
serverChannelOptions.applyAllChannelOptions(to: serverChannel).flatMap {
serverChannelInit(serverChannel)
}.flatMap {
serverChannel.pipeline.addHandler(AcceptHandler(childChannelInitializer: childChannelInit,
childChannelOptions: childChannelOptions),
name: "AcceptHandler")
}.flatMap {
register(eventLoop, serverChannel)
}.map {
serverChannel as Channel
}.flatMapError { error in
serverChannel.close0(error: error, mode: .all, promise: nil)
return eventLoop.makeFailedFuture(error)
}
}.flatMap {
$0
}
}
private class AcceptHandler: ChannelInboundHandler {
public typealias InboundIn = SocketChannel
private let childChannelInit: ((Channel) -> EventLoopFuture<Void>)?
private let childChannelOptions: ChannelOptions.Storage
init(childChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?, childChannelOptions: ChannelOptions.Storage) {
self.childChannelInit = childChannelInitializer
self.childChannelOptions = childChannelOptions
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if event is ChannelShouldQuiesceEvent {
context.channel.close().whenFailure { error in
context.fireErrorCaught(error)
}
}
context.fireUserInboundEventTriggered(event)
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let accepted = self.unwrapInboundIn(data)
let ctxEventLoop = context.eventLoop
let childEventLoop = accepted.eventLoop
let childChannelInit = self.childChannelInit ?? { (_: Channel) in childEventLoop.makeSucceededFuture(()) }
@inline(__always)
func setupChildChannel() -> EventLoopFuture<Void> {
return self.childChannelOptions.applyAllChannelOptions(to: accepted).flatMap { () -> EventLoopFuture<Void> in
childEventLoop.assertInEventLoop()
return childChannelInit(accepted)
}
}
@inline(__always)
func fireThroughPipeline(_ future: EventLoopFuture<Void>) {
ctxEventLoop.assertInEventLoop()
future.flatMap { (_) -> EventLoopFuture<Void> in
ctxEventLoop.assertInEventLoop()
guard !context.pipeline.destroyed else {
return context.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel)
}
context.fireChannelRead(data)
return context.eventLoop.makeSucceededFuture(())
}.whenFailure { error in
ctxEventLoop.assertInEventLoop()
self.closeAndFire(context: context, accepted: accepted, err: error)
}
}
if childEventLoop === ctxEventLoop {
fireThroughPipeline(setupChildChannel())
} else {
fireThroughPipeline(childEventLoop.flatSubmit {
return setupChildChannel()
}.hop(to: ctxEventLoop))
}
}
private func closeAndFire(context: ChannelHandlerContext, accepted: SocketChannel, err: Error) {
accepted.close(promise: nil)
if context.eventLoop.inEventLoop {
context.fireErrorCaught(err)
} else {
context.eventLoop.execute {
context.fireErrorCaught(err)
}
}
}
}
}
private extension Channel {
func registerAndDoSynchronously(_ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
// this is pretty delicate at the moment:
// In many cases `body` must be _synchronously_ follow `register`, otherwise in our current
// implementation, `epoll` will send us `EPOLLHUP`. To have it run synchronously, we need to invoke the
// `flatMap` on the eventloop that the `register` will succeed on.
self.eventLoop.assertInEventLoop()
return self.register().flatMap {
self.eventLoop.assertInEventLoop()
return body(self)
}
}
}
/// A `ClientBootstrap` is an easy way to bootstrap a `SocketChannel` when creating network clients.
///
/// Usually you re-use a `ClientBootstrap` once you set it up and called `connect` multiple times on it.
/// This way you ensure that the same `EventLoop`s will be shared across all your connections.
///
/// Example:
///
/// ```swift
/// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
/// defer {
/// try! group.syncShutdownGracefully()
/// }
/// let bootstrap = ClientBootstrap(group: group)
/// // Enable SO_REUSEADDR.
/// .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
/// .channelInitializer { channel in
/// // always instantiate the handler _within_ the closure as
/// // it may be called multiple times (for example if the hostname
/// // resolves to both IPv4 and IPv6 addresses, cf. Happy Eyeballs).
/// channel.pipeline.addHandler(MyChannelHandler())
/// }
/// try! bootstrap.connect(host: "example.org", port: 12345).wait()
/// /* the Channel is now connected */
/// ```
///
/// The connected `SocketChannel` will operate on `ByteBuffer` as inbound and on `IOData` as outbound messages.
public final class ClientBootstrap: NIOClientTCPBootstrapProtocol {
private let group: EventLoopGroup
private var protocolHandlers: Optional<() -> [ChannelHandler]>
private var _channelInitializer: ChannelInitializerCallback
private var channelInitializer: ChannelInitializerCallback {
if let protocolHandlers = self.protocolHandlers {
return { channel in
self._channelInitializer(channel).flatMap {
channel.pipeline.addHandlers(protocolHandlers(), position: .first)
}
}
} else {
return self._channelInitializer
}
}
@usableFromInline
internal var _channelOptions: ChannelOptions.Storage
private var connectTimeout: TimeAmount = TimeAmount.seconds(10)
private var resolver: Optional<Resolver>
private var bindTarget: Optional<SocketAddress>
/// Create a `ClientBootstrap` on the `EventLoopGroup` `group`.
///
/// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `ClientBootstrap` is
/// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by
/// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for
/// situations where it's impossible to tell ahead of time if the `EventLoopGroup` is compatible or not.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use.
public convenience init(group: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) else {
preconditionFailure("ClientBootstrap is only compatible with MultiThreadedEventLoopGroup and " +
"SelectableEventLoop. You tried constructing one with \(group) which is incompatible.")
}
self.init(validatingGroup: group)!
}
/// Create a `ClientBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use.
public init?(validatingGroup group: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) else {
return nil
}
self.group = group
self._channelOptions = ChannelOptions.Storage()
self._channelOptions.append(key: ChannelOptions.tcpOption(.tcp_nodelay), value: 1)
self._channelInitializer = { channel in channel.eventLoop.makeSucceededFuture(()) }
self.protocolHandlers = nil
self.resolver = nil
self.bindTarget = nil
}
/// Initialize the connected `SocketChannel` with `initializer`. The most common task in initializer is to add
/// `ChannelHandler`s to the `ChannelPipeline`.
///
/// The connected `Channel` will operate on `ByteBuffer` as inbound and `IOData` as outbound messages.
///
/// - warning: The `handler` closure may be invoked _multiple times_ so it's usually the right choice to instantiate
/// `ChannelHandler`s within `handler`. The reason `handler` may be invoked multiple times is that to
/// successfully set up a connection multiple connections might be setup in the process. Assuming a
/// hostname that resolves to both IPv4 and IPv6 addresses, NIO will follow
/// [_Happy Eyeballs_](https://en.wikipedia.org/wiki/Happy_Eyeballs) and race both an IPv4 and an IPv6
/// connection. It is possible that both connections get fully established before the IPv4 connection
/// will be closed again because the IPv6 connection 'won the race'. Therefore the `channelInitializer`
/// might be called multiple times and it's important not to share stateful `ChannelHandler`s in more
/// than one `Channel`.
///
/// - parameters:
/// - handler: A closure that initializes the provided `Channel`.
public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self {
self._channelInitializer = handler
return self
}
/// Sets the protocol handlers that will be added to the front of the `ChannelPipeline` right after the
/// `channelInitializer` has been called.
///
/// Per bootstrap, you can only set the `protocolHandlers` once. Typically, `protocolHandlers` are used for the TLS
/// implementation. Most notably, `NIOClientTCPBootstrap`, NIO's "universal bootstrap" abstraction, uses
/// `protocolHandlers` to add the required `ChannelHandler`s for many TLS implementations.
public func protocolHandlers(_ handlers: @escaping () -> [ChannelHandler]) -> Self {
precondition(self.protocolHandlers == nil, "protocol handlers can only be set once")
self.protocolHandlers = handlers
return self
}
/// Specifies a `ChannelOption` to be applied to the `SocketChannel`.
///
/// - parameters:
/// - option: The option to be applied.
/// - value: The value for the option.
@inlinable
public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self {
self._channelOptions.append(key: option, value: value)
return self
}
/// Specifies a timeout to apply to a connection attempt.
//
/// - parameters:
/// - timeout: The timeout that will apply to the connection attempt.
public func connectTimeout(_ timeout: TimeAmount) -> Self {
self.connectTimeout = timeout
return self
}
/// Specifies the `Resolver` to use or `nil` if the default should be used.
///
/// - parameters:
/// - resolver: The resolver that will be used during the connection attempt.
public func resolver(_ resolver: Resolver?) -> Self {
self.resolver = resolver
return self
}
/// Bind the `SocketChannel` to `address`.
///
/// Using `bind` is not necessary unless you need the local address to be bound to a specific address.
///
/// - note: Using `bind` will disable Happy Eyeballs on this `Channel`.
///
/// - parameters:
/// - address: The `SocketAddress` to bind on.
public func bind(to address: SocketAddress) -> ClientBootstrap {
self.bindTarget = address
return self
}
func makeSocketChannel(eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily) throws -> SocketChannel {
return try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, protocolFamily: protocolFamily)
}
/// Specify the `host` and `port` to connect to for the TCP `Channel` that will be established.
///
/// - parameters:
/// - host: The host to connect to.
/// - port: The port to connect to.
/// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected.
public func connect(host: String, port: Int) -> EventLoopFuture<Channel> {
let loop = self.group.next()
let resolver = self.resolver ?? GetaddrinfoResolver(loop: loop,
aiSocktype: .stream,
aiProtocol: CInt(IPPROTO_TCP))
let connector = HappyEyeballsConnector(resolver: resolver,
loop: loop,
host: host,
port: port,
connectTimeout: self.connectTimeout) { eventLoop, protocolFamily in
return self.initializeAndRegisterNewChannel(eventLoop: eventLoop, protocolFamily: protocolFamily) {
$0.eventLoop.makeSucceededFuture(())
}
}
return connector.resolveAndConnect()
}
private func connect(freshChannel channel: Channel, address: SocketAddress) -> EventLoopFuture<Void> {
let connectPromise = channel.eventLoop.makePromise(of: Void.self)
channel.connect(to: address, promise: connectPromise)
let cancelTask = channel.eventLoop.scheduleTask(in: self.connectTimeout) {
connectPromise.fail(ChannelError.connectTimeout(self.connectTimeout))
channel.close(promise: nil)
}
connectPromise.futureResult.whenComplete { (_: Result<Void, Error>) in
cancelTask.cancel()
}
return connectPromise.futureResult
}
internal func testOnly_connect(injectedChannel: SocketChannel,
to address: SocketAddress) -> EventLoopFuture<Channel> {
return self.initializeAndRegisterChannel(injectedChannel) { channel in
return self.connect(freshChannel: channel, address: address)
}
}
/// Specify the `address` to connect to for the TCP `Channel` that will be established.
///
/// - parameters:
/// - address: The address to connect to.
/// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected.
public func connect(to address: SocketAddress) -> EventLoopFuture<Channel> {
return self.initializeAndRegisterNewChannel(eventLoop: self.group.next(),
protocolFamily: address.protocol) { channel in
return self.connect(freshChannel: channel, address: address)
}
}
/// Specify the `unixDomainSocket` path to connect to for the UDS `Channel` that will be established.
///
/// - parameters:
/// - unixDomainSocketPath: The _Unix domain socket_ path to connect to.
/// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected.
public func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> {
do {
let address = try SocketAddress(unixDomainSocketPath: unixDomainSocketPath)
return self.connect(to: address)
} catch {
return self.group.next().makeFailedFuture(error)
}
}
#if !os(Windows)
/// Use the existing connected socket file descriptor.
///
/// - parameters:
/// - descriptor: The _Unix file descriptor_ representing the connected stream socket.
/// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`.
@available(*, deprecated, renamed: "ClientBoostrap.withConnectedSocket(_:)")
public func withConnectedSocket(descriptor: CInt) -> EventLoopFuture<Channel> {
return self.withConnectedSocket(descriptor)
}
#endif
/// Use the existing connected socket file descriptor.
///
/// - parameters:
/// - descriptor: The _Unix file descriptor_ representing the connected stream socket.
/// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`.
public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
let eventLoop = group.next()
let channelInitializer = self.channelInitializer
let channel: SocketChannel
do {
channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, socket: socket)
} catch {
return eventLoop.makeFailedFuture(error)
}
func setupChannel() -> EventLoopFuture<Channel> {
eventLoop.assertInEventLoop()
return self._channelOptions.applyAllChannelOptions(to: channel).flatMap {
channelInitializer(channel)
}.flatMap {
eventLoop.assertInEventLoop()
let promise = eventLoop.makePromise(of: Void.self)
channel.registerAlreadyConfigured0(promise: promise)
return promise.futureResult
}.map {
channel
}.flatMapError { error in
channel.close0(error: error, mode: .all, promise: nil)
return channel.eventLoop.makeFailedFuture(error)
}
}
if eventLoop.inEventLoop {
return setupChannel()
} else {
return eventLoop.flatSubmit { setupChannel() }
}
}
private func initializeAndRegisterNewChannel(eventLoop: EventLoop,
protocolFamily: NIOBSDSocket.ProtocolFamily,
_ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> {
let channel: SocketChannel
do {
channel = try self.makeSocketChannel(eventLoop: eventLoop, protocolFamily: protocolFamily)
} catch {
return eventLoop.makeFailedFuture(error)
}
return self.initializeAndRegisterChannel(channel, body)
}
private func initializeAndRegisterChannel(_ channel: SocketChannel,
_ body: @escaping (Channel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> {
let channelInitializer = self.channelInitializer
let channelOptions = self._channelOptions
let eventLoop = channel.eventLoop
@inline(__always)
func setupChannel() -> EventLoopFuture<Channel> {
eventLoop.assertInEventLoop()
return channelOptions.applyAllChannelOptions(to: channel).flatMap {
if let bindTarget = self.bindTarget {
return channel.bind(to: bindTarget).flatMap {
channelInitializer(channel)
}
} else {
return channelInitializer(channel)
}
}.flatMap {
eventLoop.assertInEventLoop()
return channel.registerAndDoSynchronously(body)
}.map {
channel
}.flatMapError { error in
channel.close0(error: error, mode: .all, promise: nil)
return channel.eventLoop.makeFailedFuture(error)
}
}
if eventLoop.inEventLoop {
return setupChannel()
} else {
return eventLoop.flatSubmit {
setupChannel()
}
}
}
}
/// A `DatagramBootstrap` is an easy way to bootstrap a `DatagramChannel` when creating datagram clients
/// and servers.
///
/// Example:
///
/// ```swift
/// let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
/// defer {
/// try! group.syncShutdownGracefully()
/// }
/// let bootstrap = DatagramBootstrap(group: group)
/// // Enable SO_REUSEADDR.
/// .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
/// .channelInitializer { channel in
/// channel.pipeline.addHandler(MyChannelHandler())
/// }
/// let channel = try! bootstrap.bind(host: "127.0.0.1", port: 53).wait()
/// /* the Channel is now ready to send/receive datagrams */
///
/// try channel.closeFuture.wait() // Wait until the channel un-binds.
/// ```
///
/// The `DatagramChannel` will operate on `AddressedEnvelope<ByteBuffer>` as inbound and outbound messages.
public final class DatagramBootstrap {
private let group: EventLoopGroup
private var channelInitializer: Optional<ChannelInitializerCallback>
@usableFromInline
internal var _channelOptions: ChannelOptions.Storage
/// Create a `DatagramBootstrap` on the `EventLoopGroup` `group`.
///
/// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `DatagramBootstrap` is
/// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by
/// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for
/// situations where it's impossible to tell ahead of time if the `EventLoopGroup` is compatible or not.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use.
public convenience init(group: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) else {
preconditionFailure("DatagramBootstrap is only compatible with MultiThreadedEventLoopGroup and " +
"SelectableEventLoop. You tried constructing one with \(group) which is incompatible.")
}
self.init(validatingGroup: group)!
}
/// Create a `DatagramBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use.
public init?(validatingGroup group: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) else {
return nil
}
self._channelOptions = ChannelOptions.Storage()
self.group = group
self.channelInitializer = nil
}
/// Initialize the bound `DatagramChannel` with `initializer`. The most common task in initializer is to add
/// `ChannelHandler`s to the `ChannelPipeline`.
///
/// - parameters:
/// - handler: A closure that initializes the provided `Channel`.
public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self {
self.channelInitializer = handler
return self
}
/// Specifies a `ChannelOption` to be applied to the `DatagramChannel`.
///
/// - parameters:
/// - option: The option to be applied.
/// - value: The value for the option.
@inlinable
public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self {
self._channelOptions.append(key: option, value: value)
return self
}
#if !os(Windows)
/// Use the existing bound socket file descriptor.
///
/// - parameters:
/// - descriptor: The _Unix file descriptor_ representing the bound datagram socket.
@available(*, deprecated, renamed: "DatagramBootstrap.withBoundSocket(_:)")
public func withBoundSocket(descriptor: CInt) -> EventLoopFuture<Channel> {
return self.withBoundSocket(descriptor)
}
#endif
/// Use the existing bound socket file descriptor.
///
/// - parameters:
/// - descriptor: The _Unix file descriptor_ representing the bound datagram socket.
public func withBoundSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel {
return try DatagramChannel(eventLoop: eventLoop, socket: socket)
}
return bind0(makeChannel: makeChannel) { (eventLoop, channel) in
let promise = eventLoop.makePromise(of: Void.self)
channel.registerAlreadyConfigured0(promise: promise)
return promise.futureResult
}
}
/// Bind the `DatagramChannel` to `host` and `port`.
///
/// - parameters:
/// - host: The host to bind on.
/// - port: The port to bind on.
public func bind(host: String, port: Int) -> EventLoopFuture<Channel> {
return bind0 {
return try SocketAddress.makeAddressResolvingHost(host, port: port)
}
}
/// Bind the `DatagramChannel` to `address`.
///
/// - parameters:
/// - address: The `SocketAddress` to bind on.
public func bind(to address: SocketAddress) -> EventLoopFuture<Channel> {
return bind0 { address }
}
/// Bind the `DatagramChannel` to a UNIX Domain Socket.
///
/// - parameters:
/// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. `path` must not exist, it will be created by the system.
public func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel> {
return bind0 {
return try SocketAddress(unixDomainSocketPath: unixDomainSocketPath)
}
}
/// Bind the `DatagramChannel` to a UNIX Domain Socket.
///
/// - parameters:
/// - unixDomainSocketPath: The path of the UNIX Domain Socket to bind on. `path` must not exist, it will be created by the system.
/// - cleanupExistingSocketFile: Whether to cleanup an existing socket file at `path`.
public func bind(unixDomainSocketPath: String, cleanupExistingSocketFile: Bool) -> EventLoopFuture<Channel> {
if cleanupExistingSocketFile {
do {
try BaseSocket.cleanupSocket(unixDomainSocketPath: unixDomainSocketPath)
} catch {
return group.next().makeFailedFuture(error)
}
}
return self.bind(unixDomainSocketPath: unixDomainSocketPath)
}
private func bind0(_ makeSocketAddress: () throws -> SocketAddress) -> EventLoopFuture<Channel> {
let address: SocketAddress
do {
address = try makeSocketAddress()
} catch {
return group.next().makeFailedFuture(error)
}
func makeChannel(_ eventLoop: SelectableEventLoop) throws -> DatagramChannel {
return try DatagramChannel(eventLoop: eventLoop,
protocolFamily: address.protocol)
}
return bind0(makeChannel: makeChannel) { (eventLoop, channel) in
channel.register().flatMap {
channel.bind(to: address)
}
}
}
private func bind0(makeChannel: (_ eventLoop: SelectableEventLoop) throws -> DatagramChannel, _ registerAndBind: @escaping (EventLoop, DatagramChannel) -> EventLoopFuture<Void>) -> EventLoopFuture<Channel> {
let eventLoop = self.group.next()
let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) }
let channelOptions = self._channelOptions
let channel: DatagramChannel
do {
channel = try makeChannel(eventLoop as! SelectableEventLoop)
} catch {
return eventLoop.makeFailedFuture(error)
}
func setupChannel() -> EventLoopFuture<Channel> {
eventLoop.assertInEventLoop()
return channelOptions.applyAllChannelOptions(to: channel).flatMap {
channelInitializer(channel)
}.flatMap {
eventLoop.assertInEventLoop()
return registerAndBind(eventLoop, channel)
}.map {
channel
}.flatMapError { error in
eventLoop.makeFailedFuture(error)
}
}
if eventLoop.inEventLoop {
return setupChannel()
} else {
return eventLoop.flatSubmit {
setupChannel()
}
}
}
}
/// A `NIOPipeBootstrap` is an easy way to bootstrap a `PipeChannel` which uses two (uni-directional) UNIX pipes
/// and makes a `Channel` out of them.
///
/// Example bootstrapping a `Channel` using `stdin` and `stdout`:
///
/// let channel = try NIOPipeBootstrap(group: group)
/// .channelInitializer { channel in
/// channel.pipeline.addHandler(MyChannelHandler())
/// }
/// .withPipes(inputDescriptor: STDIN_FILENO, outputDescriptor: STDOUT_FILENO)
///
public final class NIOPipeBootstrap {
private let group: EventLoopGroup
private var channelInitializer: Optional<ChannelInitializerCallback>
@usableFromInline
internal var _channelOptions: ChannelOptions.Storage
/// Create a `NIOPipeBootstrap` on the `EventLoopGroup` `group`.
///
/// The `EventLoopGroup` `group` must be compatible, otherwise the program will crash. `NIOPipeBootstrap` is
/// compatible only with `MultiThreadedEventLoopGroup` as well as the `EventLoop`s returned by
/// `MultiThreadedEventLoopGroup.next`. See `init(validatingGroup:)` for a fallible initializer for
/// situations where it's impossible to tell ahead of time if the `EventLoopGroup`s are compatible or not.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use.
public convenience init(group: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) else {
preconditionFailure("NIOPipeBootstrap is only compatible with MultiThreadedEventLoopGroup and " +
"SelectableEventLoop. You tried constructing one with \(group) which is incompatible.")
}
self.init(validatingGroup: group)!
}
/// Create a `NIOPipeBootstrap` on the `EventLoopGroup` `group`, validating that `group` is compatible.
///
/// - parameters:
/// - group: The `EventLoopGroup` to use.
public init?(validatingGroup group: EventLoopGroup) {
guard NIOOnSocketsBootstraps.isCompatible(group: group) else {
return nil
}
self._channelOptions = ChannelOptions.Storage()
self.group = group
self.channelInitializer = nil
}
/// Initialize the connected `PipeChannel` with `initializer`. The most common task in initializer is to add
/// `ChannelHandler`s to the `ChannelPipeline`.
///
/// The connected `Channel` will operate on `ByteBuffer` as inbound and outbound messages. Please note that
/// `IOData.fileRegion` is _not_ supported for `PipeChannel`s because `sendfile` only works on sockets.
///
/// - parameters:
/// - handler: A closure that initializes the provided `Channel`.
public func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self {
self.channelInitializer = handler
return self
}
/// Specifies a `ChannelOption` to be applied to the `PipeChannel`.
///
/// - parameters:
/// - option: The option to be applied.
/// - value: The value for the option.
@inlinable
public func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self {
self._channelOptions.append(key: option, value: value)
return self
}
private func validateFileDescriptorIsNotAFile(_ descriptor: CInt) throws {
precondition(MultiThreadedEventLoopGroup.currentEventLoop == nil,
"limitation in SwiftNIO: cannot bootstrap PipeChannel on EventLoop")
var s: stat = .init()
try withUnsafeMutablePointer(to: &s) { ptr in
try Posix.fstat(descriptor: descriptor, outStat: ptr)
}
switch s.st_mode & S_IFMT {
case S_IFREG, S_IFDIR, S_IFLNK, S_IFBLK:
throw ChannelError.operationUnsupported
default:
() // Let's default to ok
}
}
/// Create the `PipeChannel` with the provided file descriptor which is used for both input & output.
///
/// This method is useful for specialilsed use-cases where you want to use `NIOPipeBootstrap` for say a serial line.
///
/// - note: If this method returns a succeeded future, SwiftNIO will close `fileDescriptor` when the `Channel`
/// becomes inactive. You _must not_ do any further operations with `fileDescriptor`, including `close`.
/// If this method returns a failed future, you still own the file descriptor and are responsible for
/// closing it.
///
/// - parameters:
/// - fileDescriptor: The _Unix file descriptor_ for the input & output.
/// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`.
public func withInputOutputDescriptor(_ fileDescriptor: CInt) -> EventLoopFuture<Channel> {
let inputFD = fileDescriptor
let outputFD = dup(fileDescriptor)
return self.withPipes(inputDescriptor: inputFD, outputDescriptor: outputFD).flatMapErrorThrowing { error in
try! Posix.close(descriptor: outputFD)
throw error
}
}
/// Create the `PipeChannel` with the provided input and output file descriptors.
///
/// The input and output file descriptors must be distinct. If you have a single file descriptor, consider using
/// `ClientBootstrap.withConnectedSocket(descriptor:)` if it's a socket or
/// `NIOPipeBootstrap.withInputOutputDescriptor` if it is not a socket.
///
/// - note: If this method returns a succeeded future, SwiftNIO will close `inputDescriptor` and `outputDescriptor`
/// when the `Channel` becomes inactive. You _must not_ do any further operations `inputDescriptor` or
/// `outputDescriptor`, including `close`.
/// If this method returns a failed future, you still own the file descriptors and are responsible for
/// closing them.
///
/// - parameters:
/// - inputDescriptor: The _Unix file descriptor_ for the input (ie. the read side).
/// - outputDescriptor: The _Unix file descriptor_ for the output (ie. the write side).
/// - returns: an `EventLoopFuture<Channel>` to deliver the `Channel`.
public func withPipes(inputDescriptor: CInt, outputDescriptor: CInt) -> EventLoopFuture<Channel> {
precondition(inputDescriptor >= 0 && outputDescriptor >= 0 && inputDescriptor != outputDescriptor,
"illegal file descriptor pair. The file descriptors \(inputDescriptor), \(outputDescriptor) " +
"must be distinct and both positive integers.")
let eventLoop = group.next()
do {
try self.validateFileDescriptorIsNotAFile(inputDescriptor)
try self.validateFileDescriptorIsNotAFile(outputDescriptor)
} catch {
return eventLoop.makeFailedFuture(error)
}
let channelInitializer = self.channelInitializer ?? { _ in eventLoop.makeSucceededFuture(()) }
let channel: PipeChannel
do {
let inputFH = NIOFileHandle(descriptor: inputDescriptor)
let outputFH = NIOFileHandle(descriptor: outputDescriptor)
channel = try PipeChannel(eventLoop: eventLoop as! SelectableEventLoop,
inputPipe: inputFH,
outputPipe: outputFH)
} catch {
return eventLoop.makeFailedFuture(error)
}
func setupChannel() -> EventLoopFuture<Channel> {
eventLoop.assertInEventLoop()
return self._channelOptions.applyAllChannelOptions(to: channel).flatMap {
channelInitializer(channel)
}.flatMap {
eventLoop.assertInEventLoop()
let promise = eventLoop.makePromise(of: Void.self)
channel.registerAlreadyConfigured0(promise: promise)
return promise.futureResult
}.map {
channel
}.flatMapError { error in
channel.close0(error: error, mode: .all, promise: nil)
return channel.eventLoop.makeFailedFuture(error)
}
}
if eventLoop.inEventLoop {
return setupChannel()
} else {
return eventLoop.flatSubmit {
setupChannel()
}
}
}
}
| 46.296362 | 248 | 0.638359 |
7602e87d04a8d8e38e84bfbac57c14d7003707e7 | 226 | //
// Repo.swift
// MVVMPureObservables
//
// Created by krawiecp-home on 25/01/2019.
// Copyright © 2019 tailec. All rights reserved.
//
import Foundation
struct Repo: Decodable {
let id: Int
let name: String
}
| 15.066667 | 49 | 0.668142 |
89f17c8f55681bb7d01f9f8a3ab6785aa2fffef5 | 5,913 | //
// DeviceTrackerSee.swift
// HomeAssistant
//
// Created by Robert Trencheny on 6/13/18.
// Copyright © 2018 Robbie Trencheny. All rights reserved.
//
import Foundation
import ObjectMapper
import CoreLocation
import CoreMotion
public class DeviceTrackerSee: Mappable {
public var HorizontalAccuracy: CLLocationAccuracy?
public var Attributes: [String: Any] = [:]
public var Battery: Float = 0.0
public var DeviceID: String?
public var Hostname: String?
public var Location: CLLocationCoordinate2D?
public var SourceType: UpdateTypes = .GlobalPositioningSystem
public var LocationName: String?
public var ConsiderHome: TimeInterval?
// Attributes
public var Speed: CLLocationSpeed?
public var Altitude: CLLocationDistance?
public var Course: CLLocationDirection?
public var VerticalAccuracy: CLLocationAccuracy?
public var Trigger: LocationUpdateTrigger = .Unknown
public var Timestamp: Date?
public var Floor: Int?
// CMMotionActivity
public var ActivityType: String?
public var ActivityConfidence: String?
public var ActivityStartDate: Date?
init() {}
public required init?(map: Map) {}
public convenience init(trigger: LocationUpdateTrigger, location: CLLocation?, zone: RLMZone?) {
self.init()
self.Trigger = trigger
self.SourceType = (self.Trigger == .BeaconRegionEnter || self.Trigger == .BeaconRegionExit
? .BluetoothLowEnergy : .GlobalPositioningSystem)
if let location = location, (
trigger != .BeaconRegionEnter
&& trigger != .BeaconRegionExit
&& trigger != .GPSRegionEnter) {
self.SetLocation(location: location)
} else if let zone = zone {
self.SetZone(zone: zone)
}
}
public func SetZone(zone: RLMZone) {
self.HorizontalAccuracy = zone.Radius
self.Location = zone.locationCoordinates()
if zone.ID == "zone.home" {
switch self.Trigger {
case .RegionEnter, .GPSRegionEnter, .BeaconRegionEnter:
self.LocationName = LocationNames.Home.rawValue
case .RegionExit, .GPSRegionExit:
self.LocationName = LocationNames.NotHome.rawValue
case .BeaconRegionExit:
self.ConsiderHome = TimeInterval(exactly: 180)
self.ClearLocation()
default:
break
}
} else {
switch self.Trigger {
case .BeaconRegionEnter:
self.LocationName = zone.Name
case .BeaconRegionExit:
self.ClearLocation()
default:
break
}
}
}
public func SetLocation(location: CLLocation) {
self.HorizontalAccuracy = location.horizontalAccuracy
self.Location = location.coordinate
self.Speed = location.speed
self.Altitude = location.altitude
self.Course = location.course
self.VerticalAccuracy = location.verticalAccuracy
self.Timestamp = location.timestamp
self.Floor = location.floor?.level
}
public func SetActivity(activity: CMMotionActivity) {
self.ActivityType = activity.activityType
self.ActivityConfidence = activity.confidence.description
self.ActivityStartDate = activity.startDate
}
public func ClearLocation() {
self.HorizontalAccuracy = nil
self.Location = nil
self.Speed = nil
self.Altitude = nil
self.Course = nil
self.VerticalAccuracy = nil
self.Timestamp = nil
}
public var cllocation: CLLocation? {
if let location = self.Location, let altitude = self.Altitude, let hAccuracy = self.HorizontalAccuracy,
let vAccuracy = self.VerticalAccuracy, let timestamp = self.Timestamp {
return CLLocation(coordinate: location, altitude: altitude, horizontalAccuracy: hAccuracy,
verticalAccuracy: vAccuracy, timestamp: timestamp)
} else if let location = self.Location {
return CLLocation(latitude: location.latitude, longitude: location.longitude)
}
return nil
}
// Mappable
public func mapping(map: Map) {
Attributes <- map["attributes"]
Battery <- (map["battery"], FloatToIntTransform())
DeviceID <- map["dev_id"]
Location <- (map["gps"], CLLocationCoordinate2DTransform())
HorizontalAccuracy <- map["gps_accuracy"]
Hostname <- map["host_name"]
SourceType <- (map["source_type"], EnumTransform<UpdateTypes>())
LocationName <- map["location_name"]
ConsiderHome <- (map["consider_home"], TimeIntervalToString())
Speed <- map["attributes.speed"]
Altitude <- map["attributes.altitude"]
Course <- map["attributes.course"]
VerticalAccuracy <- map["attributes.vertical_accuracy"]
Trigger <- (map["attributes.trigger"], EnumTransform<LocationUpdateTrigger>())
Timestamp <- (map["attributes.timestamp"], HomeAssistantTimestampTransform())
Floor <- map["attributes.floor"]
ActivityType <- map["attributes.activity_type"]
ActivityConfidence <- map["attributes.activity_confidence"]
ActivityStartDate <- (map["attributes.activity_start_date"], HomeAssistantTimestampTransform())
}
}
public enum UpdateTypes: String {
case GlobalPositioningSystem = "gps"
case Router = "router"
case Bluetooth = "bluetooth"
case BluetoothLowEnergy = "bluetooth_le"
}
public enum LocationNames: String {
case Home = "home"
case NotHome = "not_home"
}
| 36.054878 | 111 | 0.623034 |
71ad2ddb51db05843a4e33d92307f00293987941 | 2,992 | //
// HandyJSONExtension.swift
// Alamofire
//
// Created by Fanxx on 2019/8/8.
//
import UIKit
import HandyJSON
extension FX {
public struct HandyJSON {
open class StringArrayTransform: TransformOf<[String], String> {
public init() {
super.init(fromJSON: { (json) -> [String]? in
return json?.components(separatedBy: ",").filter({ !$0.isEmpty })
}, toJSON: { (values) -> String? in
return values?.joined(separator: ",")
})
}
}
open class StringArrayTransformOf<TargetType: FXStringConvertible>: TransformOf<[TargetType], String> {
public init() {
super.init(fromJSON: { (json) -> [TargetType]? in
let strings = json?.components(separatedBy: ",")
return strings?.compactMap({ (s) -> TargetType? in
return TargetType(string: s)
})
}, toJSON: { (values) -> String? in
if let vs = values, vs.count > 0 {
let str = vs.map({ $0.toString() }).joined(separator: ",")
return str
}else{
return ""
}
})
}
}
open class MillisecondDateTransform: DateTransform {
open override func transformFromJSON(_ value: Any?) -> Date? {
var v: Any? = nil
if let timeInt = value as? Double {
v = timeInt / 1000
}
if let timeStr = value as? String, !timeStr.isEmpty {
v = String(timeStr[timeStr.startIndex...timeStr.index(timeStr.endIndex, offsetBy: -3)])
}
return super.transformFromJSON(v)
}
open override func transformToJSON(_ value: Date?) -> Double? {
if let d = super.transformToJSON(value) {
return d * 1000
}
return nil
}
}
open class BoolStringTransform: TransformType {
public typealias Object = Bool
public typealias JSON = String
var trueString: String
var falseString: String?
public init(true string1: String, false string2: String? = nil) {
self.trueString = string1
self.falseString = string2
}
public func transformFromJSON(_ value: Any?) -> Bool? {
if let v = value as? String {
return v == trueString
}
return false
}
public func transformToJSON(_ value: Bool?) -> String? {
if let v = value {
return v ? trueString : falseString
}
return nil
}
}
}
}
| 36.048193 | 111 | 0.462233 |
6248d24e3808260494a1700caa544e0b51e5c39c | 22,462 | //
// LDUser.swift
// LaunchDarkly
//
// Copyright © 2017 Catamorphic Co. All rights reserved.
//
import Foundation
typealias UserKey = String //use for identifying semantics for strings, particularly in dictionaries
/**
LDUser allows clients to collect information about users in order to refine the feature flag values sent to the SDK. For example, the client app may launch with the SDK defined anonymous user. As the user works with the client app, information may be collected as needed and sent to LaunchDarkly. The client app controls the information collected, which LaunchDarkly does not use except as the client directs to refine feature flags. Client apps should follow [Apple's Privacy Policy](apple.com/legal/privacy) when collecting user information.
The SDK caches last known feature flags for use on app startup to provide continuity with the last app run. Provided the LDClient is online and can establish a connection with LaunchDarkly servers, cached information will only be used a very short time. Once the latest feature flags arrive at the SDK, the SDK no longer uses cached feature flags. The SDK retains feature flags on the last 5 client defined users. The SDK will retain feature flags until they are overwritten by a different user's feature flags, or until the user removes the app from the device.
The SDK does not cache user information collected, except for the user key. The user key is used to identify the cached feature flags for that user. Client app developers should use caution not to use sensitive user information as the user-key.
*/
public struct LDUser {
///String keys associated with LDUser properties.
public enum CodingKeys: String, CodingKey {
///Key names match the corresponding LDUser property
case key, name, firstName, lastName, country, ipAddress = "ip", email, avatar, custom, isAnonymous = "anonymous", device, operatingSystem = "os", config, privateAttributes = "privateAttrs"
}
/**
LDUser attributes that can be marked private.
The SDK will not include private attribute values in analytics events, but private attribute names will be sent.
See Also: `LDConfig.allUserAttributesPrivate`, `LDConfig.privateUserAttributes`, and `privateAttributes`.
*/
public static var privatizableAttributes: [String] {
[CodingKeys.name.rawValue, CodingKeys.firstName.rawValue, CodingKeys.lastName.rawValue, CodingKeys.country.rawValue, CodingKeys.ipAddress.rawValue, CodingKeys.email.rawValue, CodingKeys.avatar.rawValue, CodingKeys.custom.rawValue]
}
static var sdkSetAttributes: [String] {
[CodingKeys.device.rawValue, CodingKeys.operatingSystem.rawValue]
}
///Client app defined string that uniquely identifies the user. If the client app does not define a key, the SDK will assign an identifier associated with the anonymous user. The key cannot be made private.
public var key: String
///Client app defined name for the user. (Default: nil)
public var name: String?
///Client app defined first name for the user. (Default: nil)
public var firstName: String?
///Client app defined last name for the user. (Default: nil)
public var lastName: String?
///Client app defined country for the user. (Default: nil)
public var country: String?
///Client app defined ipAddress for the user. (Default: nil)
public var ipAddress: String?
///Client app defined email address for the user. (Default: nil)
public var email: String?
///Client app defined avatar for the user. (Default: nil)
public var avatar: String?
///Client app defined dictionary for the user. The client app may declare top level dictionary items as private. If the client app defines custom as private, the SDK considers the dictionary private except for device & operatingSystem (which cannot be made private). See `privateAttributes` for details. (Default: nil)
public var custom: [String: Any]?
///Client app defined isAnonymous for the user. If the client app does not define isAnonymous, the SDK will use the `key` to set this attribute. isAnonymous cannot be made private. (Default: true)
public var isAnonymous: Bool
///Client app defined device for the user. The SDK will determine the device automatically, however the client app can override the value. The SDK will insert the device into the `custom` dictionary. The device cannot be made private. (Default: the system identified device)
public var device: String?
///Client app defined operatingSystem for the user. The SDK will determine the operatingSystem automatically, however the client app can override the value. The SDK will insert the operatingSystem into the `custom` dictionary. The operatingSystem cannot be made private. (Default: the system identified operating system)
public var operatingSystem: String?
/**
Client app defined privateAttributes for the user.
The SDK will not include private attribute values in analytics events, but private attribute names will be sent.
This attribute is ignored if `LDConfig.allUserAttributesPrivate` is true. Combined with `LDConfig.privateUserAttributes`. The SDK considers attributes appearing in either list as private. Client apps may define attributes found in `privatizableAttributes` and top level `custom` dictionary keys here. (Default: nil)
See Also: `LDConfig.allUserAttributesPrivate` and `LDConfig.privateUserAttributes`.
*/
public var privateAttributes: [String]?
///An NSObject wrapper for the Swift LDUser struct. Intended for use in mixed apps when Swift code needs to pass a user into an Objective-C method.
public var objcLdUser: ObjcLDUser {
return ObjcLDUser(self)
}
internal var flagStore: FlagMaintaining = FlagStore()
/**
Initializer to create a LDUser. Client configurable attributes each have an optional parameter to facilitate setting user information into the LDUser. The SDK will automatically set `key`, `device`, `operatingSystem`, and `isAnonymous` attributes if the client does not provide them. The SDK embeds `device` and `operatingSystem` into the `custom` dictionary for transmission to LaunchDarkly.
- parameter key: String that uniquely identifies the user. If the client app does not define a key, the SDK will assign an identifier associated with the anonymous user.
- parameter name: Client app defined name for the user. (Default: nil)
- parameter firstName: Client app defined first name for the user. (Default: nil)
- parameter lastName: Client app defined last name for the user. (Default: nil)
- parameter country: Client app defined country for the user. (Default: nil)
- parameter ipAddress: Client app defined ipAddress for the user. (Default: nil)
- parameter email: Client app defined email address for the user. (Default: nil)
- parameter avatar: Client app defined avatar for the user. (Default: nil)
- parameter custom: Client app defined dictionary for the user. The client app may declare top level dictionary items as private. If the client app defines custom as private, the SDK considers the dictionary private except for device & operatingSystem (which cannot be made private). See `privateAttributes` for details. (Default: nil)
- parameter isAnonymous: Client app defined isAnonymous for the user. If the client app does not define isAnonymous, the SDK will use the `key` to set this attribute. (Default: nil)
- parameter device: Client app defined device for the user. The SDK will determine the device automatically, however the client app can override the value. The SDK will insert the device into the `custom` dictionary. (Default: nil)
- parameter operatingSystem: Client app defined operatingSystem for the user. The SDK will determine the operatingSystem automatically, however the client app can override the value. The SDK will insert the operatingSystem into the `custom` dictionary. (Default: nil)
- parameter privateAttributes: Client app defined privateAttributes for the user. (Default: nil)
*/
public init(key: String? = nil,
name: String? = nil,
firstName: String? = nil,
lastName: String? = nil,
country: String? = nil,
ipAddress: String? = nil,
email: String? = nil,
avatar: String? = nil,
custom: [String: Any]? = nil,
isAnonymous: Bool? = nil,
device: String? = nil,
operatingSystem: String? = nil,
privateAttributes: [String]? = nil) {
let environmentReporter = EnvironmentReporter()
let selectedKey = key ?? LDUser.defaultKey(environmentReporter: environmentReporter)
self.key = selectedKey
self.name = name
self.firstName = firstName
self.lastName = lastName
self.country = country
self.ipAddress = ipAddress
self.email = email
self.avatar = avatar
self.custom = custom
self.isAnonymous = isAnonymous ?? (selectedKey == LDUser.defaultKey(environmentReporter: environmentReporter))
self.device = device ?? custom?[CodingKeys.device.rawValue] as? String ?? environmentReporter.deviceModel
self.operatingSystem = operatingSystem ?? custom?[CodingKeys.operatingSystem.rawValue] as? String ?? environmentReporter.systemVersion
self.privateAttributes = privateAttributes
Log.debug(typeName(and: #function) + "user: \(self)")
}
/**
Initializer that takes a [String: Any] and creates a LDUser from the contents. Uses any keys present to define corresponding attribute values. Initializes attributes not present in the dictionary to their default value. Attempts to set `device` and `operatingSystem` from corresponding values embedded in `custom`. Attempts to set feature flags from values set in `config`.
- parameter userDictionary: Dictionary with LDUser attribute keys and values.
*/
public init(userDictionary: [String: Any]) {
key = userDictionary[CodingKeys.key.rawValue] as? String ?? LDUser.defaultKey(environmentReporter: EnvironmentReporter())
isAnonymous = userDictionary[CodingKeys.isAnonymous.rawValue] as? Bool ?? false
name = userDictionary[CodingKeys.name.rawValue] as? String
firstName = userDictionary[CodingKeys.firstName.rawValue] as? String
lastName = userDictionary[CodingKeys.lastName.rawValue] as? String
country = userDictionary[CodingKeys.country.rawValue] as? String
ipAddress = userDictionary[CodingKeys.ipAddress.rawValue] as? String
email = userDictionary[CodingKeys.email.rawValue] as? String
avatar = userDictionary[CodingKeys.avatar.rawValue] as? String
privateAttributes = userDictionary[CodingKeys.privateAttributes.rawValue] as? [String]
custom = userDictionary[CodingKeys.custom.rawValue] as? [String: Any]
device = custom?[CodingKeys.device.rawValue] as? String
operatingSystem = custom?[CodingKeys.operatingSystem.rawValue] as? String
flagStore = FlagStore(featureFlagDictionary: userDictionary[CodingKeys.config.rawValue] as? [String: Any])
Log.debug(typeName(and: #function) + "user: \(self)")
}
/**
Internal initializer that accepts an environment reporter, used for testing
*/
init(environmentReporter: EnvironmentReporting) {
self.init(key: LDUser.defaultKey(environmentReporter: environmentReporter), isAnonymous: true, device: environmentReporter.deviceModel, operatingSystem: environmentReporter.systemVersion)
}
//swiftlint:disable:next cyclomatic_complexity
private func value(for attribute: String) -> Any? {
switch attribute {
case CodingKeys.key.rawValue: return key
case CodingKeys.isAnonymous.rawValue: return isAnonymous
case CodingKeys.name.rawValue: return name
case CodingKeys.firstName.rawValue: return firstName
case CodingKeys.lastName.rawValue: return lastName
case CodingKeys.country.rawValue: return country
case CodingKeys.ipAddress.rawValue: return ipAddress
case CodingKeys.email.rawValue: return email
case CodingKeys.avatar.rawValue: return avatar
case CodingKeys.custom.rawValue: return custom
case CodingKeys.device.rawValue: return device
case CodingKeys.operatingSystem.rawValue: return operatingSystem
case CodingKeys.config.rawValue: return flagStore.featureFlags
case CodingKeys.privateAttributes.rawValue: return privateAttributes
default: return nil
}
}
///Returns the custom dictionary without the SDK set device and operatingSystem attributes
var customWithoutSdkSetAttributes: [String: Any]? {
custom?.filter { key, _ in !LDUser.sdkSetAttributes.contains(key) }
}
///Dictionary with LDUser attribute keys and values, with options to include feature flags and private attributes. LDConfig object used to help resolving what attributes should be private.
/// - parameter includeFlagConfig: Controls whether the resulting dictionary includes feature flags under the `config` key
/// - parameter includePrivateAttributes: Controls whether the resulting dictionary includes private attributes
/// - parameter config: Provides supporting information for defining private attributes
func dictionaryValue(includeFlagConfig: Bool, includePrivateAttributes includePrivate: Bool, config: LDConfig) -> [String: Any] {
var dictionary = [String: Any]()
var redactedAttributes = [String]()
let combinedPrivateAttributes = config.allUserAttributesPrivate ? LDUser.privatizableAttributes
: (privateAttributes ?? []) + (config.privateUserAttributes ?? [])
dictionary[CodingKeys.key.rawValue] = key
let optionalAttributes = LDUser.privatizableAttributes.filter { attribute in
attribute != CodingKeys.custom.rawValue
}
optionalAttributes.forEach { attribute in
let value = self.value(for: attribute)
if !includePrivate && combinedPrivateAttributes.contains(attribute) && value != nil {
redactedAttributes.append(attribute)
} else {
dictionary[attribute] = value
}
}
var customDictionary = [String: Any]()
if !includePrivate && combinedPrivateAttributes.contains(CodingKeys.custom.rawValue) && !(customWithoutSdkSetAttributes?.isEmpty ?? true) {
redactedAttributes.append(CodingKeys.custom.rawValue)
} else {
if let custom = customWithoutSdkSetAttributes, !custom.isEmpty {
custom.keys.forEach { customAttribute in
if !includePrivate && combinedPrivateAttributes.contains(customAttribute) && custom[customAttribute] != nil {
redactedAttributes.append(customAttribute)
} else {
customDictionary[customAttribute] = custom[customAttribute]
}
}
}
}
customDictionary[CodingKeys.device.rawValue] = device
customDictionary[CodingKeys.operatingSystem.rawValue] = operatingSystem
dictionary[CodingKeys.custom.rawValue] = customDictionary.isEmpty ? nil : customDictionary
if !includePrivate && !redactedAttributes.isEmpty {
let redactedAttributeSet: Set<String> = Set(redactedAttributes)
dictionary[CodingKeys.privateAttributes.rawValue] = redactedAttributeSet.sorted()
}
dictionary[CodingKeys.isAnonymous.rawValue] = isAnonymous
if includeFlagConfig {
dictionary[CodingKeys.config.rawValue] = flagStore.featureFlags
}
return dictionary
}
///Default key is the LDUser.key the SDK provides when any intializer is called without defining the key. The key should be constant with respect to the client app installation on a specific device. (The key may change if the client app is uninstalled and then reinstalled on the same device.)
///- parameter environmentReporter: The environmentReporter provides selected information that varies between OS regarding how it's determined
static func defaultKey(environmentReporter: EnvironmentReporting) -> String {
//For iOS & tvOS, this should be UIDevice.current.identifierForVendor.UUIDString
//For macOS & watchOS, this should be a UUID that the sdk creates and stores so that the value returned here should be always the same
return environmentReporter.vendorUUID ?? UserDefaults.standard.installationKey
}
}
extension UserDefaults {
struct Keys {
fileprivate static let deviceIdentifier = "ldDeviceIdentifier"
}
fileprivate var installationKey: String {
if let key = self.string(forKey: Keys.deviceIdentifier) {
return key
}
let key = UUID().uuidString
self.set(key, forKey: Keys.deviceIdentifier)
return key
}
}
extension LDUser: Equatable {
///Compares users by comparing their user keys only, to allow the client app to collect user information over time
public static func == (lhs: LDUser, rhs: LDUser) -> Bool {
lhs.key == rhs.key
}
}
///Class providing ObjC interoperability with the LDUser struct
@objc final class LDUserWrapper: NSObject {
let wrapped: LDUser
init(user: LDUser) {
wrapped = user
super.init()
}
}
extension LDUserWrapper: NSCoding {
struct Keys {
fileprivate static let featureFlags = "featuresJsonDictionary"
}
func encode(with encoder: NSCoder) {
encoder.encode(wrapped.key, forKey: LDUser.CodingKeys.key.rawValue)
encoder.encode(wrapped.name, forKey: LDUser.CodingKeys.name.rawValue)
encoder.encode(wrapped.firstName, forKey: LDUser.CodingKeys.firstName.rawValue)
encoder.encode(wrapped.lastName, forKey: LDUser.CodingKeys.lastName.rawValue)
encoder.encode(wrapped.country, forKey: LDUser.CodingKeys.country.rawValue)
encoder.encode(wrapped.ipAddress, forKey: LDUser.CodingKeys.ipAddress.rawValue)
encoder.encode(wrapped.email, forKey: LDUser.CodingKeys.email.rawValue)
encoder.encode(wrapped.avatar, forKey: LDUser.CodingKeys.avatar.rawValue)
encoder.encode(wrapped.custom, forKey: LDUser.CodingKeys.custom.rawValue)
encoder.encode(wrapped.isAnonymous, forKey: LDUser.CodingKeys.isAnonymous.rawValue)
encoder.encode(wrapped.device, forKey: LDUser.CodingKeys.device.rawValue)
encoder.encode(wrapped.operatingSystem, forKey: LDUser.CodingKeys.operatingSystem.rawValue)
encoder.encode(wrapped.privateAttributes, forKey: LDUser.CodingKeys.privateAttributes.rawValue)
encoder.encode([Keys.featureFlags: wrapped.flagStore.featureFlags.dictionaryValue.withNullValuesRemoved], forKey: LDUser.CodingKeys.config.rawValue)
}
convenience init?(coder decoder: NSCoder) {
var user = LDUser(key: decoder.decodeObject(forKey: LDUser.CodingKeys.key.rawValue) as? String,
name: decoder.decodeObject(forKey: LDUser.CodingKeys.name.rawValue) as? String,
firstName: decoder.decodeObject(forKey: LDUser.CodingKeys.firstName.rawValue) as? String,
lastName: decoder.decodeObject(forKey: LDUser.CodingKeys.lastName.rawValue) as? String,
country: decoder.decodeObject(forKey: LDUser.CodingKeys.country.rawValue) as? String,
ipAddress: decoder.decodeObject(forKey: LDUser.CodingKeys.ipAddress.rawValue) as? String,
email: decoder.decodeObject(forKey: LDUser.CodingKeys.email.rawValue) as? String,
avatar: decoder.decodeObject(forKey: LDUser.CodingKeys.avatar.rawValue) as? String,
custom: decoder.decodeObject(forKey: LDUser.CodingKeys.custom.rawValue) as? [String: Any],
isAnonymous: decoder.decodeBool(forKey: LDUser.CodingKeys.isAnonymous.rawValue),
privateAttributes: decoder.decodeObject(forKey: LDUser.CodingKeys.privateAttributes.rawValue) as? [String]
)
user.device = decoder.decodeObject(forKey: LDUser.CodingKeys.device.rawValue) as? String
user.operatingSystem = decoder.decodeObject(forKey: LDUser.CodingKeys.operatingSystem.rawValue) as? String
let wrappedFlags = decoder.decodeObject(forKey: LDUser.CodingKeys.config.rawValue) as? [String: Any]
user.flagStore = FlagStore(featureFlagDictionary: wrappedFlags?[Keys.featureFlags] as? [String: Any])
self.init(user: user)
}
///Method to configure NSKeyed(Un)Archivers to convert version 2.3.0 and older user caches to 2.3.1 and later user cache formats. Note that the v3 SDK no longer caches LDUsers, rather only feature flags and the LDUser.key are cached.
class func configureKeyedArchiversToHandleVersion2_3_0AndOlderUserCacheFormat() {
NSKeyedUnarchiver.setClass(LDUserWrapper.self, forClassName: "LDUserModel")
NSKeyedArchiver.setClassName("LDUserModel", for: LDUserWrapper.self)
}
}
extension LDUser: TypeIdentifying { }
#if DEBUG
extension LDUser {
///Testing method to get the user attribute value from a LDUser struct
func value(forAttribute attribute: String) -> Any? {
value(for: attribute)
}
//Compares all user properties. Excludes the composed FlagStore, which contains the users feature flags
func isEqual(to otherUser: LDUser) -> Bool {
key == otherUser.key
&& name == otherUser.name
&& firstName == otherUser.firstName
&& lastName == otherUser.lastName
&& country == otherUser.country
&& ipAddress == otherUser.ipAddress
&& email == otherUser.email
&& avatar == otherUser.avatar
&& AnyComparer.isEqual(custom, to: otherUser.custom)
&& isAnonymous == otherUser.isAnonymous
&& device == otherUser.device
&& operatingSystem == otherUser.operatingSystem
&& privateAttributes == otherUser.privateAttributes
}
}
#endif
| 61.708791 | 563 | 0.714318 |
08cc7c60a35d5ff6c12e2c27dae3b6b7a5e2fc8a | 2,322 | import Foundation
import azureSwiftRuntime
public protocol StreamingJobsStop {
var headerParameters: [String: String] { get set }
var subscriptionId : String { get set }
var resourceGroupName : String { get set }
var jobName : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void;
}
extension Commands.StreamingJobs {
// Stop stops a running streaming job. This will cause a running streaming job to stop processing input events and
// producing output. This method may poll for completion. Polling can be canceled by passing the cancel channel
// argument. The channel will be used to cancel polling and any outstanding HTTP requests.
internal class StopCommand : BaseCommand, StreamingJobsStop {
public var subscriptionId : String
public var resourceGroupName : String
public var jobName : String
public var apiVersion = "2016-03-01"
public init(subscriptionId: String, resourceGroupName: String, jobName: String) {
self.subscriptionId = subscriptionId
self.resourceGroupName = resourceGroupName
self.jobName = jobName
super.init()
self.method = "Post"
self.isLongRunningOperation = true
self.path = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/stop"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{jobName}"] = String(describing: self.jobName)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void {
client.executeAsyncLRO(command: self) {
(error) in
completionHandler(error)
}
}
}
}
| 45.529412 | 158 | 0.656761 |
8f157b6e6d85f4f7aa5be557d244dc5894c05f81 | 971 | //
// Genome
//
// Created by Logan Wright
// Copyright © 2016 lowriDevs. All rights reserved.
//
// MIT
//
import PureJsonSerializer
// MARK: MappableObject Initialization
public extension Array where Element : JsonConvertibleType {
public init(js: Json, context: Context = EmptyJson) throws {
let array = js.arrayValue ?? [js]
try self.init(js: array, context: context)
}
public init(js: [Json], context: Context = EmptyJson) throws {
self = try js.map { try Element.newInstance($0, context: context) }
}
}
public extension Set where Element : JsonConvertibleType {
public init(js: Json, context: Context = EmptyJson) throws {
let array = js.arrayValue ?? [js]
try self.init(js: array, context: context)
}
public init(js: [Json], context: Context = EmptyJson) throws {
let array = try js.map { try Element.newInstance($0, context: context) }
self.init(array)
}
}
| 26.972222 | 80 | 0.643666 |
9068a9f0ffc10206e86f96c73a00d91d15d93e84 | 870 | //
// ZLVedioViewController.swift
// HeadNews
//
// Created by fengei on 16/8/30.
// Copyright © 2016年 fengei. All rights reserved.
//
import UIKit
class ZLVedioViewController: 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.166667 | 106 | 0.675862 |
20d3884dce84e52a343133c54f72919cdbb5482b | 586 | //
// Created by Трыков Юрий on 2019-07-03.
// Copyright (c) 2019 trykov. All rights reserved.
//
import Foundation
struct WeatherVO {
let id: Int
let main: String
let description: String
let icon: String
}
extension WeatherVO {
init?(dto: WeatherDTO) {
guard let id = dto.id,
let main = dto.main,
let description = dto.description,
let icon = dto.icon else {
return nil
}
self.id = id
self.main = main
self.description = description
self.icon = icon
}
}
| 18.903226 | 50 | 0.559727 |
7a2d5117d3a360b3520fa503b776793e06eed385 | 896 | class Solution {
func myAtoi(_ str: String) -> Int {
if str.count == 0 {
return 0
}
let chars = Array(str)
var i = 0
while i < str.count && chars[i] == " " {
i += 1
}
var sign = 1
if i < str.count {
if chars[i] == "-" {
i += 1
sign = -1
} else if chars[i] == "+" {
i += 1
}
}
var result = 0
while i < str.count && "0" <= chars[i] && chars[i] <= "9" {
result = result * 10 + sign * Int(chars[i].asciiValue! - 48)
if result < INT_MIN {
return INT_MIN
} else if result > INT_MAX {
return INT_MAX
}
i += 1
}
return result
}
let (INT_MIN, INT_MAX) = (Int(Int32.min), Int(Int32.max))
}
| 26.352941 | 72 | 0.373884 |
5d2e1808518c7ddac238c6e7c002f60e4e5315f1 | 496 | //
// FoodTableViewCell.swift
// POP
//
// Created by taehy.k on 2021/10/14.
//
import UIKit
class FoodTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension FoodTableViewCell: ReusableView, NibLoadableView {}
| 19.076923 | 65 | 0.671371 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.