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
|
---|---|---|---|---|---|
50a5e8481bd6871a944c7519b824f35c5afe5e23 | 6,339 | import Foundation
import Dip
class Dependencies {
func createContainer() -> DependencyContainer {
let container = DependencyContainer()
registerLogic(container: container)
registerViewModels(container: container)
registerDaos(container: container)
registerRepos(container: container)
registerServices(container: container)
registerNetworking(container: container)
registerBle(container: container)
registerWiring(container: container)
registerSystem(container: container)
// Throws if components fail to instantiate
try! container.bootstrap()
return container
}
private func registerViewModels(container: DependencyContainer) {
container.register { HomeViewModel(startPermissions: try container.resolve(), rootNav: try container.resolve()) }
container.register { OnboardingWireframe(container: container) }
container.register { OnboardingViewModel() }
container.register { HealthQuizViewModel(symptomRepo: try container.resolve(), rootNav: try container.resolve()) }
container.register { AlertsViewModel(alertRepo: try container.resolve()) }
container.register { DebugViewModel(bleAdapter: try container.resolve(),
cenKeyDao: try container.resolve(),
api: try container.resolve()) }
}
private func registerDaos(container: DependencyContainer) {
container.register(.singleton) { RealmProvider() }
container.register(.singleton) { RealmCENDao(realmProvider: try container.resolve()) as CENDao }
container.register(.eagerSingleton) { RealmCENReportDao(realmProvider: try container.resolve()) as CENReportDao }
container.register(.singleton) { RealmCENKeyDao(realmProvider: try container.resolve(),
cenLogic: try container.resolve()) as CENKeyDao }
}
private func registerRepos(container: DependencyContainer) {
container.register(.singleton) { SymptomRepoImpl(coEpiRepo: try container.resolve()) as SymptomRepo }
container.register(.singleton) { AlertRepoImpl(cenReportsRepo: try container.resolve(),
coEpiRepo: try container.resolve()) as AlertRepo }
container.register(.singleton) { CENRepoImpl(cenDao: try container.resolve()) as CENRepo }
container.register(.eagerSingleton) { CenReportRepoImpl(cenReportDao: try container.resolve()) as CENReportRepo }
container.register(.singleton) { CENKeyRepoImpl(cenKeyDao: try container.resolve()) as CENKeyRepo }
container.register(.eagerSingleton) { CoEpiRepoImpl(cenRepo: try container.resolve(),
api: try container.resolve(),
periodicKeysFetcher: try container.resolve(),
cenMatcher: try container.resolve(),
cenKeyDao: try container.resolve(),
reportsHandler: try container.resolve()) as CoEpiRepo }
}
private func registerServices(container: DependencyContainer) {
container.register(.singleton) { ContactReceivedHandler(cenKeyRepo: try container.resolve(),
cenLogic: try container.resolve()) }
container.register(.singleton) { AppBadgeUpdaterImpl() as AppBadgeUpdater }
container.register(.singleton) { NotificationShowerImpl() as NotificationShower }
container.register(.singleton) { BackgroundTasksManager() }
container.register(.eagerSingleton) { FetchAlertsBackgroundRegisterer(tasksManager: try container.resolve(),
coEpiRepo: try container.resolve()) }
container.register(.singleton) { MatchingReportsHandlerImpl(reportsDao: try container.resolve(),
notificationShower: try container.resolve(),
appBadgeUpdater: try container.resolve())
as MatchingReportsHandler }
container.register(.eagerSingleton) { NotificationsDelegate(rootNav: try container.resolve()) }
}
private func registerLogic(container: DependencyContainer) {
container.register(.singleton) { CenLogic() }
// container.register(.eagerSingleton) { AlertNotificationsShower(alertsRepo: try container.resolve()) }
}
private func registerNetworking(container: DependencyContainer) {
container.register(.singleton) { CoEpiApiImpl() as CoEpiApi }
}
private func registerWiring(container: DependencyContainer) {
container.register(.eagerSingleton) { ScannedCensHandler(coepiRepo: try container.resolve(),
bleAdapter: try container.resolve()) }
container.register(.eagerSingleton) { PeriodicCenKeysFetcher(api: try container.resolve()) }
container.register(.singleton) { CenMatcherImpl(cenRepo: try container.resolve(),
cenLogic: try container.resolve()) as CenMatcher }
container.register(.singleton) { MatchingReportsHandlerImpl(reportsDao: try container.resolve(),
notificationShower: try container.resolve(),
appBadgeUpdater: try container.resolve())
as MatchingReportsHandler }
container.register(.eagerSingleton) { RootNav() }
}
private func registerBle(container: DependencyContainer) {
container.register(.eagerSingleton) { BleAdapter(cenReadHandler: try container.resolve()) }
}
private func registerSystem(container: DependencyContainer) {
container.register(.singleton) { KeyValueStoreImpl() as KeyValueStore }
container.register(.singleton) { StartPermissionsImpl() as StartPermissions }
}
}
| 58.694444 | 122 | 0.61587 |
ac97fe1bc2a430cb80a19a42dfc0704e11862d01 | 291 | //
// ListAllPackagesCommand.swift
// Jasmine
//
// Created by Nikola Majcen on 20.03.2021..
//
import Foundation
final class ListAllPackagesCommand {
}
// MARK: - Command
extension ListAllPackagesCommand: Command {
var arguments: [String] {
return ["formulae"]
}
}
| 13.227273 | 44 | 0.666667 |
0801232a8cd50a140a6917210fc630967c9977e0 | 529 | //
// LoginNavigator.swift
// MVVM Movie App
//
// Created by Rafsan Ahmad on 18/04/2021.
// Copyright © 2021 R.Ahmad. All rights reserved.
//
import UIKit
protocol LoginNavigatable {
func toMain()
}
final class LoginNavigator {
private let navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func toMain() {
navigationController.dismiss(animated: true, completion: nil)
}
}
| 20.346154 | 69 | 0.699433 |
d6115a7276d5260cf24c57c527c9ede42f282900 | 392 | import Foundation
protocol PlayableChunk: SendableChunk {
var end: Int64 { get }
var senderId: Int64 { get }
var start: Int64 { get }
}
extension PlayableChunk {
var age: TimeInterval {
return Date().timeIntervalSince1970 - TimeInterval(self.end) / 1000
}
var byCurrentUser: Bool {
return self.senderId == BackendClient.instance.session?.id
}
}
| 21.777778 | 75 | 0.665816 |
11678181e620b24364dee02134bac7af38e53dd8 | 251 |
import Foundation
// This extension is required as part of supporting resources in SPM.
// It's included in all other buid products.
extension Bundle {
static var module: Bundle = {
Bundle(for: LocalePickerViewController.self)
}()
}
| 22.818182 | 69 | 0.713147 |
89ddd4c473500adaa239610f39ec62dc7aae1840 | 838 | //
// DataConvertable.swift
// WalletKit
//
// Created by yuzushioh on 2018/02/11.
// Copyright © 2018 yuzushioh. All rights reserved.
//
// Adapted for Provenance on 2021/01/31
// by jdfigure
//
import Foundation
protocol DataConvertable {
static func +(lhs: Data, rhs: Self) -> Data
static func +=(lhs: inout Data, rhs: Self)
}
extension DataConvertable {
static func +(lhs: Data, rhs: Self) -> Data {
var value = rhs
var data = Data()
withUnsafePointer(to:&value, { (ptr: UnsafePointer<Self>) -> Void in
data = Data( buffer: UnsafeBufferPointer(start: ptr, count: 1))
})
return lhs + data
}
static func +=(lhs: inout Data, rhs: Self) {
lhs = lhs + rhs
}
}
extension UInt8: DataConvertable {}
extension UInt32: DataConvertable {}
| 21.487179 | 76 | 0.612172 |
71949b89bea18ad741e53571fde02a700a3d31b5 | 1,075 | //
// PostDetailLabelTableViewCell.swift
// Posts
//
// Created by Joshua Simmons on 20/03/2019.
// Copyright © 2019 Joshua. All rights reserved.
//
import Foundation
import UIKit
import TinyConstraints
class PostDetailLabelTableViewCell: UITableViewCell {
// MARK: Public properties
let bodyLabel = UILabel().then {
$0.font = Fonts.avenirNext.ofSize(16)
$0.textColor = Colors.darkGray
$0.numberOfLines = 0
}
// MARK: Initialisation
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Setup
private func setupView() {
selectionStyle = .none
buildView()
}
private func buildView() {
let insets = UIEdgeInsets.uniform(28) + UIEdgeInsets.vertical(-8)
addSubview(bodyLabel)
bodyLabel.edgesToSuperview(insets: insets)
}
}
| 21.938776 | 79 | 0.655814 |
f4e96ad97489bc8dfe7f068b4628c7cb703851cb | 1,021 | //
// WalletNewNameContract.swift
// RaccoonWallet
//
// Created by Taizo Kusuda on 2018/08/19
// Copyright © 2018年 T TECH, LIMITED LIABILITY CO. All rights reserved.
//
import UIKit
protocol WalletNewNameView: BaseView {
var presenter: WalletNewNamePresentation! { get set }
func enableOk()
func disableOk()
}
protocol WalletNewNamePresentation: BasePresentation {
var view: WalletNewNameView? { get set }
var interactor: WalletNewNameUseCase! { get set }
var router: WalletNewNameWireframe! { get set }
func didInputName(_ name: String)
func didClickOk()
func didClickPrivacyPolicy()
}
protocol WalletNewNameUseCase: class {
var output: WalletNewNameInteractorOutput! { get set }
}
protocol WalletNewNameInteractorOutput: class {
}
protocol WalletNewNameWireframe: class {
var viewController: UIViewController? { get set }
static func assembleModule() -> UIViewController
func presentWalletNewCompleted(_ name: String)
func presentPrivacyPolicy()
}
| 23.744186 | 72 | 0.737512 |
71b3b4b53408b2550ee6925d9a56813891353476 | 4,269 | import Foundation
#if canImport(XCTest)
import XCTest
/// Used for observing tests and handling internal library errors.
public class SwiftyMockyTestObserver: NSObject, XCTestObservation {
/// [Internal] Current test case
private static var currentTestCase: XCTestCase?
/// [Internal] Setup observing once
private static let setupBlock: (() -> Void) = {
XCTestObservationCenter.shared.addTestObserver(SwiftyMockyTestObserver())
Matcher.fatalErrorHandler = SwiftyMockyTestObserver.handleFatalError
return {}
}()
/// Call this method to setup custom error handling for SwiftyMocky, that allows to gracefully handle missing stub fatal errors.
/// In general it should be done automatically and there should be no reason to call it directly.
public static func setup() {
setupBlock()
}
/// [Internal] Observer for test start
///
/// - Parameter testCase: current test
public func testCaseWillStart(_ testCase: XCTestCase) {
SwiftyMockyTestObserver.currentTestCase = testCase
}
/// [Internal] Observer for test finished
///
/// - Parameter testCase: current test
public func testCaseDidFinish(_ testCase: XCTestCase) {
SwiftyMockyTestObserver.currentTestCase = nil
}
/// [Internal] used to notify about internal error. Do not call it directly.
///
/// - Parameters:
/// - message: Message
/// - file: File
/// - line: Line
public static func handleFatalError(message: String, file: StaticString, line: UInt) {
guard let testCase = SwiftyMockyTestObserver.currentTestCase else {
XCTFail(message, file: file, line: line)
return
}
let continueAfterFailure = testCase.continueAfterFailure
defer { testCase.continueAfterFailure = continueAfterFailure }
testCase.continueAfterFailure = false
let methodName = getNameOfExtecutedTestCase(testCase)
if let name = methodName, let failingLine = FilesExlorer().findTestCaseLine(for: name, file: file) {
testCase.recordFailure(withDescription: message, inFile: file.description, atLine: Int(failingLine), expected: false)
} else if let name = methodName {
XCTFail("\(name) - \(message)", file: file, line: line)
} else {
XCTFail(message, file: file, line: line)
}
}
/// [Internal] Geting name of current test
///
/// - Parameter testCase: Test case
/// - Returns: Name
private static func getNameOfExtecutedTestCase(_ testCase: XCTestCase) -> String? {
return testCase.name.components(separatedBy: " ")[1].components(separatedBy: "]").first
}
}
#else
public class SwiftyMockyTestObserver: NSObject {
/// [Internal] No setup whatsoever
@objc public static func setup() {
// Empty on purpose
}
public static func handleFatalError(message: String, file: StaticString, line: UInt) {
// Empty on purpose
}
}
#endif
/// [Internal] Internal dependency that looks for line of test case, that caused test failure.
private class FilesExlorer {
/// Parses test case file to get line number assigned with test
///
/// - Parameter testCase: Test case
/// - Parameter file: File we should look in
/// - Returns: Line number or nil, if unable to find
func findTestCaseLine(for methodName: String, file: StaticString) -> UInt? {
guard let content = getFileContent(file: file.description) else {
return nil
}
let lines = content.components(separatedBy: "\n")
let offset = lines.enumerated().first { (index, line) -> Bool in
return line.contains(methodName)
}?.offset
guard let line = offset else { return nil }
let lineAdditionalOffset: UInt = 2 // just to show error within test case, below the name.
return UInt(line) + lineAdditionalOffset
}
private func getFileContent(file: String) -> String? {
// TODO: look for file encoding from file attributes
guard let fileData = FileManager().contents(atPath: file) else { return nil }
return String(data: fileData, encoding: .utf8) ?? String(data: fileData, encoding: .utf16)
}
}
| 39.527778 | 132 | 0.665027 |
6427a16cc11a8875f8be8f9a59841fd98b5bd802 | 5,255 | // Copyright Trust Wallet. All rights reserved.
//
// This file is part of TrustSDK. The full TrustSDK copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import Foundation
import TrustWalletCore
public struct SigningInputEncoder {
private init() { }
public static func encode(data: Data, privateKey: Data, for coin: CoinType) throws -> SigningInput {
switch coin {
case .aeternity:
var input = try AeternitySigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .aion:
var input = try AionSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .algorand:
var input = try AlgorandSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .binance:
var input = try BinanceSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .cosmos,
.kava,
.terra:
var input = try CosmosSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .ethereum,
.ethereumClassic,
.callisto,
.goChain,
.poanetwork,
.tomoChain,
.thunderToken,
.wanchain:
var input = try EthereumSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .eos:
var input = try EOSSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .filecoin:
var input = try FilecoinSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .fio:
var input = try FIOSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .harmony:
var input = try HarmonySigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .icon:
var input = try IconSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .ioTeX:
var input = try IoTeXSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .near:
var input = try NEARSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .neo:
var input = try NEOSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .nuls:
var input = try NULSSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .nano:
var input = try NanoSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .nebulas:
var input = try NebulasSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .nimiq:
var input = try NimiqSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .polkadot,
.kusama:
var input = try PolkadotSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .xrp:
var input = try RippleSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .solana:
var input = try SolanaSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .stellar,
.kin:
var input = try StellarSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .theta:
var input = try ThetaSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .tezos:
var input = try TezosSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .tron:
var input = try TronSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .veChain:
var input = try VeChainSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .waves:
var input = try WavesSigningInput(serializedData: data)
input.privateKey = privateKey
return input
case .zilliqa:
var input = try ZilliqaSigningInput(serializedData: data)
input.privateKey = privateKey
return input
default:
throw TrustSDKError.coinNotSupported
}
}
}
| 36.748252 | 104 | 0.588011 |
11b294175853741f842615f1f1186d45b3ec074b | 8,838 | //
// ListViewController.swift
// music-library
//
// Created by hell 'n silence on 4/20/18.
// Copyright © 2018 Bohdan Podvirnyi. All rights reserved.
//
import UIKit
import CoreData
class ListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var table: UITableView!
var records: [NSManagedObject] = []
var chosenRow: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
if !isAppAlreadyLaunched() {
UserDefaults.standard.set(0, forKey: "id")
UserDefaults.standard.set("Last Added", forKey: "sorting")
UserDefaults.standard.set("↓", forKey: "sortingOrder")
}
}
override func viewWillAppear(_ animated: Bool) {
loading()
}
//MARK: - Checking if app already launched once
func isAppAlreadyLaunched() -> Bool {
if UserDefaults.standard.bool(forKey: "isAppAlreadyLaunchedOnce") {
return true
} else {
UserDefaults.standard.set(true, forKey: "isAppAlreadyLaunchedOnce")
return false
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records.count
}
//MARK: - Cells appearance
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "cell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ListViewCell else {
self.showAlert(title: "Fatal Error", message: "The dequeued cell is not an instance of ListViewCell")
fatalError("The dequeued cell is not an instance of ListViewCell.")
}
let record = records[indexPath.row]
cell.artistLabel.text = record.value(forKey: "artist") as? String
cell.nameLabel.text = record.value(forKey: "title") as? String
cell.albumLabel.text = String(describing: record.value(forKey: "album")!) + " (" + String(describing: record.value(forKey: "year")!) + ")"
return cell
}
//MARK: - Tapping on specific row in TableView
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
chosenRow = indexPath.row
performSegue(withIdentifier: "toRecordInfo", sender: self)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
//MARK: - Enabling swipe for rows in TableView
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//MARK: - Edit button
let edit = UITableViewRowAction(style: .normal, title: "Edit") { action, index in
self.chosenRow = indexPath.row
self.performSegue(withIdentifier: "toEditRecord", sender: self)
}
edit.backgroundColor = UIColor.lightGray
//MARK: - Delete button
let delete = UITableViewRowAction(style: .normal, title: "Delete") { action, index in
self.chosenRow = indexPath.row
self.deleting()
}
delete.backgroundColor = UIColor.red
return [delete, edit]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//MARK: - Segue to DetailsViewController
if let destinationViewController = segue.destination as? DetailsViewController {
destinationViewController.artist = String(describing: records[chosenRow].value(forKey: "artist")!)
destinationViewController.name = String(describing: records[chosenRow].value(forKey: "title")!)
destinationViewController.album = String(describing: records[chosenRow].value(forKey: "album")!)
destinationViewController.year = records[chosenRow].value(forKey: "year") as! Int
destinationViewController.info = String(describing: records[chosenRow].value(forKey: "info")!)
destinationViewController.id = records[chosenRow].value(forKey: "id") as! Int
}
//MARK: - Segue to EditingViewController
if let destinationViewController = segue.destination as? EditingViewController {
destinationViewController.artist = String(describing: records[chosenRow].value(forKey: "artist")!)
destinationViewController.name = String(describing: records[chosenRow].value(forKey: "title")!)
destinationViewController.album = String(describing: records[chosenRow].value(forKey: "album")!)
destinationViewController.year = records[chosenRow].value(forKey: "year") as! Int
destinationViewController.info = String(describing: records[chosenRow].value(forKey: "info")!)
destinationViewController.editingId = records[chosenRow].value(forKey: "id") as! Int
destinationViewController.edit = true
}
}
//MARK: - Loading from CoreData to TableView
func loading() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Data")
do {
records = try managedContext.fetch(fetchRequest)
sorting()
} catch let error as NSError {
self.showAlert(title: "Error: Could not fetch", message: String(describing: error))
}
}
//MARK: - Sorting TableView according to UserDefaults
func sorting() {
let sortingType = UserDefaults.standard.string(forKey: "sorting")!
let sortingOrder = UserDefaults.standard.string(forKey: "sortingOrder")!
switch sortingOrder {
case "↓":
switch sortingType {
case "Last Added":
records.sort(by: { ($0.value(forKey: "id") as! Int) > ($1.value(forKey: "id") as! Int) } )
case "Artist":
records.sort(by: { ($0.value(forKey: "artist") as! String) < ($1.value(forKey: "artist") as! String) } )
case "Name":
records.sort(by: { ($0.value(forKey: "title") as! String) < ($1.value(forKey: "title") as! String) } )
case "Album":
records.sort(by: { ($0.value(forKey: "album") as! String) < ($1.value(forKey: "album") as! String) } )
case "Year":
records.sort(by: { ($0.value(forKey: "year") as! Int) < ($1.value(forKey: "year") as! Int) } )
default: break
}
case "↑":
switch sortingType {
case "Last Added":
records.sort(by: { ($0.value(forKey: "id") as! Int) < ($1.value(forKey: "id") as! Int) } )
case "Artist":
records.sort(by: { ($0.value(forKey: "artist") as! String) > ($1.value(forKey: "artist") as! String) } )
case "Name":
records.sort(by: { ($0.value(forKey: "title") as! String) > ($1.value(forKey: "title") as! String) } )
case "Album":
records.sort(by: { ($0.value(forKey: "album") as! String) > ($1.value(forKey: "album") as! String) } )
case "Year":
records.sort(by: { ($0.value(forKey: "year") as! Int) > ($1.value(forKey: "year") as! Int) } )
default: break
}
default: break
}
table.reloadData()
}
//MARK: - Deleting record from CoreData
func deleting() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequestToDelete = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
let predicate = NSPredicate(format: "id == %d", (records[chosenRow].value(forKey: "id") as! Int))
fetchRequestToDelete.predicate = predicate
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequestToDelete)
do {
try managedContext.execute(deleteRequest)
self.showAlert(title: "Delete", message: "Record deleted successfully")
self.loading()
} catch let error as NSError {
self.showAlert(title: "Error: Could not delete", message: String(describing: error))
}
}
}
| 46.03125 | 146 | 0.606811 |
380a74ed63746dc1107082de0c10127f50c65ba6 | 1,745 | //
// BaseClause.swift
// ThingIFSDK
//
// Created on 2017/01/23.
// Copyright (c) 2017 Kii. All rights reserved.
//
import Foundation
/** Base protocol for all clause classes. */
public protocol BaseClause {
}
/** Protocol for Equals clause classes */
public protocol BaseEquals: BaseClause {
/** Name of a field. */
var field: String { get }
/** Value of a field. */
var value: AnyObject { get }
}
/** Protocol for Not Equals clause classes */
public protocol BaseNotEquals: BaseClause {
/** Type of a contained instance */
associatedtype EqualClauseType: BaseEquals
/** Contained Equals clause instance. */
var equals: EqualClauseType { get }
}
/** Protocol for Range clause classes. */
public protocol BaseRange: BaseClause {
/** Name of a field. */
var field: String { get }
/** Lower limit for an instance. */
var lowerLimit: NSNumber? { get }
/** Include or not lower limit. */
var lowerIncluded: Bool? { get }
/** Upper limit for an instance. */
var upperLimit: NSNumber? { get }
/** Include or not upper limit. */
var upperIncluded: Bool? { get }
}
/** Protocol for And clause classes. */
public protocol BaseAnd: BaseClause {
/** Type of contained instances */
associatedtype ClausesType
/** Contained clauses. */
var clauses: [ClausesType] { get }
/** Add a clause. */
mutating func add(_ clause: ClausesType) -> Void
}
/** Protocol for Or clause classes. */
public protocol BaseOr: BaseClause {
/** Type of contained instances */
associatedtype ClausesType
/** Contained clauses. */
var clauses: [ClausesType] { get }
/** Add a clause. */
mutating func add(_ clause: ClausesType) -> Void
}
| 22.960526 | 52 | 0.643553 |
332e8ac0bb95ebeb3e40cff3f600a8015628aca1 | 16,867 | //
// ViewControllerCopyFiles.swift
// RsyncOSX
//
// Created by Thomas Evensen on 12/09/2016.
// Copyright © 2016 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length function_body_length file_length
import Foundation
import Cocoa
protocol GetSource: class {
func getSourceindex(index: Int)
}
protocol Updateremotefilelist: class {
func updateremotefilelist()
}
class ViewControllerCopyFiles: NSViewController, SetConfigurations, Delay, VcCopyFiles, VcSchedule, Connected, VcExecute {
var copysinglefiles: CopySingleFiles?
var remotefilelist: Remotefilelist?
var rsyncindex: Int?
var estimated: Bool = false
private var restoretabledata: [String]?
var diddissappear: Bool = false
var outputprocess: OutputProcess?
private var maxcount: Int = 0
@IBOutlet weak var numberofrows: NSTextField!
@IBOutlet weak var server: NSTextField!
@IBOutlet weak var rcatalog: NSTextField!
@IBOutlet weak var info: NSTextField!
@IBOutlet weak var restoretableView: NSTableView!
@IBOutlet weak var rsynctableView: NSTableView!
@IBOutlet weak var commandString: NSTextField!
@IBOutlet weak var remoteCatalog: NSTextField!
@IBOutlet weak var restorecatalog: NSTextField!
@IBOutlet weak var working: NSProgressIndicator!
@IBOutlet weak var search: NSSearchField!
@IBOutlet weak var restorebutton: NSButton!
@IBAction func totinfo(_ sender: NSButton) {
guard ViewControllerReference.shared.norsync == false else {
_ = Norsync()
return
}
self.configurations!.processtermination = .remoteinfotask
globalMainQueue.async(execute: { () -> Void in
self.presentAsSheet(self.viewControllerRemoteInfo!)
})
}
@IBAction func quickbackup(_ sender: NSButton) {
guard ViewControllerReference.shared.norsync == false else {
_ = Norsync()
return
}
self.openquickbackup()
}
@IBAction func automaticbackup(_ sender: NSButton) {
self.configurations!.processtermination = .automaticbackup
self.configurations?.remoteinfotaskworkqueue = RemoteInfoTaskWorkQueue(inbatch: false)
self.presentAsSheet(self.viewControllerEstimating!)
}
// Userconfiguration button
@IBAction func userconfiguration(_ sender: NSButton) {
globalMainQueue.async(execute: { () -> Void in
self.presentAsSheet(self.viewControllerUserconfiguration!)
})
}
// Abort button
@IBAction func abort(_ sender: NSButton) {
self.working.stopAnimation(nil)
guard self.copysinglefiles != nil else { return }
self.restorebutton.isEnabled = true
self.copysinglefiles!.abort()
}
// Do the work
@IBAction func restore(_ sender: NSButton) {
guard self.remoteCatalog.stringValue.isEmpty == false && self.restorecatalog.stringValue.isEmpty == false else {
self.info.stringValue = Infocopyfiles().info(num: 3)
return
}
guard self.copysinglefiles != nil else { return }
self.restorebutton.isEnabled = false
if self.estimated == false {
self.working.startAnimation(nil)
self.copysinglefiles!.executecopyfiles(remotefile: self.remoteCatalog!.stringValue, localCatalog: self.restorecatalog!.stringValue, dryrun: true)
self.estimated = true
self.outputprocess = self.copysinglefiles?.outputprocess
} else {
self.presentAsSheet(self.viewControllerProgress!)
self.copysinglefiles!.executecopyfiles(remotefile: self.remoteCatalog!.stringValue, localCatalog: self.restorecatalog!.stringValue, dryrun: false)
self.estimated = false
}
}
private func displayRemoteserver(index: Int?) {
guard index != nil else {
self.server.stringValue = ""
self.rcatalog.stringValue = ""
return
}
let hiddenID = self.configurations!.gethiddenID(index: index!)
guard hiddenID > -1 else { return }
globalMainQueue.async(execute: { () -> Void in
self.server.stringValue = self.configurations!.getResourceConfiguration(hiddenID, resource: .offsiteServer)
self.rcatalog.stringValue = self.configurations!.getResourceConfiguration(hiddenID, resource: .remoteCatalog)
})
}
override func viewDidLoad() {
super.viewDidLoad()
ViewControllerReference.shared.setvcref(viewcontroller: .vccopyfiles, nsviewcontroller: self)
self.restoretableView.delegate = self
self.restoretableView.dataSource = self
self.rsynctableView.delegate = self
self.rsynctableView.dataSource = self
self.working.usesThreadedAnimation = true
self.search.delegate = self
self.restorecatalog.delegate = self
self.remoteCatalog.delegate = self
self.restoretableView.doubleAction = #selector(self.tableViewDoubleClick(sender:))
}
override func viewDidAppear() {
super.viewDidAppear()
ViewControllerReference.shared.activetab = .vccopyfiles
guard self.diddissappear == false else {
globalMainQueue.async(execute: { () -> Void in
self.rsynctableView.reloadData()
})
return
}
if let restorePath = ViewControllerReference.shared.restorePath {
self.restorecatalog.stringValue = restorePath
} else {
self.restorecatalog.stringValue = ""
}
self.verifylocalCatalog()
globalMainQueue.async(execute: { () -> Void in
self.rsynctableView.reloadData()
})
}
override func viewDidDisappear() {
super.viewDidDisappear()
self.diddissappear = true
}
@objc(tableViewDoubleClick:) func tableViewDoubleClick(sender: AnyObject) {
guard self.remoteCatalog.stringValue.isEmpty == false else { return }
guard self.restorecatalog.stringValue.isEmpty == false else { return }
let question: String = NSLocalizedString("Copy single files or directory?", comment: "Restore")
let text: String = NSLocalizedString("Start restore?", comment: "Restore")
let dialog: String = NSLocalizedString("Restore", comment: "Restore")
let answer = Alerts.dialogOrCancel(question: question, text: text, dialog: dialog)
if answer {
self.restorebutton.isEnabled = false
self.working.startAnimation(nil)
self.copysinglefiles!.executecopyfiles(remotefile: remoteCatalog!.stringValue, localCatalog: restorecatalog!.stringValue, dryrun: false)
}
}
private func verifylocalCatalog() {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.restorecatalog.stringValue) == false {
self.info.stringValue = Infocopyfiles().info(num: 1)
} else {
self.info.stringValue = Infocopyfiles().info(num: 0)
}
}
private func inprogress() -> Bool {
guard self.copysinglefiles != nil else { return false }
if self.copysinglefiles?.process != nil {
return true
} else {
return false
}
}
func tableViewSelectionDidChange(_ notification: Notification) {
let myTableViewFromNotification = (notification.object as? NSTableView)!
if myTableViewFromNotification == self.restoretableView {
self.info.stringValue = Infocopyfiles().info(num: 0)
let indexes = myTableViewFromNotification.selectedRowIndexes
if let index = indexes.first {
guard self.restoretabledata != nil else { return }
self.remoteCatalog.stringValue = self.restoretabledata![index]
guard self.remoteCatalog.stringValue.isEmpty == false && self.restorecatalog.stringValue.isEmpty == false else {
self.info.stringValue = Infocopyfiles().info(num: 3)
return
}
self.commandString.stringValue = self.copysinglefiles!.getCommandDisplayinView(remotefile: self.remoteCatalog.stringValue, localCatalog: self.restorecatalog.stringValue)
self.estimated = false
self.restorebutton.title = "Estimate"
self.restorebutton.isEnabled = true
}
} else {
let indexes = myTableViewFromNotification.selectedRowIndexes
self.commandString.stringValue = ""
if let index = indexes.first {
guard self.inprogress() == false else {
self.working.stopAnimation(nil)
guard self.copysinglefiles != nil else { return }
self.restorebutton.isEnabled = true
self.copysinglefiles!.abort()
return
}
let config = self.configurations!.getConfigurations()[index]
guard self.connected(config: config) == true else {
self.restorebutton.isEnabled = false
self.info.stringValue = Infocopyfiles().info(num: 4)
return
}
self.info.stringValue = Infocopyfiles().info(num: 0)
self.restorebutton.title = "Estimate"
self.restorebutton.isEnabled = false
self.remoteCatalog.stringValue = ""
self.rsyncindex = index
let hiddenID = self.configurations!.getConfigurationsDataSourcecountBackupSnapshot()![index].value(forKey: "hiddenID") as? Int ?? -1
self.copysinglefiles = CopySingleFiles(hiddenID: hiddenID)
self.remotefilelist = Remotefilelist(hiddenID: hiddenID)
self.working.startAnimation(nil)
self.displayRemoteserver(index: index)
} else {
self.rsyncindex = nil
self.restoretabledata = nil
globalMainQueue.async(execute: { () -> Void in
self.restoretableView.reloadData()
})
}
}
}
}
extension ViewControllerCopyFiles: NSSearchFieldDelegate {
func controlTextDidChange(_ notification: Notification) {
if (notification.object as? NSTextField)! == self.search {
self.delayWithSeconds(0.25) {
if self.search.stringValue.isEmpty {
globalMainQueue.async(execute: { () -> Void in
if let index = self.rsyncindex {
if let hiddenID = self.configurations!.getConfigurationsDataSourcecountBackupSnapshot()![index].value(forKey: "hiddenID") as? Int {
self.remotefilelist = Remotefilelist(hiddenID: hiddenID)
}
}
})
} else {
globalMainQueue.async(execute: { () -> Void in
self.restoretabledata = self.restoretabledata!.filter({$0.contains(self.search.stringValue)})
self.restoretableView.reloadData()
})
}
}
self.verifylocalCatalog()
} else {
self.delayWithSeconds(0.25) {
self.verifylocalCatalog()
self.restorebutton.title = "Estimate"
self.restorebutton.isEnabled = true
self.estimated = false
guard self.remoteCatalog.stringValue.count > 0 else { return }
self.commandString.stringValue = self.copysinglefiles?.getCommandDisplayinView(remotefile: self.remoteCatalog.stringValue, localCatalog: self.restorecatalog.stringValue) ?? ""
}
}
}
func searchFieldDidEndSearching(_ sender: NSSearchField) {
if let index = self.rsyncindex {
if self.configurations!.getConfigurationsDataSourcecountBackupSnapshot()![index].value(forKey: "hiddenID") as? Int != nil {
self.working.startAnimation(nil)
}
}
}
}
extension ViewControllerCopyFiles: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
if tableView == self.restoretableView {
let numberofrows: String = NSLocalizedString("Number remote files:", comment: "Copy files")
guard self.restoretabledata != nil else {
self.numberofrows.stringValue = numberofrows
return 0
}
self.numberofrows.stringValue = numberofrows + String(self.restoretabledata!.count)
return self.restoretabledata!.count
} else {
return self.configurations?.getConfigurationsDataSourcecountBackupSnapshot()?.count ?? 0
}
}
}
extension ViewControllerCopyFiles: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if tableView == self.restoretableView {
guard self.restoretabledata != nil else { return nil }
let cellIdentifier = "files"
let text: String = self.restoretabledata![row]
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: self) as? NSTableCellView {
cell.textField?.stringValue = text
return cell
}
} else {
guard row < self.configurations!.getConfigurationsDataSourcecountBackupSnapshot()!.count else { return nil }
let object: NSDictionary = self.configurations!.getConfigurationsDataSourcecountBackupSnapshot()![row]
let cellIdentifier: String = tableColumn!.identifier.rawValue
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: self) as? NSTableCellView {
cell.textField?.stringValue = object.value(forKey: cellIdentifier) as? String ?? ""
return cell
}
}
return nil
}
}
extension ViewControllerCopyFiles: UpdateProgress {
func processTermination() {
self.maxcount = self.outputprocess?.getMaxcount() ?? 0
if let vc = ViewControllerReference.shared.getvcref(viewcontroller: .vcprogressview) as? ViewControllerProgressProcess {
vc.processTermination()
self.restorebutton.isEnabled = false
self.restorebutton.title = "Estimate"
} else {
self.restorebutton.title = "Restore"
self.restorebutton.isEnabled = true
}
self.working.stopAnimation(nil)
self.presentAsSheet(self.viewControllerInformation!)
}
func fileHandler() {
if let vc = ViewControllerReference.shared.getvcref(viewcontroller: .vcprogressview) as? ViewControllerProgressProcess {
vc.fileHandler()
}
}
}
extension ViewControllerCopyFiles: Count {
func maxCount() -> Int {
return self.maxcount
}
func inprogressCount() -> Int {
guard self.copysinglefiles?.outputprocess != nil else { return 0 }
return self.copysinglefiles!.outputprocess!.count()
}
}
extension ViewControllerCopyFiles: DismissViewController {
func dismiss_view(viewcontroller: NSViewController) {
self.dismiss(viewcontroller)
}
}
extension ViewControllerCopyFiles: GetOutput {
func getoutput() -> [String] {
return self.copysinglefiles!.getOutput()
}
}
extension ViewControllerCopyFiles: TemporaryRestorePath {
func temporaryrestorepath() {
if let restorePath = ViewControllerReference.shared.restorePath {
self.restorecatalog.stringValue = restorePath
} else {
self.restorecatalog.stringValue = ""
}
self.verifylocalCatalog()
}
}
extension ViewControllerCopyFiles: NewProfile {
func newProfile(profile: String?) {
self.restoretabledata = nil
globalMainQueue.async(execute: { () -> Void in
self.restoretableView.reloadData()
})
}
func enableProfileMenu() {
//
}
}
extension ViewControllerCopyFiles: OpenQuickBackup {
func openquickbackup() {
self.configurations!.processtermination = .quicktask
globalMainQueue.async(execute: { () -> Void in
self.presentAsSheet(self.viewControllerQuickBackup!)
})
}
}
extension ViewControllerCopyFiles: Updateremotefilelist {
func updateremotefilelist() {
self.restoretabledata = self.remotefilelist?.remotefilelist
globalMainQueue.async(execute: { () -> Void in
self.restoretableView.reloadData()
})
self.working.stopAnimation(nil)
self.remotefilelist = nil
}
}
| 40.545673 | 191 | 0.63645 |
11dc6f2b1d288c4269f392397b9fde49effe1d30 | 759 | //
// Accessibility.swift
// Tokamak
//
// Created by Matvii Hodovaniuk on 2/21/19.
//
public struct Accessibility: Equatable {
public let identifier: String?
public let language: String?
public let label: String?
public let hint: String?
public let value: String?
public let elementsHidden: Bool
public let isModal: Bool
public init(
elementsHidden: Bool = false,
hint: String? = nil,
isModal: Bool = false,
label: String? = "",
language: String? = nil,
value: String? = "",
identifier: String? = ""
) {
self.elementsHidden = elementsHidden
self.hint = hint
self.isModal = isModal
self.label = label
self.language = language
self.value = value
self.identifier = identifier
}
}
| 21.685714 | 44 | 0.653491 |
bfa35e7d4eef8a5e0c98872d30ac33aaa8460fdc | 1,240 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension QuickLookObject {
// checks the rules for the "prefer summary" flag to be set
func shouldPreferSummary(mirror: LoggerMirror) -> Bool {
#if APPLE_FRAMEWORKS_AVAILABLE
if let obj = mirror.value as? AnyObject {
if obj.responds(to: Selector(("debugQuickLookObject"))) {
switch self {
case .text(_), .attributedString(_), .int(_), .uInt(_), .float(_): return false
default: return true
}
}
}
#endif
return false
}
}
extension QuickLookObject {
func getStringIfAny() -> String? {
switch self {
case .text(let str): return str
default: return nil
}
}
}
| 31.794872 | 95 | 0.540323 |
4aefd950c81ed6254ff2b9bda4d4c5abb6d50886 | 282 | //
// ListDefaultInteractor.swift
// ListDefault
//
// Created by Tibor Bödecs on 2018. 03. 08..
// Copyright © 2018. Tibor Bödecs. All rights reserved.
//
import Foundation
import UIKit
class ListDefaultInteractor: ListInteractor {
weak var presenter: ListPresenter?
}
| 16.588235 | 56 | 0.723404 |
f7a7dc4ae5eff272d3c1448cf01cdf6d4bebbae4 | 2,088 | // Copyright 2022 Pera Wallet, LDA
// 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.
//
// OptionsView.swift
import UIKit
import MacaroonUIKit
final class OptionsView: View {
private lazy var theme = OptionsViewTheme()
private(set) lazy var optionsCollectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = theme.cellSpacing
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.contentInset = UIEdgeInsets(theme.collectionViewEdgeInsets)
collectionView.backgroundColor = theme.backgroundColor.uiColor
collectionView.register(OptionsCell.self)
return collectionView
}()
override init(frame: CGRect) {
super.init(frame: frame)
customize(theme)
}
func customize(_ theme: OptionsViewTheme) {
customizeBaseAppearance(backgroundColor: theme.backgroundColor)
addOptionsCollectionView(theme)
}
func prepareLayout(_ layoutSheet: NoLayoutSheet) {}
func customizeAppearance(_ styleSheet: NoStyleSheet) {}
}
extension OptionsView {
private func addOptionsCollectionView(_ theme: OptionsViewTheme) {
addSubview(optionsCollectionView)
optionsCollectionView.snp.makeConstraints {
$0.top.equalToSuperview().inset(theme.topInset)
$0.leading.trailing.bottom.equalToSuperview()
}
}
}
| 33.677419 | 93 | 0.728927 |
3a9456a226593695f71aaec4145a908b22050369 | 799 | //
/*******************************************************************************
File name: Product.swift
Author: Kairon (李凯隆)
Blog : https://coderkllee.github.io
E-mail: [email protected]
Description:
History:
5/12/2019: File created.
********************************************************************************/
import Foundation
class Product {
var name: String?
var cellImageName: String?
var fullscreenImageName: String?
init(name: String, cellImageName: String, fullscreenImageName: String) {
self.name = name
self.cellImageName = cellImageName
self.fullscreenImageName = fullscreenImageName
}
}
| 24.212121 | 81 | 0.440551 |
091b011f95327ad4eb3ef7af905671e595325831 | 13,666 | //
// InsulinDeliveryTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 1/30/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import LoopKit
private let ReuseIdentifier = "Right Detail"
public final class InsulinDeliveryTableViewController: UITableViewController {
@IBOutlet var needsConfigurationMessageView: ErrorBackgroundView!
@IBOutlet weak var iobValueLabel: UILabel!
@IBOutlet weak var iobDateLabel: UILabel!
@IBOutlet weak var totalValueLabel: UILabel!
@IBOutlet weak var totalDateLabel: UILabel!
@IBOutlet weak var dataSourceSegmentedControl: UISegmentedControl!
public var doseStore: DoseStore? {
didSet {
if let doseStore = doseStore {
doseStoreObserver = NotificationCenter.default.addObserver(forName: nil, object: doseStore, queue: OperationQueue.main, using: { [weak self] (note) -> Void in
switch note.name {
case Notification.Name.DoseStoreValuesDidChange:
if self?.isViewLoaded == true {
self?.reloadData()
}
case Notification.Name.DoseStoreReadyStateDidChange:
switch doseStore.readyState {
case .ready:
self?.state = .display
case .failed(let error):
self?.state = .unavailable(error)
default:
self?.state = .unavailable(nil)
}
default:
break
}
})
} else {
doseStoreObserver = nil
}
}
}
private var updateTimer: Timer? {
willSet {
if let timer = updateTimer {
timer.invalidate()
}
}
}
public override func viewDidLoad() {
super.viewDidLoad()
switch doseStore?.readyState {
case .ready?:
state = .display
case .failed(let error)?:
state = .unavailable(error)
default:
state = .unavailable(nil)
}
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateTimelyStats(nil)
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let updateInterval = TimeInterval(minutes: 5)
let timer = Timer(
fireAt: Date().dateCeiledToTimeInterval(updateInterval).addingTimeInterval(2),
interval: updateInterval,
target: self,
selector: #selector(updateTimelyStats(_:)),
userInfo: nil,
repeats: true
)
updateTimer = timer
RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
updateTimer = nil
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if tableView.isEditing {
tableView.endEditing(true)
}
}
deinit {
doseStoreObserver = nil
}
// MARK: - Data
private enum State {
case unknown
case unavailable(Error?)
case display
}
private var state = State.unknown {
didSet {
if isViewLoaded {
reloadData()
}
}
}
private enum DataSourceSegment: Int {
case reservoir = 0
case history
}
private enum Values {
case reservoir([ReservoirValue])
case history([PersistedPumpEvent])
}
// Not thread-safe
private var values = Values.reservoir([]) {
didSet {
let count: Int
switch values {
case .reservoir(let values):
count = values.count
case .history(let values):
count = values.count
}
if count > 0 {
navigationItem.rightBarButtonItem = self.editButtonItem
}
}
}
private func reloadData() {
switch state {
case .unknown:
break
case .unavailable(let error):
self.tableView.tableHeaderView?.isHidden = true
self.tableView.tableFooterView = UIView()
tableView.backgroundView = needsConfigurationMessageView
if let error = error {
needsConfigurationMessageView.errorDescriptionLabel.text = String(describing: error)
} else {
needsConfigurationMessageView.errorDescriptionLabel.text = nil
}
case .display:
self.tableView.backgroundView = nil
self.tableView.tableHeaderView?.isHidden = false
self.tableView.tableFooterView = nil
switch DataSourceSegment(rawValue: dataSourceSegmentedControl.selectedSegmentIndex)! {
case .reservoir:
doseStore?.getReservoirValues(since: Date.distantPast) { (result) in
DispatchQueue.main.async { () -> Void in
switch result {
case .failure(let error):
self.state = .unavailable(error)
case .success(let reservoirValues):
self.values = .reservoir(reservoirValues)
self.tableView.reloadData()
}
}
self.updateTimelyStats(nil)
self.updateTotal()
}
case .history:
doseStore?.getPumpEventValues(since: Date.distantPast) { (result) in
DispatchQueue.main.async { () -> Void in
switch result {
case .failure(let error):
self.state = .unavailable(error)
case .success(let pumpEventValues):
self.values = .history(pumpEventValues)
self.tableView.reloadData()
}
}
self.updateTimelyStats(nil)
self.updateTotal()
}
}
}
}
@objc func updateTimelyStats(_: Timer?) {
updateIOB()
}
private lazy var iobNumberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
return formatter
}()
private lazy var timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter
}()
private func updateIOB() {
if case .display = state {
doseStore?.insulinOnBoard(at: Date()) { (result) -> Void in
DispatchQueue.main.async {
switch result {
case .failure:
self.iobValueLabel.text = "…"
self.iobDateLabel.text = nil
case .success(let iob):
self.iobValueLabel.text = self.iobNumberFormatter.string(from: NSNumber(value: iob.value))
self.iobDateLabel.text = String(format: NSLocalizedString("com.loudnate.InsulinKit.IOBDateLabel", tableName: "InsulinKit", value: "at %1$@", comment: "The format string describing the date of an IOB value. The first format argument is the localized date."), self.timeFormatter.string(from: iob.startDate))
}
}
}
}
}
private func updateTotal() {
if case .display = state {
let midnight = Calendar.current.startOfDay(for: Date())
doseStore?.getTotalUnitsDelivered(since: midnight) { (result) in
DispatchQueue.main.async {
switch result {
case .failure(let error):
self.state = .unavailable(error)
case .success(let result):
self.totalValueLabel.text = NumberFormatter.localizedString(from: NSNumber(value: result.value), number: .none)
self.totalDateLabel.text = String(format: NSLocalizedString("com.loudnate.InsulinKit.totalDateLabel", tableName: "InsulinKit", value: "since %1$@", comment: "The format string describing the starting date of a total value. The first format argument is the localized date."), DateFormatter.localizedString(from: result.startDate, dateStyle: .none, timeStyle: .short))
}
}
}
}
}
private var doseStoreObserver: Any? {
willSet {
if let observer = doseStoreObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
@IBAction func selectedSegmentChanged(_ sender: Any) {
reloadData()
}
// MARK: - Table view data source
public override func numberOfSections(in tableView: UITableView) -> Int {
switch state {
case .unknown, .unavailable:
return 0
case .display:
return 1
}
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch values {
case .reservoir(let values):
return values.count
case .history(let values):
return values.count
}
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifier, for: indexPath)
if case .display = state {
switch self.values {
case .reservoir(let values):
let entry = values[indexPath.row]
let volume = NumberFormatter.localizedString(from: NSNumber(value: entry.unitVolume), number: .decimal)
let time = timeFormatter.string(from: entry.startDate)
cell.textLabel?.text = "\(volume) U"
cell.detailTextLabel?.text = time
cell.accessoryType = .none
cell.selectionStyle = .none
case .history(let values):
let entry = values[indexPath.row]
let time = timeFormatter.string(from: entry.date)
cell.textLabel?.text = entry.title ?? NSLocalizedString("Unknown", comment: "The default title to use when an entry has none")
cell.detailTextLabel?.text = time
cell.accessoryType = entry.isUploaded ? .checkmark : .none
cell.selectionStyle = .default
}
}
return cell
}
public override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
public override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete, case .display = state {
switch values {
case .reservoir(let reservoirValues):
var reservoirValues = reservoirValues
let value = reservoirValues.remove(at: indexPath.row)
self.values = .reservoir(reservoirValues)
tableView.deleteRows(at: [indexPath], with: .automatic)
doseStore?.deleteReservoirValue(value) { (_, error) -> Void in
if let error = error {
self.presentAlertController(with: error)
self.reloadData()
}
}
case .history(let historyValues):
var historyValues = historyValues
let value = historyValues.remove(at: indexPath.row)
self.values = .history(historyValues)
tableView.deleteRows(at: [indexPath], with: .automatic)
doseStore?.deletePumpEvent(value) { (error) -> Void in
if let error = error {
self.presentAlertController(with: error)
self.reloadData()
}
}
}
}
}
public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if case .display = state, case .history(let history) = values {
let entry = history[indexPath.row]
let vc = CommandResponseViewController(command: { (completionHandler) -> String in
var description = [String]()
description.append(self.timeFormatter.string(from: entry.date))
if let title = entry.title {
description.append(title)
}
if let dose = entry.dose {
description.append(String(describing: dose))
}
if let raw = entry.raw {
description.append(raw.hexadecimalString)
}
return description.joined(separator: "\n\n")
})
vc.title = NSLocalizedString("Pump Event", comment: "The title of the screen displaying a pump event")
show(vc, sender: indexPath)
}
}
}
| 33.826733 | 390 | 0.549393 |
01797fc3fbbbf094fbd0d4ede4311daf6cc2a69c | 545 | //
// Button.swift
// TccSwift
//
// Created by hrk on 2020/10/29.
//
import Foundation
// Button (Read, Notify): Bool CHR_BUTTON
public class ButtonResponse: TccResponse {
static func parse(_ data: Data) -> ButtonResponse? {
switch data[0] {
case 0x01: return ButtonFunctionResponse(data)
default: return nil
}
}
}
public class ButtonFunctionResponse: ButtonResponse {
public let isPushed: Bool
init(_ data:Data) {
isPushed = data[1] != 0 // 0x80 pushed, 0x00 released
}
}
| 20.185185 | 61 | 0.633028 |
48bb44fc839db5ada53078df9d8558852b4d7e07 | 746 | //
// Assertions.swift
// BreakingBadTests
//
// Created by Joshua Simmons on 15/02/2021.
//
import Foundation
import XCTest
import Difference
public func XCTAssertEqualWithDiff<T: Equatable>(
_ expected: @autoclosure () throws -> T,
_ received: @autoclosure () throws -> T,
file: StaticString = #filePath,
line: UInt = #line
) {
do {
let expected = try expected()
let received = try received()
XCTAssertTrue(
expected == received,
"Found difference for \n" + diff(expected, received).joined(separator: ", "),
file: file,
line: line
)
}
catch {
XCTFail("Caught error while testing: \(error)", file: file, line: line)
}
}
| 23.3125 | 89 | 0.589812 |
e8b081fa75b3de8163a1c60454fdf8980c1e98a2 | 633 | //
// CardProductCode.swift
// SbankenClient
//
// Created by Terje Tjervaag on 04/10/2019.
// Copyright © 2019 SBanken. All rights reserved.
//
import Foundation
public enum CardProductCode: String, Codable {
case debitCard = "DebitCard"
case debitCardCl = "DebitCardCL"
case creditCard = "CreditCard"
case creditCardCl = "CreditCardCL"
case debitCardYouth = "DebitCardYouth"
case debitCardYouthCl = "DebitCardYouthCL"
case x2xCard = "X2XCard"
case x2xCardChild = "X2XCardChild"
case x2xCardChildNet = "X2XCardChildNet"
case electronCard = "ElectronCard"
case unknown = "Unknown"
}
| 26.375 | 50 | 0.7109 |
084af83830c869cf78eebf8c89339cec85234da4 | 1,630 | //
// Optional+Validatable.swift
// TinyValidation
//
// Created by Roy Hsu on 2018/9/27.
//
// MARK: - Validatable
// swiftlint:disable syntactic_sugar
extension Optional {
/// Similiar to explicitValidated(by rule:)
@discardableResult
public func explicitValidated(
by validator: (Optional<Wrapped>) throws -> Wrapped
)
rethrows -> Wrapped { return try validator(self) }
/// If the nil value is one of requirements to validate, and you don't want
/// to skip the validation by optional chaining.
/// Please use these two explicit validation methods.
///
/// Example:
///
/// ```
/// var message: String? = nil
///
/// // The validation rule will be triggered.
/// let result: String = try message.explicitValidated(by: rule)
///
/// // The validation will be skipped due to optional chaining
/// let result: String? = try message?.validated(by: rule)
/// ```
///
@discardableResult
public func explicitValidated<Rule>(by rule: Rule)
throws -> Wrapped
where
Rule: ValidationRule,
Rule.Value == Wrapped { return try rule.validate(self) }
@discardableResult
public func explicitValidated<Rule>(by rules: [Rule])
throws -> Wrapped
where
Rule: ValidationRule,
Rule.Value == Wrapped {
let value = try rules.reduce(self) { currentValue, rule in
return try currentValue.explicitValidated(by: rule)
}
guard let validValue = value else { throw NonNullError() }
return validValue
}
}
// swiftlint:enable syntactic_sugar
| 25.46875 | 79 | 0.631902 |
214efdf51608681e4a4800e50d3089aeb3a54fc5 | 4,291 | // Copyright 2020 Tokamak contributors
//
// 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.
//
// Created by Carson Katri on 06/28/2020.
//
public protocol Shape: View {
func path(in rect: CGRect) -> Path
}
public protocol ShapeStyle {}
public extension ShapeStyle where Self: View, Self.Body == _ShapeView<Rectangle, Self> {
var body: some View {
_ShapeView(shape: Rectangle(), style: self)
}
}
public protocol InsettableShape: Shape {
associatedtype InsetShape: InsettableShape
func inset(by amount: CGFloat) -> InsetShape
}
public struct ForegroundStyle: ShapeStyle {
public init() {}
}
public struct FillStyle: Equatable, ShapeStyle {
public var isEOFilled: Bool
public var isAntialiased: Bool
public init(eoFill: Bool = false, antialiased: Bool = true) {
isEOFilled = eoFill
isAntialiased = antialiased
}
}
public struct _ShapeView<Content, Style>: PrimitiveView where Content: Shape, Style: ShapeStyle {
@Environment(\.self) public var environment
@Environment(\.foregroundColor) public var foregroundColor
public var shape: Content
public var style: Style
public var fillStyle: FillStyle
public init(shape: Content, style: Style, fillStyle: FillStyle = FillStyle()) {
self.shape = shape
self.style = style
self.fillStyle = fillStyle
}
}
public extension Shape {
func trim(from startFraction: CGFloat = 0, to endFraction: CGFloat = 1) -> some Shape {
_TrimmedShape(shape: self, startFraction: startFraction, endFraction: endFraction)
}
}
public extension Shape {
func offset(_ offset: CGSize) -> OffsetShape<Self> {
OffsetShape(shape: self, offset: offset)
}
func offset(_ offset: CGPoint) -> OffsetShape<Self> {
OffsetShape(shape: self, offset: CGSize(width: offset.x, height: offset.y))
}
func offset(x: CGFloat = 0, y: CGFloat = 0) -> OffsetShape<Self> {
OffsetShape(shape: self, offset: .init(width: x, height: y))
}
func scale(
x: CGFloat = 1,
y: CGFloat = 1,
anchor: UnitPoint = .center
) -> ScaledShape<Self> {
ScaledShape(
shape: self,
scale: CGSize(width: x, height: y),
anchor: anchor
)
}
func scale(_ scale: CGFloat, anchor: UnitPoint = .center) -> ScaledShape<Self> {
self.scale(x: scale, y: scale, anchor: anchor)
}
func rotation(_ angle: Angle, anchor: UnitPoint = .center) -> RotatedShape<Self> {
RotatedShape(shape: self, angle: angle, anchor: anchor)
}
func transform(_ transform: CGAffineTransform) -> TransformedShape<Self> {
TransformedShape(shape: self, transform: transform)
}
}
public extension Shape {
func size(_ size: CGSize) -> some Shape {
_SizedShape(shape: self, size: size)
}
func size(width: CGFloat, height: CGFloat) -> some Shape {
size(.init(width: width, height: height))
}
}
public extension Shape {
func stroke(style: StrokeStyle) -> some Shape {
_StrokedShape(shape: self, style: style)
}
func stroke(lineWidth: CGFloat = 1) -> some Shape {
stroke(style: StrokeStyle(lineWidth: lineWidth))
}
}
public extension Shape {
func fill<S>(
_ content: S,
style: FillStyle = FillStyle()
) -> some View where S: ShapeStyle {
_ShapeView(shape: self, style: content, fillStyle: style)
}
func fill(style: FillStyle = FillStyle()) -> some View {
_ShapeView(shape: self, style: ForegroundStyle(), fillStyle: style)
}
func stroke<S>(_ content: S, style: StrokeStyle) -> some View where S: ShapeStyle {
stroke(style: style).fill(content)
}
func stroke<S>(_ content: S, lineWidth: CGFloat = 1) -> some View where S: ShapeStyle {
stroke(content, style: StrokeStyle(lineWidth: lineWidth))
}
}
public extension Shape {
var body: some View {
_ShapeView(shape: self, style: ForegroundStyle())
}
}
| 28.045752 | 97 | 0.693545 |
21f44eff2b08c41b456cdf09006eb545769e1699 | 12,584 | //
// BRCameraPlugin.swift
// BreadWallet
//
// Created by Samuel Sutch on 10/9/16.
// Copyright © 2016 Aaron Voisine. All rights reserved.
//
import Foundation
@available(iOS 8.0, *)
@objc open class BRCameraPlugin: NSObject, BRHTTPRouterPlugin, UIImagePickerControllerDelegate,
UINavigationControllerDelegate, CameraOverlayDelegate {
let controller: UIViewController
var response: BRHTTPResponse?
var picker: UIImagePickerController?
init(fromViewController: UIViewController) {
self.controller = fromViewController
super.init()
}
open func hook(_ router: BRHTTPRouter) {
// GET /_camera/take_picture
//
// Optionally pass ?overlay=<id> (see overlay ids below) to show an overlay
// in picture taking mode
//
// Status codes:
// - 200: Successful image capture
// - 204: User canceled image picker
// - 404: Camera is not available on this device
// - 423: Multiple concurrent take_picture requests. Only one take_picture request may be in flight at once.
//
router.get("/_camera/take_picture") { (request, match) -> BRHTTPResponse in
if self.response != nil {
print("[BRCameraPlugin] already taking a picture")
return BRHTTPResponse(request: request, code: 423)
}
if !UIImagePickerController.isSourceTypeAvailable(.camera)
|| UIImagePickerController.availableCaptureModes(for: .rear) == nil {
print("[BRCameraPlugin] no camera available")
return BRHTTPResponse(request: request, code: 404)
}
let response = BRHTTPResponse(async: request)
self.response = response
DispatchQueue.main.async {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .camera
picker.cameraCaptureMode = .photo
// set overlay
if let overlay = request.query["overlay"] , overlay.count == 1 {
print(["BRCameraPlugin] overlay = \(overlay)"])
let screenBounds = UIScreen.main.bounds
if overlay[0] == "id" {
picker.showsCameraControls = false
picker.allowsEditing = false
picker.hidesBarsOnTap = true
picker.isNavigationBarHidden = true
let overlay = IDCameraOverlay(frame: screenBounds)
overlay.delegate = self
overlay.backgroundColor = UIColor.clear
picker.cameraOverlayView = overlay
}
}
self.picker = picker
self.controller.present(picker, animated: true, completion: nil)
}
return response
}
// GET /_camera/picture/(id)
//
// Return a picture as taken by take_picture
//
// Status codes:
// - 200: Successfully returned iamge
// - 404: Couldn't find image with that ID
//
router.get("/_camera/picture/(id)") { (request, match) -> BRHTTPResponse in
var id: String!
if let ids = match["id"] , ids.count == 1 {
id = ids[0]
} else {
return BRHTTPResponse(request: request, code: 500)
}
let resp = BRHTTPResponse(async: request)
do {
let imgDat = try self.readImage(id)
resp.provide(200, data: imgDat, contentType: "image/jpeg")
} catch let e {
print("[BRCameraPlugin] error reading image: \(e)")
resp.provide(500)
}
return resp
}
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
guard let resp = self.response else {
return
}
defer {
self.response = nil
DispatchQueue.main.async {
picker.dismiss(animated: true, completion: nil)
}
}
resp.provide(204, json: nil)
}
open func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
defer {
DispatchQueue.main.async {
picker.dismiss(animated: true, completion: nil)
}
}
guard let resp = self.response else {
return
}
guard var img = info[UIImagePickerControllerOriginalImage] as? UIImage else {
print("[BRCameraPlugin] error picking image... original image doesnt exist. data: \(info)")
resp.provide(500)
response = nil
return
}
resp.request.queue.async {
defer {
self.response = nil
}
do {
if let overlay = self.picker?.cameraOverlayView as? CameraOverlay {
if let croppedImg = overlay.cropImage(img) {
img = croppedImg
}
}
let id = try self.writeImage(img)
print(["[BRCameraPlugin] wrote image to \(id)"])
resp.provide(200, json: ["id": id])
} catch let e {
print("[BRCameraPlugin] error writing image: \(e)")
resp.provide(500)
}
}
}
func takePhoto() {
self.picker?.takePicture()
}
func cancelPhoto() {
if let picker = self.picker {
self.imagePickerControllerDidCancel(picker)
}
}
func readImage(_ name: String) throws -> [UInt8] {
let fm = FileManager.default
let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let picDirUrl = docsUrl.appendingPathComponent("pictures", isDirectory: true)
let picUrl = picDirUrl.appendingPathComponent("\(name).jpeg")
guard let dat = try? Data(contentsOf: picUrl) else {
throw ImageError.couldntRead
}
let bp = (dat as NSData).bytes.bindMemory(to: UInt8.self, capacity: dat.count)
return Array(UnsafeBufferPointer(start: bp, count: dat.count))
}
func writeImage(_ image: UIImage) throws -> String {
guard let dat = UIImageJPEGRepresentation(image, 0.5) else {
throw ImageError.errorConvertingImage
}
let name = (NSData(uInt256: (dat as NSData).sha256()) as NSData).base58String()
let fm = FileManager.default
let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let picDirUrl = docsUrl.appendingPathComponent("pictures", isDirectory: true)
let picDirPath = picDirUrl.path
var attrs = try? fm.attributesOfItem(atPath: picDirPath)
if attrs == nil {
try fm.createDirectory(atPath: picDirPath, withIntermediateDirectories: true, attributes: nil)
attrs = try fm.attributesOfItem(atPath: picDirPath)
}
let picUrl = picDirUrl.appendingPathComponent("\(name).jpeg")
try dat.write(to: picUrl, options: [])
return name
}
}
enum ImageError: Error {
case errorConvertingImage
case couldntRead
}
protocol CameraOverlayDelegate {
func takePhoto()
func cancelPhoto()
}
protocol CameraOverlay {
func cropImage(_ image: UIImage) -> UIImage?
}
class IDCameraOverlay: UIView, CameraOverlay {
var delegate: CameraOverlayDelegate?
let takePhotoButton: UIButton
let cancelButton: UIButton
let overlayRect: CGRect
override init(frame: CGRect) {
overlayRect = CGRect(x: 0, y: 0, width: frame.width, height: frame.width * CGFloat(4.0/3.0))
takePhotoButton = UIButton(type: .custom)
takePhotoButton.setImage(UIImage(named: "camera-btn"), for: UIControlState())
takePhotoButton.setImage(UIImage(named: "camera-btn-pressed"), for: .highlighted)
takePhotoButton.frame = CGRect(x: 0, y: 0, width: 79, height: 79)
takePhotoButton.center = CGPoint(
x: overlayRect.midX,
y: overlayRect.maxX + (frame.height - overlayRect.maxX) * 0.75
)
cancelButton = UIButton(type: .custom)
cancelButton.setTitle(NSLocalizedString("Cancel", comment: ""), for: UIControlState())
cancelButton.frame = CGRect(x: 0, y: 0, width: 88, height: 44)
cancelButton.center = CGPoint(x: takePhotoButton.center.x * 0.3, y: takePhotoButton.center.y)
cancelButton.setTitleColor(UIColor.white, for: UIControlState())
super.init(frame: frame)
takePhotoButton.addTarget(self, action: #selector(IDCameraOverlay.doTakePhoto(_:)),
for: .touchUpInside)
cancelButton.addTarget(self, action: #selector(IDCameraOverlay.doCancelPhoto(_:)),
for: .touchUpInside)
self.addSubview(cancelButton)
self.addSubview(takePhotoButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not implemented")
}
func doTakePhoto(_ target: UIControl) {
delegate?.takePhoto()
}
func doCancelPhoto(_ target: UIControl) {
delegate?.cancelPhoto()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
UIColor.black.withAlphaComponent(0.92).setFill()
UIRectFill(overlayRect)
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
ctx.setBlendMode(.destinationOut)
let width = rect.size.width * 0.9
var cutout = CGRect(origin: overlayRect.origin,
size: CGSize(width: width, height: width * 0.65))
cutout.origin.x = (overlayRect.size.width - cutout.size.width) * 0.5
cutout.origin.y = (overlayRect.size.height - cutout.size.height) * 0.5
let path = UIBezierPath(rect: cutout.integral)
path.fill()
ctx.setBlendMode(.normal)
let str = NSLocalizedString("Center your ID in the box", comment: "") as NSString
let style = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
style.alignment = .center
let attr = [
NSParagraphStyleAttributeName: style,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 17),
NSForegroundColorAttributeName: UIColor.white
]
str.draw(in: CGRect(x: 0, y: cutout.maxY + 14.0, width: rect.width, height: 22), withAttributes: attr)
}
func cropImage(_ image: UIImage) -> UIImage? {
guard let cgimg = image.cgImage else {
return nil
}
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let width = rect.size.width * 0.9
var cutout = CGRect(origin: rect.origin,
size: CGSize(width: width, height: width * 0.65))
cutout.origin.x = (rect.size.width - cutout.size.width) * 0.5
cutout.origin.y = (rect.size.height - cutout.size.height) * 0.5
cutout = cutout.integral
func rad(_ f: CGFloat) -> CGFloat {
return f / 180.0 * CGFloat(M_PI)
}
var transform: CGAffineTransform!
switch image.imageOrientation {
case .left:
transform = CGAffineTransform(rotationAngle: rad(90)).translatedBy(x: 0, y: -image.size.height)
case .right:
transform = CGAffineTransform(rotationAngle: rad(-90)).translatedBy(x: -image.size.width, y: 0)
case .down:
transform = CGAffineTransform(rotationAngle: rad(-180)).translatedBy(x: -image.size.width,
y: -image.size.height)
default:
transform = CGAffineTransform.identity
}
transform = transform.scaledBy(x: image.scale, y: image.scale)
cutout = cutout.applying(transform)
guard let retRef = cgimg.cropping(to: cutout) else {
return nil
}
return UIImage(cgImage: retRef, scale: image.scale, orientation: image.imageOrientation)
}
}
| 38.959752 | 118 | 0.571043 |
1df4a61fb8556a12903b6a556f7f7fe2aa337078 | 251 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a<T {
class a<T> : A {
protocol e
protocol A {
let : (f: e
import
protocol A
| 20.916667 | 87 | 0.729084 |
181086c910f5b6c048c3b1e79c7497abedb98b42 | 321 | import UIKit
extension UIStoryboard {
func instantiateViewController<T: UIViewController>(ofType _: T.Type, withIdentifier identifier: String? = nil) -> T {
let identifier = identifier ?? String(describing: T.self)
return instantiateViewController(withIdentifier: identifier) as! T
}
}
| 29.181818 | 122 | 0.70405 |
e0aef369f8ab71dc0a8d3395e5ee76ebb735b900 | 2,190 | //
// AppDelegate.swift
// ExpandButtonAnimation
//
// Created by Anantha Krishnan K G on 29/08/18.
// Copyright © 2018 Ananth. 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.595745 | 285 | 0.756164 |
c119e92e82b92155f25d98a4a2cc3ef79dd3342a | 5,300 | //
// MetadataMappings.swift
// player-sdk-swift
//
// Copyright (c) 2021 nacamar GmbH - Ybrid®, a Hybrid Dynamic Live Audio Technology
//
// 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
class IcyMetadata : AbstractMetadata {
private let data:[String:String]
override var description:String { get {
return "\(type(of: self)) with keys \(data.keys)"
}}
init(icyData:[String:String]) {
self.data = icyData
super.init()
}
override var streamUrl:String? { get {
return super.delegate?.streamUrl ??
data["StreamUrl"]?.trimmingCharacters(in: CharacterSet.init(charactersIn: "'"))
}}
// content of icy-data "StreamTitle", mostly "[$ARTIST - ]$TITLE"
override var currentInfo: Item? { get {
guard let displayTitle = data["StreamTitle"]?.trimmingCharacters(in: CharacterSet.init(charactersIn: "'")) else {
return nil
}
return Item(displayTitle:displayTitle)
}}
// content of http-headers "icy-name" and "icy-genre" ("ice-*" were mapped to "icy-*")
override var serviceInfo: Service? { get {
guard let name = data["icy-name"] else { return nil }
return Service(identifier: name, displayName: name, genre: data["icy-genre"],
description: data["icy-description"], infoUri: data["icy-url"] )
}}
}
class OpusMetadata : AbstractMetadata {
private let vorbis:[String:String]
override var description:String { get {
return "\(type(of: self)) with vorbis comments \(vorbis.keys)"
}}
init(vorbisComments:[String:String]) {
self.vorbis = vorbisComments
super.init()
}
override var currentInfo: Item? { get {
let displayTitle = combinedTitle(comments: vorbis) ?? ""
// guard let displayTitle = combinedTitle(comments: vorbis) else {
// return nil
// }
return Item(displayTitle:displayTitle, title:vorbis["TITLE"], artist:vorbis["ARTIST"],
album:vorbis["ALBUM"], version:vorbis["VERSION"],
description:vorbis["DESCRIPTION"], genre:vorbis["GENRE"])
}}
// returns "[$ALBUM - ][$ARTIST - ]$TITLE[ ($VERSION)]"
private func combinedTitle(comments: [String:String]) -> String? {
let relevant:[String] = ["ALBUM", "ARTIST", "TITLE"]
let playout = relevant
.filter { comments[$0] != nil }
.map { comments[$0]! }
var result = playout.joined(separator: " - ")
if let version = comments["VERSION"] {
result += " (\(version))"
}
if result.count > 0 {
return result
}
return nil
}
}
class YbridMetadata : AbstractMetadata {
let v2:YbridV2Metadata
init(ybridV2:YbridV2Metadata) {
self.v2 = ybridV2
super.init()
}
override var currentInfo: Item? { get {
return createItem(ybrid: v2.currentItem)
}}
override var nextInfo: Item? { get {
return createItem(ybrid: v2.nextItem)
}}
override var serviceInfo: Service? { get {
// content of __responseObject.metatdata.station
let ybridStation = v2.station
let name = ybridStation.name
return Service(identifier: name, displayName: name, genre: ybridStation.genre)
}}
private func createItem(ybrid: YbridItem) -> Item? {
let type = typeFrom(type: ybrid.type)
let displayTitle = combinedTitle(item: ybrid)
let playbackLength = TimeInterval( ybrid.durationMillis / 1_000 )
return Item(displayTitle:displayTitle, identifier:ybrid.id, type:type,
title:ybrid.title, artist:ybrid.artist,
description:ybrid.description, playbackLength: playbackLength)
}
private func typeFrom(type: String) -> ItemType {
if let type = ItemType(rawValue: type) {
return type
}
return ItemType.UNKNOWN
}
// returns "$TITLE[ by $ARTIST]"
private func combinedTitle(item: YbridItem) -> String {
var result = item.title
if !item.artist.isEmpty {
result += "\nby \(item.artist)"
}
return result
}
}
| 35.57047 | 121 | 0.630189 |
3891d48f1ec55566540e269df19367476d0a0e7e | 7,626 | //
// 🦠 Corona-Warn-App
//
import XCTest
import Combine
@testable import ENA
class DatePickerDayViewModelTests: XCTestCase {
func testTodayNotSelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .today(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: false
)
XCTAssertFalse(viewModel.isSelected)
XCTAssertEqual(viewModel.fontSize, 16)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .background))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textTint))
XCTAssertEqual(viewModel.fontWeight, "bold")
XCTAssertEqual(viewModel.accessibilityTraits, [.button])
XCTAssertEqual(viewModel.dayString, "1")
XCTAssertEqual(viewModel.accessibilityLabel, "1. Januar 2001")
XCTAssertTrue(viewModel.isSelectable)
}
func testTodaySelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .today(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: true
)
XCTAssertTrue(viewModel.isSelected)
XCTAssertEqual(viewModel.fontSize, 16)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .tint))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textContrast))
XCTAssertEqual(viewModel.fontWeight, "bold")
XCTAssertEqual(viewModel.accessibilityTraits, [.button, .selected])
XCTAssertEqual(viewModel.dayString, "1")
XCTAssertEqual(viewModel.accessibilityLabel, "1. Januar 2001")
XCTAssertTrue(viewModel.isSelectable)
}
func testUpTo21DaysAgoNotSelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .upTo21DaysAgo(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: false
)
XCTAssertFalse(viewModel.isSelected)
XCTAssertEqual(viewModel.fontSize, 16)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .background))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textPrimary1))
XCTAssertEqual(viewModel.fontWeight, "regular")
XCTAssertEqual(viewModel.accessibilityTraits, [.button])
XCTAssertEqual(viewModel.dayString, "1")
XCTAssertEqual(viewModel.accessibilityLabel, "1. Januar 2001")
XCTAssertTrue(viewModel.isSelectable)
}
func testUpTo21DaysAgoSelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .upTo21DaysAgo(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: true
)
XCTAssertTrue(viewModel.isSelected)
XCTAssertEqual(viewModel.fontSize, 16)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .tint))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textContrast))
XCTAssertEqual(viewModel.fontWeight, "medium")
XCTAssertEqual(viewModel.accessibilityTraits, [.button, .selected])
XCTAssertEqual(viewModel.dayString, "1")
XCTAssertEqual(viewModel.accessibilityLabel, "1. Januar 2001")
XCTAssertTrue(viewModel.isSelectable)
}
func testMoreThan21DaysAgoNotSelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .moreThan21DaysAgo(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: false
)
XCTAssertFalse(viewModel.isSelected)
XCTAssertEqual(viewModel.fontSize, 16)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .background))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textPrimary3))
XCTAssertEqual(viewModel.fontWeight, "regular")
XCTAssertEqual(viewModel.accessibilityTraits, [])
XCTAssertEqual(viewModel.dayString, "1")
XCTAssertEqual(viewModel.accessibilityLabel, "1. Januar 2001")
XCTAssertFalse(viewModel.isSelectable)
}
func testFutureNotSelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .future(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: false
)
XCTAssertFalse(viewModel.isSelected)
XCTAssertEqual(viewModel.fontSize, 16)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .background))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textPrimary3))
XCTAssertEqual(viewModel.fontWeight, "regular")
XCTAssertEqual(viewModel.accessibilityTraits, [])
XCTAssertEqual(viewModel.dayString, "1")
XCTAssertEqual(viewModel.accessibilityLabel, "1. Januar 2001")
XCTAssertFalse(viewModel.isSelectable)
}
func testTapOnFutureDate() {
let expectation = XCTestExpectation(description: "onTapOnDate not called")
expectation.isInverted = true
let viewModel = DatePickerDayViewModel(
datePickerDay: .future(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in expectation.fulfill() },
isSelected: false
)
viewModel.onTap()
wait(for: [expectation], timeout: .medium)
}
func testTapOnMoreThan21DaysAgoDate() {
let expectation = XCTestExpectation(description: "onTapOnDate not called")
expectation.isInverted = true
let viewModel = DatePickerDayViewModel(
datePickerDay: .moreThan21DaysAgo(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in expectation.fulfill() },
isSelected: false
)
viewModel.onTap()
wait(for: [expectation], timeout: .medium)
}
func testTapOnUpTo21DaysAgoDate() {
let expectation = XCTestExpectation(description: "onTapOnDate called")
let viewModel = DatePickerDayViewModel(
datePickerDay: .upTo21DaysAgo(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in expectation.fulfill() },
isSelected: false
)
viewModel.onTap()
wait(for: [expectation], timeout: .medium)
}
func testTapOnTodayDate() {
let expectation = XCTestExpectation(description: "onTapOnDate called")
let viewModel = DatePickerDayViewModel(
datePickerDay: .today(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in expectation.fulfill() },
isSelected: false
)
viewModel.onTap()
wait(for: [expectation], timeout: .medium)
}
func testChangeTodayFromNotSelectedToSelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .today(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: false
)
XCTAssertFalse(viewModel.isSelected)
viewModel.isSelected = true
XCTAssertTrue(viewModel.isSelected)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .tint))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textContrast))
XCTAssertEqual(viewModel.accessibilityTraits, [.button, .selected])
}
func testChangeTodayFromSelectedToNotSelected() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .today(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: true
)
XCTAssertTrue(viewModel.isSelected)
viewModel.isSelected = false
XCTAssertFalse(viewModel.isSelected)
XCTAssertEqual(viewModel.backgroundColor, .enaColor(for: .background))
XCTAssertEqual(viewModel.textColor, .enaColor(for: .textTint))
XCTAssertEqual(viewModel.accessibilityTraits, [.button])
}
func testSelectIfSameDateWithSameDate() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .today(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: false
)
XCTAssertFalse(viewModel.isSelected)
viewModel.selectIfSameDate(date: Date(timeIntervalSinceReferenceDate: 0))
XCTAssertTrue(viewModel.isSelected)
}
func testSelectIfSameDateWithDifferentDate() {
let viewModel = DatePickerDayViewModel(
datePickerDay: .today(Date(timeIntervalSinceReferenceDate: 0)),
onTapOnDate: { _ in },
isSelected: false
)
XCTAssertFalse(viewModel.isSelected)
viewModel.selectIfSameDate(date: Date(timeIntervalSinceReferenceDate: 24 * 60 * 60))
XCTAssertFalse(viewModel.isSelected)
}
}
| 30.023622 | 86 | 0.763047 |
fe7809ddd251b017e164c0f1c904e6ca1fbe1399 | 2,136 | import CoreBluetooth
public final class Bluetooth: BaseSource, Source, Controllable {
public enum Status: String {
case unknown = "Unknown"
case resetting = "Resetting"
case unsupported = "Unsupported"
case unauthorized = "Unauthorized"
case off = "Off"
case on = "On"
fileprivate init(manager: CBCentralManager) {
switch manager.state {
case .unknown: self = .unknown
case .resetting: self = .resetting
case .unsupported: self = .unsupported
case .unauthorized: self = .unauthorized
case .poweredOff: self = .off
case .poweredOn: self = .on
}
}
}
public static var availability: SourceAvailability {
let manager = CBCentralManager(delegate: nil, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: false])
return manager.state != .unsupported ? .available : .unavailable
}
public static let name = "Bluetooth"
public var isUpdating: Bool {
return manager.delegate != nil
}
public private(set) var status: GenericUnitlessValue<Status>
public var allValues: [Value] {
return [
status,
]
}
private let manager: CBCentralManager
public override init() {
let queue = DispatchQueue(label: "")
manager = CBCentralManager(delegate: nil, queue: queue, options: [CBCentralManagerOptionShowPowerAlertKey: false])
let status = Status(manager: manager)
self.status = GenericUnitlessValue(displayName: "Status", backingValue: status, formattedValue: status.rawValue)
}
public func startUpdating() {
manager.delegate = self
}
public func stopUpdating() {
manager.delegate = nil
}
}
extension Bluetooth: CBCentralManagerDelegate {
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
let status = Status(manager: manager)
self.status.update(backingValue: status, formattedValue: status.rawValue)
notifyListenersPropertyValuesUpdated()
}
}
| 27.384615 | 124 | 0.641386 |
8950aa824f2a9548f8af62701868c72b81731b76 | 4,270 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// Campaign.swift
// Tracker
//
import Foundation
enum CampaignKeys: String, EnumCollection {
case ATCampaign = "ATCampaign"
case ATCampaignDate = "ATCampaignDate"
case ATCampaignAdded = "ATCampaignAdded"
}
/// Wrapper class for marketing campaign tracking
public class Campaign: ScreenInfo {
/// Campaign id (XTO)
@objc public var campaignId: String = ""
override init(tracker: Tracker) {
super.init(tracker: tracker)
}
/// Create a new campaign with an identifier
///
/// - Parameter campaignId: campaignId identifier
@objc public init(campaignId: String) {
super.init()
self.campaignId = campaignId
}
/// Set parameters in buffer
override func setParams() {
let userDefaults = UserDefaults.standard
let encodeOption = ParamOption()
encodeOption.encode = true
if let remanentCampaign = userDefaults.value(forKey: CampaignKeys.ATCampaign.rawValue) as? String, let campaignDate = userDefaults.object(forKey: CampaignKeys.ATCampaignDate.rawValue) as? Date {
let nbDays: Int = Tool.daysBetweenDates(campaignDate, toDate: Date())
if let lifetimeString = tracker.configuration.parameters["campaignLifetime"],
let lifetime = Int(lifetimeString), nbDays > lifetime {
userDefaults.removeObject(forKey: CampaignKeys.ATCampaign.rawValue)
} else {
let remanent = remanentCampaign
_ = tracker.setParam("xtor", value: remanent, options: encodeOption)
}
} else {
userDefaults.set(Date(), forKey: CampaignKeys.ATCampaignDate.rawValue)
userDefaults.setValue(campaignId, forKey: CampaignKeys.ATCampaign.rawValue)
}
_ = tracker.setParam("xto", value: campaignId, options: encodeOption)
userDefaults.setValue(true, forKey: CampaignKeys.ATCampaignAdded.rawValue)
if(tracker.configuration.parameters["campaignLastPersistence"]?.lowercased() == "true") {
userDefaults.set(Date(), forKey: CampaignKeys.ATCampaignDate.rawValue)
userDefaults.setValue(campaignId, forKey: CampaignKeys.ATCampaign.rawValue)
}
userDefaults.synchronize()
}
}
/// Wrapper class to manage Campaign instances
public class Campaigns: NSObject {
/// Tracker instance
var tracker: Tracker
/**
Campaigns initializer
- parameter tracker: the tracker instance
- returns: Campaigns instance
*/
init(tracker: Tracker) {
self.tracker = tracker;
}
/// Add tagging data for a campaign
///
/// - Parameter campaignId: campaign identifier
/// - Returns: the Campaign instance
@objc public func add(campaignId: String) -> Campaign {
let campaign = Campaign(tracker: tracker)
campaign.campaignId = campaignId
tracker.businessObjects[campaign.id] = campaign
return campaign
}
}
| 35.882353 | 202 | 0.689696 |
0ac95d6beaaf34858fadc33d44ae0ce9354250d1 | 199 | //
// Point.swift
// luminate
//
// Created by Prayash Thapa on 10/10/17.
// Copyright © 2017 com.reality.af. All rights reserved.
//
import UIKit
struct Point {
let destination: String
}
| 13.266667 | 57 | 0.658291 |
28576585114e107c7b4b34bc94c0e474f4be504c | 456 | //
// AssignExpression.swift
//
//
// Created by RagnaCron on 27.10.21.
//
final class AssignExpression: Expression {
let name: Token
let value: Expression
override func accept<V: ExpressionVisitor, R>(visitor: V) throws -> R where R == V.ExpressionVisitorReturnType {
return try visitor.visitAssign(expr: self)
}
init(name: Token, value: Expression) {
self.name = name
self.value = value
}
}
| 21.714286 | 116 | 0.631579 |
1464ed5c5347474c0b223da43731f0eca17cdd0c | 6,478 | //
// ViewController.swift
// carouselPOC
//
// Created by Omar AlQasmi on 5/13/20.
// Copyright © 2020 testting.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController , UICollectionViewDelegate {
@IBOutlet weak var carousel: UICollectionView!
//UIcollectionView Declare datasource and design/flow
let collectionDataSource = CollectionDataSource()
let flowLayout = ZoomAndSnapFlowLayout()
// MARK:- ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
carousel.delegate = self
carousel.allowsMultipleSelection = true
carousel.dataSource = collectionDataSource
carousel.collectionViewLayout = flowLayout
carousel.contentInsetAdjustmentBehavior = .always
//Select the third cell by default
carousel.performBatchUpdates(nil) { (isLoded) in
if isLoded{
self.carousel.scrollToItem(at:IndexPath(item: 2, section: 0), at: .centeredHorizontally, animated: false)
}
}
}
// MARK:- Get selected cell index
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
carousel.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
workWithSelectedCell(indexPath.row)
}
// MARK:- Get cell index on scroll
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var visibleRect = CGRect()
visibleRect.origin = carousel.contentOffset
visibleRect.size = carousel.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
guard let indexPath = carousel.indexPathForItem(at: visiblePoint) else { return }
workWithSelectedCell(indexPath.row)
}
// MARK:- Work with selected cell
func workWithSelectedCell (_ index : Int){
print("Selected = \(index)")
print(collectionDataSource.items[index])
}
}
// MARK:- Collection Design and flow Class
class ZoomAndSnapFlowLayout: UICollectionViewFlowLayout {
let activeDistance: CGFloat = 130
let zoomFactor: CGFloat = 0.7
override init() {
super.init()
scrollDirection = .horizontal
minimumLineSpacing = 15
itemSize = CGSize(width: 60, height: 60)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepare() {
guard let collectionView = collectionView else { fatalError() }
let verticalInsets = (collectionView.frame.height - collectionView.adjustedContentInset.top - collectionView.adjustedContentInset.bottom - itemSize.height) / 2
let horizontalInsets = (collectionView.frame.width - collectionView.adjustedContentInset.right - collectionView.adjustedContentInset.left - itemSize.width) / 2
sectionInset = UIEdgeInsets(top: verticalInsets, left: horizontalInsets, bottom: verticalInsets, right: horizontalInsets)
super.prepare()
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = collectionView else { return nil }
let rectAttributes = super.layoutAttributesForElements(in: rect)!.map { $0.copy() as! UICollectionViewLayoutAttributes }
let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.frame.size)
// Make the cells be zoomed when they reach the center of the screen
for attributes in rectAttributes where attributes.frame.intersects(visibleRect) {
let distance = visibleRect.midX - attributes.center.x
let normalizedDistance = distance / activeDistance
if distance.magnitude < activeDistance {
let zoom = 1 + zoomFactor * (1 - normalizedDistance.magnitude)
attributes.transform3D = CATransform3DMakeScale(zoom, zoom, 1)
attributes.zIndex = Int(zoom.rounded())
}
}
return rectAttributes
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else { return .zero }
// Add some snapping behaviour so that the zoomed cell is always centered
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.frame.width, height: collectionView.frame.height)
guard let rectAttributes = super.layoutAttributesForElements(in: targetRect) else { return .zero }
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
let horizontalCenter = proposedContentOffset.x + collectionView.frame.width / 2
for layoutAttributes in rectAttributes {
let itemHorizontalCenter = layoutAttributes.center.x
if (itemHorizontalCenter - horizontalCenter).magnitude < offsetAdjustment.magnitude {
offsetAdjustment = itemHorizontalCenter - horizontalCenter
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
// Invalidate layout so that every cell get a chance to be zoomed when it reaches the center of the screen
return true
}
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size
return context
}
}
//MARK:- Data Source Class
class CollectionDataSource: NSObject, UICollectionViewDataSource {
var items = ["zero","one","two","three","four","five","six","seven","8","9","10","11","12","13","14","15","16","17","18"]
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "carCell", for: indexPath) as! MyCollectionViewCell
cell.lblTitle.text = items[indexPath.row]
return cell
}
}
| 43.47651 | 167 | 0.703303 |
5d95c1b2aa675789b58aba88c9998f169ba951a9 | 4,222 | //
// SnippetElementView.swift
// mRayon
//
// Created by Lakr Aream on 2022/3/3.
//
import RayonModule
import SwiftUI
struct SnippetElementView: View {
@EnvironmentObject var store: RayonStore
let identity: RDSnippet.ID
@State var openEdit: Bool = false
var body: some View {
VStack(alignment: .leading, spacing: 4) {
HStack {
Image(systemName: store.snippetGroup[identity].getSFAvatar())
.font(.system(.subheadline, design: .rounded))
.frame(width: 20)
Text(store.snippetGroup[identity].name)
.font(.system(.headline, design: .rounded))
.bold()
Spacer()
}
Text(store.snippetGroup[identity].comment)
.font(.system(.footnote, design: .rounded))
Divider()
VStack(spacing: 0) {
Text(
store
.snippetGroup[identity]
.code
.trimmingCharacters(in: .whitespacesAndNewlines)
)
.font(.system(.subheadline, design: .monospaced))
Spacer()
}
.frame(height: 90)
Divider()
Text(identity.uuidString)
.font(.system(size: 8, weight: .light, design: .rounded))
}
.padding()
.background(
Color(UIColor.systemGray6)
.roundedCorner()
)
.background(
NavigationLink(isActive: $openEdit) {
EditSnippetView { identity }
} label: {
Group {}
}
)
.onTapGesture {
debugPrint(#function)
}
.overlay(
Menu {
Section {
Button {
let snippet = store.snippetGroup[identity]
guard !snippet.name.isEmpty,
!snippet.code.isEmpty
else {
return
}
RayonUtil.createExecuteFor(snippet: snippet)
} label: {
Label("Execute", systemImage: "paperplane")
}
Button {
let snippet = store.snippetGroup[identity]
guard !snippet.name.isEmpty,
!snippet.code.isEmpty
else {
return
}
UIBridge.sendPasteboard(str: snippet.code)
} label: {
Label("Copy Script", systemImage: "chevron.left.forwardslash.chevron.right")
}
}
Section {
Button {
openEdit = true
} label: {
Label("Edit", systemImage: "pencil")
}
Button {
var newSnippet = store.snippetGroup[identity]
newSnippet.id = .init()
store.snippetGroup.insert(newSnippet)
} label: {
Label("Duplicate", systemImage: "plus.square.on.square")
}
}
Section {
Button {
delete()
} label: {
Label("Delete", systemImage: "trash")
}
}
} label: {
Color.accentColor
.opacity(0.0001)
}
.offset(x: 0, y: 4)
)
}
func delete() {
UIBridge.requiresConfirmation(
message: "Are you sure you want to delete this snippet?"
) { confirmed in
if confirmed {
store.snippetGroup.delete(identity)
}
}
}
}
struct SnippetElementView_Previews: PreviewProvider {
static var previews: some View {
SnippetElementView(identity: UUID())
}
}
| 31.744361 | 100 | 0.418996 |
149d4b2d00296e3335345083de41fdc0ca45bfb2 | 8,354 | //
// ATCFirebaseSocialGraphManager.swift
// ChatApp
//
// Created by Florian Marcu on 9/15/18.
// Copyright © 2018 Instamobile. All rights reserved.
//
import FirebaseFirestore
class ATCFirebaseSocialGraphManager: ATCSocialGraphManagerProtocol {
let reportingManager = ATCFirebaseUserReporter()
func fetchFriends(viewer: ATCUser, completion: @escaping (_ friends: [ATCUser]) -> Void) {
self.fetchFriendships(viewer: viewer) { (friendships) in
completion(friendships.compactMap({$0.type == .mutual ? $0.otherUser : nil}))
}
}
func fetchFriendships(viewer: ATCUser, completion: @escaping (_ friendships: [ATCChatFriendship]) -> Void) {
guard let uid = viewer.uid else { return }
let serialQueue = DispatchQueue(label: "com.iosapptemplates.friendshipsfetching.queue")
// Exclude all users that are reported
reportingManager.userIDsBlockedOrReported(by: viewer) { (illegalUserIDsSet) in
let ref = Firestore.firestore().collection("friendships").whereField("user1", isEqualTo: uid)
let usersRef = Firestore.firestore().collection("users")
ref.getDocuments { (querySnapshot, error) in
if error != nil {
completion([])
return
}
guard let querySnapshot = querySnapshot else {
return
}
let documentsAsUser1 = querySnapshot.documents
let ref2 = Firestore.firestore().collection("friendships").whereField("user2", isEqualTo: uid)
ref2.getDocuments { (querySnapshot, error) in
if error != nil {
completion([])
return
}
guard let querySnapshot = querySnapshot else {
completion([])
return
}
var hydratedUsers: [ATCUser] = []
let documentsAsUser2 = querySnapshot.documents
let otherUserIDsAsUser1 = documentsAsUser1.compactMap({$0.data()["user2"] as? String}).filter({!illegalUserIDsSet.contains($0)})
let otherUserIDsAsUser2 = documentsAsUser2.compactMap({$0.data()["user1"] as? String}).filter({!illegalUserIDsSet.contains($0)})
let friendsIDs = otherUserIDsAsUser1.filter({otherUserIDsAsUser2.contains($0)}) // Mutual friends
let outboundRequestsUserIDs = Set(otherUserIDsAsUser1.filter({!otherUserIDsAsUser2.contains($0)})) // I made the request, but it wasn't accepted yet
let inboundRequestsUserIDs = Set(otherUserIDsAsUser2.filter({!otherUserIDsAsUser1.contains($0)})) // They made a request, but I didn't accept it yet
let allUniqueUsersIDsToBeHydrated = Array(Set(otherUserIDsAsUser1 + otherUserIDsAsUser2))
if allUniqueUsersIDsToBeHydrated.count == 0 {
completion([])
return
}
for userID in allUniqueUsersIDsToBeHydrated {
usersRef.document(userID).getDocument(completion: { (document, error) in
if let userDict = document?.data() {
let user = ATCUser(representation: userDict)
serialQueue.sync {
hydratedUsers.append(user)
}
if hydratedUsers.count == allUniqueUsersIDsToBeHydrated.count {
// Now that we hydrated all the users that are in the friendships table,
// related to the current user (user1 or user2), we send back the full response
// First we add the friends
let friendships = friendsIDs.map({ATCChatFriendship(currentUser: viewer, otherUser: self.user(for: $0, in: hydratedUsers), type: .mutual)})
// Then we add the inbound requests
let inboundRequests = inboundRequestsUserIDs.map({ATCChatFriendship(currentUser: viewer, otherUser: self.user(for: $0, in: hydratedUsers), type: .inbound)})
// Then we add the outbound requests
let outboundRequests = outboundRequestsUserIDs.map({ATCChatFriendship(currentUser: viewer, otherUser: self.user(for: $0, in: hydratedUsers), type: .outbound)})
completion(friendships + inboundRequests + outboundRequests)
}
}
})
}
}
}
}
}
private func user(for id: String, in users: [ATCUser]) -> ATCUser {
for user in users {
if user.uid == id {
return user
}
}
fatalError()
}
func fetchUsers(viewer: ATCUser, completion: @escaping (_ friends: [ATCUser]) -> Void) {
reportingManager.userIDsBlockedOrReported(by: viewer) { (illegalUserIDsSet) in
let usersRef = Firestore.firestore().collection("users")
usersRef.getDocuments { (querySnapshot, error) in
if error != nil {
return
}
guard let querySnapshot = querySnapshot else {
return
}
var users: [ATCUser] = []
let documents = querySnapshot.documents
for document in documents {
let data = document.data()
let user = ATCUser(representation: data)
if let userID = user.uid {
if userID != viewer.uid && !illegalUserIDsSet.contains(userID) {
users.append(user)
}
}
}
completion(users)
}
}
}
func sendFriendRequest(viewer: ATCUser, to user: ATCUser, completion: @escaping () -> Void) {
guard let u1 = viewer.uid, let u2 = user.uid else { return }
let friendshipRef = Firestore.firestore().collection("friendships")
friendshipRef.addDocument(data: [
"user1" : u1,
"user2" : u2
]) { (error) in
self.postGraphUpdateNotification()
completion()
}
}
func acceptFriendRequest(viewer: ATCUser, from user: ATCUser, completion: @escaping () -> Void) {
guard let uid = viewer.uid, let user2UID = user.uid else { return }
let friendshipRef = Firestore.firestore().collection("friendships")
friendshipRef.addDocument(data: ["user1" : uid,
"user2" : user2UID]) { (error) in
self.postGraphUpdateNotification()
self.postGraphUpdateNotification()
completion()
}
}
func cancelFriendRequest(viewer: ATCUser, to user: ATCUser, completion: @escaping () -> Void) {
guard let uid = viewer.uid, let user2UID = user.uid else { return }
let friendshipRef = Firestore.firestore()
.collection("friendships")
.whereField("user1", isEqualTo: uid)
.whereField("user2", isEqualTo: user2UID)
friendshipRef.getDocuments { (snapshot, error) in
guard let snapshot = snapshot else {
completion()
return
}
snapshot.documents.forEach({ (document) in
Firestore.firestore().collection("friendships").document(document.documentID).delete(completion: { (error) in
self.postGraphUpdateNotification()
})
})
completion()
}
}
func postGraphUpdateNotification() {
NotificationCenter.default.post(name: kSocialGraphDidUpdateNotificationName, object: nil)
}
}
| 48.853801 | 195 | 0.530405 |
914ecc8300f10769638bc468f2fc7c982bd0466a | 1,219 | //
// VCS.swift
// CI2Go
//
// Created by Atsushi Nagase on 2018/06/17.
// Copyright © 2018 LittleApps Inc. All rights reserved.
//
import Foundation
enum VCS: String, Codable {
case github
case bitbucket
init?(shortName: String) {
switch shortName {
case VCS.github.shortName:
self = .github
case VCS.bitbucket.shortName:
self = .bitbucket
default:
return nil
}
}
init?(longName: String) {
switch longName {
case VCS.github.longName:
self = .github
case VCS.bitbucket.longName:
self = .bitbucket
default:
return nil
}
}
var host: String {
switch self {
case .github:
return "github.com"
case .bitbucket:
return "bitbucket.org"
}
}
var shortName: String {
switch self {
case .github:
return "gh"
case .bitbucket:
return "bb"
}
}
var longName: String {
switch self {
case .github:
return "github"
case .bitbucket:
return "bitbucket"
}
}
}
| 19.046875 | 57 | 0.497129 |
466763d31bbfc69a64032b9c5e536739b2cc8762 | 8,645 | //
// IGCHeader.swift
// Iguazu
//
// Created by Engin Kurutepe on 12/06/16.
// Copyright © 2016 Fifteen Jugglers Software. All rights reserved.
//
import Foundation
/// Representation of the Header field types as listed in
/// http://carrier.csi.cam.ac.uk/forsterlewis/soaring/igc_file_format/igc_format_2008.html#link_3.3
///
/// - date: flight date
/// - accuracy: typical accuracy the logger is capable of
/// - pilotInCharge: name of PIC
/// - crew: name of crew
/// - gliderType: free-text glider make/model
/// - gliderRegistration: official registration of the glider
/// - gpsDatum: GPS datum used for the fixes
/// - firmwareVersion: free-text firmware version of the logger (not implemeneted)
/// - hardwareVersion: free-text hardware version of the logger (not implemeneted)
/// - loggerType: logger make/model (not implemeneted)
/// - gpsType: gps make/model etc (not implemeneted)
/// - altimeterType: altimeter make/model etc (not implemeneted)
/// - competitionID: competition callsign of the glider
/// - competitionClass: competition class of the glider
public enum IGCHeaderField {
enum HeaderRecordCode: String {
case date = "DTE"
case accuracy = "FXA"
case pilot = "PLT"
case crew = "CM2"
case gliderType = "GTY"
case gliderRegistration = "GID"
case gpsDatum = "DTM"
case firmwareVersion = "RFW"
case hardwareVersion = "RHW"
case loggerType = "FTY"
case gpsType = "GPS"
case altimeterType = "PRS"
case competitionID = "CID"
case competitionClass = "CCL"
}
// UTC date this file was recorded
case date(flightDate: Date)
// Fix accuracy in meters, see also FXA three-letter-code reference
case accuracy(accuracy: Int)
// Name of the competing pilot
case pilotInCharge(name: String)
// Name of the second pilot in a two-seater
case crew(name: String)
// Free-text name of the glider model
case gliderType(gliderType: String)
// Glider registration number, e.g. N-number
case gliderRegistration(registration: String)
// GPS datum used for the log points - use igc code 100 / WGS84 unless you are insane.
case gpsDatum(code: Int, datum: String)
// Any free-text string descibing the firmware revision of the logger
case firmwareVersion(version: String)
// Any free-text string giving the hardware revision number of the logger
case hardwareVersion(version: String)
// Logger free-text manufacturer and model
case loggerType(brand: String, model: String)
// Manufacturer and model of the GPS receiver used in the logger.
case gpsType(brand: String, model: String, channels: Int, maximumAltitude: Int)
// Free-text (separated by commas) description of the pressure sensor used in the logger
case altimeterType(brand: String, model: String, maximumAltitude: Int)
// The fin-number by which the glider is generally recognised
case competitionID(id: String)
// Any free-text description of the class this glider is in, e.g. Standard, 15m, 18m, Open.
case competitionClass(competitionClass: String)
static func parseHLine(hLine: String) -> IGCHeaderField? {
guard let prefix = hLine.igcHeaderPrefix() else { return nil }
switch prefix {
case .date:
return parseDateString(hLine: hLine)
case .accuracy:
return parseAccuracyString(hLine: hLine)
case .pilot:
let name = parseFreeTextLine(line: hLine, prefix: HeaderRecordCode.pilot.rawValue)
return .pilotInCharge(name: name)
case .crew:
let name = parseFreeTextLine(line: hLine, prefix: HeaderRecordCode.crew.rawValue)
return .crew(name: name)
case .gliderType:
let name = parseFreeTextLine(line: hLine, prefix: HeaderRecordCode.gliderType.rawValue)
return .gliderType(gliderType: name)
case .gliderRegistration:
let value = parseFreeTextLine(line: hLine, prefix: HeaderRecordCode.gliderRegistration.rawValue)
return .gliderRegistration(registration: value)
case .gpsDatum:
// Punt on parsing this header. Assume it's standard.
return .gpsDatum(code: 100, datum: "WGS-1984")
case .firmwareVersion:
return .firmwareVersion(version: "0.0.0")
case .hardwareVersion:
return .hardwareVersion(version: "0.0.0")
case .loggerType:
return .loggerType(brand: "Unknown Brand", model: "Unknown Model")
case .gpsType:
return .gpsType(brand: "Unknown Brand", model: "Unknown Model", channels: 0, maximumAltitude: 0)
case .altimeterType:
return .altimeterType(brand: "Unknown Brand", model: "Unknown Model", maximumAltitude: 0)
case .competitionID:
let value = parseFreeTextLine(line: hLine, prefix: HeaderRecordCode.competitionID.rawValue)
return .competitionID(id: value)
case .competitionClass:
let value = parseFreeTextLine(line: hLine, prefix: HeaderRecordCode.competitionClass.rawValue)
return .competitionClass(competitionClass: value)
}
}
static func parseDateString(hLine: String) -> IGCHeaderField? {
guard let prefixRange = hLine.range(of: HeaderRecordCode.date.rawValue) else { return nil }
let maybeDateString = hLine.suffix(from: prefixRange.upperBound)
guard let dateStartIndex = maybeDateString.firstIndex(where: { $0.isNumber }) else { return nil }
let dateEndIndex = maybeDateString.index(dateStartIndex, offsetBy: 5)
let dateString = maybeDateString[dateStartIndex...dateEndIndex]
guard let date = Date.parse(headerDateString: String(dateString)) else { return nil }
return .date(flightDate: date)
}
static func parseAccuracyString(hLine: String) -> IGCHeaderField {
guard let prefixRange = hLine.range(of: HeaderRecordCode.accuracy.rawValue) else { fatalError() }
let accuracyString = hLine.suffix(from: prefixRange.upperBound)
guard let accuracy = Int(accuracyString) else { fatalError() }
return .accuracy(accuracy: accuracy)
}
static func parseFreeTextLine(line: String, prefix: String) -> String {
guard let _ = line.range(of: prefix),
let separatorRange = line.range(of: ":") else { fatalError() }
let value = line.suffix(from: separatorRange.upperBound)
.trimmingCharacters(in: .whitespacesAndNewlines)
return value
}
}
/// Represents the header section contained in an IGC file
public struct IGCHeader {
/// header fields in this section
public let headerFields: [IGCHeaderField]
init?(igcString: String) {
let lines = igcString.components(separatedBy: .newlines)
.filter({ (line) -> Bool in
return line.hasPrefix("H")
})
headerFields = lines.compactMap { IGCHeaderField.parseHLine(hLine: $0) }
}
public var flightDate: Date {
return headerFields
.compactMap { (field) -> Date? in
switch field {
case .date(let flightDate):
return flightDate
default:
return nil
}
}
.first!
}
public var pilotInCharge: String? {
return headerFields.compactMap({ (field) -> String? in
switch field {
case .pilotInCharge(let name):
return name
default:
return nil
}
}).first
}
public var crew: String? {
return headerFields.compactMap({ (field) -> String? in
switch field {
case .crew(let name):
return name
default:
return nil
}
}).first
}
public var gliderType: String? {
return headerFields.compactMap({ (header) -> String? in
switch header {
case .gliderType(let value):
return value
default:
return nil
}
}).first
}
public var gliderRegistration: String? {
return headerFields.compactMap({ (header) -> String? in
switch header {
case .gliderRegistration(let value):
return value
default:
return nil
}
}).first
}
public var competitionID: String? {
return headerFields.compactMap({ (header) -> String? in
switch header {
case .competitionID(let value):
return value
default:
return nil
}
}).first
}
public init(with date: Date, pic: String, crew: String?, gliderType: String, gliderRegistration: String) {
var headers: [IGCHeaderField] = [
.date(flightDate: date),
.pilotInCharge(name: pic),
.gliderType(gliderType: gliderType),
.gliderRegistration(registration: gliderRegistration)
]
if let crew = crew {
headers.append(.crew(name: crew))
}
self.headerFields = headers
}
}
| 34.16996 | 108 | 0.675535 |
4afc8b5fd709b87529c2970890676c1b9684a74f | 8,620 | //===--- LazySequence.swift -----------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A sequence on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Lazy sequences can be used to avoid needless storage allocation
/// and computation, because they use an underlying sequence for
/// storage and compute their elements on demand. For example,
///
/// [1, 2, 3].lazy.map { $0 * 2 }
///
/// is a sequence containing { `2`, `4`, `6` }. Each time an element
/// of the lazy sequence is accessed, an element of the underlying
/// array is accessed and transformed by the closure.
///
/// Sequence operations taking closure arguments, such as `map` and
/// `filter`, are normally eager: they use the closure immediately and
/// return a new array. Using the `lazy` property gives the standard
/// library explicit permission to store the closure and the sequence
/// in the result, and defer computation until it is needed.
///
/// To add new lazy sequence operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazySequenceProtocol`s. For example, given an eager `scan`
/// method defined as follows
///
/// extension Sequence {
/// /// Returns an array containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// (1..<6).scan(0, +) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(n)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: (ResultElement, Element) -> ResultElement
/// ) -> [ResultElement] {
/// var result = [initial]
/// for x in self {
/// result.append(nextPartialResult(result.last!, x))
/// }
/// return result
/// }
/// }
///
/// we can build a sequence that lazily computes the elements in the
/// result of `scan`:
///
/// struct LazyScanIterator<Base: IteratorProtocol, ResultElement>
/// : IteratorProtocol {
/// mutating func next() -> ResultElement? {
/// return nextElement.map { result in
/// nextElement = base.next().map { nextPartialResult(result, $0) }
/// return result
/// }
/// }
/// var nextElement: ResultElement? // The next result of next().
/// var base: Base // The underlying iterator.
/// let nextPartialResult: (ResultElement, Base.Element) -> ResultElement
/// }
///
/// struct LazyScanSequence<Base: Sequence, ResultElement>
/// : LazySequenceProtocol // Chained operations on self are lazy, too
/// {
/// func makeIterator() -> LazyScanIterator<Base.Iterator, ResultElement> {
/// return LazyScanIterator(
/// nextElement: initial, base: base.makeIterator(),
/// nextPartialResult: nextPartialResult)
/// }
/// let initial: ResultElement
/// let base: Base
/// let nextPartialResult:
/// (ResultElement, Base.Element) -> ResultElement
/// }
///
/// and finally, we can give all lazy sequences a lazy `scan` method:
///
/// extension LazySequenceProtocol {
/// /// Returns a sequence containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// Array((1..<6).lazy.scan(0, +)) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(1)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: @escaping (ResultElement, Element) -> ResultElement
/// ) -> LazyScanSequence<Self, ResultElement> {
/// return LazyScanSequence(
/// initial: initial, base: self, nextPartialResult: nextPartialResult)
/// }
/// }
///
/// - See also: `LazySequence`
///
/// - Note: The explicit permission to implement further operations
/// lazily applies only in contexts where the sequence is statically
/// known to conform to `LazySequenceProtocol`. Thus, side-effects such
/// as the accumulation of `result` below are never unexpectedly
/// dropped or deferred:
///
/// extension Sequence where Element == Int {
/// func sum() -> Int {
/// var result = 0
/// _ = self.map { result += $0 }
/// return result
/// }
/// }
///
/// [We don't recommend that you use `map` this way, because it
/// creates and discards an array. `sum` would be better implemented
/// using `reduce`].
public protocol LazySequenceProtocol: Sequence {
/// A `Sequence` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements: Sequence = Self where Elements.Element == Element
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing an extra
/// `LazySequence` layer. For example,
///
/// _prext_ example needed
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements { get }
}
/// When there's no special associated `Elements` type, the `elements`
/// property is provided.
extension LazySequenceProtocol where Elements == Self {
/// Identical to `self`.
@inlinable // protocol-only
public var elements: Self { return self }
}
extension LazySequenceProtocol {
@inlinable // protocol-only
public var lazy: LazySequence<Elements> {
return elements.lazy
}
}
extension LazySequenceProtocol where Elements: LazySequenceProtocol {
@inlinable // protocol-only
public var lazy: Elements {
return elements
}
}
/// A sequence containing the same elements as a `Base` sequence, but
/// on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`
@frozen // lazy-performance
public struct LazySequence<Base: Sequence> {
@usableFromInline
internal var _base: Base
/// Creates a sequence that has the same elements as `base`, but on
/// which some operations such as `map` and `filter` are implemented
/// lazily.
@inlinable // lazy-performance
internal init(_base: Base) {
self._base = _base
}
}
extension LazySequence: Sequence {
public typealias Element = Base.Element
public typealias Iterator = Base.Iterator
@inlinable
public __consuming func makeIterator() -> Iterator {
return _base.makeIterator()
}
@inlinable // lazy-performance
public var underestimatedCount: Int {
return _base.underestimatedCount
}
@inlinable // lazy-performance
@discardableResult
public __consuming func _copyContents(
initializing buf: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
return _base._copyContents(initializing: buf)
}
@inlinable // lazy-performance
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
return _base._customContainsEquatableElement(element)
}
@inlinable // generic-performance
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
return _base._copyToContiguousArray()
}
}
extension LazySequence: LazySequenceProtocol {
public typealias Elements = Base
/// The `Base` (presumably non-lazy) sequence from which `self` was created.
@inlinable // lazy-performance
public var elements: Elements { return _base }
}
extension Sequence {
/// A sequence containing the same elements as this sequence,
/// but on which some operations, such as `map` and `filter`, are
/// implemented lazily.
@inlinable // protocol-only
public var lazy: LazySequence<Self> {
return LazySequence(_base: self)
}
}
| 35.327869 | 84 | 0.638051 |
224152ee3c028b26e49ae8984744d1d50f175cce | 11,148 | //
// ViewController.swift
// YouAreMySunshine
//
// Created by Joseph Erlandson on 4/29/17.
// Copyright © 2017 JosephErlandson. All rights reserved.
//
import UIKit
import Charts
import CoreLocation
class DashboardViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var topView: UIView!
@IBOutlet weak var highNumberLabel: UILabel!
@IBOutlet weak var averageNumberLabel: UILabel!
@IBOutlet weak var segmentControl: UISegmentedControl!
@IBOutlet weak var collectionView: UICollectionView! {
didSet {
collectionView.delegate = self
collectionView.dataSource = self
collectionView?.allowsMultipleSelection = true
}
}
@IBOutlet weak var barChart: HorizontalBarChartView! {
didSet {
barChart.xAxis.drawAxisLineEnabled = false
barChart.xAxis.drawGridLinesEnabled = false
barChart.xAxis.drawLabelsEnabled = false
barChart.xAxis.drawLimitLinesBehindDataEnabled = false
barChart.drawGridBackgroundEnabled = false
barChart.rightAxis.drawGridLinesEnabled = false
barChart.rightAxis.drawLimitLinesBehindDataEnabled = false
barChart.rightAxis.drawLabelsEnabled = false
barChart.rightAxis.drawAxisLineEnabled = false
barChart.rightAxis.drawZeroLineEnabled = false
barChart.rightAxis.drawTopYLabelEntryEnabled = false
barChart.leftAxis.drawGridLinesEnabled = false
barChart.leftAxis.drawLimitLinesBehindDataEnabled = false
barChart.leftAxis.drawLabelsEnabled = false
barChart.leftAxis.drawAxisLineEnabled = false
barChart.leftAxis.drawZeroLineEnabled = false
barChart.leftAxis.drawTopYLabelEntryEnabled = false
//barChart.legend.
barChart.drawGridBackgroundEnabled = false
barChart.doubleTapToZoomEnabled = false
barChart.pinchZoomEnabled = false
barChart.chartDescription?.text = ""
barChart.delegate = self
}
}
var activeApplianceList = [Appliance(name: "Free", energy: 100, energyUsage: 100.0, timeUsed: Date(), color: UIColor.lightGray, image: UIImage(named: "tv")!)]
let applianceList = [
Appliance(name: "Clothes Dryer", energy: 3000, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 80/255, green: 40/255, blue: 18/255, alpha: 1.0), image: UIImage(named: "dryer")!),
Appliance(name: "Clothes Washer", energy: 500, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 96/255, green: 54/255, blue: 24/255, alpha: 1.0), image: UIImage(named: "cwasher")!),
Appliance(name: "Coffee Maker", energy: 800, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 133/255, green: 87/255, blue: 35/255, alpha: 1.0), image: UIImage(named: "coffee")!),
Appliance(name: "Laptop", energy: 60, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 137/255, green: 32/255, blue: 52/255, alpha: 1.0), image: UIImage(named: "laptop")!),
Appliance(name: "Dishwasher", energy: 1800, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 122/255, green: 26/255, blue: 87/255, alpha: 1.0), image: UIImage(named: "dwasher")!),
Appliance(name: "Microwave", energy: 1200, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 111/255, green: 37/255, blue: 108/255, alpha: 1.0), image: UIImage(named: "microwave")!),
Appliance(name: "Central A/C", energy: 3500, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 0/255, green: 52/255, blue: 77/255, alpha: 1.0), image: UIImage(named: "ac")!),
Appliance(name: "Fridge", energy: 180, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 0/255, green: 48/255, blue: 102/255, alpha: 1.0), image: UIImage(named: "fridge")!),
Appliance(name: "Space Heater", energy: 1500, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 87/255, green: 82/255, blue: 126/255, alpha: 1.0), image: UIImage(named: "heater")!),
Appliance(name: "50\" LCD TV", energy: 150, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 0/255, green: 66/255, blue: 54/255, alpha: 1.0), image: UIImage(named: "tv")!),
Appliance(name: "Toaster", energy: 1200, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 64/255, green: 70/255, blue: 22/255, alpha: 1.0), image: UIImage(named: "toaster")!),
Appliance(name: "Game Console", energy: 100, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 159/255, green: 155/255, blue: 116/255, alpha: 1.0), image: UIImage(named: "game")!),
Appliance(name: "Hot Shower", energy: 4000, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 102/255, green: 141/255, blue: 60/255, alpha: 1.0), image: UIImage(named: "wheater")!),
Appliance(name: "Dehumidifier", energy: 280, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 129/255, green: 108/255, blue: 91/255, alpha: 1.0), image: UIImage(named: "dehum")!),
Appliance(name: "Stove Top", energy: 1500, energyUsage: 0.0, timeUsed: Date(), color: UIColor(red: 199/255, green: 108/255, blue: 191/255, alpha: 1.0), image: UIImage(named: "stovetop")!),
]
let locationManager = CLLocationManager()
var selectedUpperBound: Double!
var totalWatNumber = 0.0
var selectedIndex: Int!
var totalEnergyUsed = 0.0
override func viewDidLoad() {
super.viewDidLoad()
highNumberLabel.alpha = 0.0
//saverageNumberLabel.alpha = 0.0
let energyValue = activeApplianceList.map( { $0.energy })
updateGraph(activeAppliances: energyValue)
NotificationCenter.default.addObserver(self, selector: #selector(self.addAppliance), name: NSNotification.Name(rawValue: "addAppliance"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.itemDeselect), name: NSNotification.Name(rawValue: "deselectView"), object: nil)
print("TEST")
// For use in foreground
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.startUpdatingLocation()
} else {
let watts = NetworkHelper.fetchPredictedIrradiance(lat: 19.602378, long: -155.487192)
totalWatNumber = CalculationHelper.wattHours(wattHrM2: watts)
activeApplianceList[activeApplianceList.endIndex - 1].energyUsage = totalWatNumber
print("Free wattage: \(activeApplianceList[0].energyUsage)")
updateGraph(activeAppliances: activeApplianceList.map( { $0.energyUsage }))
averageNumberLabel.text = "Total energy: \(0) / \(Int(totalWatNumber))"
//alert prompt
let alert = UIAlertController(title: "Notice!", message: "We have noticed that your location services are disabled, for better accuracy please turn them on!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
print("TOTAL WATT: \(totalWatNumber)")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Graph
func updateGraph(activeAppliances: Array<Double>) {
let dataEntries = [BarChartDataEntry(x: 0.0, yValues: activeAppliances)]
print("updateGraph dataEntries: \(dataEntries)")
var index = 0
var labels = [String]()
for e in activeAppliances {
print("active appliance: \(e)")
// labels.append(index)
index = index + 1
}
var dataEntries2 = [BarChartDataEntry]()
for e in activeAppliances {
dataEntries2.append(BarChartDataEntry(x: 0.0, y:e))
}
let barChartDataSet = BarChartDataSet(values: dataEntries, label: "")
let colorValues = activeApplianceList.map( { $0.color })
barChartDataSet.colors = colorValues//ChartColorTemplates.material()
let labelValues = activeApplianceList.map( { $0.name })
barChartDataSet.stackLabels = labelValues
let barChartData = BarChartData(dataSet: barChartDataSet)
barChartData.setValueFont(UIFont.systemFont(ofSize: 12.0))
barChart.data = barChartData
}
// MARK: - Core Location
private func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
// If status has not yet been determied, ask for authorization
manager.requestWhenInUseAuthorization()
break
case .authorizedWhenInUse:
// If authorized when in use
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.startUpdatingLocation()
break
case .authorizedAlways:
// If always authorized
manager.startUpdatingLocation()
break
case .restricted:
// If restricted by e.g. parental controls. User can't enable Location Services
break
case .denied:
// If user denied your app access to Location Services, but can grant access from Settings.app
break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0]// as! CLLocation
let long = userLocation.coordinate.longitude
let lat = userLocation.coordinate.latitude
let watts = NetworkHelper.fetchPredictedIrradiance(lat: lat, long: long)
print("TEMP: \(watts)")
print("LAT: \(lat), LONG: \(long)")
totalWatNumber = CalculationHelper.wattHours(wattHrM2: watts)
activeApplianceList[activeApplianceList.endIndex - 1].energyUsage = totalWatNumber
averageNumberLabel.text = "Total energy: \(0) / \(Int(totalWatNumber))"
updateGraph(activeAppliances: activeApplianceList.map( { $0.energyUsage }))
print("Free Wattage: \(activeApplianceList[0].energyUsage)")
manager.stopUpdatingLocation()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "dashToDetail" {
let viewController = segue.destination as! DetailViewController
//let indexPath = self.tableView.indexPathForSelectedRow()
viewController.appliance = activeApplianceList[selectedIndex]
viewController.totalWatNumber = totalWatNumber
}
}
}
| 49.110132 | 216 | 0.64747 |
62dd5f68335c18d97aae3f1c1bbca3f222507a8c | 217 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum B class B{deinit{class a<h where B:A{let a
| 36.166667 | 87 | 0.764977 |
50bc9ad1c1b393cdf2de06547d037b751cbbd022 | 6,608 | import MixboxTestsFoundation
import MixboxFoundation
import MixboxDi
open class BaseElementInteractionDependenciesFactory: ElementInteractionDependenciesFactory {
private let parentDi: DependencyResolver
private let dependencyInjectionFactory: DependencyInjectionFactory
public init(
dependencyResolver: DependencyResolver,
dependencyInjectionFactory: DependencyInjectionFactory)
{
self.parentDi = dependencyResolver
self.dependencyInjectionFactory = dependencyInjectionFactory
}
open func registerSpecificDependencies(di: DependencyRegisterer, fileLine: FileLine) {
// should be overriden
}
// swiftlint:disable:next function_body_length
public func elementInteractionDependencies(
interaction: ElementInteraction,
fileLine: FileLine,
elementInteractionWithDependenciesPerformer: ElementInteractionWithDependenciesPerformer,
retriableTimedInteractionState: RetriableTimedInteractionState,
elementSettings: ElementSettings,
interactionSettings: InteractionSettings)
-> ElementInteractionDependencies
{
let di = makeDi()
di.register(type: ElementInteractionWithDependenciesPerformer.self) { _ in
elementInteractionWithDependenciesPerformer
}
di.register(type: ElementSettings.self) { _ in
elementSettings
}
di.register(type: InteractionSettings.self) { _ in
interactionSettings
}
di.register(type: ElementInteraction.self) { _ in
interaction
}
di.register(type: RetriableTimedInteractionState.self) { _ in
retriableTimedInteractionState
}
di.register(type: HumanReadableInteractionDescriptionBuilderSource.self) { _ in
HumanReadableInteractionDescriptionBuilderSource(
elementName: elementSettings.name
)
}
di.register(type: InteractionResultMaker.self) { di in
InteractionResultMakerImpl(
elementHierarchyDescriptionProvider: try di.resolve(),
deviceScreenshotTaker: try di.resolve(),
extendedStackTraceProvider: try di.resolve(),
fileLine: fileLine
)
}
di.register(type: InteractionFailureResultFactory.self) { di in
InteractionFailureResultFactoryImpl(
applicationStateProvider: try di.resolve(),
messagePrefix: "Действие неуспешно",
interactionResultMaker: try di.resolve()
)
}
di.register(type: InteractionRetrier.self) { di in
InteractionRetrierImpl(
dateProvider: try di.resolve(),
timeout: interactionSettings.interactionTimeout,
retrier: try di.resolve(),
retriableTimedInteractionState: try di.resolve()
)
}
di.register(type: SnapshotForInteractionResolver.self) { di in
SnapshotForInteractionResolverImpl(
retriableTimedInteractionState: try di.resolve(),
interactionRetrier: try di.resolve(),
performerOfSpecificImplementationOfInteractionForVisibleElement: try di.resolve(),
interactionFailureResultFactory: try di.resolve(),
elementResolverWithScrollingAndRetries: try di.resolve()
)
}
di.register(type: NestedInteractionPerformer.self) { di in
NestedInteractionPerformerImpl(
elementInteractionDependenciesFactory: self,
elementInteractionWithDependenciesPerformer: try di.resolve(),
retriableTimedInteractionState: try di.resolve(),
elementSettings: try di.resolve(),
fileLine: fileLine,
performanceLogger: try di.resolve()
)
}
di.register(type: InteractionResultMaker.self) { di in
InteractionResultMakerImpl(
elementHierarchyDescriptionProvider: try di.resolve(),
deviceScreenshotTaker: try di.resolve(),
extendedStackTraceProvider: try di.resolve(),
fileLine: fileLine
)
}
di.register(type: PerformerOfSpecificImplementationOfInteractionForVisibleElement.self) { di in
PerformerOfSpecificImplementationOfInteractionForVisibleElementImpl(
elementVisibilityChecker: try di.resolve(),
interactionSettings: try di.resolve(),
interactionFailureResultFactory: try di.resolve(),
scroller: try di.resolve()
)
}
di.register(type: ElementResolverWithScrollingAndRetries.self) { di in
ElementResolverWithScrollingAndRetriesImpl(
elementResolver: try di.resolve(),
interactionSettings: try di.resolve(),
applicationFrameProvider: try di.resolve(),
eventGenerator: try di.resolve(),
retrier: try di.resolve()
)
}
di.register(type: ElementResolver.self) { di in
WaitingForQuiescenceElementResolver(
elementResolver: ElementResolverImpl(
elementFinder: try di.resolve(),
interactionSettings: try di.resolve()
),
applicationQuiescenceWaiter: try di.resolve()
)
}
di.register(type: Scroller.self) { di in
ScrollerImpl(
scrollingHintsProvider: try di.resolve(),
elementVisibilityChecker: try di.resolve(),
elementResolver: try di.resolve(),
applicationFrameProvider: try di.resolve(),
eventGenerator: try di.resolve(),
interactionSettings: try di.resolve()
)
}
registerSpecificDependencies(di: di, fileLine: fileLine)
return ElementInteractionDependenciesImpl(
dependencyResolver: MixboxDiTestFailingDependencyResolver(
dependencyResolver: di
)
)
}
private func makeDi() -> DependencyInjection {
let localDi = dependencyInjectionFactory.dependencyInjection()
return DelegatingDependencyInjection(
dependencyResolver: CompoundDependencyResolver(
resolvers: [localDi, parentDi]
),
dependencyRegisterer: localDi
)
}
}
| 41.3 | 103 | 0.626362 |
9c02827deb7cb1f30e5e5d4817e075f68269d8ab | 3,791 | //
// ImagePickerPreviewView.swift
// ComponentKit
//
// Created by William Lee on 2018/5/12.
// Copyright © 2018 William Lee. All rights reserved.
//
import UIKit
class ImagePickerPreviewView: UIView {
private let scrollView = UIScrollView()
private let imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
self.setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.scrollView.bounces = false
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.scrollView.bounces = true
}
}
// MARK: - Public
extension ImagePickerPreviewView {
func update(with image: UIImage?) {
self.imageView.image = image
self.resetSize()
}
}
// MARK: - UIScrollViewDelegate
extension ImagePickerPreviewView: UIScrollViewDelegate {
//缩放视图
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
//缩放响应,设置imageView的中心位置
func scrollViewDidZoom(_ scrollView: UIScrollView) {
self.updateImageOrigin()
}
}
// MARK: - Setup
private extension ImagePickerPreviewView {
func setupView() {
self.backgroundColor = UIColor.black
let singleTap = UITapGestureRecognizer(target:self, action:#selector(tapSingle(_:)))
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
self.scrollView.addGestureRecognizer(singleTap)
self.scrollView.delegate = self
self.scrollView.maximumZoomScale = 2
self.scrollView.minimumZoomScale = 1
//self.scrollView.bounces = false
self.scrollView.backgroundColor = self.backgroundColor
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.showsHorizontalScrollIndicator = false
self.addSubview(self.scrollView)
self.imageView.backgroundColor = self.backgroundColor
self.imageView.contentMode = .scaleAspectFit
self.scrollView.addSubview(self.imageView)
}
func setupLayout() {
self.scrollView.layout.add { (make) in
make.top().bottom().leading().trailing().equal(self)
}
}
}
// MARK: - Action
private extension ImagePickerPreviewView {
@objc func tapSingle(_ sender: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}, completion: { (_) in
self.update(with: nil)
})
}
}
// MARK: - Utility
private extension ImagePickerPreviewView {
func resetSize() {
self.scrollView.zoomScale = 1.0
let imageSize: CGSize = self.imageView.image?.size ?? CGSize(width: 16, height: 9)
let scale = imageSize.height / imageSize.width
self.imageView.frame.size.width = self.scrollView.bounds.width
self.imageView.frame.size.height = self.imageView.bounds.size.width * scale
self.scrollView.contentSize = self.imageView.bounds.size
self.updateImageOrigin()
}
func updateImageOrigin() {
if self.imageView.frame.size.width < self.scrollView.bounds.width {
self.imageView.frame.origin.x = self.scrollView.bounds.width / 2.0 - self.imageView.frame.width / 2.0
} else {
self.imageView.frame.origin.x = 0
}
if self.imageView.frame.size.height < self.scrollView.bounds.height {
self.imageView.frame.origin.y = self.scrollView.bounds.height / 2.0 - self.imageView.frame.height / 2.0
} else {
self.imageView.frame.origin.y = 0
}
}
}
| 22.837349 | 109 | 0.675284 |
ebfa2a6035de6c99a3db6c2e251b9d5dbb907098 | 3,530 | //
// ListViewController.swift
// DarwinDigitalTest
//
// Created by Bojan Markovic on 24/05/2019.
// Copyright © 2019 Bojan. All rights reserved.
//
import Foundation
import UIKit
final class ListViewController: UIViewController {
// MARK: - Outlets
@IBOutlet private weak var tableView: UITableView?
@IBOutlet private weak var searchBar: UISearchBar?
// MARK: - Properties
private var allUsers: [User] = [] // this property will be used for filtering during search
private var isSearchActive: Bool = false // indicate if searching users is active
var users: [User] = [] {
didSet {
users.sort { $0.name < $1.name }
allUsers = users
tableView?.reloadData()
}
}
var selectedRow: Int = 0
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Set table view delegate and data source
tableView?.dataSource = self
tableView?.delegate = self
// Set tab bar controller delegate in order to pass users to MapViewController
self.tabBarController?.delegate = self
// Setup search bar
searchBar?.delegate = self
searchBar?.placeholder = "Type user name to search"
}
// MARK: - Prepare for Seque
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let detailVC = segue.destination as? UserDetailViewController {
detailVC.user = isSearchActive ? allUsers[selectedRow] : users[selectedRow]
}
}
}
// MARK: - UITableViewDataSource
extension ListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isSearchActive ? allUsers.count : users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let userCell = tableView.dequeueReusableCell(withIdentifier: String(describing: UserTableViewCell.self), for: indexPath) as! UserTableViewCell
userCell.configureCellWith(user: isSearchActive ? allUsers[indexPath.row] : users[indexPath.row])
return userCell
}
}
// MARK: - UITableViewDelegate
extension ListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedRow = indexPath.row
performSegue(withIdentifier: "showDetail", sender: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - UITabBarDelegate
extension ListViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if let mapViewController = viewController as? MapViewController {
mapViewController.users = users
}
}
}
// MARK: - UISearchBarDelegate
extension ListViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
isSearchActive = !searchText.isEmpty
allUsers = users
if isSearchActive {
allUsers = allUsers.filter { $0.name.contains(searchText) }
}
tableView?.reloadData()
}
}
| 32.685185 | 150 | 0.667705 |
d78aee1b289e10b85d0d38486afa4a73e390da1c | 559 | //
// PhotoCell.swift
// TumblerFeed
//
// Created by Amzad Chowdhury on 9/12/18.
// Copyright © 2018 Amzad Chowdhury. All rights reserved.
//
import UIKit
import AlamofireImage
class PhotoCell: UITableViewCell {
@IBOutlet weak var photoView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 19.964286 | 65 | 0.67263 |
e630299e1dbb17978c629f5095480fd18606397d | 1,073 | //
// TypeHolderExample.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
<<<<<<< HEAD
public struct TypeHolderExample: Codable {
=======
public struct TypeHolderExample: Codable {
>>>>>>> ooof
public var stringItem: String
public var numberItem: Double
public var integerItem: Int
public var boolItem: Bool
public var arrayItem: [Int]
public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) {
self.stringItem = stringItem
self.numberItem = numberItem
self.integerItem = integerItem
self.boolItem = boolItem
self.arrayItem = arrayItem
}
<<<<<<< HEAD
public enum CodingKeys: String, CodingKey, CaseIterable {
=======
public enum CodingKeys: String, CodingKey, CaseIterable {
>>>>>>> ooof
case stringItem = "string_item"
case numberItem = "number_item"
case integerItem = "integer_item"
case boolItem = "bool_item"
case arrayItem = "array_item"
}
}
| 23.844444 | 109 | 0.656104 |
0144a397328711737cd676258917815f3ead1060 | 1,232 | //
// KBChatRoomService.swift
// KBChat
//
// Created by 周昊 on 2020/12/28.
//
import UIKit
class KBChatRoomService: NSObject {
static func sendMessage(_ message: String) {
let secToken = iPadProToken
let toToken = (KBToolUtils.shareInstance.token == iPhone11Token) ? secToken : iPhone11Token
guard let user = (KBToolUtils.shareInstance.token?.prefix(2)) else {
return
}
let queryItems = [URLQueryItem(name: "fromToken", value: KBToolUtils.shareInstance.token),
URLQueryItem(name: "toToken", value: toToken),
URLQueryItem(name: "title", value: "\(String(user))token用户"),
URLQueryItem(name: "subTitle", value: message)]
var urlComps = URLComponents(string: "\(DOMAINURL)kbpush/push")!
urlComps.queryItems = queryItems
guard let url = urlComps.url else {
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
// Handle data
print(data as Any)
print(response as Any)
print(error as Any)
}
task.resume()
}
}
| 29.333333 | 99 | 0.566558 |
0aaf188eca4021a2fe7cac222f3c01d8acbbdb54 | 500 | //
// WBMessageViewController.swift
// Sina
//
// Created by Macintosh HD on 16/8/17.
// Copyright © 2016年 lidingyuan. All rights reserved.
//
import UIKit
class WBMessageViewController: WBBaseViewController {
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.
}
}
| 20 | 58 | 0.678 |
5de883998611835c1daa64617800c6ff04671164 | 202 | //
// FlickrPhotoCell.swift
// iOS Labs
//
// Created by Андрей Исаев on 08.09.2021.
//
import UIKit
class FlickrPhotoCell: UITableViewCell {
@IBOutlet weak var photoView: UIImageView!
}
| 13.466667 | 46 | 0.683168 |
75124561699b527723a5cda8811a1ee364086bf9 | 2,642 | //
// CreateNewZimVC.swift
// Zimcher
//
// Created by Weiyu Huang on 1/3/16.
// Copyright © 2016 Zimcher. All rights reserved.
//
import UIKit
class CreateNewZimVC: ViewControllerWithKBLayoutGuide {
@IBOutlet weak var tableView: TableViewWithIntrinsicSize!
var entryField: EntryField!
override func viewDidLoad() {
super.viewDidLoad()
entryField = EntryField(tableView: tableView)
entryField.headerFooterHeight = 1
entryField.headerFooterColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
entryField.feedData(generateData())
}
private func generateData() -> [EntryFieldData]
{
let data0 = ValidatableTextEntryFieldData()
data0.promptText = "Zim name"
data0.placeholderText = "e.g. Hooping, Skateboarding"
data0.keyboardType = .Default
//data.textValidator = IsValid.email
//data.invalidAlertMessage = "Please enter a valid email address"
let data1 = ValidatableTextEntryFieldData()
data1.promptText = "Description"
data1.placeholderText = ""
data1.keyboardType = .Default
let data2 = SelectableCellData()
data2.promptText = "Publicity"
data2.hasDisclosureArrow = false
data2.onSelectCallback = {[weak self] cell in
self?.alert(cell)
cell.setSelected(false, animated: true)
}
let r: [EntryFieldData] = [data0, data1, data2]
//r.forEach {[unowned self] in $0.onFailCallback = self.showTopAlert }
return r
}
private func alert(cell: UITableViewCell)
{
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
func alertActionHandler(action: UIAlertAction)
{
guard let c = cell as? SelectableCell else { return }
//stub!
c.placeholderText = action.title
}
let actions = [
UIAlertAction(title: "Public", style: .Default, handler: alertActionHandler),
UIAlertAction(title: "Request required", style: .Default, handler: alertActionHandler),
UIAlertAction(title: "Invitation only", style: .Default, handler: alertActionHandler),
UIAlertAction(title: "Private", style: .Default, handler: alertActionHandler),
UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
]
actions.forEach(alertController.addAction)
presentViewController(alertController, animated: true, completion: nil)
}
} | 33.443038 | 103 | 0.630961 |
28d28e23ba59734055c65fcc06cb77a5418539bb | 2,151 | //
// MPCircleRefreshView.swift
// RxZhiHuDaily
//
// Created by Maple on 2017/10/14.
// Copyright © 2017年 Maple. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
/// 下拉刷新圆圈View
class MPCircleRefreshView: UIView {
fileprivate let circleLayer = CAShapeLayer()
fileprivate let indicatorView = UIActivityIndicatorView()
fileprivate let disposeBag = DisposeBag()
fileprivate var isRefreshing: Bool = false
init() {
super.init(frame: CGRect.zero)
addSubview(indicatorView)
layer.addSublayer(circleLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
indicatorView.center = CGPoint(x: frame.width/2, y: frame.height/2)
setupLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
fileprivate func setupLayer() {
circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: 8, y: 8), radius: 8, startAngle: CGFloat(Double.pi * 0.5), endAngle: CGFloat(Double.pi * 0.5 + 2 * Double.pi), clockwise: true).cgPath
circleLayer.strokeColor = UIColor.white.cgColor
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.strokeStart = 0.0
circleLayer.strokeEnd = 0.0
circleLayer.lineWidth = 1.0
circleLayer.lineCap = kCALineCapRound
let xy = (frame.width - 16) * 0.5
circleLayer.frame = CGRect(x: xy, y: xy, width: 16, height: 16)
}
}
extension MPCircleRefreshView {
/// 设置圆圈的绘制百分比
func pullToRefresh(progress: CGFloat) {
circleLayer.isHidden = progress == 0
circleLayer.strokeEnd = progress
}
/// 开始刷新
func beginRefresh(begin: @escaping () -> Void) {
if isRefreshing {
//防止刷新未结束又开始请求刷新
return
}
circleLayer.removeFromSuperlayer()
circleLayer.strokeEnd = 0
indicatorView.startAnimating()
begin()
}
/// 结束刷新
func endRefresh() {
layer.addSublayer(circleLayer)
setupLayer()
isRefreshing = false
indicatorView.stopAnimating()
}
}
| 27.576923 | 196 | 0.62994 |
e840751ae837cac3747cfd55d38ba76dfeaed467 | 6,129 | //
// CameraIO.swift
// HowAwayAreYou
//
// Created by 史 翔新 on 2020/07/12.
// Copyright © 2020 Crazism. All rights reserved.
//
import Foundation
import Combine
import AVFoundation
final class CameraIO {
let captureSession: AVCaptureSession
let captureDevice: AVCaptureDevice
private let videoDataOutput: AVCaptureVideoDataOutput
private let depthDataOutput: AVCaptureDepthDataOutput
private let faceOutput: AVCaptureMetadataOutput
private let captureOutputReceiver: CaptureOutputReceiver
private let synchronizer: AVCaptureDataOutputSynchronizer
private let outputProcessQueue = DispatchQueue(label: "CameraIO")
typealias SynchronizedData = (sampleBuffer: CMSampleBuffer, depthData: AVDepthData, facesBounds: [CGRect])
let synchronizedDataPublisher: CurrentValueSubject<SynchronizedData?, Never> = .init(nil)
enum CameraIOInitError: Error {
case failedToFindDevice
}
init() throws {
guard let device = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera, .builtInTripleCamera],
mediaType: .depthData,
position: .back)
.devices.first else {
throw CameraIOInitError.failedToFindDevice
}
let session = AVCaptureSession()
session.beginConfiguration()
defer { session.commitConfiguration() }
session.sessionPreset = .photo
let input = try AVCaptureDeviceInput(device: device)
session.addInput(input)
let receiver = CaptureOutputReceiver()
let videoDataOutput = AVCaptureVideoDataOutput()
videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey: videoDataOutput.availableVideoPixelFormatTypes[0]] as [String: Any]
session.addOutput(videoDataOutput)
let depthDataOutput = AVCaptureDepthDataOutput()
depthDataOutput.isFilteringEnabled = true
session.addOutput(depthDataOutput)
let faceOutput = AVCaptureMetadataOutput()
session.addOutput(faceOutput)
faceOutput.metadataObjectTypes = [.face]
let synchronizer = AVCaptureDataOutputSynchronizer(dataOutputs: [videoDataOutput, depthDataOutput, faceOutput])
synchronizer.setDelegate(receiver, queue: outputProcessQueue)
try device.setupBestActiveDepthFormat()
self.videoDataOutput = videoDataOutput
self.depthDataOutput = depthDataOutput
self.faceOutput = faceOutput
self.captureSession = session
self.captureDevice = device
self.captureOutputReceiver = receiver
self.synchronizer = synchronizer
receiver.delegate = self
}
}
extension CameraIO: CaptureOutputDelegate {
func dataOutputSynchronizer(_ synchronizer: AVCaptureDataOutputSynchronizer, didOutput synchronizedDataCollection: AVCaptureSynchronizedDataCollection) {
guard let sampleBuffer = synchronizedDataCollection.synchronizedData(for: videoDataOutput) as? AVCaptureSynchronizedSampleBufferData else { return }
guard let depthData = synchronizedDataCollection.synchronizedData(for: depthDataOutput) as? AVCaptureSynchronizedDepthData else { return }
let faces = synchronizedDataCollection.synchronizedData(for: faceOutput) as! AVCaptureSynchronizedMetadataObjectData? // swiftlint:disable:this force_cast
self.synchronizedDataPublisher.send((sampleBuffer.sampleBuffer, depthData.depthData, faces?.metadataObjects.map { $0.bounds } ?? []))
}
}
private protocol CaptureOutputDelegate: AnyObject {
func dataOutputSynchronizer(_ synchronizer: AVCaptureDataOutputSynchronizer, didOutput synchronizedDataCollection: AVCaptureSynchronizedDataCollection)
}
private final class CaptureOutputReceiver: NSObject, AVCaptureDataOutputSynchronizerDelegate {
weak var delegate: CaptureOutputDelegate?
func dataOutputSynchronizer(_ synchronizer: AVCaptureDataOutputSynchronizer, didOutput synchronizedDataCollection: AVCaptureSynchronizedDataCollection) {
delegate?.dataOutputSynchronizer(synchronizer, didOutput: synchronizedDataCollection)
}
}
extension CameraIO: ImageProcessorInput {
var running: Bool {
get {
captureSession.isRunning
}
set {
if newValue {
captureSession.startRunning()
} else {
captureSession.stopRunning()
}
}
}
var dataPublisher: AnyPublisher<ImageProcessorInput.Data?, Never> {
synchronizedDataPublisher.compactMap {
guard let data = $0 else { return nil }
guard let sampleBuffer = CMSampleBufferGetImageBuffer(data.sampleBuffer) else { return nil }
let depthData = data.depthData.depthDataMap
let facesBounds = data.facesBounds
return (sampleBuffer, depthData, facesBounds)
}.eraseToAnyPublisher()
}
}
private extension AVCaptureDevice {
func setupBestActiveDepthFormat() throws {
let depthFormats = activeFormat.supportedDepthDataFormats
let filtered = depthFormats.filter({
CMFormatDescriptionGetMediaSubType($0.formatDescription) == kCVPixelFormatType_DepthFloat32
})
let selectedFormat = filtered.max(on: \.dimensionWidth)
try lockForConfiguration()
defer { unlockForConfiguration() }
activeDepthDataFormat = selectedFormat
}
}
private extension AVCaptureDevice.Format {
var dimensionWidth: Int32 {
CMVideoFormatDescriptionGetDimensions(formatDescription).width
}
}
private extension Sequence {
func max<Value: Comparable>(on transform: (Element) throws -> Value) rethrows -> Element? {
return try self.max(by: { try transform($0) < transform($1) })
}
}
| 35.427746 | 162 | 0.681188 |
72dc70d38ff958deff22a700d76e1a60c8c59c62 | 4,897 | import FunctionalSwift
import UIKit
class TitledSwitchView: UIView {
// MARK: - Public properties
var title: String? {
get {
return titleLabel.styledText
}
set {
titleLabel.styledText = newValue
}
}
var valueChangeHandler: ((Bool) -> Void)?
var isOn: Bool {
get {
return switchControl.isOn
}
set {
switchControl.isOn = newValue
}
}
// MARK: - UI properties
private lazy var titleLabel: UILabel = {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.setStyles(UILabel.DynamicStyle.body, UILabel.Styles.multiline)
return $0
}(UILabel())
lazy var switchControl: UISwitch = {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.setStyles(UISwitch.Styles.mustardOnTintColor)
$0.addTarget(self, action: #selector(onSwitchValueChange(_:)), for: .valueChanged)
$0.setContentHuggingPriority(.required, for: .horizontal)
$0.setContentCompressionResistancePriority(.required, for: .horizontal)
return $0
}(UISwitch())
private var titleLabelTrailingConstraint: NSLayoutConstraint?
// MARK: - Initialization/Deinitialization
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
subscribeToNotifications()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder:) is not implemented")
}
private func setupUI() {
addSubview <^> [titleLabel, switchControl]
setupConstraints()
}
private func setupConstraints() {
NSLayoutConstraint.deactivate(currentConstraints)
if UIApplication.shared.preferredContentSizeCategory.isAccessibilitySizeCategory {
let trailingConstraint = trailing.constraint(equalTo: titleLabel.trailing,
constant: trailingMarginValue())
titleLabelTrailingConstraint = trailingConstraint
currentConstraints = [
titleLabel.top.constraint(equalTo: topMargin, constant: Space.single),
titleLabel.leading.constraint(equalTo: leadingMargin),
trailingConstraint,
switchControl.top.constraint(equalTo: titleLabel.bottom, constant: Space.single),
switchControl.leading.constraint(equalTo: leadingMargin),
bottomMargin.constraint(equalTo: switchControl.bottom, constant: Space.single),
]
} else {
currentConstraints = [
titleLabel.top.constraint(equalTo: topMargin, constant: Space.single),
titleLabel.leading.constraint(equalTo: leadingMargin),
bottomMargin.constraint(equalTo: titleLabel.bottom, constant: Space.single),
switchControl.leading.constraint(equalTo: titleLabel.trailing, constant: Space.double),
switchControl.centerY.constraint(equalTo: centerY),
trailingMargin.constraint(equalTo: switchControl.trailing),
]
}
NSLayoutConstraint.activate(currentConstraints)
}
deinit {
cancelNotificationsSubscriptions()
}
// MARK: - Private properties
private var currentConstraints: [NSLayoutConstraint] = []
// MARK: - Configuring Content Margins
override func layoutMarginsDidChange() {
super.layoutMarginsDidChange()
titleLabelTrailingConstraint?.constant = trailingMarginValue()
}
private func trailingMarginValue() -> CGFloat {
if #available(iOS 11.0, *) {
return directionalLayoutMargins.trailing
} else {
return layoutMargins.right
}
}
// MARK: - Notifications
private func subscribeToNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(onUIContentSizeCategoryDidChange),
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
private func cancelNotificationsSubscriptions() {
NotificationCenter.default.removeObserver(self,
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
@objc
private func onUIContentSizeCategoryDidChange() {
titleLabel.styledText = title
setupConstraints()
}
@objc
private func onSwitchValueChange(_ sender: UISwitch) {
valueChangeHandler?(sender.isOn)
}
}
// MARK: - TableViewCellDataProviderSupport
extension TitledSwitchView: TableViewCellDataProviderSupport {
class var estimatedCellHeight: CGFloat {
return 56.0
}
}
| 31.191083 | 103 | 0.619563 |
ebd0714e57ea477fd53fd2e222c57f7836c41b72 | 709 | //
// Location.swift
// BucketlistTutorials
//
// Created by Alberto Landi Cortiñas on 5/16/22.
//
import Foundation
import CoreLocation
struct Location: Identifiable, Codable, Equatable {
var id: UUID
var name: String
var description: String
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
static let example = Location(id: UUID(), name: "Las Mercedes", description: "Neighborhood with lots of restaurants.", latitude: 10.481940, longitude: -66.861530)
static func ==(lhs: Location, rhs: Location) -> Bool {
lhs.id == rhs.id
}
}
| 25.321429 | 166 | 0.67701 |
1c5764fa5bebb0b4ddfeb24d2d8fbe6ea7e0bbf4 | 999 | import SwiftUI
struct Cardify: AnimatableModifier {
var radius: Double
var animatableData: Double {
get { radius }
set { radius = newValue }
}
init(isFaceUp: Bool) {
radius = isFaceUp ? 0 : 180
}
func body(content: Content) -> some View {
ZStack {
let shape = RoundedRectangle(cornerRadius: Consts.cornerRadius)
if radius < 90 {
shape.fill().foregroundColor(.white).opacity(0.1)
shape.strokeBorder(lineWidth: Consts.lineWidth)
} else {
shape.fill()
}
content.opacity(radius < 90 ? 1 : 0)
}
.rotation3DEffect(Angle.degrees(radius), axis: (0, 1, 0))
}
private struct Consts {
static let cornerRadius: CGFloat = 10
static let lineWidth: CGFloat = 3
}
}
extension View {
func cardify(isFaceUp: Bool) -> some View {
self.modifier(Cardify(isFaceUp: isFaceUp))
}
}
| 25.615385 | 75 | 0.553554 |
14701f32bbb2cbd17ed4f6681224ba05b85011ad | 725 | //
// HTTPClient.swift
// VirtualTouristMeyer
//
// Created by Meyer, Gustavo on 6/24/19.
// Copyright © 2019 Gustavo Meyer. All rights reserved.
//
import Foundation
/// The HTTP client result to represent the HTTP Result in enum.
///
/// - success: The sucess HTTP
/// - failure: The failure HTTP
public enum HTTPClientResult {
case success(Data, HTTPURLResponse)
case failure(Error)
}
/// A protocol to make HTTP Request
protocol HTTPClient {
/// Makes a HTTP GET request
///
/// - Parameters:
/// - urlResquest: The `URL`
/// - completion: The completion handler to retrive the HTTP response
func makeRequest(from url: URL, completion: @escaping (HTTPClientResult) -> Void)
}
| 24.166667 | 86 | 0.675862 |
b91367124ce9bdaa7422cef5bbda28e24042d0ab | 1,870 | import EngagementSDK
import Lottie
import UIKit
class ImageSliderResultsViewController: Widget {
private let model: ImageSliderWidgetModel
override init(model: ImageSliderWidgetModel) {
self.model = model
super.init(model: model)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
let imageSliderView = CustomImageSliderView()
imageSliderView.slider.isUserInteractionEnabled = false
imageSliderView.titleLabel.text = model.question
let averageImageIndex: Int = Int(round(Float(model.averageMagnitude) * Float(model.options.count - 1)))
URLSession.shared.dataTask(with: model.options[averageImageIndex].imageURL) { data, _, error in
if let error = error {
print("Failed to load image from url: \(error)")
return
}
DispatchQueue.main.async {
if let data = data {
if let image = UIImage(data: data) {
let thumbSize = CGSize(width: 40, height: 40)
UIGraphicsBeginImageContextWithOptions(thumbSize, false, 0.0)
image.draw(in: CGRect(x: 0, y: 0, width: thumbSize.width, height: thumbSize.height))
guard let scaledImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()
imageSliderView.slider.setThumbImage(scaledImage, for: .normal)
}
}
}
}.resume()
imageSliderView.slider.value = Float(model.averageMagnitude)
view = imageSliderView
}
override func viewDidLoad() {
super.viewDidLoad()
model.registerImpression()
}
}
| 35.283019 | 116 | 0.60107 |
1da2b1afcc2c3c76d2e3f71f2d6863b20299a596 | 1,705 | //
// AppDelegate+Pin.swift
// falcon
//
// Created by Manu Herrera on 02/05/2019.
// Copyright © 2019 muun. All rights reserved.
//
import UIKit
extension AppDelegate {
internal func isDisplayingPin() -> Bool {
if let window = pinWindow, window.isKeyWindow {
return true
}
return navController.viewControllers.contains(where: { return $0 is PinViewController })
}
internal func presentLockWindow() {
let pinController = PinViewController(state: .locked, lockDelegate: self)
lockNavController = UINavigationController(rootViewController: pinController)
pinWindow = UIWindow(frame: UIScreen.main.bounds)
pinWindow!.rootViewController = lockNavController
pinWindow!.makeKeyAndVisible()
lockManager.isShowingLockScreen = true
}
}
extension AppDelegate: LockDelegate {
public func unlockApp() {
dismissPinWindow()
lockManager.isShowingLockScreen = false
}
internal func logOut() {
lockManager.wipeDataAndLogOut()
resetWindowToLogOut()
dismissPinWindow()
lockManager.isShowingLockScreen = false
}
fileprivate func resetWindowToLogOut() {
navController.setViewControllers([LogOutViewController()], animated: true)
_window!.rootViewController = navController
_window!.makeKeyAndVisible()
}
fileprivate func dismissPinWindow() {
UIView.animate(withDuration: 0.3, animations: {
self.pinWindow?.alpha = 0
}, completion: { _ in
self.lockNavController.dismiss(animated: true, completion: nil)
self.window?.makeKeyAndVisible()
})
}
}
| 25.833333 | 96 | 0.663343 |
75630ca3a210ae40b566f45ced52c7ede744d0c3 | 1,365 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Firebase
import GoogleSignIn
@objc(SignInViewController)
class SignInViewController: UIViewController, GIDSignInUIDelegate {
@IBOutlet weak var signInButton: GIDSignInButton!
var handle: AuthStateDidChangeListenerHandle?
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signInSilently()
handle = Auth.auth().addStateDidChangeListener() { (auth, user) in
if user != nil {
MeasurementHelper.sendLoginEvent()
self.performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
}
}
}
deinit {
if let handle = handle {
Auth.auth().removeStateDidChangeListener(handle)
}
}
}
| 30.333333 | 87 | 0.717949 |
56b6c737294c359652b19f9b28bdc2f25c4a7bb4 | 4,239 | //
// FifteenViewController.swift
// SHSegmentedControlTableView
//
// Created by angle on 2018/5/24.
// Copyright © 2018 angle. All rights reserved.
//
import UIKit
import SHSegmentedControl
class FifteenViewController: SHBaseViewController, SHSegTableViewDelegate {
var segTableView:SHSegmentedControlTableView!
var segmentControl:SHSegmentControl!
var headerView:UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let tab1 = TestOneTableView.init(frame: CGRect.init(), style: UITableViewStyle.plain)
tab1.num = 15
tab1.label = "一"
let tab2 = TestOneTableView.init(frame: CGRect.init(), style: UITableViewStyle.plain)
tab2.num = 5
tab2.label = "二"
let tab3 = TestOneTableView.init(frame: CGRect.init(), style: UITableViewStyle.plain)
tab3.num = 30
tab3.label = "三"
let tab4 = TestOneTableView.init(frame: CGRect.init(), style: UITableViewStyle.plain)
tab4.num = 30
tab4.label = "四"
let tab5 = TestOneTableView.init(frame: CGRect.init(), style: UITableViewStyle.plain)
tab5.num = 30
tab5.label = "五"
let tab6 = TestOneTableView.init(frame: CGRect.init(), style: UITableViewStyle.plain)
tab6.num = 30
tab6.label = "六"
let tab7 = TestOneTableView.init(frame: CGRect.init(), style: UITableViewStyle.plain)
tab7.num = 30
tab7.label = "七"
self.headerView = self.getHeaderView()
self.segmentControl = self.getSegmentControl()
self.segTableView = self.getSegTableView()
self.segTableView.tableViews = [tab1, tab2, tab3, tab4, tab5, tab6, tab7]
self.view.addSubview(self.segTableView)
}
func segTableViewDidScrollY(_ offsetY: CGFloat) {
}
func segTableViewDidScroll(_ tableView: UIScrollView!) {
}
func segTableViewDidScrollSub(_ subTableView: UIScrollView!) {
}
func segTableViewDidScrollProgress(_ progress: CGFloat, originalIndex: Int, targetIndex: Int) {
if progress == 1 {
self.segmentControl.setSegmentSelectedIndex(targetIndex)
}
}
func getHeaderView() -> UIView {
if self.headerView != nil {
return self.headerView
}
let header:UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 200))
header.backgroundColor = UIColor.purple
return header
}
func getSegTableView() -> SHSegmentedControlTableView {
if self.segTableView != nil {
return self.segTableView
}
let segTable:SHSegmentedControlTableView = SHSegmentedControlTableView.init(frame: self.view.bounds)
segTable.delegateCell = self
segTable.topView = self.headerView
segTable.barView = self.segmentControl
return segTable
}
func getSegmentControl() -> SHSegmentControl {
if self.segmentControl != nil {
return self.segmentControl
}
let segment:SHSegmentControl = SHSegmentControl.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH * 2, height: 45), items: ["分栏一","分栏二","分栏三","分栏四","分栏五","分栏六","分栏七"])
segment.titleSelectColor = UIColor.red
segment.reloadViews()
weak var weakSelf = self
segment.curClick = {(index: NSInteger) ->Void in
// 使用?的好处 就是一旦 self 被释放,就什么也不做
weakSelf?.segTableView.setSegmentSelect(index)
}
return segment
}
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.
}
*/
}
| 32.113636 | 181 | 0.627506 |
ff3173da134b0a1a7788c0e40c051950a489b352 | 623 | @testable import TestProject
class MultipleVariableMock: MultipleVariable {
var invokedASetter = false
var invokedASetterCount = 0
var invokedA: String?
var invokedAList = [String]()
var invokedAGetter = false
var invokedAGetterCount = 0
var stubbedA: String! = ""
override var a: String {
set {
invokedASetter = true
invokedASetterCount += 1
invokedA = newValue
invokedAList.append(newValue)
}
get {
invokedAGetter = true
invokedAGetterCount += 1
return stubbedA
}
}
}
| 24.92 | 46 | 0.589085 |
de2755bb5620cf741354c49232988a6908d8333d | 1,077 | //
// LocationDictionary-CoreLocation.swift
// CloudKitWebServices
//
// Created by Eric Dorphy on 6/16/21.
// Copyright © 2021 Twin Cities App Dev LLC. All rights reserved.
//
import CoreLocation
extension LocationDictionary {
init(from location: CLLocation) {
self.latitude = location.coordinate.latitude
self.longitude = location.coordinate.longitude
self.horizontalAccuracy = location.horizontalAccuracy
self.verticalAccuracy = location.verticalAccuracy
self.altitude = location.altitude
self.speed = location.speed
self.course = location.course
self.timestamp = location.timestamp
if #available(iOS 10.0, macOS 10.15, tvOS 10.0, watchOS 3.0, *) {
self.speedAccuracy = location.speedAccuracy
} else {
self.speedAccuracy = -1
}
if #available(iOS 13.4, macOS 10.15.4, tvOS 13.4, watchOS 6.2, *) {
self.courseAccuracy = location.courseAccuracy
} else {
self.courseAccuracy = -1
}
}
}
| 30.771429 | 75 | 0.63324 |
2248c8a77cd0c30bfb08c33d609d92a9b32fcf02 | 280 | //
// Bundle+extension.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/10/24.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
extension Bundle{
var nameSpace :String{
return infoDictionary?["CFBundleExecutable"] as? String ?? ""
}
}
| 16.470588 | 69 | 0.642857 |
d90734e4b5d124832df92f592c23a3f2964ed3b6 | 1,286 | //
// MediaObserver.swift
// RCTAgora
//
// Created by LXH on 2020/4/10.
// Copyright © 2020 Syan. All rights reserved.
//
import Foundation
import AgoraRtcKit
class MediaObserver: NSObject {
private var emitter: (_ data: Dictionary<String, Any?>?) -> Void
private var maxMetadataSize = 0
private var metadataList = [String]()
init(_ emitter: @escaping (_ data: Dictionary<String, Any?>?) -> Void) {
self.emitter = emitter
}
func addMetadata(_ metadata: String) {
metadataList.append(metadata)
}
func setMaxMetadataSize(_ size: Int) {
maxMetadataSize = size
}
}
extension MediaObserver: AgoraMediaMetadataDataSource {
func metadataMaxSize() -> Int {
return maxMetadataSize
}
func readyToSendMetadata(atTimestamp timestamp: TimeInterval) -> Data? {
if metadataList.count > 0 {
return metadataList.remove(at: 0).data(using: .utf8)
}
return nil
}
}
extension MediaObserver: AgoraMediaMetadataDelegate {
func receiveMetadata(_ data: Data, fromUser uid: Int, atTimestamp timestamp: TimeInterval) {
emitter([
"buffer": String(data: data, encoding: .utf8),
"uid": uid,
"timeStampMs": timestamp
])
}
}
| 24.730769 | 96 | 0.636081 |
3a43ac1e0026ae4a104decd6330a80c5bc9989fd | 838 | // #221
func application(_ app: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?)
-> Bool {
app.isIdleTimerDisabled = true
return true
}
class AppDelegate: UIResponder,
UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
}
}
| 39.904762 | 179 | 0.770883 |
39a7401f9b77dd932e42cfa1ed8d5910f2409531 | 3,255 | //
// Snowflake.swift
// Sword
//
import Foundation
/// The stored type of a Discord Snowflake ID.
public struct Snowflake: Codable {
/// Discord's epoch
public static let epoch = Date(timeIntervalSince1970: 1420070400)
/// Number of generated ID's for the process
public var numberInProcess: Int {
return Int(rawValue & 0xFFF)
}
/// Discord's internal process under worker that generated this snowflake
public var processId: Int {
return Int((rawValue & 0x1F000) >> 12)
}
/// The internal value storage for a snowflake
public let rawValue: UInt64
/// Time when snowflake was created
public var timestamp: Date {
return Date(timeInterval: Double(
(rawValue & 0xFFFFFFFFFFC00000) >> 22) / 1000, since: Snowflake.epoch
)
}
/// Discord's internal worker ID that generated this snowflake
public var workerId: Int {
return Int((rawValue & 0x3E0000) >> 17)
}
/// Initialize from a UInt64
public init(_ snowflake: UInt64) {
self.rawValue = snowflake
}
/// Initialize from any type
/// Currently supports:
/// - String
public init?(_ any: Any?) {
guard let any = any else {
return nil
}
if let string = any as? String, let snowflake = UInt64(string) {
self.init(snowflake)
return
}
return nil
}
/**
Creates a fake snowflake that would have been created at the specified date
Useful for things like the messages before/after/around endpoint
- parameter date: The date to make a fake snowflake for
- returns: A fake snowflake with the specified date, or nil if the specified date will not make a valid snowflake
*/
public static func fakeSnowflake(date: Date) -> Snowflake? {
let intervalSinceDiscordEpoch = Int64(
date.timeIntervalSince(Snowflake.epoch) * 1000
)
guard intervalSinceDiscordEpoch > 0 else { return nil }
guard intervalSinceDiscordEpoch < (1 << 41) else { return nil }
return Snowflake(UInt64(intervalSinceDiscordEpoch) << 22)
}
}
// MARK: Snowflake Conformances
/// Snowflake conformance to ExpressibleByIntegerLiteral
extension Snowflake: ExpressibleByIntegerLiteral {
public typealias IntegerLiteralType = UInt64
/// Initialize from an integer literal
public init(integerLiteral value: UInt64) {
self.rawValue = value
}
}
/// Snowflake conformance to CustomStringConvertible
extension Snowflake: CustomStringConvertible {
/// Description for string Conversion
public var description: String {
return self.rawValue.description
}
}
/// Snowflake conformance to RawRepresentable
extension Snowflake: RawRepresentable, Equatable {
public typealias RawValue = UInt64
/// Init for rawValue conformance
public init(rawValue: UInt64) {
self.rawValue = rawValue
}
}
/// Snowflake conformance to Comparable
extension Snowflake: Comparable {
/// Used to compare Snowflakes (which is useful because a greater Snowflake was made later)
public static func <(lhs: Snowflake, rhs: Snowflake) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
/// Snowflake conformance to Hashable
extension Snowflake: Hashable {
/// The hash value of the Snowflake
public var hashValue: Int {
return self.rawValue.hashValue
}
}
| 25.038462 | 116 | 0.707834 |
e95368f7ab24b2f5d7caa0374ac8bfc07c3211be | 751 | //
// ViewController.swift
// App_Start
//
// Created by David on 2022/01/27.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var TestButton: UIButton!
@IBAction func doSomething(_ sender: Any) {
TestButton.backgroundColor = .orange
let stroyboard = UIStoryboard(name: "Main", bundle: nil)
let detailVC = stroyboard.instantiateViewController(identifier: "DetailViewController") as DetailViewController
self.present(detailVC, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
TestButton.backgroundColor = UIColor.red
}
}
| 24.225806 | 120 | 0.655126 |
db04076d3ce7e3b9898a05580b756aadd3d47416 | 898 | //
// OID.swift
// EJDB-Swift
//
// Created by Safx Developer on 2015/07/29.
// Copyright © 2015年 Safx Developers. All rights reserved.
//
import Foundation
public final class OID {
internal(set) var oid: bson_oid_t = bson_oid_t()
public init() {}
public init(string: String) {
string.withCString { s in
bson_oid_from_string(&oid, s)
}
}
public init(oid: bson_oid_t) {
self.oid = oid
}
public static func generate() -> OID {
let o = OID()
bson_oid_gen(&o.oid)
return o
}
}
extension OID: CustomStringConvertible {
public var description: String {
var ch = Array<Int8>(count: 25, repeatedValue: 0)
ch.withUnsafeMutableBufferPointer { p -> () in
bson_oid_to_string(&oid, p.baseAddress)
()
}
return String.fromCString(ch) ?? ""
}
}
| 19.955556 | 59 | 0.580178 |
ac5811787ab63f0c37e2b38698d6650b742b16a7 | 692 | //
// DateFormatter+Months.swift
// GoCubs
//
// Created by Ellen Shapiro on 2/20/17.
// Copyright © 2017 Designated Nerd Software. All rights reserved.
//
import Foundation
extension DateFormatter {
private static let cub_simpleFormatter = DateFormatter()
static func cub_shortMonthName(for monthInt: Int) -> String {
guard
monthInt <= 12,
monthInt >= 1 else {
fatalError("This is not a month")
}
guard let shortMonths = self.cub_simpleFormatter.shortMonthSymbols else {
fatalError("Could not access short month symbols")
}
return shortMonths[monthInt - 1]
}
}
| 23.862069 | 81 | 0.617052 |
e6d13c062bf3874fa605b61591ea813333e20eba | 343 | //
// MapResources.swift
// GMapsTest
//
// Created by Daniel Illescas Romero on 17/12/2019.
// Copyright © 2019 Daniel Illescas Romero. All rights reserved.
//
import Foundation
import Alamofire
protocol MapResourcesRepository {
func resources(mapFrame: MapFrame, completionHandler: @escaping (Result<MapResource, AFError>) -> Void)
}
| 22.866667 | 104 | 0.752187 |
abe0749f6e02c25efe77cd681bc8e3616c8cb258 | 1,645 | //
// AlbumViewLayout.swift
// Persephone
//
// Created by Daniel Barber on 2019/2/18.
// Copyright © 2019 Dan Barber. All rights reserved.
//
import AppKit
class FlexibleGridViewLayout: NSCollectionViewFlowLayout {
let maxItemWidth: CGFloat = 200
var extraHeight: CGFloat = 0
var scrollPosition: CGFloat = 0
required init?(coder aDecoder: NSCoder) {
super.init()
minimumLineSpacing = 0
minimumInteritemSpacing = 0
sectionInset = NSEdgeInsets(
top: 10,
left: 30,
bottom: 50,
right: 30
)
}
override func prepare() {
super.prepare()
guard let collectionView = collectionView
else { return }
let width = collectionView.bounds.size.width
var divider: CGFloat = 1
var itemWidth: CGFloat = 0
repeat {
let totalPaddingWidth = sectionInset.left + sectionInset.right
let totalGutterWidth = (divider - 1) * (minimumInteritemSpacing)
itemWidth = (width - totalPaddingWidth - totalGutterWidth - 1) / divider
divider = divider + 1
} while itemWidth > maxItemWidth
let itemHeight = itemWidth + extraHeight
itemSize = NSSize(width: itemWidth, height: itemHeight)
}
func saveScrollPosition() {
guard let collectionView = collectionView
else { return }
if let scrollView = collectionView.enclosingScrollView {
scrollPosition = scrollView.documentVisibleRect.minY / collectionView.bounds.height
}
}
func setScrollPosition() {
guard let collectionView = collectionView
else { return }
collectionView.scroll(NSPoint(x: 0, y: scrollPosition * collectionView.bounds.height))
}
}
| 24.552239 | 90 | 0.68693 |
01a6e68ab5cde64165797d39455619a02220c504 | 24,884 | /**
_____ _ _ _____ ______ _
| __ \ | | | | | __ \ | ____| | |
| |__) | | |__| | | |__) | | |__ _ __ __ _ _ __ ___ _____ _____ _ __| | __
| ___/ | __ | | ___/ | __| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
| | | | | | | | _ | | | | | (_| | | | | | | __/\ V V / (_) | | | <
|_| |_| |_| |_| (_) |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_\
Copyright (c) 2016 Wesley de Groot (http://www.wesleydegroot.nl), WDGWV (http://www.wdgwv.com)
Variable prefixes:
PFS = PHP.Framework Shared
PFT = PHP.Framework Tests (internal)
PFI = PHP.Framework Internal
PFU = PHP.Framework Unspecified
usage:
php.the_php_function(and, parameters, ofcourse)
documentation:
http://wdg.github.io/php.framework/
wiki:
https://github.com/wdg/php.framework/wiki
questions/bugs:
https://github.com/wdg/php.framework/issues
---------------------------------------------------
File: PHPFrameworkSwiftStringExtensions.swift
Created: 18-FEB-2016
Creator: Wesley de Groot | g: @wdg | t: @wesdegroot
Issue: N/A
Prefix: N/A
---------------------------------------------------
*/
import Foundation
/**
Extensions for Strings
*/
public extension String {
private struct HTMLEntities {
static let characterEntities : [String: Character] = [
// XML predefined entities:
"&" : "&",
""" : "\"",
"'" : "'",
"<" : "<",
">" : ">",
// HTML character entity references:
" " : "\u{00A0}",
"¡" : "\u{00A1}",
"¢" : "\u{00A2}",
"£" : "\u{00A3}",
"¤" : "\u{00A4}",
"¥" : "\u{00A5}",
"¦" : "\u{00A6}",
"§" : "\u{00A7}",
"¨" : "\u{00A8}",
"©" : "\u{00A9}",
"ª" : "\u{00AA}",
"«" : "\u{00AB}",
"¬" : "\u{00AC}",
"­" : "\u{00AD}",
"®" : "\u{00AE}",
"¯" : "\u{00AF}",
"°" : "\u{00B0}",
"±" : "\u{00B1}",
"²" : "\u{00B2}",
"³" : "\u{00B3}",
"´" : "\u{00B4}",
"µ" : "\u{00B5}",
"¶" : "\u{00B6}",
"·" : "\u{00B7}",
"¸" : "\u{00B8}",
"¹" : "\u{00B9}",
"º" : "\u{00BA}",
"»" : "\u{00BB}",
"¼" : "\u{00BC}",
"½" : "\u{00BD}",
"¾" : "\u{00BE}",
"¿" : "\u{00BF}",
"À" : "\u{00C0}",
"Á" : "\u{00C1}",
"Â" : "\u{00C2}",
"Ã" : "\u{00C3}",
"Ä" : "\u{00C4}",
"Å" : "\u{00C5}",
"Æ" : "\u{00C6}",
"Ç" : "\u{00C7}",
"È" : "\u{00C8}",
"É" : "\u{00C9}",
"Ê" : "\u{00CA}",
"Ë" : "\u{00CB}",
"Ì" : "\u{00CC}",
"Í" : "\u{00CD}",
"Î" : "\u{00CE}",
"Ï" : "\u{00CF}",
"Ð" : "\u{00D0}",
"Ñ" : "\u{00D1}",
"Ò" : "\u{00D2}",
"Ó" : "\u{00D3}",
"Ô" : "\u{00D4}",
"Õ" : "\u{00D5}",
"Ö" : "\u{00D6}",
"×" : "\u{00D7}",
"Ø" : "\u{00D8}",
"Ù" : "\u{00D9}",
"Ú" : "\u{00DA}",
"Û" : "\u{00DB}",
"Ü" : "\u{00DC}",
"Ý" : "\u{00DD}",
"Þ" : "\u{00DE}",
"ß" : "\u{00DF}",
"à" : "\u{00E0}",
"á" : "\u{00E1}",
"â" : "\u{00E2}",
"ã" : "\u{00E3}",
"ä" : "\u{00E4}",
"å" : "\u{00E5}",
"æ" : "\u{00E6}",
"ç" : "\u{00E7}",
"è" : "\u{00E8}",
"é" : "\u{00E9}",
"ê" : "\u{00EA}",
"ë" : "\u{00EB}",
"ì" : "\u{00EC}",
"í" : "\u{00ED}",
"î" : "\u{00EE}",
"ï" : "\u{00EF}",
"ð" : "\u{00F0}",
"ñ" : "\u{00F1}",
"ò" : "\u{00F2}",
"ó" : "\u{00F3}",
"ô" : "\u{00F4}",
"õ" : "\u{00F5}",
"ö" : "\u{00F6}",
"÷" : "\u{00F7}",
"ø" : "\u{00F8}",
"ù" : "\u{00F9}",
"ú" : "\u{00FA}",
"û" : "\u{00FB}",
"ü" : "\u{00FC}",
"ý" : "\u{00FD}",
"þ" : "\u{00FE}",
"ÿ" : "\u{00FF}",
"Œ" : "\u{0152}",
"œ" : "\u{0153}",
"Š" : "\u{0160}",
"š" : "\u{0161}",
"Ÿ" : "\u{0178}",
"ƒ" : "\u{0192}",
"ˆ" : "\u{02C6}",
"˜" : "\u{02DC}",
"Α" : "\u{0391}",
"Β" : "\u{0392}",
"Γ" : "\u{0393}",
"Δ" : "\u{0394}",
"Ε" : "\u{0395}",
"Ζ" : "\u{0396}",
"Η" : "\u{0397}",
"Θ" : "\u{0398}",
"Ι" : "\u{0399}",
"Κ" : "\u{039A}",
"Λ" : "\u{039B}",
"Μ" : "\u{039C}",
"Ν" : "\u{039D}",
"Ξ" : "\u{039E}",
"Ο" : "\u{039F}",
"Π" : "\u{03A0}",
"Ρ" : "\u{03A1}",
"Σ" : "\u{03A3}",
"Τ" : "\u{03A4}",
"Υ" : "\u{03A5}",
"Φ" : "\u{03A6}",
"Χ" : "\u{03A7}",
"Ψ" : "\u{03A8}",
"Ω" : "\u{03A9}",
"α" : "\u{03B1}",
"β" : "\u{03B2}",
"γ" : "\u{03B3}",
"δ" : "\u{03B4}",
"ε" : "\u{03B5}",
"ζ" : "\u{03B6}",
"η" : "\u{03B7}",
"θ" : "\u{03B8}",
"ι" : "\u{03B9}",
"κ" : "\u{03BA}",
"λ" : "\u{03BB}",
"μ" : "\u{03BC}",
"ν" : "\u{03BD}",
"ξ" : "\u{03BE}",
"ο" : "\u{03BF}",
"π" : "\u{03C0}",
"ρ" : "\u{03C1}",
"ς" : "\u{03C2}",
"σ" : "\u{03C3}",
"τ" : "\u{03C4}",
"υ" : "\u{03C5}",
"φ" : "\u{03C6}",
"χ" : "\u{03C7}",
"ψ" : "\u{03C8}",
"ω" : "\u{03C9}",
"ϑ" : "\u{03D1}",
"ϒ" : "\u{03D2}",
"ϖ" : "\u{03D6}",
" " : "\u{2002}",
" " : "\u{2003}",
" " : "\u{2009}",
"‌" : "\u{200C}",
"‍" : "\u{200D}",
"‎" : "\u{200E}",
"‏" : "\u{200F}",
"–" : "\u{2013}",
"—" : "\u{2014}",
"‘" : "\u{2018}",
"’" : "\u{2019}",
"‚" : "\u{201A}",
"“" : "\u{201C}",
"”" : "\u{201D}",
"„" : "\u{201E}",
"†" : "\u{2020}",
"‡" : "\u{2021}",
"•" : "\u{2022}",
"…" : "\u{2026}",
"‰" : "\u{2030}",
"′" : "\u{2032}",
"″" : "\u{2033}",
"‹" : "\u{2039}",
"›" : "\u{203A}",
"‾" : "\u{203E}",
"⁄" : "\u{2044}",
"€" : "\u{20AC}",
"ℑ" : "\u{2111}",
"℘" : "\u{2118}",
"ℜ" : "\u{211C}",
"™" : "\u{2122}",
"ℵ" : "\u{2135}",
"←" : "\u{2190}",
"↑" : "\u{2191}",
"→" : "\u{2192}",
"↓" : "\u{2193}",
"↔" : "\u{2194}",
"↵" : "\u{21B5}",
"⇐" : "\u{21D0}",
"⇑" : "\u{21D1}",
"⇒" : "\u{21D2}",
"⇓" : "\u{21D3}",
"⇔" : "\u{21D4}",
"∀" : "\u{2200}",
"∂" : "\u{2202}",
"∃" : "\u{2203}",
"∅" : "\u{2205}",
"∇" : "\u{2207}",
"∈" : "\u{2208}",
"∉" : "\u{2209}",
"∋" : "\u{220B}",
"∏" : "\u{220F}",
"∑" : "\u{2211}",
"−" : "\u{2212}",
"∗" : "\u{2217}",
"√" : "\u{221A}",
"∝" : "\u{221D}",
"∞" : "\u{221E}",
"∠" : "\u{2220}",
"∧" : "\u{2227}",
"∨" : "\u{2228}",
"∩" : "\u{2229}",
"∪" : "\u{222A}",
"∫" : "\u{222B}",
"∴" : "\u{2234}",
"∼" : "\u{223C}",
"≅" : "\u{2245}",
"≈" : "\u{2248}",
"≠" : "\u{2260}",
"≡" : "\u{2261}",
"≤" : "\u{2264}",
"≥" : "\u{2265}",
"⊂" : "\u{2282}",
"⊃" : "\u{2283}",
"⊄" : "\u{2284}",
"⊆" : "\u{2286}",
"⊇" : "\u{2287}",
"⊕" : "\u{2295}",
"⊗" : "\u{2297}",
"⊥" : "\u{22A5}",
"⋅" : "\u{22C5}",
"⌈" : "\u{2308}",
"⌉" : "\u{2309}",
"⌊" : "\u{230A}",
"⌋" : "\u{230B}",
"⟨" : "\u{2329}",
"⟩" : "\u{232A}",
"◊" : "\u{25CA}",
"♠" : "\u{2660}",
"♣" : "\u{2663}",
"♥" : "\u{2665}",
"♦" : "\u{2666}",
]
}
/**
get string length
*/
public var length: Int {
get {
return self.characters.count
}
}
/**
contains
- Parameter s: String to check
- Returns: true/false
*/
public func contains(_ s: String) -> Bool {
return self.range(of: s) != nil ? true : false
}
/**
Replace
- Parameter target: String
- Parameter withString: Replacement
- Returns: Replaced string
*/
public func replace(_ target: String, withString: String) -> String {
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literalSearch, range: nil)
}
/**
Replace (Case Insensitive)
- Parameter target: String
- Parameter withString: Replacement
- Returns: Replaced string
*/
public func ireplace(_ target: String, withString: String) -> String {
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.caseInsensitiveSearch, range: nil)
}
/**
Character At Index
- Parameter index: The index
- Returns Character
*/
func characterAtIndex(_ index: Int) -> Character! {
var cur = 0
for char in self.characters {
if cur == index {
return char
}
cur += 1
}
return nil
}
/**
Character Code At Index
- Parameter index: The index
- Returns Character
*/
func charCodeAtindex(_ index: Int) -> Int! {
return self.charCodeAt(index)
}
/**
add subscript
- Parameter i: The index
- Returns: The ranged string
*/
public subscript(i: Int) -> Character {
get {
let index = self.characters.index(self.startIndex, offsetBy: i)
return self[index]
}
}
/**
add subscript
- Parameter r: Range [1..2]
- Returns: The ranged string.
*/
public subscript(r: Range<Int>) -> String {
get {
let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.characters.index(self.startIndex, offsetBy: r.upperBound - 1)
return self[startIndex..<endIndex]
}
}
/**
add subscript
- Parameter r: Range [1..2]
- Returns: The ranged string.
*/
public subscript(r: CountableClosedRange<Int>) -> String {
get {
let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.characters.index(self.startIndex, offsetBy: r.upperBound)
return self[startIndex..<endIndex]
}
}
/**
Finds the string between two bookend strings if it can be found.
- parameter left: The left bookend
- parameter right: The right bookend
- returns: The string between the two bookends, or nil if the bookends cannot be found, the bookends are the same or appear contiguously.
*/
func between(_ left: String, _ right: String) -> String? {
guard
let leftRange = range(of: left), rightRange = range(of: right, options: .backwardsSearch)
where left != right && leftRange.upperBound != rightRange.lowerBound
else {return nil}
// return self[leftRange.endIndex...rightRange.index(before: rightRange.startIndex)]
return self[leftRange.upperBound...rightRange.lowerBound] //rightRange.startIndex.predecessor()]
}
// https://gist.github.com/stevenschobert/540dd33e828461916c11
func camelize() -> String {
let source = clean(" ", allOf: "-", "_")
if source.characters.contains(" ") {
let first = source.substring(to: source.characters.index(source.startIndex, offsetBy: 1))
let cammel = NSString(format: "%@", (source as NSString).capitalized.replacingOccurrences(of: " ", with: "", options: [], range: nil)) as String
let rest = String(cammel.characters.dropFirst())
return "\(first)\(rest)"
} else {
let first = (source as NSString).lowercased.substring(to: source.characters.index(source.startIndex, offsetBy: 1))
let rest = String(source.characters.dropFirst())
return "\(first)\(rest)"
}
}
func capitalize() -> String {
return self.capitalized
}
func chompLeft(_ prefix: String) -> String {
if let prefixRange = range(of: prefix) {
if prefixRange.upperBound >= endIndex {
return self[startIndex..<prefixRange.lowerBound]
} else {
return self[prefixRange.upperBound..<endIndex]
}
}
return self
}
func chompRight(_ suffix: String) -> String {
if let suffixRange = range(of: suffix, options: .backwardsSearch) {
if suffixRange.upperBound >= endIndex {
return self[startIndex..<suffixRange.lowerBound]
} else {
return self[suffixRange.upperBound..<endIndex]
}
}
return self
}
func collapseWhitespace() -> String {
let components = self.components(separatedBy: CharacterSet.whitespacesAndNewlines).filter {!$0.isEmpty}
return components.joined(separator: " ")
}
func clean(_ with: String, allOf: String...) -> String {
var string = self
for target in allOf {
string = string.replacingOccurrences(of: target, with: with)
}
return string
}
func count(_ substring: String) -> Int {
return components(separatedBy: substring).count - 1
}
func endsWith(_ suffix: String) -> Bool {
return hasSuffix(suffix)
}
func ensureLeft(_ prefix: String) -> String {
if startsWith(prefix) {
return self
} else {
return "\(prefix)\(self)"
}
}
func ensureRight(_ suffix: String) -> String {
if endsWith(suffix) {
return self
} else {
return "\(self)\(suffix)"
}
}
func indexOf(_ substring: String) -> Int? {
if let range = range(of: substring) {
return characters.distance(from: startIndex, to: range.lowerBound)
}
return nil
}
func initials() -> String {
let words = self.components(separatedBy: " ")
return words.reduce("") {$0 + $1[0...0]}
}
func initialsFirstAndLast() -> String {
let words = self.components(separatedBy: " ")
return words.reduce("") {($0 == "" ? "" : $0[0...0]) + $1[0...0]}
}
func isAlpha() -> Bool {
for chr in characters {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z")) {
return false
}
}
return true
}
func isAlphaNumeric() -> Bool {
let alphaNumeric = CharacterSet.alphanumerics
return components(separatedBy: alphaNumeric).joined(separator: "").length == 0
}
func isEmpty() -> Bool {
let nonWhitespaceSet = CharacterSet.whitespacesAndNewlines.inverted
return components(separatedBy: nonWhitespaceSet).joined(separator: "").length != 0
}
func isNumeric() -> Bool {
if let _ = NumberFormatter().number(from: self) {
return true
}
return false
}
func join<S : Sequence>(_ elements: S) -> String {
return elements.map {String($0)}.joined(separator: self)
}
func latinize() -> String {
return self.folding(.diacriticInsensitiveSearch, locale: Locale.current())
}
func lines() -> [String] {
return characters.split {$0 == "\n"}.map(String.init)
}
func pad(_ n: Int, _ string: String = " ") -> String {
return "".join([string.times(n), self, string.times(n)])
}
func padLeft(_ n: Int, _ string: String = " ") -> String {
return "".join([string.times(n), self])
}
func padRight(_ n: Int, _ string: String = " ") -> String {
return "".join([self, string.times(n)])
}
func slugify() -> String {
let slugCharacterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
return latinize().lowercased()
.components(separatedBy: slugCharacterSet.inverted)
.filter {$0 != ""}
.joined(separator: "-")
}
func split(_ separator: Character) -> [String] {
return characters.split {$0 == separator}.map(String.init)
}
var textLines: [String] {
return split("\n")
}
var words: [String] {
return split(" ")
}
func startsWith(_ prefix: String) -> Bool {
return hasPrefix(prefix)
}
func stripPunctuation() -> String {
return components(separatedBy: NSCharacterSet.punctuation())
.joined(separator: "")
.components(separatedBy: " ")
.filter {$0 != ""}
.joined(separator: " ")
}
func times(_ n: Int) -> String {
return (0..<n).reduce("") {$0.0 + self}
}
func toFloat() -> Float? {
if let number = NumberFormatter().number(from: self) {
return number.floatValue
}
return nil
}
func toInt() -> Int? {
if let number = NumberFormatter().number(from: self) {
return number.intValue
}
return nil
}
func toDouble(_ locale: Locale = Locale.system()) -> Double? {
let nf = NumberFormatter()
nf.locale = locale
if let number = nf.number(from: self) {
return number.doubleValue
}
return nil
}
/**
Convert anything to bool...
- Returns: Bool
*/
func toBool() -> Bool? {
let trimmed = self.trimmed().lowercased()
if trimmed == "true" || trimmed == "false" {
return (trimmed as NSString).boolValue
}
return nil
}
func toDate(_ format: String = "yyyy-MM-dd") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
func toDateTime(_ format : String = "yyyy-MM-dd HH:mm:ss") -> Date? {
return toDate(format)
}
/**
trimmedLeft
- Returns: Left trimmed string
*/
func trimmedLeft() -> String {
if let range = rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines.inverted) {
return self[range.lowerBound..<endIndex]
}
return self
}
/**
trimmedRight
- Returns: Right trimmed string
*/
func trimmedRight() -> String {
if let range = rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines.inverted, options: NSString.CompareOptions.backwardsSearch) {
return self[startIndex..<range.upperBound]
}
return self
}
/**
trimmed
- Returns: Left & Right trimmed.
*/
func trimmed() -> String {
return trimmedLeft().trimmedRight()
}
/**
Convert the number in the string to the corresponding\
Unicode character, e.g.\
<pre>
decodeNumeric("64", 10) --> "@"
decodeNumeric("20ac", 16) --> "€"
</pre>
- Parameter string
- Parameter base
- Returns: Character
*/
private func decodeNumeric(_ string : String, base : Int32) -> Character? {
let code = UInt32(strtoul(string, nil, base))
return Character(UnicodeScalar(code))
}
/**
Decode the HTML character entity to the corresponding\
Unicode character, return `nil` for invalid input.\
<pre>
decode("&#64;") --> "@"
decode("&#x20ac;") --> "€"
decode("&lt;") --> "<"
decode("&foo;") --> nil
</pre>
- Parameter entity: The entities
- Returns: Character
*/
private func decode(_ entity : String) -> Character? {
if entity.hasPrefix("&#x") || entity.hasPrefix("&#X") {
return decodeNumeric(entity.substring(from: entity.characters.index(entity.startIndex, offsetBy: 3)), base: 16)
} else if entity.hasPrefix("&#") {
return decodeNumeric(entity.substring(from: entity.characters.index(entity.startIndex, offsetBy: 2)), base: 10)
} else {
return HTMLEntities.characterEntities[entity]
}
}
/**
Returns a new string made by replacing in the `String` all HTML character entity references with the corresponding character.
- Returns: the decoded HTML
*/
func decodeHTML() -> String {
var result = ""
var position = startIndex
// Find the next '&' and copy the characters preceding it to `result`:
while let ampRange = self.range(of: "&", range: position..<endIndex) {
result.append(self[position..<ampRange.lowerBound])
position = ampRange.lowerBound
// Find the next ';' and copy everything from '&' to ';' into `entity`
if let semiRange = self.range(of: ";", range: position..<endIndex) {
let entity = self[position..<semiRange.upperBound]
position = semiRange.upperBound
if let decoded = decode(entity) {
// Replace by decoded character:
result.append(decoded)
} else {
// Invalid entity, copy verbatim:
result.append(entity)
}
} else {
// No matching ';'.
break
}
}
// Copy remaining characters to `result`:
result.append(self[position..<endIndex])
return result
}
/**
Encode the HTML
- Returns: the encoded HTML
*/
public func encodeHTML() -> String {
// Ok, this feels weird.
var _tempString = self
// First do the amperstand, otherwise it will ruin everything.
_tempString = _tempString.replace("&", withString: "&")
// Loop trough the HTMLEntities.
for (index, value) in HTMLEntities.characterEntities {
// Ignore the "&".
if (String(value) != "&") {
// Replace val, with index.
_tempString = _tempString.replace(String(value), withString: index)
}
}
// return and be happy
return _tempString
}
/**
getHTMLEntities
- Returns: the HTMLEntities.
*/
public func getHTMLEntities() -> [String: Character] {
// PHP, Shame on you. but here you'll go.
return HTMLEntities.characterEntities
}
/**
Charcode for the character at index x
- Parameter Char: the character index
- Returns: charcode (int)
*/
func charCodeAt(_ Char: Int) -> Int {
// ok search for the character...
if (self.length > Char) {
let character = String(self.characterAtIndex(Char))
return Int(String(character.unicodeScalars.first!.value))!
} else {
return 0
}
}
func UcharCodeAt(_ Char: Int) -> UInt {
// ok search for the character...
if (self.length > Int(Char)) {
let character = String(self.characterAtIndex(Int(Char)))
return UInt(String(character.unicodeScalars.first!.value))!
} else {
return 0
}
}
/**
Substring a string.
- Parameter start: the start
- Parameter length: the length
- Returns: the substring
*/
func substr(_ start: Int, _ length: Int = 0) -> String {
let str = self
if (length == 0) {
// We'll only have a 'start' position
if (start < 1) {
// Count down to end.
let startPosition: Int = (str.characters.count + start)
return str[startPosition...str.characters.count]
} else {
// Ok we'll start at point...
return str[start...str.characters.count]
}
} else {
// Ok, this could be fun, but we can also..
// Nevermind.
// We'll need to handle the length...
if (length > 0) {
if (start < 1) {
// We'll know this trick!
let startPosition: Int = (str.characters.count + start)
// Will be postitive in the end. (hopefully :P)
// Ok, this is amazing! let me explain
// String Count - (String count - -Start Point) + length
// ^^^ -- is + (Since Start Point is a negative number)
// String Count - Start point + length
var endPosition: Int = ((str.characters.count - (str.characters.count + start)) + length)
// If the endposition > the string, just string length.
if (endPosition > str.characters.count) {
endPosition = str.characters.count
}
// i WILL return ;)
return str[startPosition...endPosition]
} else {
// We'll know this trick!
let startPosition: Int = start
// Will be postitive in the end. (hopefully :P)
var endPosition: Int = ((str.characters.count - start) + length)
// If the endposition > the string, just string length.
if (endPosition > str.characters.count) {
endPosition = str.characters.count
}
// i WILL return ;)
return str[startPosition...endPosition]
}
} else {
// End tries to be funny.
// so fix that.
// Length (end = negative)
if (start < 1) {
// But, Wait. Start is also negative?!
// Count down to end.
let startPosition: Int = (str.characters.count + start)
// We'll doing some magic here again, please, i don't explain this one also! (HAHA)
var endPosition: Int = (str.characters.count - ((str.characters.count + start) + (length + 1)))
// If the endposition > the string, just string length.
if (endPosition > str.characters.count) {
endPosition = str.characters.count
}
// i WILL return ;)
return str[startPosition...endPosition]
} else {
// Ok we'll start at point...
// Count down to end.
let startPosition: Int = (str.characters.count - start)
// We'll doing some magic here again, please, i don't explain this one also! (HAHA)
var endPosition: Int = (str.characters.count - ((str.characters.count - start) + (length + 1)))
// If the endposition > the string, just string length.
if (endPosition > str.characters.count) {
endPosition = str.characters.count
}
// i WILL return ;)
return str[startPosition...endPosition]
}
}
// we'll having fun now!
}
// And it's done.
}
}
| 26.138655 | 147 | 0.554774 |
72c266b39aa26a46439ab53c182c316d9f16b339 | 1,229 | //
// Pie.swift
// Memorize
//
// Created by zen on 6/14/20.
// Copyright © 2020 Evoluteix. All rights reserved.
//
import SwiftUI
struct Pie: Shape {
private(set) var startAngle: Angle
private(set) var endAngle: Angle
private(set) var clockwise: Bool = false
var animatableData: AnimatablePair<Double, Double> {
get {
AnimatablePair(startAngle.radians, endAngle.radians)
}
set {
startAngle = Angle.radians(newValue.first)
endAngle = Angle.radians(newValue.second)
}
}
func path(in rect: CGRect) -> Path {
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius = min(rect.width, rect.height) / 2
let start = CGPoint(
x: center.x + radius * cos(CGFloat(startAngle.radians)),
y: center.y + radius * sin(CGFloat(startAngle.radians))
)
var p = Path()
p.move(to: center)
p.addLine(to: start)
p.addArc(
center: center,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: clockwise
)
p.addLine(to: center)
return p
}
}
| 25.604167 | 68 | 0.554109 |
080c02faec7adf6bfc2bcefa086ebe9f01322424 | 1,151 | //
// ChartAxisLabelsGeneratorNumber.swift
// SwiftCharts
//
// Created by ischuetz on 27/06/16.
// Copyright © 2016 ivanschuetz. All rights reserved.
//
import Foundation
import UIKit
/// Generates a single formatted number for scalar
open class ChartAxisLabelsGeneratorNumber: ChartAxisLabelsGeneratorBase {
public let labelSettings: ChartLabelSettings
public let formatter: NumberFormatter
public init(labelSettings: ChartLabelSettings, formatter: NumberFormatter = ChartAxisLabelsGeneratorNumber.defaultFormatter) {
self.labelSettings = labelSettings
self.formatter = formatter
}
open override func generate(_ scalar: Double) -> [ChartAxisLabel] {
let text = formatter.string(from: NSNumber(value: scalar))!
return [ChartAxisLabel(text: text, settings: labelSettings)]
}
public static var defaultFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
return formatter
}()
open override func fonts(_ scalar: Double) -> [UIFont] {
return [labelSettings.font]
}
}
| 29.512821 | 130 | 0.702867 |
145e2df30efd004a5f5c6ffdbbe91795bb4726c3 | 1,363 | //
// CarouselView.swift
// SwiftUIToyBox
//
// Created by yuoku on 15/02/2021.
// Copyright © 2021 yuoku. All rights reserved.
//
import SwiftUI
struct CarouselView: View {
@ObservedObject var viewModel: CarouselViewModel
var body: some View {
ZStack {
VStack {
imageCarouselView(uiimages: [
Assets.fox.image,
Assets.iceland.image,
Assets.tree.image,
])
Spacer()
}
}
.navigationBarTitle(Text("カルーセル"))
}
}
extension CarouselView {
func imageCarouselView(uiimages: [UIImage]) -> some View {
GeometryReader { geometry in
ImageCarouselView(numberOfImages: uiimages.count) {
ForEach(uiimages, id: \.self) { uiimage in
Image(uiImage: uiimage)
.resizable()
.scaledToFill()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
}
}
.frame(width: UIScreen.main.bounds.width, height: 300, alignment: .center)
}
}
// MARK: - PreviewProvider
struct CarouselView_Previews: PreviewProvider {
static var previews: some View {
CarouselBuilder.build()
}
}
| 25.716981 | 88 | 0.530448 |
e687c1b07e930f28ae2091902be8ce2cb932e6ea | 3,358 | //
// main.swift
// PrepareReactNativeConfig
//
// Created by Stijn on 29/01/2019.
// Copyright © 2019 Pedro Belo. All rights reserved.
//
import Errors
import Foundation
import HighwayLibrary
import PrepareForConfigurationLibrary
import SignPost
import SourceryWorker
import Terminal
import ZFile
let signPost = SignPost.shared
let xcbuild = XCBuild()
let highWay: Highway!
let highwayRunner: HighwayRunner!
let dispatchGroup = DispatchGroup()
do
{
signPost.message("🏗\(pretty_function()) ...")
var environmentJsonFilesFolder: FolderProtocol = FileSystem.shared.currentFolder
if try environmentJsonFilesFolder.parentFolder().name == "Products"
{
// Case where we are building from xcode
// .build/RNConfigurationHighwaySetup/Build/Products/Debug/env.debug.json
let relativePath = "../../../../"
environmentJsonFilesFolder = try environmentJsonFilesFolder.subfolder(named: relativePath)
signPost.message("⚠️ building from xcode detected, moving \(relativePath) up")
signPost.message("ℹ️ .env.<#configuration#>.json are expected to be in \n\(environmentJsonFilesFolder)")
}
let rnConfigurationSrcRoot = try File(path: #file).parentFolder().parentFolder().parentFolder()
let dependecyService = DependencyService(in: rnConfigurationSrcRoot)
let dumpService = DumpService(swiftPackageFolder: rnConfigurationSrcRoot)
let package = try Highway.package(for: rnConfigurationSrcRoot, dependencyService: dependecyService, dumpService: dumpService)
let sourceryBuilder = SourceryBuilder(dependencyService: dependecyService)
highWay = try Highway(package: package, dependencyService: dependecyService, sourceryBuilder: sourceryBuilder)
highwayRunner = HighwayRunner(highway: highWay, dispatchGroup: dispatchGroup)
let prepareCode = try PrepareCode(rnConfigurationSrcRoot: rnConfigurationSrcRoot, environmentJsonFilesFolder: environmentJsonFilesFolder, signPost: signPost)
do
{
try prepareCode.attempt()
// enable and have a look at the file to make it work if you want.
try highwayRunner.addGithooksPrePush()
highwayRunner.runSourcery(handleSourceryOutput)
dispatchGroup.notify(queue: DispatchQueue.main)
{
highwayRunner.runSwiftformat(handleSwiftformat)
dispatchGroup.wait()
guard highwayRunner.errors?.count ?? 0 <= 0 else
{
SignPost.shared.error(
"""
❌ PREPARE **RNConfiguration**
\(highwayRunner.errors!)
❌
♥️ Fix it by adding environment files
\(ConfigurationDisk.JSONFileName.allCases.map { "* \($0.rawValue)" }.joined(separator: "\n"))
"""
)
exit(EXIT_FAILURE)
}
signPost.message("🏗\(pretty_function()) ✅")
exit(EXIT_SUCCESS)
}
dispatchMain()
}
}
catch
{
signPost.error(
"""
❌ \(pretty_function())
\(error)
❌
♥️ Fix it by adding environment files
\(ConfigurationDisk.JSONFileName.allCases.map { "* \($0.rawValue)" }.joined(separator: "\n"))
"""
)
exit(EXIT_FAILURE)
}
| 32.601942 | 161 | 0.649196 |
76ef32d9ac75488a37f540f051b284d6d87e7b2f | 2,220 | //
// UIColor+Arithmetic.swift
// Colorly
//
// Created by Adam Graham on 3/24/19.
// Copyright © 2019 Adam Graham. All rights reserved.
//
import UIKit
/// Returns the result of adding two colors together.
public func +(lhs: UIColor, rhs: UIColor) -> UIColor {
var (r1, g1, b1, a1) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
lhs.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
var (r2, g2, b2, a2) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
rhs.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
return UIColor(red: clamp(r1 + r2, 0.0, 1.0),
green: clamp(g1 + g2, 0.0, 1.0),
blue: clamp(b1 + b2, 0.0, 1.0),
alpha: clamp((a1 + a2) / 2.0, 0.0, 1.0))
}
/// Returns the result of subtracting one color from another.
public func -(lhs: UIColor, rhs: UIColor) -> UIColor {
var (r1, g1, b1, a1) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
lhs.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
var (r2, g2, b2, a2) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
rhs.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
return UIColor(red: clamp(r1 - r2, 0.0, 1.0),
green: clamp(g1 - g2, 0.0, 1.0),
blue: clamp(b1 - b2, 0.0, 1.0),
alpha: clamp((a1 + a2) / 2.0, 0.0, 1.0))
}
/// Returns the result of multiplying a color by a multiplier.
public func *(color: UIColor, multiplier: CGFloat) -> UIColor {
var (r, g, b, a) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
color.getRed(&r, green: &g, blue: &b, alpha: &a)
return UIColor(red: clamp(r * multiplier, 0.0, 1.0),
green: clamp(g * multiplier, 0.0, 1.0),
blue: clamp(b * multiplier, 0.0, 1.0),
alpha: a)
}
/// Returns the result of dividing a color by a divisor.
public func /(color: UIColor, divisor: CGFloat) -> UIColor {
var (r, g, b, a) = (CGFloat(), CGFloat(), CGFloat(), CGFloat())
color.getRed(&r, green: &g, blue: &b, alpha: &a)
return UIColor(red: clamp(r / divisor, 0.0, 1.0),
green: clamp(g / divisor, 0.0, 1.0),
blue: clamp(b / divisor, 0.0, 1.0),
alpha: a)
}
| 37 | 71 | 0.539189 |
18cd440d441382eb29354fb37023d2d0fc050f36 | 1,667 | //
// JLIndentator.swift
// Chromatism
//
// Created by Johannes Lund on 2015-06-05.
// Copyright (c) 2015 anviking. All rights reserved.
//
import Foundation
//
//class JLIndentator: NSObject, UITextViewDelegate {
//
//
// let expression = NSRegularExpression(pattern: "[\\t| ]*", options: nil, error: nil)!
//
// func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// let oldString: String?
//
// if text == "\n" {
// // Return
// // Start the new line with as many tabs or white spaces as the previous one.
// let lineRange = [textView.text lineRangeForRange:range];
// let prefixRange = expression.firstMatchInString(textView.text, options: nil, range: lineRange)
// NSString *prefixString = [textView.text substringWithRange:prefixRange];
//
// UITextPosition *beginning = textView.beginningOfDocument;
// UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
// UITextPosition *stop = [textView positionFromPosition:start offset:range.length];
//
// UITextRange *textRange = [textView textRangeFromPosition:start toPosition:stop];
//
// [textView replaceRange:textRange withText:[NSString stringWithFormat:@"\n%@",prefixString]];
//
// return NO;
// }
//
// if (range.length > 0)
// {
// _oldString = [textView.text substringWithRange:range];
// }
//
// return YES;
// }
// }
//} | 36.23913 | 121 | 0.595681 |
5d7f6320f2611ce6d2c6611be1431b01b3299f63 | 2,177 | //
// AppDelegate.swift
// TipCal
//
// Created by oscar rodriguez on 12/8/16.
// Copyright © 2016 oscar rodriguez. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.319149 | 285 | 0.755627 |
bf67c5daee6adb0e4e77b49c7c7d3a536b537651 | 1,544 | // Copyright © 2020 Ralf Ebert
// Licensed under MIT license.
import SetDiffTools
import XCTest
struct GhostDescription: Identifiable {
var id = UUID()
var name: String
}
class Ghost {
var name: String
init(name: String) {
self.name = name
}
}
@available(iOS 13.0, macOS 10.15, *)
class ObjectDescriptorMappingTests: XCTestCase {
func testObjectDescriptorMapping() {
var ghosts = [Ghost]()
var ghostMapping = ObjectDescriptorMapping<UUID, GhostDescription, Ghost>(
handleAdd: { descriptor in
let p = Ghost(name: descriptor.name)
ghosts.append(p)
return p
},
handleRemove: { ghost in
ghosts.removeAll { $0 === ghost }
},
handleUpdate: { descriptor, ghost in
ghost.name = descriptor.name + "!"
}
)
var casperDescription = GhostDescription(name: "Casper")
ghostMapping.update([casperDescription])
XCTAssertEqual(["Casper!"], ghosts.map { $0.name })
let casper = ghosts[0]
// update
casperDescription.name = "Casper Cool"
ghostMapping.update([casperDescription])
XCTAssertEqual(["Casper Cool!"], ghosts.map { $0.name })
XCTAssertTrue(casper === ghosts[0])
// add & remove
ghostMapping.update([GhostDescription(name: "Slimer")])
XCTAssertEqual(["Slimer!"], ghosts.map { $0.name })
XCTAssertTrue(casper !== ghosts[0])
}
}
| 26.169492 | 82 | 0.579663 |
72aef7a01fdf9ea6c912a391e6024145c6651660 | 1,105 | //
// DoubleExtension.swift
// JSExtensions
//
// Created by jesse on 2017/10/18.
//
import Foundation
//MARK: - Math Properties
extension Double {
public var abs: Double {
return Swift.abs(self)
}
/// 向上取整
public var ceil: Double {
return Foundation.ceil(self)
}
/// 向下取整
public var floor: Double {
return Foundation.floor(self)
}
/// 四舍五入
public var round: Double {
return Foundation.round(self)
}
public var isPositive: Bool {
return self > 0
}
public var isNegative: Bool {
return self < 0
}
}
//MARK: - Methods
extension Double {
/// 返回小数点后几位
public func decimalPoint(_ point: Int) -> String {
return String(format: "%.\(point)f", self)
}
}
//MARK: - Change Number Type Properties
extension Double {
public var int: Int {
return Int(self)
}
public var float: Float {
return Float(self)
}
public var cgFloat: CGFloat {
return CGFloat(self)
}
public var string: String {
return String(self)
}
}
| 16.742424 | 54 | 0.576471 |
56e0afbcceee1fc29c9dca0f595a50147181dd53 | 159 | import Foundation
struct CrowdloanContributionResponse {
let accountId: AccountId
let index: FundIndex
let contribution: CrowdloanContribution?
}
| 19.875 | 44 | 0.786164 |
e272939552eb5ee8a04c16fab9f16af61e5f71d5 | 566 | // 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
var x1 =I Bool !(a)
}
func prefix(with: Strin) -> <T>(() -> T) in
// Disol g
func j(d: h) -> <k>(() -> k) -> h {
return { n n "\(}
c i< typealias k = a<j<n>, l>
}
| 33.294118 | 79 | 0.662544 |
f4699ef7029e5ee86dcb25c43f98479cb76265fd | 18,034 | //
// ChartData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class ChartData: NSObject
{
internal var _yMax: Double = -Double.greatestFiniteMagnitude
internal var _yMin: Double = Double.greatestFiniteMagnitude
internal var _xMax: Double = -Double.greatestFiniteMagnitude
internal var _xMin: Double = Double.greatestFiniteMagnitude
internal var _leftAxisMax: Double = -Double.greatestFiniteMagnitude
internal var _leftAxisMin: Double = Double.greatestFiniteMagnitude
internal var _rightAxisMax: Double = -Double.greatestFiniteMagnitude
internal var _rightAxisMin: Double = Double.greatestFiniteMagnitude
internal var _dataSets = [IChartDataSet]()
public override init()
{
super.init()
_dataSets = [IChartDataSet]()
}
@objc public init(dataSets: [IChartDataSet]?)
{
super.init()
_dataSets = dataSets ?? [IChartDataSet]()
self.initialize(dataSets: _dataSets)
}
@objc public convenience init(dataSet: IChartDataSet?)
{
self.init(dataSets: dataSet === nil ? nil : [dataSet!])
}
internal func initialize(dataSets: [IChartDataSet])
{
notifyDataChanged()
}
/// Call this method to let the ChartData know that the underlying data has changed.
/// Calling this performs all necessary recalculations needed when the contained data has changed.
@objc open func notifyDataChanged()
{
calcMinMax()
}
@objc open func calcMinMaxY(fromX: Double, toX: Double)
{
_dataSets.forEach { $0.calcMinMaxY(fromX: fromX, toX: toX) }
// apply the new data
calcMinMax()
}
/// calc minimum and maximum y value over all datasets
@objc open func calcMinMax()
{
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
_dataSets.forEach { calcMinMax(dataSet: $0) }
_leftAxisMax = -Double.greatestFiniteMagnitude
_leftAxisMin = Double.greatestFiniteMagnitude
_rightAxisMax = -Double.greatestFiniteMagnitude
_rightAxisMin = Double.greatestFiniteMagnitude
// left axis
let firstLeft = getFirstLeft(dataSets: dataSets)
if firstLeft !== nil
{
_leftAxisMax = firstLeft!.yMax
_leftAxisMin = firstLeft!.yMin
for dataSet in _dataSets
{
if dataSet.axisDependency == .left
{
if dataSet.yMin < _leftAxisMin
{
_leftAxisMin = dataSet.yMin
}
if dataSet.yMax > _leftAxisMax
{
_leftAxisMax = dataSet.yMax
}
}
}
}
// right axis
let firstRight = getFirstRight(dataSets: dataSets)
if firstRight !== nil
{
_rightAxisMax = firstRight!.yMax
_rightAxisMin = firstRight!.yMin
for dataSet in _dataSets
{
if dataSet.axisDependency == .right
{
if dataSet.yMin < _rightAxisMin
{
_rightAxisMin = dataSet.yMin
}
if dataSet.yMax > _rightAxisMax
{
_rightAxisMax = dataSet.yMax
}
}
}
}
}
/// Adjusts the current minimum and maximum values based on the provided Entry object.
@objc open func calcMinMax(entry e: ChartDataEntry, axis: YAxis.AxisDependency)
{
if _yMax < e.y
{
_yMax = e.y
}
if _yMin > e.y
{
_yMin = e.y
}
if _xMax < e.x
{
_xMax = e.x
}
if _xMin > e.x
{
_xMin = e.x
}
if axis == .left
{
if _leftAxisMax < e.y
{
_leftAxisMax = e.y
}
if _leftAxisMin > e.y
{
_leftAxisMin = e.y
}
}
else
{
if _rightAxisMax < e.y
{
_rightAxisMax = e.y
}
if _rightAxisMin > e.y
{
_rightAxisMin = e.y
}
}
}
/// Adjusts the minimum and maximum values based on the given DataSet.
@objc open func calcMinMax(dataSet d: IChartDataSet)
{
if _yMax < d.yMax
{
_yMax = d.yMax
}
if _yMin > d.yMin
{
_yMin = d.yMin
}
if _xMax < d.xMax
{
_xMax = d.xMax
}
if _xMin > d.xMin
{
_xMin = d.xMin
}
if d.axisDependency == .left
{
if _leftAxisMax < d.yMax
{
_leftAxisMax = d.yMax
}
if _leftAxisMin > d.yMin
{
_leftAxisMin = d.yMin
}
}
else
{
if _rightAxisMax < d.yMax
{
_rightAxisMax = d.yMax
}
if _rightAxisMin > d.yMin
{
_rightAxisMin = d.yMin
}
}
}
/// The number of LineDataSets this object contains
@objc open var dataSetCount: Int
{
return _dataSets.count
}
/// The smallest y-value the data object contains.
@objc open var yMin: Double
{
return _yMin
}
@nonobjc
open func getYMin() -> Double
{
return _yMin
}
@objc open func getYMin(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
if _leftAxisMin == Double.greatestFiniteMagnitude
{
return _rightAxisMin
}
else
{
return _leftAxisMin
}
}
else
{
if _rightAxisMin == Double.greatestFiniteMagnitude
{
return _leftAxisMin
}
else
{
return _rightAxisMin
}
}
}
/// The greatest y-value the data object contains.
@objc open var yMax: Double
{
return _yMax
}
@nonobjc
open func getYMax() -> Double
{
return _yMax
}
@objc open func getYMax(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
if _leftAxisMax == -Double.greatestFiniteMagnitude
{
return _rightAxisMax
}
else
{
return _leftAxisMax
}
}
else
{
if _rightAxisMax == -Double.greatestFiniteMagnitude
{
return _leftAxisMax
}
else
{
return _rightAxisMax
}
}
}
/// The minimum x-value the data object contains.
@objc open var xMin: Double
{
return _xMin
}
/// The maximum x-value the data object contains.
@objc open var xMax: Double
{
return _xMax
}
/// All DataSet objects this ChartData object holds.
@objc open var dataSets: [IChartDataSet]
{
get
{
return _dataSets
}
set
{
_dataSets = newValue
notifyDataChanged()
}
}
/// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not.
///
/// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.**
///
/// - Parameters:
/// - dataSets: the DataSet array to search
/// - type:
/// - ignorecase: if true, the search is not case-sensitive
/// - Returns: The index of the DataSet Object with the given label. Sensitive or not.
internal func getDataSetIndexByLabel(_ label: String, ignorecase: Bool) -> Int
{
// TODO: Return nil instead of -1
if ignorecase
{
return dataSets.firstIndex { $0.label?.caseInsensitiveCompare(label) == .orderedSame }
?? -1
}
else
{
return dataSets.firstIndex { $0.label == label }
?? -1
}
}
/// Get the Entry for a corresponding highlight object
///
/// - Parameters:
/// - highlight:
/// - Returns: The entry that is highlighted
@objc open func entryForHighlight(_ highlight: Highlight) -> ChartDataEntry?
{
if highlight.dataSetIndex >= dataSets.count
{
return nil
}
else
{
return dataSets[highlight.dataSetIndex].entryForXValue(highlight.x, closestToY: highlight.y)
}
}
/// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.**
///
/// - Parameters:
/// - label:
/// - ignorecase:
/// - Returns: The DataSet Object with the given label. Sensitive or not.
@objc open func getDataSetByLabel(_ label: String, ignorecase: Bool) -> IChartDataSet?
{
let index = getDataSetIndexByLabel(label, ignorecase: ignorecase)
if index < 0 || index >= _dataSets.count
{
return nil
}
else
{
return _dataSets[index]
}
}
@objc open func getDataSetByIndex(_ index: Int) -> IChartDataSet!
{
if index < 0 || index >= _dataSets.count
{
return nil
}
return _dataSets[index]
}
@objc open func addDataSet(_ dataSet: IChartDataSet!)
{
calcMinMax(dataSet: dataSet)
_dataSets.append(dataSet)
}
/// Removes the given DataSet from this data object.
/// Also recalculates all minimum and maximum values.
///
/// - Returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed.
@objc @discardableResult open func removeDataSet(_ dataSet: IChartDataSet) -> Bool
{
guard let i = _dataSets.firstIndex(where: { $0 === dataSet }) else { return false }
return removeDataSetByIndex(i)
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - Returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed.
@objc @discardableResult open func removeDataSetByIndex(_ index: Int) -> Bool
{
if index >= _dataSets.count || index < 0
{
return false
}
_dataSets.remove(at: index)
calcMinMax()
return true
}
/// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list.
@objc open func addEntry(_ e: ChartDataEntry, dataSetIndex: Int)
{
if _dataSets.count > dataSetIndex && dataSetIndex >= 0
{
let set = _dataSets[dataSetIndex]
if !set.addEntry(e) { return }
calcMinMax(entry: e, axis: set.axisDependency)
}
else
{
print("ChartData.addEntry() - Cannot add Entry because dataSetIndex too high or too low.", terminator: "\n")
}
}
/// Removes the given Entry object from the DataSet at the specified index.
@objc @discardableResult open func removeEntry(_ entry: ChartDataEntry, dataSetIndex: Int) -> Bool
{
// entry outofbounds
if dataSetIndex >= _dataSets.count
{
return false
}
// remove the entry from the dataset
let removed = _dataSets[dataSetIndex].removeEntry(entry)
if removed
{
calcMinMax()
}
return removed
}
/// Removes the Entry object closest to the given xIndex from the ChartDataSet at the
/// specified index.
///
/// - Returns: `true` if an entry was removed, `false` ifno Entry was found that meets the specified requirements.
@objc @discardableResult open func removeEntry(xValue: Double, dataSetIndex: Int) -> Bool
{
if dataSetIndex >= _dataSets.count
{
return false
}
if let entry = _dataSets[dataSetIndex].entryForXValue(xValue, closestToY: Double.nan)
{
return removeEntry(entry, dataSetIndex: dataSetIndex)
}
return false
}
/// - Returns: The DataSet that contains the provided Entry, or null, if no DataSet contains this entry.
@objc open func getDataSetForEntry(_ e: ChartDataEntry) -> IChartDataSet?
{
return _dataSets.first { $0.entryForXValue(e.x, closestToY: e.y) === e }
}
/// - Returns: The index of the provided DataSet in the DataSet array of this data object, or -1 if it does not exist.
@objc open func indexOfDataSet(_ dataSet: IChartDataSet) -> Int
{
// TODO: Return nil instead of -1
return _dataSets.firstIndex { $0 === dataSet } ?? -1
}
/// - Returns: The first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found.
@objc open func getFirstLeft(dataSets: [IChartDataSet]) -> IChartDataSet?
{
return dataSets.first { $0.axisDependency == .left }
}
/// - Returns: The first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found.
@objc open func getFirstRight(dataSets: [IChartDataSet]) -> IChartDataSet?
{
return dataSets.first { $0.axisDependency == .right }
}
/// - Returns: All colors used across all DataSet objects this object represents.
@objc open func getColors() -> [NSUIColor]?
{
// TODO: Don't return nil
return _dataSets.flatMap { $0.colors }
}
/// Sets a custom IValueFormatter for all DataSets this data object contains.
@objc open func setValueFormatter(_ formatter: IValueFormatter)
{
dataSets.forEach { $0.valueFormatter = formatter }
}
/// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains.
@objc open func setValueTextColor(_ color: NSUIColor)
{
dataSets.forEach { $0.valueTextColor = color }
}
/// Sets the font for all value-labels for all DataSets this data object contains.
@objc open func setValueFont(_ font: NSUIFont)
{
dataSets.forEach { $0.valueFont = font }
}
/// Enables / disables drawing values (value-text) for all DataSets this data object contains.
@objc open func setDrawValues(_ enabled: Bool)
{
dataSets.forEach { $0.drawValuesEnabled = enabled }
}
/// Enables / disables highlighting values for all DataSets this data object contains.
/// If set to true, this means that values can be highlighted programmatically or by touch gesture.
@objc open var highlightEnabled: Bool
{
get { return dataSets.allSatisfy { $0.highlightEnabled } }
set { dataSets.forEach { $0.highlightEnabled = newValue } }
}
/// if true, value highlightning is enabled
@objc open var isHighlightEnabled: Bool { return highlightEnabled }
/// Clears this data object from all DataSets and removes all Entries.
/// Don't forget to invalidate the chart after this.
@objc open func clearValues()
{
dataSets.removeAll(keepingCapacity: false)
notifyDataChanged()
}
/// Checks if this data object contains the specified DataSet.
///
/// - Returns: `true` if so, `false` ifnot.
@objc open func contains(dataSet: IChartDataSet) -> Bool
{
return dataSets.contains { $0 === dataSet }
}
/// The total entry count across all DataSet objects this data object contains.
@objc open var entryCount: Int
{
return _dataSets.reduce(0) { $0 + $1.entryCount }
}
/// The DataSet object with the maximum number of entries or null if there are no DataSets.
@objc open var maxEntryCountSet: IChartDataSet?
{
return dataSets.max { $0.entryCount < $1.entryCount }
}
// MARK: - Accessibility
/// When the data entry labels are generated identifiers, set this property to prepend a string before each identifier
///
/// For example, if a label is "#3", settings this property to "Item" allows it to be spoken as "Item #3"
@objc open var accessibilityEntryLabelPrefix: String?
/// When the data entry value requires a unit, use this property to append the string representation of the unit to the value
///
/// For example, if a value is "44.1", setting this property to "m" allows it to be spoken as "44.1 m"
@objc open var accessibilityEntryLabelSuffix: String?
/// If the data entry value is a count, set this to true to allow plurals and other grammatical changes
/// **default**: false
@objc open var accessibilityEntryLabelSuffixIsCount: Bool = false
}
| 29.515548 | 169 | 0.556449 |
71b44c9f8a521c9a214fe77a32aff655d619f2df | 2,459 | //
// Zap
//
// Created by Otto Suess on 28.01.18.
// Copyright © 2018 Otto Suess. All rights reserved.
//
import Bond
import Foundation
import Lightning
import ReactiveKit
import SwiftBTC
import SwiftLnd
extension ChannelState: Comparable {
var sortRank: Int {
switch self {
case .active:
return 0
case .opening:
return 1
case .forceClosing:
return 2
case .closing:
return 3
case .inactive:
return 4
}
}
public static func < (lhs: ChannelState, rhs: ChannelState) -> Bool {
return lhs.sortRank < rhs.sortRank
}
}
final class ChannelListViewModel: NSObject {
private let channelService: ChannelService
let dataSource: MutableObservableArray<ChannelViewModel>
let searchString = Observable<String?>(nil)
var maxChannelCapacity: Satoshi = 1
init(channelService: ChannelService) {
self.channelService = channelService
dataSource = MutableObservableArray()
super.init()
combineLatest(channelService.open, channelService.pending, searchString)
.observeOn(DispatchQueue.main)
.observeNext { [weak self] in
self?.updateChannels(open: $0, pending: $1, searchString: $2)
}
.dispose(in: reactive.bag)
}
private func updateChannels(open: [Channel], pending: [Channel], searchString: String?) {
let viewModels = (open + pending)
.map { ChannelViewModel(channel: $0, channelService: channelService) }
.filter { $0.matchesSearchString(searchString) }
let sortedViewModels = viewModels.sorted {
if $0.channel.state != $1.channel.state {
return $0.channel.state < $1.channel.state
} else {
return $0.channel.remotePubKey < $1.channel.remotePubKey
}
}
maxChannelCapacity = viewModels
.max(by: { $0.channel.capacity < $1.channel.capacity })?
.channel.capacity ?? 1
dataSource.replace(with: sortedViewModels, performDiff: true)
}
func refresh() {
channelService.update()
}
func close(_ channel: Channel, completion: @escaping (SwiftLnd.Result<CloseStatusUpdate>) -> Void) {
channelService.close(channel, completion: completion)
}
}
| 28.593023 | 104 | 0.597397 |
5b10f8613c1c514c6cb484d91fcd953d18dcd15c | 3,809 | //
// main.swift
// OperatorsAndStrings
//
// Created by Ankush Bhatia on 25/06/21.
//
import Foundation
// =================================
// Operators
// An operator is a special symbol or phrase that you use to check, change, or combine values.
// +, -, *, /, =
// Operator Types
// - Unary Operators: Applied on single target
// - Unary Prefix: Applies immediately before target like -a
// - Unary Postfix: Applies immediately after target like a-
// - Binary Operators: Operate on 2 targets eg: 2 + 3. They are also called as infix operator
// - Ternary Operators: Operate on 3 targets. Swift has only one operator. i.e. ternary operator (a ? b : c)
// Operand: Value that operators effect are operands. e.g.: 1 + 2, 1&2 are operands and + is operator
// 1. Assignment Operator
//let a = 12
//var b = 3
//print(b)
//b = a
//print(b)
//let (firstValue, secondValue) = (11, 22)
//print(firstValue)
//print(secondValue)
// 2. Arithmetic Operators
// Addition (+)
//let value = 1 + 2
//print(value)
// Subtraction (-)
//let value = 2 - 1
//print(value)
// Multiplication (*)
//let value = 1 * 2
//print(value)
// Division (/)
//let value = 10 / 2
//print(value)
// Remainder Operator (Modulo Operator)
//let value = 4 % 3
//print(value)
// 3. Unary Minus Operator
//let value = -2
//print(value)
// 4. Unary Plus Operator
//let value = +2
//print(value)
// 5. Compound Assignment Operator
//var value = 4
//value += 1
//print(value)
//var value = 4
//value -= 1
//print(value)
// 6. Comparison Operator
// Example of ==
//let first = 2
//let second = 3
//print(first == second)
// Example of !=
//let first = 2
//let second = 3
//print(first != second)
// Example of >
//let first = 2
//let second = 3
//print(first > second)
// Example of <
//let first = 2
//let second = 3
//print(first < second)
// Example of >=
//let first = 2
//let second = 2
//print(first >= second)
// Example of <=
//let first = 2
//let second = 3
//print(first <= second)
// Example of ===
//class A {}
//var ob1 = A()
//let ob2 = ob1
//print(ob1 === ob2)
// Example of !==
//class A {}
//class B {}
//var ob1 = A()
//let ob2 = B()
//print(ob1 !== ob2)
// 7. Ternary Conditional Operator
//var value: String?
//let result = value == nil ? 0 : 1
//print(result)
// 8. Nil Coalescing Operator
//var value: String? = "False"
//let result = value ?? "True"
//print(result)
// 9. Range Operator
// Example of Closed Range Operator
//for index in 0...2 {
// print(index)
//}
// Example of Half Open Range
//for index in 0..<2 {
// print(index)
//}
// Example of One Sided Range
//var values: [Int] = [0, 1, 2, 3, 4]
//for value in values[2...] {
// print(value)
//}
// 10. Logical Operators
// Example of Logical NOT
//var value = true
//if !value {
// print(value)
//} else {
// print("Nothing to print")
//}
// Example of Logical AND
//let first = true
//let second = true
//if first && second {
// print(true)
//} else {
// print("Nothing to print")
//}
// Example of Logical OR
//let first = false
//let second = false
//if first || second {
// print(true)
//} else {
// print("Nothing to print")
//}
// =================================
// Strings - Series of characters
//
//let value = "Hi! My name is Ankush."
//print(value)
// Multiline
//let result = """
// Hi! My name
// is Ankush Bhatia.
// """
//print(result)
// Initialising empty sting
//
//var emptyString = "Hi"
//if emptyString.isEmpty {
// print("String is empty.")
//} else {
// print("Nothing to print")
//}
// String Mutability
//var result = "Hi "
//result += "Ankush!"
//print(result)
// Concatenation
//var result = "Hi "
//print(result + "Ankush")
// String Interpolation
//let apples = 4
//var result = "I have \(apples) apples."
//print(result)
| 17.966981 | 111 | 0.598057 |
1c3aeabdd8c1539c1282afd415581ab254561717 | 1,438 | /*
Copyright (c) 2016 Andrey Ilskiy.
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 Foundation
class FoundationTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 31.26087 | 111 | 0.670376 |
bf9c70ea3ca043bd80d2f4b21757ab0909bd8ff3 | 602 | /**
* Plot
* Copyright (c) John Sundell 2021
* MIT license, see LICENSE file for details
*/
import Foundation
/// Enum defining how a given element should be closed.
public enum ElementClosingMode {
/// The standard (default) closing mode, which creates a pair of opening
/// and closing tags, for example `<html></html>`.
case standard
/// For elements that are never closed, for example the leading declaration
/// tags found at the top of XML documents.
case neverClosed
/// For elements that close themselves, for example `<img src="..."/>`.
case selfClosing
}
| 30.1 | 79 | 0.689369 |
91ad0510e73ed389617030848265d513c0823f93 | 87 | /*:
# Type Casting
* Type Check
* Type Casting
by Giftbot
*/
//: [Next](@next)
| 8.7 | 17 | 0.551724 |
69ca7fea1ac0c47efa348663214fc09f5f8d83e8 | 578 | //
// CookieStorageService.swift
// AuthorizeMeDemo
//
// Created by Radislav Crechet on 6/1/17.
// Copyright © 2017 RubyGarage. All rights reserved.
//
import Foundation
struct CookieStorageService {
static func deleteCookies(withDomainLike substring: String) {
guard let cookies = HTTPCookieStorage.shared.cookies else {
return
}
cookies.forEach { cookie in
if cookie.domain.range(of: substring) != nil {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
}
}
| 22.230769 | 67 | 0.614187 |
0a42d97534ec17674eb53d69b185ab26f977dbef | 2,100 | //
// TrendArrowCalculations.swift
// MiaomiaoClientUI
//
// Created by Bjørn Inge Berg on 26/03/2019.
// Copyright © 2019 Mark Wilson. All rights reserved.
//
import Foundation
import LoopKit
//https://github.com/dabear/FloatingGlucose/blob/master/FloatingGlucose/Classes/Utils/GlucoseMath.cs
class TrendArrowCalculation {
static func calculateSlope(current: LibreGlucose, last: LibreGlucose) -> Double
{
if current.timestamp == last.timestamp {
return 0.0
}
let _curr = Double(current.timestamp.timeIntervalSince1970 * 1000)
let _last = Double(last.timestamp.timeIntervalSince1970 * 1000)
return (Double(last.unsmoothedGlucose) - Double(current.unsmoothedGlucose)) / (_last - _curr)
}
static func calculateSlopeByMinute(current: LibreGlucose, last: LibreGlucose) -> Double
{
return calculateSlope(current: current, last: last) * 60000;
}
static func GetGlucoseDirection(current: LibreGlucose?, last: LibreGlucose?) -> GlucoseTrend {
NSLog("GetGlucoseDirection:: current:\(current), last: \(last)")
guard let current = current, let last = last else {
return GlucoseTrend.flat
}
let s = calculateSlopeByMinute(current: current, last: last)
NSLog("Got trendarrow value of \(s))")
switch s {
case _ where s <= (-3.5):
return GlucoseTrend.downDownDown
case _ where s <= (-2):
return GlucoseTrend.downDown
case _ where s <= (-1):
return GlucoseTrend.down
case _ where s <= (1):
return GlucoseTrend.flat
case _ where s <= (2):
return GlucoseTrend.up
case _ where s <= (3.5):
return GlucoseTrend.upUp
case _ where s <= (40):
return GlucoseTrend.flat //flat is the new (tm) "unknown"!
default:
NSLog("Got unknown trendarrow value of \(s))")
return GlucoseTrend.flat
}
}
}
| 31.343284 | 101 | 0.597619 |
ed9bc1bdcc8e617cf111a3eab6a1f383f147ca94 | 3,054 | //
// PDFTableMergeUtil_Spec.swift
// TPPDF_Tests
//
// Created by Philip Niedertscheider on 22.12.19.
// Copyright © 2019 techprimate GmbH & Co. KG. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import TPPDF
class PDFTableMergeUtilSpec: QuickSpec {
override func spec() {
describe("PDFTableMergeUtil") {
let ROWS = 10
let COLS = 10
var table = PDFTable()
beforeEach {
table = PDFTable(rows: ROWS, columns: COLS)
for row in 0..<ROWS {
for column in 0..<COLS {
table[row, column].content = "\(row),\(column)".asTableContent
}
}
}
context("no merging") {
it("should return a node for each cell") {
let result = PDFTableMergeUtil.calculateMerged(table: table)
expect(result).to(haveCount(ROWS))
for i in 0..<ROWS {
expect(result[i]).to(haveCount(COLS))
}
for row in 0..<ROWS {
for col in 0..<COLS {
let node = result[row][col]
expect(node.cell) === table.cells[row][col]
expect(node.moreRowsSpan) == 0
expect(node.moreColumnsSpan) == 0
}
}
}
}
context("with merging") {
it("should return a node with merged row span") {
for row in 0..<ROWS {
table[row: row].merge()
}
let result = PDFTableMergeUtil.calculateMerged(table: table)
expect(result).to(haveCount(ROWS))
for i in 0..<ROWS {
expect(result[i]).to(haveCount(1))
}
for row in 0..<ROWS {
let node = result[row][0]
expect(node.cell) === table.cells[row][0]
expect(node.moreRowsSpan) == 0
expect(node.moreColumnsSpan) == COLS - 1
}
}
it("should return a node with merged row span") {
for index in 0..<COLS {
table[column: index].merge()
}
let result = PDFTableMergeUtil.calculateMerged(table: table)
expect(result).to(haveCount(1))
for col in 0..<COLS {
expect(result[0]).to(haveCount(COLS))
let node = result[0][col]
expect(node.cell) === table.cells[0][col]
expect(node.moreRowsSpan) == ROWS - 1
expect(node.moreColumnsSpan) == 0
}
}
}
}
}
}
| 34.314607 | 86 | 0.422069 |
6ac7a1f8134c81f64b26e88cdc21abac56b0fa2b | 1,495 | //
// CKDataModel.swift
// Crypto Keyboard
//
// Created by zj on 2021/2/9.
// Copyright © 2021 Onekey. All rights reserved.
//
import Foundation
import SwiftUI
struct CKModel {
var pasteboardItems: [String]
init() {
pasteboardItems = CKModel.readFromKeychain()
}
mutating func add(item: String) {
pasteboardItems.insert(item, at: 0)
if pasteboardItems.count > 10 {
_ = pasteboardItems.popLast()
}
save()
}
mutating func remove(at index: Int) {
pasteboardItems.remove(at: index)
save()
}
func save() {
CKModel.writeTokeychain(pasteboardItems)
}
static func readFromKeychain() -> [String] {
if let retrievedData = KeychainWrapper.standard.data(forKey: "CKPasteboardItems") {
do {
if let decodedArray = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(retrievedData) as? [String] {
return decodedArray
}
} catch {
print("Couldn't read file.")
}
}
return []
}
static func writeTokeychain(_ items: [String]) {
do {
let encodedData = try NSKeyedArchiver.archivedData(withRootObject: items, requiringSecureCoding: true)
_ = KeychainWrapper.standard.set(encodedData, forKey: "CKPasteboardItems")
} catch {
print("Couldn't encoded data.")
}
}
}
| 25.338983 | 121 | 0.573913 |
d9b32dabd05b49ab182e1fc4f97b5bce4bfa69ba | 6,703 | //
// InputTextFieldView.swift
// ShopApp
//
// Created by Evgeniy Antonov on 12/8/17.
// Copyright © 2017 Evgeniy Antonov. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
enum InputTextFieldViewState: Int {
case normal
case highlighted
case error
}
enum InputTextFieldViewKeybordType: Int {
case email // 0
case password // 1
case name // 2
case phone // 3
case zip // 4
case `default` // 5
case cardNumber // 6
case cvv // 7
}
@objc protocol InputTextFieldViewDelegate: class {
@objc optional func textFieldView(_ view: InputTextFieldView, didEndUpdate text: String)
@objc optional func textFieldView(_ view: InputTextFieldView, didUpdate text: String)
}
class InputTextFieldView: PlaceholderedTextField, UITextFieldDelegate {
@IBOutlet private weak var underlineView: UIView!
@IBOutlet private weak var underlineViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var errorMessageLabel: UILabel!
@IBOutlet private weak var showPasswordButton: UIButton!
@IBInspectable var keyboardType: Int = InputTextFieldViewKeybordType.name.rawValue {
didSet {
setupKeyboardType(with: keyboardType)
setupKeyboardSecureTextEntry(with: keyboardType)
setupKeyboardCapitalization(with: keyboardType)
}
}
@IBInspectable var hideShowPasswordButton: Bool = true {
didSet {
setupKeyboardSecureTextEntry(with: keyboardType)
}
}
private let underlineViewAlphaDefault: CGFloat = 0.2
private let underlineViewAlphaHighlighted: CGFloat = 1
private let underlineViewHeightDefault: CGFloat = 1
private let underlineViewHeightHighlighted: CGFloat = 2
private let errorColor = UIColor(displayP3Red: 0.89, green: 0.31, blue: 0.31, alpha: 1)
weak var delegate: InputTextFieldViewDelegate?
override var text: String? {
didSet {
setPlaceholderPosition()
}
}
var state: InputTextFieldViewState = .normal {
didSet {
updateUI()
}
}
var errorMessage: String? {
didSet {
state = .error
errorMessageLabel.text = errorMessage
updateUI()
}
}
// MARK: - View lifecycle
init() {
super.init(frame: CGRect.zero)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - Setup
private func commonInit() {
loadFromNib()
textField?.delegate = self
setupViews()
updateUI()
}
private func setupViews() {
backgroundColor = UIColor.clear
errorMessageLabel.textColor = errorColor
}
private func updateUI() {
underlineView.alpha = state == .normal ? underlineViewAlphaDefault : underlineViewAlphaHighlighted
underlineViewHeightConstraint.constant = state == .normal ? underlineViewHeightDefault : underlineViewHeightHighlighted
underlineView.backgroundColor = state == .error ? errorColor : UIColor.black
errorMessageLabel.isHidden = state != .error
}
private func setupKeyboardType(with type: Int) {
let type: UIKeyboardType
switch keyboardType {
case InputTextFieldViewKeybordType.email.rawValue:
type = .emailAddress
case InputTextFieldViewKeybordType.phone.rawValue:
type = .phonePad
case InputTextFieldViewKeybordType.cardNumber.rawValue, InputTextFieldViewKeybordType.cvv.rawValue:
type = .numberPad
default:
type = .default
}
textField?.keyboardType = type
}
private func setupKeyboardCapitalization(with type: Int) {
switch type {
case InputTextFieldViewKeybordType.name.rawValue:
textField?.autocapitalizationType = .words
case InputTextFieldViewKeybordType.email.rawValue:
textField?.autocapitalizationType = .none
default:
textField?.autocapitalizationType = .sentences
}
}
private func setupKeyboardSecureTextEntry(with type: Int) {
let secureTextEntry = type == InputTextFieldViewKeybordType.password.rawValue || type == InputTextFieldViewKeybordType.cvv.rawValue
textField?.isSecureTextEntry = secureTextEntry
showPasswordButton?.isHidden = type != InputTextFieldViewKeybordType.password.rawValue || hideShowPasswordButton == true
}
// MARK: - Actions
@IBAction func editingDidBegin(_ sender: UITextField) {
state = .highlighted
if placeholderVerticallyConstraint.constant == 0 {
updatePlaceholderPosition(toTop: true, animated: true)
}
}
@IBAction func editingDidEnd(_ sender: UITextField) {
state = .normal
guard let text = textField.text else {
return
}
delegate?.textFieldView?(self, didEndUpdate: text)
if text.isEmpty {
updatePlaceholderPosition(toTop: false, animated: true)
}
}
@IBAction func editingChanged(_ sender: UITextField) {
if state != .highlighted {
state = .highlighted
}
if keyboardType == InputTextFieldViewKeybordType.cardNumber.rawValue {
textField.text = textField.text?.asCardMaskNumber()
}
guard let text = textField.text else {
return
}
delegate?.textFieldView?(self, didUpdate: text)
}
@IBAction func showPasswordTapped(_ sender: UIButton) {
showPasswordButton.isSelected = !showPasswordButton.isSelected
textField?.isSecureTextEntry = !showPasswordButton.isSelected
}
// MARK: - UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let generatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) else {
return true
}
switch keyboardType {
case InputTextFieldViewKeybordType.cardNumber.rawValue:
return generatedString.asCardDefaultNumber().count <= CreditCardLimit.cardNumberMaxCount
case InputTextFieldViewKeybordType.cvv.rawValue:
return generatedString.count <= CreditCardLimit.cvvMaxCount
default:
return true
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
endEditing(true)
return true
}
}
| 32.07177 | 139 | 0.649858 |
1d4a62d0af1ae5c7dd5c37872e45d39723eeb089 | 705 | //
// Copyright (c) Vatsal Manot
//
import Swift
import SwiftUI
/// A modifier that controls a view's visibility.
public struct _VisibilityModifier: ViewModifier {
@usableFromInline
let isVisible: Bool
@usableFromInline
init(isVisible: Bool) {
self.isVisible = isVisible
}
@inlinable
public func body(content: Content) -> some View {
content.opacity(isVisible ? 1 : 0)
}
}
// MARK: - Helpers -
extension View {
/// Sets a view's visibility.
///
/// The view still retains its frame.
@inlinable
public func visible(_ isVisible: Bool = true) -> some View {
modifier(_VisibilityModifier(isVisible: isVisible))
}
}
| 20.142857 | 64 | 0.638298 |
2f767ddf3f7c72f6fd98267b1312bf51b8d3e229 | 6,413 | import Foundation
public typealias Closure = (Double) -> Void
enum UntarError: Error, LocalizedError {
case notFound(file: String)
case corruptFile(type: UnicodeScalar)
public var errorDescription: String? {
switch self {
case let .notFound(file: file): return "Source file \(file) not found"
case let .corruptFile(type: type): return "Invalid block type \(type) found"
}
}
}
public extension FileManager {
// MARK: - Definitions
private static var tarBlockSize: UInt64 = 512
private static var tarTypePosition: UInt64 = 156
private static var tarNamePosition: UInt64 = 0
private static var tarNameSize: UInt64 = 100
private static var tarSizePosition: UInt64 = 124
private static var tarSizeSize: UInt64 = 12
private static var tarMaxBlockLoadInMemory: UInt64 = 100
// MARK: - Private Methods
private func createFilesAndDirectories(path: String, tarObject: Any, size: UInt64,
progress progressClosure: Closure?) throws -> Bool {
try createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
var location: UInt64 = 0
while location < size {
var blockCount: UInt64 = 1
if let closure = progressClosure { closure(Double(location) / Double(size)) }
let type = self.type(object: tarObject, offset: location)
switch type {
case "0": // File
let name = self.name(object: tarObject, offset: location)
let filePath = path + name
let size = self.size(object: tarObject, offset: location)
if size == 0 { try "".write(toFile: filePath, atomically: true, encoding: .utf8) }
else {
blockCount += (size - 1) / FileManager.tarBlockSize + 1 // size / tarBlockSize rounded up
writeFileData(object: tarObject, location: location + FileManager.tarBlockSize,
length: size, path: filePath)
}
case "5": // Directory
let name = self.name(object: tarObject, offset: location)
let directoryPath = path + name
try createDirectory(atPath: directoryPath, withIntermediateDirectories: true,
attributes: nil)
case "\0": break // Null block
case "x": blockCount += 1 // Extra header block
case "1": fallthrough
case "2": fallthrough
case "3": fallthrough
case "4": fallthrough
case "6": fallthrough
case "7": fallthrough
case "g": // Not a file nor directory
let size = self.size(object: tarObject, offset: location)
blockCount += UInt64(ceil(Double(size) / Double(FileManager.tarBlockSize)))
default: throw UntarError.corruptFile(type: type) // Not a tar type
}
location += blockCount * FileManager.tarBlockSize
}
return true
}
private func type(object: Any, offset: UInt64) -> UnicodeScalar {
let typeData = data(object: object, location: offset + FileManager.tarTypePosition, length: 1)!
return UnicodeScalar([UInt8](typeData)[0])
}
private func name(object: Any, offset: UInt64) -> String {
let nameData = data(object: object, location: offset + FileManager.tarNamePosition,
length: FileManager.tarNameSize)!
let nameBytes = [UInt8](nameData)
return String(bytes: nameBytes, encoding: .ascii)!
}
private func size(object: Any, offset: UInt64) -> UInt64 {
let sizeData = data(object: object, location: offset + FileManager.tarSizePosition,
length: FileManager.tarSizeSize)!
let sizeString = String(bytes: [UInt8](sizeData), encoding: .ascii)!
return UInt64(sizeString, radix: 8)! // Size is an octal number, convert to decimal
}
private func writeFileData(object: Any, location _loc: UInt64, length _len: UInt64,
path: String) {
if let data = object as? Data {
createFile(atPath: path, contents: data.subdata(in: Int(_loc) ..< Int(_loc + _len)),
attributes: nil)
} else if let fileHandle = object as? FileHandle {
if NSData().write(toFile: path, atomically: false) {
let destinationFile = FileHandle(forWritingAtPath: path)!
fileHandle.seek(toFileOffset: _loc)
let maxSize = FileManager.tarMaxBlockLoadInMemory * FileManager.tarBlockSize
var length = _len, location = _loc
while length > maxSize {
destinationFile.write(fileHandle.readData(ofLength: Int(maxSize)))
location += maxSize
length -= maxSize
}
destinationFile.write(fileHandle.readData(ofLength: Int(length)))
destinationFile.closeFile()
}
}
}
private func data(object: Any, location: UInt64, length: UInt64) -> Data? {
if let data = object as? Data {
return data.subdata(in: Int(location) ..< Int(location + length))
} else if let fileHandle = object as? FileHandle {
fileHandle.seek(toFileOffset: location)
return fileHandle.readData(ofLength: Int(length))
}
return nil
}
// MARK: - Public Methods
// Return true when no error for convenience
@discardableResult func createFilesAndDirectories(path: String, tarData: Data,
progress: Closure? = nil) throws -> Bool {
try createFilesAndDirectories(path: path, tarObject: tarData, size: UInt64(tarData.count),
progress: progress)
}
@discardableResult func createFilesAndDirectories(url: URL, tarData: Data,
progress: Closure? = nil) throws -> Bool {
try createFilesAndDirectories(path: url.path, tarData: tarData, progress: progress)
}
@discardableResult func createFilesAndDirectories(path: String, tarPath: String,
progress: Closure? = nil) throws -> Bool {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: tarPath) {
let attributes = try fileManager.attributesOfItem(atPath: tarPath)
let size = attributes[.size] as! UInt64
let fileHandle = FileHandle(forReadingAtPath: tarPath)!
let result = try createFilesAndDirectories(path: path, tarObject: fileHandle, size: size,
progress: progress)
fileHandle.closeFile()
return result
}
throw UntarError.notFound(file: tarPath)
}
}
| 42.753333 | 99 | 0.643225 |
1830fedebf6432136163ea884a3ced92cb815873 | 2,108 | //
// Assert.swift
// LemmyAppTests
//
// Created by Avery Pierce on 10/14/20.
//
import XCTest
@testable import Cavy
func assertDecodes<D: DataProvider, T: Codable>(_ dataPackage: Spec<D, T>, printData: Bool = false, file: StaticString = #filePath, line: UInt = #line, completion: @escaping () -> Void) {
assertDecodes(to: dataPackage.type, fromDataProvidedBy: dataPackage.dataProvider, printData: printData, completion: completion)
}
func assertDecodes<T: Decodable>(to Type: T.Type, fromDataProvidedBy dataProvider: DataProvider, printData: Bool = false, file: StaticString = #filePath, line: UInt = #line, completion: @escaping () -> Void) {
dataProvider.getData { (result) in
let data = assertSuccess(result, file: file, line: line)
if let data = data, !data.isEmpty, printData {
print(try! prettyJSON(data))
}
assertDecodes(to: Type, from: data, file: file, line: line)
completion()
}
}
func assertDecodes<T: Decodable>(to Type: T.Type, from data: Data?, file: StaticString = #filePath, line: UInt = #line) {
XCTAssertNotNil(data, "data was nil", file: file, line: line)
XCTAssertFalse(data!.isEmpty, "data was empty", file: file, line: line)
do {
let _ = try JSONDecoder().decode(Type.self, from: data!)
} catch let error {
print(error)
print(try? prettyJSON(data!) ?? "(cannot pretty print json)")
XCTFail(error.localizedDescription, file: file, line: line)
}
}
func prettyJSON(_ data: Data) throws -> String {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
let prettyData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
return String(data: prettyData, encoding: .utf8)!
}
@discardableResult func assertSuccess<T, E: Error>(_ result: Result<T, E>, file: StaticString = #filePath, line: UInt = #line) -> T! {
switch result {
case .success(let value): return value
case .failure(let error):
XCTFail(error.localizedDescription, file: file, line: line)
return nil
}
}
| 39.773585 | 209 | 0.67315 |
e9798bdb415cb040c7ede30a233c1bfe764309fd | 1,021 | public struct StateDefinition: Equatable {
public let name: Substring
public let type: Substring
public let value: Substring // Need to be more specific type
}
extension Parser {
struct StateNameIdentifierExpected: Error {}
struct ColonExpected: Error {}
struct StateTypeIdentifierExpected: Error {}
struct EqualsExpected: Error {}
struct StateDefaultValueExpected: Error {}
mutating func parseStateDefinition() throws -> StateDefinition? {
guard parseKeyword(.state) else { return nil }
guard let name = parseIdentifier() else { throw StateNameIdentifierExpected() }
guard parseKeyword(.colon) else { throw ColonExpected() }
guard let type = parseIdentifier() else { throw StateTypeIdentifierExpected() }
guard parseKeyword(.equals) else { throw EqualsExpected() }
guard let value = parseIdentifier() else { throw StateDefaultValueExpected() }
return StateDefinition(name: name, type: type, value: value)
}
}
| 40.84 | 87 | 0.701273 |
9143acf2b888e7f60514d37dc5b7233b8e628545 | 2,707 | import SwiftUI
internal final class GalleryStore: ScenarioSearchStore {
enum Status {
case standby
case ready
}
var selectedScenario: SearchedData? {
willSet { objectWillChange.send() }
}
var status = Status.standby {
willSet { objectWillChange.send() }
}
var shareItem: ImageSharingView.Item? {
willSet { objectWillChange.send() }
}
let preSnapshotCountLimit: Int
let snapshotLoader: SnapshotLoaderProtocol
func prepare() {
switch status {
case .ready:
break
case .standby:
takeSnapshots()
start()
status = .ready
}
}
@discardableResult
func takeSnapshots() -> Self {
snapshotLoader.clean()
playbook.stores.lazy
.flatMap { store in
store.scenarios.map { scenario in
(kind: store.kind, scenario: scenario)
}
}
.prefix(preSnapshotCountLimit)
.forEach { snapshotLoader.takeSnapshot(for: $0.scenario, kind: $0.kind, completion: nil) }
return self
}
init(
playbook: Playbook,
preSnapshotCountLimit: Int,
selectedScenario: SearchedData? = nil,
status: Status = .standby,
shareItem: ImageSharingView.Item? = nil,
snapshotLoader: SnapshotLoaderProtocol
) {
self.preSnapshotCountLimit = preSnapshotCountLimit
self.snapshotLoader = snapshotLoader
self.selectedScenario = selectedScenario
self.status = status
self.shareItem = shareItem
super.init(playbook: playbook)
}
convenience init(
playbook: Playbook,
preSnapshotCountLimit: Int,
screenSize: CGSize,
userInterfaceStyle: UIUserInterfaceStyle,
selectedScenario: SearchedData? = nil,
status: Status = .standby,
shareItem: ImageSharingView.Item? = nil
) {
self.init(
playbook: playbook,
preSnapshotCountLimit: preSnapshotCountLimit,
selectedScenario: selectedScenario,
status: status,
shareItem: shareItem,
snapshotLoader: SnapshotLoader(
name: "app.playbook-ui.SnapshotLoader",
baseDirectoryURL: URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true),
format: .png,
device: SnapshotDevice(
name: "PlaybookCatalog",
size: screenSize,
traitCollection: UITraitCollection(userInterfaceStyle: userInterfaceStyle)
)
)
)
}
}
| 27.907216 | 102 | 0.5785 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.