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
|
---|---|---|---|---|---|
f8a1434eb7c650071336d7fdec304223ccee4ee5 | 419 | //
// EncodableProperty.swift
//
//
// Created by Dejan Skledar on 05/09/2020.
//
import Foundation
///
///
/// Encodable property protocol implemented in Serialized where Wrapped Value is Encodable
///
///
public protocol EncodableProperty {
typealias EncodeContainer = KeyedEncodingContainer<SerializedCodingKeys>
func encodeValue(from container: inout EncodeContainer, propertyName: String) throws
}
| 19.952381 | 90 | 0.749403 |
e9da8f95e0f9124de4ea6a6a1123994dd15a55ac | 1,226 | //
// DemoUITests.swift
// DemoUITests
//
// Created by Tim on 12/05/2016.
// Copyright © 2016 timominous. All rights reserved.
//
import XCTest
class DemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.135135 | 182 | 0.659054 |
905f5aea2dc322dfb13c23a259b93c9597aaa22f | 1,214 | //
// DynamicSizeCell.swift
// Example
//
// Created by Le VanNghia on 7/9/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
import Foundation
import Sapporo
final class DynamicSizeCellModel: SACellModel {
let title: String
var des: String
init(title: String, des: String) {
self.title = title
self.des = des
super.init(cellType: DynamicSizeCell.self, selectionHandler: nil)
enableDynamicHeight(320)
}
}
final class DynamicSizeCell: SACell, SACellType {
typealias CellModel = DynamicSizeCellModel
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var desLabel: UILabel!
override func configure() {
super.configure()
guard let cellmodel = cellmodel else {
return
}
contentView.backgroundColor = .lightGray
titleLabel.text = cellmodel.title
desLabel.text = cellmodel.des
}
override func configureForSizeCalculating(_ cellmodel: SACellModel) {
super.configureForSizeCalculating(cellmodel)
if let cellmodel = cellmodel as? DynamicSizeCellModel {
desLabel.text = cellmodel.des
}
}
}
| 24.77551 | 73 | 0.644975 |
e61fd60ce3801fca96cb5a5dc28aee0990ddaa01 | 2,438 | import UIKit
import Combine
class ListBeersViewController: UIViewController, AppCoordinatorProtocol {
var appCoordinator: AppCoordinator?
var viewModel: ListBeerViewModel!
private var binding = Set<AnyCancellable>()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var lblNoSolutionAvailable: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
guard viewModel != nil else { fatalError() }
setup()
}
private func setup() {
let cellNib = UINib(nibName: BeerCell.identifier, bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: BeerCell.identifier)
setupBinding()
viewModel.start()
self.title = "Produced Beers"
}
private func setupBinding() {
viewModel.$beers.receive(on: DispatchQueue.main)
.sink { (_) in
self.tableView.reloadData()
self.tableView.isHidden = self.viewModel.noSolution
self.lblNoSolutionAvailable.isHidden = !self.viewModel.noSolution
}.store(in: &binding)
viewModel.$noSolution.receive(on: DispatchQueue.main)
.sink { (_) in
self.tableView.isHidden = self.viewModel.noSolution
self.lblNoSolutionAvailable.isHidden = !self.viewModel.noSolution
}.store(in: &binding)
}
}
extension ListBeersViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.beers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: BeerCell.identifier, for: indexPath) as? BeerCell else {
return UITableViewCell()
}
var modelAtRow = viewModel.beers[indexPath.row]
modelAtRow.barrelType = viewModel.beerBatch[indexPath.row].type
cell.viewModel = BeerCellViewModel(model: modelAtRow)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedBeer = self.viewModel.beers[indexPath.row]
// print("row: \(indexPath.row)")
// print("Beers: \(selectedBeer)")
appCoordinator?.PushBeerDetails(beerModel: selectedBeer)
}
}
| 36.939394 | 127 | 0.657916 |
7555cbdf4511acc687c9e0b49bb95342cc3e91a2 | 2,952 | //
// CustomizedActiveResult.swift
// ORKCatalog
//
// Created by 宋チュウ on 2020/07/08.
// Copyright © 2020 researchkit.org. All rights reserved.
//
import ResearchKit.Private
public class CustomizedActiveResult: ORKResult {
public var startTime: TimeInterval?
public var endTime: TimeInterval?
public var color: String?
public var text: String?
public var colorSelected: String?
enum Keys: String {
case startTime
case endTime
case color
case text
case colorSelected
}
public override init(identifier: String) {
super.init(identifier: identifier)
}
public override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(startTime, forKey: Keys.startTime.rawValue)
aCoder.encode(endTime, forKey: Keys.endTime.rawValue)
aCoder.encode(color, forKey: Keys.color.rawValue)
aCoder.encode(text, forKey: Keys.text.rawValue)
aCoder.encode(colorSelected, forKey: Keys.colorSelected.rawValue)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
startTime = aDecoder.decodeObject(forKey: Keys.startTime.rawValue) as? Double
endTime = aDecoder.decodeObject(forKey: Keys.endTime.rawValue) as? Double
color = aDecoder.decodeObject(forKey: Keys.color.rawValue) as? String
text = aDecoder.decodeObject(forKey: Keys.text.rawValue) as? String
colorSelected = aDecoder.decodeObject(forKey: Keys.colorSelected.rawValue) as? String
}
public class func supportsSecureCoding() -> Bool {
return true
}
override public func isEqual(_ object: Any?) -> Bool {
let isParentSame = super.isEqual(object)
if let castObject = object as? CustomizedActiveResult {
return (isParentSame &&
(startTime == castObject.startTime) &&
(endTime == castObject.endTime) &&
(color == castObject.color) &&
(text == castObject.text) &&
(colorSelected == castObject.colorSelected))
}
return true
}
override public func copy(with zone: NSZone? = nil) -> Any {
if let result = super.copy(with: zone) as? CustomizedActiveResult {
result.startTime = startTime
result.endTime = endTime
result.color = color
result.text = text
result.colorSelected = colorSelected
return result
} else {
return super.copy(with: zone)
}
}
public override func description(withNumberOfPaddingSpaces numberOfPaddingSpaces: UInt) -> String {
return "\(descriptionPrefix(withNumberOfPaddingSpaces: numberOfPaddingSpaces)); color: \(color ?? "") text: \(text ?? "") colorSelected: \(colorSelected ?? "") \(descriptionSuffix())"
}
}
| 35.142857 | 191 | 0.629404 |
71aecdfadb081c5b84ee7b67c8e4ead00084105d | 6,174 | //
// TableViewController.swift
// HelloWorld
//
// Created by Apple on 2019/10/15.
// Copyright © 2019 fengyuxiang. All rights reserved.
//
import UIKit
class FoodListController: UITableViewController {
var foodList: [food] = [food]()
func initFoodList(){
foodList.append(food(foodName: "cake", foodDescription: "sweet", foodAvatar: nil))
foodList.append(food(foodName: "apple", foodDescription: "sweet", foodAvatar: nil))
foodList.append(food(foodName: "banana", foodDescription: "sweet", foodAvatar: nil))
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 120
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
if let fileFood = loadFoodFile() as? [food]{
foodList = fileFood
}
else {
initFoodList()
saveFoodFile()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return foodList.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath)->
UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"foodCell", for: indexPath)
cell.textLabel?.text = foodList[indexPath.row].foodName
cell.imageView?.image = foodList[indexPath.row].foodAvatar
return cell
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
foodList.remove(at: indexPath.row)
saveFoodFile()
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// 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.destination.
// Pass the selected object to the new view controller.
if let descriptionVC = segue.destination as? FoodDescriptionViewController{
if let selectedCell = sender as? UITableViewCell{
let indexPath = tableView.indexPath(for: selectedCell)!
let selectedFood = foodList[(indexPath as NSIndexPath).row]
descriptionVC.foodForEdit = selectedFood
}
}
}
func saveFoodFile(){
let success = NSKeyedArchiver.archiveRootObject(foodList, toFile: food.ArchiveURL.path)
print(food.ArchiveURL.path)
if !success {
print("Failed to save food file!")
}
}
func loadFoodFile() -> [food]?{
return (NSKeyedUnarchiver.unarchiveObject(withFile: food.ArchiveURL.path) as? [food])
}
// 回退入口
//
@IBAction func cancelToList (segue: UIStoryboardSegue){
}
// 带数据返回
@IBAction func saveToList(segue: UIStoryboardSegue){
if let addFoodVC = segue.source as? FoodDescriptionViewController{
if let newFood = addFoodVC.newFood{
if(addFoodVC.newPage){
// append
foodList.append(newFood)
let newIndexPath = IndexPath(row: foodList.count-1, section: 0)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
else{
if let selectedIndexPath = tableView.indexPathForSelectedRow{
// update
foodList[(selectedIndexPath as NSIndexPath).row] = newFood
tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
}
}
else{
if let selectedIndexPath = tableView.indexPathForSelectedRow{
// 旧列表项内容变为空,则删除该行
foodList.remove(at: (selectedIndexPath as NSIndexPath).row)
tableView.deleteRows(at: [selectedIndexPath], with: .none)
}
else{
// 创建了一个空的项, do nothing
}
}
}
saveFoodFile()
}
}
| 35.482759 | 137 | 0.610625 |
56190697c46f79c10a7e9b4e91edd3659e0a9ff4 | 1,907 | //
// HeaderView.swift
// CharactersGrid
//
// Created by Alfian Losari on 9/22/20.
//
import UIKit
import SwiftUI
class HeaderView: UICollectionReusableView {
private let textLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
private func setupLayout() {
textLabel.font = UIFont.preferredFont(forTextStyle: .headline)
textLabel.adjustsFontForContentSizeCategory = true
textLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(textLabel)
let padding: CGFloat = 16
let labelBottomAnchor = textLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding)
labelBottomAnchor.priority = .init(999)
let labelTrailingAnchor = textLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding)
labelTrailingAnchor.priority = .init(999)
NSLayoutConstraint.activate([
textLabel.topAnchor.constraint(equalTo: topAnchor, constant: padding),
labelBottomAnchor,
textLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding),
labelTrailingAnchor
])
}
func configure(text: String) {
textLabel.text = text
}
required init?(coder: NSCoder) {
fatalError("Not supported, please register class")
}
}
struct HeaderViewRepresentable: UIViewRepresentable {
let title: String
func updateUIView(_ uiView: HeaderView, context: Context) {}
func makeUIView(context: Context) -> HeaderView {
let headerView = HeaderView()
headerView.configure(text: title)
return headerView
}
}
struct HeaderView_Previews: PreviewProvider {
static var previews: some View {
HeaderViewRepresentable(title: "Heroes")
}
}
| 27.242857 | 114 | 0.660724 |
de8a4c0b694fa8c5b884aa18e7e017c9e9d035f9 | 3,050 | // JWK+RSA.swift
//
// Copyright (c) 2020 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import SimpleKeychain
extension JWK {
var rsaPublicKey: SecKey? {
if let usage = usage, usage != "sig" { return nil }
guard keyType == "RSA",
algorithm == JWTAlgorithm.rs256.rawValue,
let modulus = rsaModulus?.a0_decodeBase64URLSafe(),
let exponent = rsaExponent?.a0_decodeBase64URLSafe() else { return nil }
let encodedKey = encodeRSAPublicKey(modulus: [UInt8](modulus), exponent: [UInt8](exponent))
if #available(iOS 10, *) {
return generateRSAPublicKey(from: encodedKey)
}
let tag = "com.auth0.tmp.RSAPublicKey"
let keychain = A0SimpleKeychain()
guard keychain.setRSAPublicKey(data: encodedKey, forKey: tag) else { return nil }
return keychain.keyRefOfRSAKey(withTag: tag)?.takeRetainedValue()
}
private func encodeRSAPublicKey(modulus: [UInt8], exponent: [UInt8]) -> Data {
let encodedModulus = modulus.a0_derEncode(as: 2) // Integer
let encodedExponent = exponent.a0_derEncode(as: 2) // Integer
let encodedSequence = (encodedModulus + encodedExponent).a0_derEncode(as: 48) // Sequence
return Data(encodedSequence)
}
@available(iOS 10, *)
private func generateRSAPublicKey(from derEncodedData: Data) -> SecKey? {
let sizeInBits = derEncodedData.count * MemoryLayout<UInt8>.size
let attributes: [CFString: Any] = [kSecClass: kSecClassKey,
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecAttrAccessible: kSecAttrAccessibleAlways,
kSecAttrKeySizeInBits: NSNumber(value: sizeInBits)]
return SecKeyCreateWithData(derEncodedData as CFData, attributes as CFDictionary, nil)
}
}
| 50 | 99 | 0.678689 |
ac1a2d92832439cb1e0141767dc169ac7dc7309c | 3,032 | //
// StudyDataSource.swift
// jsontables
//
// Created by Robert Diamond on 3/22/21.
//
import Foundation
struct Config : Codable {
var endpoint : String
}
class StudyDataSource {
lazy var fetchQueue = OperationQueue()
lazy var fetchSession = URLSession(configuration: .default, delegate: nil, delegateQueue: fetchQueue)
let DEFAULT_DIFFICULTY = 1
let DEFAULT_COUNT=5
var endpoint : String
var dataTask : URLSessionDataTask?
init() {
endpoint = "http://localhost:5000"
if let configPlist = Bundle.main.path(forResource: "config", ofType: "plist") {
if let configData = FileManager.default.contents(atPath: configPlist) {
do {
let config = try PropertyListDecoder().decode(Config.self, from: configData)
endpoint = config.endpoint
} catch {
print(error)
}
}
}
}
func fetchStudies(difficulty : Int?, count : Int?, completion : @escaping (_ data : [Study]?, _ error : Error?) -> Void) {
dataTask?.cancel()
guard let fetchURL = URL(string: "/get-randomized-studies-by-difficulty?difficulty=\(difficulty ?? DEFAULT_DIFFICULTY)&limit=\(count ?? DEFAULT_COUNT)", relativeTo: URL(string: endpoint)) else { return }
dataTask = fetchSession.dataTask(with: fetchURL) { [weak self] data, response, error in
guard let self = self else { return }
self.handleDataTask(data, response: response, error: error, completion: completion)
}
dataTask?.resume()
}
func fetchStudy(id : String, completion : @escaping (_ data : [Study]?, _ error : Error?) -> Void) {
guard let fetchURL = URL(string: "/get-studies-by-id/\(id)", relativeTo: URL(string: endpoint)) else { return }
dataTask = fetchSession.dataTask(with: fetchURL) { [weak self] data, response, error in
guard let self = self else { return }
self.handleDataTask(data, response: response, error: error, completion: completion)
}
dataTask?.resume()
}
func handleDataTask(_ data : Data?, response : URLResponse?, error : Error?, completion : @escaping (_ data : [Study]?, _ error : Error?) -> Void) {
defer {
self.dataTask = nil
}
if let error = error {
completion([], error)
} else if let data = data, let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) {
if let responseData = try? JSONDecoder().decode([Study].self, from: data) {
completion(responseData, nil)
} else {
completion([], NSError(domain: "Invalid response", code: -1, userInfo: [
NSLocalizedDescriptionKey : "Response failed to decode: invalid JSON"
]))
}
} else {
var statusCode = -1
if let response = response as? HTTPURLResponse {
statusCode = response.statusCode
}
completion([], NSError(domain: "Server Issue", code: statusCode, userInfo: [
NSLocalizedDescriptionKey : "Server issue"
]))
}
}
}
| 37.9 | 207 | 0.632916 |
ef9aa22866352bf2066d28703ef0be7e6bfe0f5d | 1,151 | protocol PrecheckfileProtocol: class {
/// The bundle identifier of your app
var appIdentifier: String { get }
/// Your Apple ID Username
var username: String { get }
/// The ID of your App Store Connect team if you're in multiple teams
var teamId: String? { get }
/// The name of your App Store Connect team if you're in multiple teams
var teamName: String? { get }
/// The default rule level unless otherwise configured
var defaultRuleLevel: String { get }
/// Should check in-app purchases?
var includeInAppPurchases: Bool { get }
/// using text indicating that your IAP is free
var freeStuffInIap: String? { get }
}
extension PrecheckfileProtocol {
var appIdentifier: String { return "" }
var username: String { return "" }
var teamId: String? { return nil }
var teamName: String? { return nil }
var defaultRuleLevel: String { return "error" }
var includeInAppPurchases: Bool { return true }
var freeStuffInIap: String? { return nil }
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.23]
| 31.108108 | 75 | 0.681147 |
399a25c5c13cb915de8b1645240b58ae8c718b9d | 1,343 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -parse -verify
// REQUIRES: objc_interop
import Foundation
class NotCopyable {}
class CopyableClass : NSCopying {
@objc(copyWithZone:) func copy(with zone: NSZone) -> AnyObject { return self }
}
@NSCopying // expected-error {{@NSCopying may only be used on 'var' declarations}}}}
func copyFunction() {}
@NSCopying // expected-error {{@NSCopying may only be used on 'var' declarations}}
struct CopyingStruct {
@NSCopying var x : CopyableClass // expected-error {{@NSCopying may only be used on properties in classes}}
}
class CopyingClassTest {
// These are ok.
@NSCopying var p1 : CopyableClass
@NSCopying var p1o : CopyableClass?
@NSCopying var p1uo : CopyableClass!
@NSCopying weak var p1w : CopyableClass?
// These are not.
@NSCopying let invalidLet : CopyableClass // expected-error {{@NSCopying requires property to be mutable}}
@NSCopying var computed : CopyableClass { get {} set {} } // expected-error {{@NSCopying is only valid on stored properties}}
@NSCopying var notClass : Int // expected-error {{@NSCopying is only valid with types that conform to the NSCopying protocol}}
@NSCopying var x : NotCopyable // expected-error {{@NSCopying is only valid with types that conform to the NSCopying protocol}}
init() {}
}
| 36.297297 | 132 | 0.718541 |
ffccc9600a2b938d6adf3debf180a8228291c3b0 | 327 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
/** What to order by. */
public enum ListOrderBy: String {
case az = "a-z"
case releaseYear = "release-year"
case dateAdded = "date-added"
public static let cases: [ListOrderBy] = [
.az,
.releaseYear,
.dateAdded,
]
}
| 18.166667 | 46 | 0.602446 |
1aef46f09048fcdca5bd91a04458705a579bbee6 | 382 | //
// ViewModifiers.swift
// ViewModifiers
//
// Created by Lucka on 24/7/2021.
//
import SwiftUI
extension View {
@inlinable func card(radius: CGFloat = 12) -> some View {
self
.padding(radius)
.background(
.thickMaterial,
in: RoundedRectangle(cornerRadius: radius, style: .continuous)
)
}
}
| 19.1 | 78 | 0.552356 |
fe0b7279ab13c15ea715e1d17d32c25387b96abc | 1,017 | //
// Configs.swift
// StoryBook
//
// Created by Artur Mkrtchyan on 2/2/18.
// Copyright © 2018 Develandoo. All rights reserved.
//
import Foundation
// All configuration variables based on the variety of environments must be placed here
enum Environment {
case debug
case release
case stagingDebug
case stagingRelease
case appstore
}
struct Config {
static let env: Environment = {
#if STAGING_DEBUG
return .stagingDebug
#elseif STAGING_RELEASE
return .stagingRelease
#elseif APPSTORE
return .appstore
#elseif DEBUG
return .debug
#elseif RELEASE
return .release
#endif
}()
static let apiBaseUrl: String = {
switch env {
case .debug,
.stagingDebug:
return "https://api.github.com"
case .stagingRelease,
.appstore,
.release:
return "https://api.github.com"
}
}()
}
| 21.1875 | 87 | 0.573255 |
f4ad98fc03d55478a6f12d8b1a0a39aa1bb9a238 | 896 | //
// Api.Entry.swift
// MyApp
//
// Created by Van Le H. on 11/20/18.
// Copyright © 2018 Asian Tech Co., Ltd. All rights reserved.
//
import Alamofire
import ObjectMapper
extension Api.Entry {
@discardableResult
static func loadEntries(completion: @escaping Completion<[Entry]>) -> Request? {
let path = Api.Path.Entry().urlString
return api.request(method: .get, urlString: path) { (result) in
DispatchQueue.main.async {
switch result {
case .success(let value):
guard let data = value as? JSObject, let entryData = data["Data"] as? JSArray else {
completion(.failure(Api.Error.json))
return
}
let entries = Mapper<Entry>().mapArray(JSONArray: entryData)
completion(.success(entries))
case .failure(let error):
completion(.failure(error))
}
}
}
}
}
| 26.352941 | 94 | 0.610491 |
2f2f60d426310aa96976462168b828bf61174d38 | 1,494 | import ProjectDescription
let project = Project(name: "FrameworkA",
targets: [
Target(name: "FrameworkA",
platform: .iOS,
product: .framework,
bundleId: "io.tuist.FrameworkA",
infoPlist: "Info.plist",
sources: ["Sources/**"],
resources: [
/* Path to resouces can be defined here */
// "Resources/**"
],
dependencies: [
/* Target dependencies can be defined here */
// .framework(path: "Frameworks/MyFramework.framework")
.project(target: "FrameworkB", path: "../FrameworkB")
]),
Target(name: "FrameworkATests",
platform: .iOS,
product: .unitTests,
bundleId: "io.tuist.FrameworkATests",
infoPlist: "Tests.plist",
sources: "Tests/**",
dependencies: [
.target(name: "FrameworkA")
])
]) | 51.517241 | 91 | 0.324632 |
5d3fd7cc90ad5fda43ff56f87c7b02fb388803b3 | 5,717 | //
// StringParam.swift
// R.swift
//
// Created by Tom Lokhorst on 2016-04-18.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
// Parts of the content of this file are loosly based on StringsFileParser.swift from SwiftGen/GenumKit.
// We don't feel this is a "substantial portion of the Software" so are not including their MIT license,
// eventhough we would like to give credit where credit is due by referring to SwiftGen thanking Olivier
// Halligon for creating SwiftGen and GenumKit.
//
// See: https://github.com/AliSoftware/SwiftGen/blob/master/GenumKit/Parsers/StringsFileParser.swift
//
import Foundation
enum FormatPart {
case spec(FormatSpecifier)
case reference(String)
var formatSpecifier: FormatSpecifier? {
switch self {
case .spec(let formatSpecifier):
return formatSpecifier
case .reference:
return nil
}
}
static func formatParts(formatString: String) -> [FormatPart] {
return createFormatParts(formatString)
}
}
// https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
enum FormatSpecifier {
case object
case double
case int
case uInt
case character
case cStringPointer
case voidPointer
case topType
var type: String {
switch self {
case .object:
return "String"
case .double:
return "Double"
case .int:
return "Int"
case .uInt:
return "UInt"
case .character:
return "Character"
case .cStringPointer:
return "CStringPointer"
case .voidPointer:
return "VoidPointer"
case .topType:
return "Any"
}
}
}
extension FormatSpecifier {
// Convenience initializer, uses last character of string,
// ignoring lengt modifiers, e.g. "lld"
init?(formatString string: String) {
guard let last = string.last else {
return nil
}
self.init(formatChar: last)
}
init?(formatChar char: Swift.Character) {
guard let lcChar = Swift.String(char).lowercased().first else { return nil }
switch lcChar {
case "@":
self = .object
case "a", "e", "f", "g":
self = .double
case "d", "i":
self = .int
case "o", "u", "x":
self = .uInt
case "c":
self = .character
case "s":
self = .cStringPointer
case "p":
self = .voidPointer
default:
return nil
}
}
}
private let referenceRegEx: NSRegularExpression = {
do {
return try NSRegularExpression(pattern: "#@([^@]+)@", options: [.caseInsensitive])
} catch {
fatalError("Error building the regular expression used to match reference")
}
}()
let formatTypesRegEx: NSRegularExpression = {
let pattern_int = "(?:h|hh|l|ll|q|z|t|j)?([dioux])" // %d/%i/%o/%u/%x with their optional length modifiers like in "%lld"
let pattern_float = "[aefg]"
let position = "([1-9]\\d*\\$)?" // like in "%3$" to make positional specifiers
let precision = "[-+]?\\d*(?:\\.\\d*)?" // precision like in "%1.2f" or "%012.10"
let reference = "#@([^@]+)@" // reference to NSStringFormatSpecType in .stringsdict
do {
return try NSRegularExpression(pattern: "(?<!%)%\(position)\(precision)(@|\(pattern_int)|\(pattern_float)|[csp]|\(reference))", options: [.caseInsensitive])
} catch {
fatalError("Error building the regular expression used to match string formats")
}
}()
// "I give %d apples to %@ %#@named@" --> [.Spec(.Int), .Spec(.String), .Reference("named")]
private func createFormatParts(_ formatString: String) -> [FormatPart] {
let nsString = formatString as NSString
let range = NSRange(location: 0, length: nsString.length)
// Extract the list of chars (conversion specifiers) and their optional positional specifier
let chars = formatTypesRegEx.matches(in: formatString, options: [], range: range).map { match -> (String, Int?) in
let range: NSRange
if match.range(at: 3).location != NSNotFound {
// [dioux] are in range #3 because in #2 there may be length modifiers (like in "lld")
range = match.range(at: 3)
} else {
// otherwise, no length modifier, the conversion specifier is in #2
range = match.range(at: 2)
}
let char = nsString.substring(with: range)
let posRange = match.range(at: 1)
if posRange.location == NSNotFound {
// No positional specifier
return (char, nil)
} else {
// Remove the "$" at the end of the positional specifier, and convert to Int
let posRange1 = NSRange(location: posRange.location, length: posRange.length - 1)
let pos = nsString.substring(with: posRange1)
return (char, Int(pos))
}
}
// Build up params array
var params = [FormatPart]()
var nextNonPositional = 1
for (str, pos) in chars {
let insertionPos: Int
if let pos = pos {
insertionPos = pos
} else {
insertionPos = nextNonPositional
nextNonPositional += 1
}
let param: FormatPart?
if let reference = referenceRegEx.firstSubstring(input: str) {
param = FormatPart.reference(reference)
} else if let char = str.first, let fs = FormatSpecifier(formatChar: char) {
param = FormatPart.spec(fs)
} else {
param = nil
}
if let param = param {
if insertionPos > 0 {
while params.count <= insertionPos - 1 {
params.append(FormatPart.spec(FormatSpecifier.topType))
}
params[insertionPos - 1] = param
}
}
}
return params
}
extension NSRegularExpression {
fileprivate func firstSubstring(input: String) -> String? {
let nsInput = input as NSString
let inputRange = NSRange(location: 0, length: nsInput.length)
guard let match = self.firstMatch(in: input, options: [], range: inputRange) else {
return nil
}
guard match.numberOfRanges > 0 else {
return nil
}
let range = match.range(at: 1)
return nsInput.substring(with: range)
}
}
| 27.485577 | 158 | 0.680252 |
f81304b766d6c238d5287783b9f0e3e6c4489ccc | 1,779 | final class ComplexModificationsFileImport: ObservableObject {
static let shared = ComplexModificationsFileImport()
var task: URLSessionTask?
@Published var fetching: Bool = false
@Published var url: URL?
@Published var error: String?
@Published var jsonData: Data?
@Published var title: String = ""
@Published var descriptions: [String] = []
public func fetchJson(_ url: URL) {
task?.cancel()
self.url = url
error = nil
jsonData = nil
title = ""
descriptions = []
task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
DispatchQueue.main.async {
guard let self = self else { return }
guard let data = data else { return }
self.fetching = false
if let error = error {
self.error = error.localizedDescription
} else {
do {
self.jsonData = data
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
self.title = json?["title"] as! String
for rule in (json?["rules"] as! [[String: Any]]) {
self.descriptions.append(rule["description"] as! String)
}
} catch {
self.jsonData = nil
self.error = error.localizedDescription
}
}
}
}
fetching = true
task?.resume()
}
public func save() {
if let data = self.jsonData {
let directory = String(cString: libkrbn_get_user_complex_modifications_assets_directory())
let time = Int(NSDate().timeIntervalSince1970)
let path = URL(fileURLWithPath: "\(directory)/\(time).json")
do {
try data.write(to: path)
} catch {
self.error = error.localizedDescription
}
}
}
}
| 26.954545 | 96 | 0.59584 |
3959c1549f5d4e58fe13c32c0e1810aad2e28f72 | 1,292 | import XCTest
@testable import TODOer
class TaskListBuilderTests: XCTestCase {
func testCreatingTaskList() {
let taskList = TaskListBuilder()
.title("Life List")
.colorHex("FFFFFF")
.isDefaultCollection(true)
.build()
XCTAssertEqual(taskList.id, -1)
XCTAssertEqual(taskList.title, "Life List")
XCTAssertEqual(taskList.type, .collection)
XCTAssertEqual(taskList.isDefaultCollection, true)
}
func testCreatingTaskListFromTemplate() {
let template = TaskList(id: 42,
title: "Life List",
color: nil,
type: .collection,
isDefaultCollection: false,
isEditable: true,
isDeletable: true)
let taskList = TaskListBuilder(template: template)
.title("Changed Title")
.isDefaultCollection(true)
.build()
XCTAssertEqual(taskList.id, 42)
XCTAssertEqual(taskList.title, "Changed Title")
XCTAssertNil(taskList.color)
XCTAssertEqual(taskList.type, .collection)
XCTAssertEqual(taskList.isDefaultCollection, true)
}
}
| 35.888889 | 59 | 0.555728 |
d9722289c4a2c8609a39df527d8e65ba9fa3675e | 653 | //
// UIActivityView.swift
// JsonUI
//
// Created by Steve Dao on 10/4/20.
// Copyright © 2020 Steve Dao. All rights reserved.
//
import Foundation
import SwiftUI
struct UIActivityView: UIViewRepresentable {
public typealias UIViewType = UIActivityIndicatorView
let style: UIActivityIndicatorView.Style
public func makeUIView(context: UIViewRepresentableContext<UIActivityView>) -> UIActivityView.UIViewType {
return UIActivityIndicatorView(style: style)
}
public func updateUIView(_ uiView: UIActivityView.UIViewType, context: UIViewRepresentableContext<UIActivityView>) {
uiView.startAnimating()
}
}
| 25.115385 | 120 | 0.748851 |
bbc717a6d442c91e0d4b66a06c46637b50a1b77a | 9,593 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import XCTest
import CloudKit
import ProcedureKit
import TestingProcedureKit
@testable import ProcedureKitCloud
class TestCKFetchRecordsOperation: TestCKDatabaseOperation, CKFetchRecordsOperationProtocol, AssociatedErrorProtocol {
typealias AssociatedError = FetchRecordsError<Record, RecordID>
var recordsByID: [RecordID: Record]? = nil
var error: Error? = nil
var recordIDs: [RecordID]? = nil
var perRecordProgressBlock: ((RecordID, Double) -> Void)? = nil
var perRecordCompletionBlock: ((Record?, RecordID?, Error?) -> Void)? = nil
var fetchRecordsCompletionBlock: (([RecordID: Record]?, Error?) -> Void)? = nil
init(recordsByID: [RecordID: Record]? = nil, error: Error? = nil) {
self.recordsByID = recordsByID
self.error = error
super.init()
}
override func main() {
fetchRecordsCompletionBlock?(recordsByID, error)
}
}
class CKFetchRecordsOperationTests: CKProcedureTestCase {
var target: TestCKFetchRecordsOperation!
var operation: CKProcedure<TestCKFetchRecordsOperation>!
override func setUp() {
super.setUp()
target = TestCKFetchRecordsOperation()
operation = CKProcedure(operation: target)
}
func test__set_get__recordIDs() {
let recordIDs: [String] = ["I'm a record ID"]
operation.recordIDs = recordIDs
XCTAssertNotNil(operation.recordIDs)
XCTAssertEqual(operation.recordIDs!, recordIDs)
XCTAssertNotNil(target.recordIDs)
XCTAssertEqual(target.recordIDs!, recordIDs)
}
func test__set_get__perRecordProgressBlock() {
var setByBlock = false
let block: (String, Double) -> Void = { recordID, progress in
setByBlock = true
}
operation.perRecordProgressBlock = block
XCTAssertNotNil(operation.perRecordProgressBlock)
target.perRecordProgressBlock?("I'm a record ID", 50.0)
XCTAssertTrue(setByBlock)
}
func test__set_get__perRecordCompletionBlock() {
var setByBlock = false
let block: (String?, String?, Error?) -> Void = { record, recordID, error in
setByBlock = true
}
operation.perRecordCompletionBlock = block
XCTAssertNotNil(operation.perRecordCompletionBlock)
target.perRecordCompletionBlock?("I'm a record", "I'm a record ID", nil)
XCTAssertTrue(setByBlock)
}
func test__success_without_completion_block() {
wait(for: operation)
XCTAssertProcedureFinishedWithoutErrors(operation)
}
func test__success_with_completion_block() {
var didExecuteBlock = false
operation.setFetchRecordsCompletionBlock { _ in
didExecuteBlock = true
}
wait(for: operation)
XCTAssertProcedureFinishedWithoutErrors(operation)
XCTAssertTrue(didExecuteBlock)
}
func test__error_without_completion_block() {
target.error = TestError()
wait(for: operation)
XCTAssertProcedureFinishedWithoutErrors(operation)
}
func test__error_with_completion_block() {
var didExecuteBlock = false
operation.setFetchRecordsCompletionBlock { _ in
didExecuteBlock = true
}
target.error = TestError()
wait(for: operation)
XCTAssertProcedureFinishedWithErrors(operation, count: 1)
XCTAssertFalse(didExecuteBlock)
}
}
class CloudKitProcedureFetchRecordOperationTests: CKProcedureTestCase {
var cloudkit: CloudKitProcedure<TestCKFetchRecordsOperation>!
var setByPerRecordProgressBlock: (TestCKFetchRecordsOperation.RecordID, Double)!
var setByPerRecordCompletionBlock: (TestCKFetchRecordsOperation.Record?, TestCKFetchRecordsOperation.RecordID?, Error?)!
override func setUp() {
super.setUp()
cloudkit = CloudKitProcedure(strategy: .immediate) { TestCKFetchRecordsOperation() }
cloudkit.container = container
cloudkit.previousServerChangeToken = token
cloudkit.resultsLimit = 10
cloudkit.recordIDs = [ "record 1", "record 2" ]
cloudkit.perRecordProgressBlock = { [unowned self] record, progress in
self.setByPerRecordProgressBlock = (record, progress)
}
cloudkit.perRecordCompletionBlock = { [unowned self] record, recordID, error in
self.setByPerRecordCompletionBlock = (record, recordID, error)
}
}
func test__set_get__errorHandlers() {
cloudkit.set(errorHandlers: [.internalError: cloudkit.passthroughSuggestedErrorHandler])
XCTAssertEqual(cloudkit.errorHandlers.count, 1)
XCTAssertNotNil(cloudkit.errorHandlers[.internalError])
}
func test__set_get_container() {
cloudkit.container = "I'm a different container!"
XCTAssertEqual(cloudkit.container, "I'm a different container!")
}
func test__set_get_previousServerChangeToken() {
cloudkit.previousServerChangeToken = "I'm a different token!"
XCTAssertEqual(cloudkit.previousServerChangeToken, "I'm a different token!")
}
func test__set_get_resultsLimit() {
cloudkit.resultsLimit = 20
XCTAssertEqual(cloudkit.resultsLimit, 20)
}
func test__set_get_recordIDs() {
cloudkit.recordIDs = [ "record id 3", "record id 4" ]
XCTAssertEqual(cloudkit.recordIDs ?? [], [ "record id 3", "record id 4" ])
}
func test__set_get_perRecordProgressBlock() {
XCTAssertNotNil(cloudkit.perRecordProgressBlock)
cloudkit.perRecordProgressBlock?("a record id", 0.1)
XCTAssertEqual(setByPerRecordProgressBlock?.0, "a record id")
XCTAssertEqual(setByPerRecordProgressBlock?.1, 0.1)
}
func test__set_get_perRecordCompletionBlock() {
let error = TestError()
XCTAssertNotNil(cloudkit.perRecordCompletionBlock)
cloudkit.perRecordCompletionBlock?("a record", "a record id", error)
XCTAssertEqual(setByPerRecordCompletionBlock?.0, "a record")
XCTAssertEqual(setByPerRecordCompletionBlock?.1, "a record id")
XCTAssertEqual(setByPerRecordCompletionBlock?.2 as? TestError ?? TestError(), error)
}
func test__cancellation() {
cloudkit.cancel()
wait(for: cloudkit)
XCTAssertProcedureCancelledWithoutErrors(cloudkit)
}
func test__success_without_completion_block_set() {
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
}
func test__success_with_completion_block_set() {
var didExecuteBlock = false
cloudkit.setFetchRecordsCompletionBlock { _ in
didExecuteBlock = true
}
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
XCTAssertTrue(didExecuteBlock)
}
func test__error_without_completion_block_set() {
cloudkit = CloudKitProcedure(strategy: .immediate) {
let operation = TestCKFetchRecordsOperation()
operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil)
return operation
}
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
}
func test__error_with_completion_block_set() {
cloudkit = CloudKitProcedure(strategy: .immediate) {
let operation = TestCKFetchRecordsOperation()
operation.error = NSError(domain: CKErrorDomain, code: CKError.internalError.rawValue, userInfo: nil)
return operation
}
var didExecuteBlock = false
cloudkit.setFetchRecordsCompletionBlock { _ in
didExecuteBlock = true
}
wait(for: cloudkit)
XCTAssertProcedureFinishedWithErrors(cloudkit, count: 1)
XCTAssertFalse(didExecuteBlock)
}
func test__error_which_retries_using_retry_after_key() {
var shouldError = true
cloudkit = CloudKitProcedure(strategy: .immediate) {
let op = TestCKFetchRecordsOperation()
if shouldError {
let userInfo = [CKErrorRetryAfterKey: NSNumber(value: 0.001)]
op.error = NSError(domain: CKErrorDomain, code: CKError.Code.serviceUnavailable.rawValue, userInfo: userInfo)
shouldError = false
}
return op
}
var didExecuteBlock = false
cloudkit.setFetchRecordsCompletionBlock { _ in didExecuteBlock = true }
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
XCTAssertTrue(didExecuteBlock)
}
func test__error_which_retries_using_custom_handler() {
var shouldError = true
cloudkit = CloudKitProcedure(strategy: .immediate) {
let op = TestCKFetchRecordsOperation()
if shouldError {
op.error = NSError(domain: CKErrorDomain, code: CKError.Code.limitExceeded.rawValue, userInfo: nil)
shouldError = false
}
return op
}
var didRunCustomHandler = false
cloudkit.set(errorHandlerForCode: .limitExceeded) { _, _, _, suggestion in
didRunCustomHandler = true
return suggestion
}
var didExecuteBlock = false
cloudkit.setFetchRecordsCompletionBlock { _ in didExecuteBlock = true }
wait(for: cloudkit)
XCTAssertProcedureFinishedWithoutErrors(cloudkit)
XCTAssertTrue(didExecuteBlock)
XCTAssertTrue(didRunCustomHandler)
}
}
| 36.2 | 125 | 0.679975 |
e6a6eb1d1c9076fff89a54001035a3b79367669f | 1,713 | //
// DropHeader.swift
// Rugby
//
// Created by Vyacheslav Khorkov on 28.02.2021.
// Copyright © 2021 Vyacheslav Khorkov. All rights reserved.
//
import ArgumentParser
private extension ArgumentHelp {
static let targetsHelp: ArgumentHelp = """
RegEx targets for removing.
\("- Use backward slashes \\ for escaping special characters; ".yellow)
\("- Add \"\" for safer use (without shell's interpretation).".yellow)
"""
}
struct Drop: ParsableCommand {
@Argument(parsing: .remaining, help: .targetsHelp) var targets: [String]
@Flag(name: .shortAndLong, help: "Invert RegEx.") var invert = false
@Option(name: .shortAndLong,
parsing: .upToNextOption,
help: "Exclude targets. (not RegEx)") var exclude: [String] = []
@Flag(name: .shortAndLong, help: "Show output without any changes.") var testFlight = false
@Option(name: .shortAndLong, help: "Project location.") var project: String = .podsProject
@Flag(name: .shortAndLong, help: "Keep sources & resources in project.\n") var keepSources = false
@Flag(name: .long, inversion: .prefixedNo, help: "Play bell sound on finish.") var bell = true
@Flag(help: "Hide metrics.") var hideMetrics = false
@Flag(name: .shortAndLong, help: "Print more information.") var verbose: Int
static var configuration = CommandConfiguration(
abstract: "• Remove any targets by RegEx.",
discussion: """
Checkout documentation for more info:
📖 \("https://github.com/swiftyfinch/Rugby/blob/main/Docs/Drop.md".cyan)
"""
)
mutating func run() throws {
try WrappedError.wrap(playBell: bell) {
try wrappedRun()
}
}
}
| 36.446809 | 102 | 0.655575 |
d62889c5607109c5722146ed9c8c7457b3991c7c | 18,730 | /**
* Atributika
*
* Copyright (c) 2017 Pavel Sharanda. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
import XCTest
import Atributika
class AtributikaTests: XCTestCase {
func testHello() {
let test = "Hello <b>World</b>!!!".style(tags:
Style("b").font(.boldSystemFont(ofSize: 45))
).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(6, 5))
XCTAssertEqual(test,reference)
}
func testHelloWithBase() {
let test = "<b>Hello World</b>!!!".style(tags: Style("b").font(.boldSystemFont(ofSize: 45)))
.styleAll(.font(.systemFont(ofSize: 12)))
.attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(0, 11))
reference.addAttributes([NSAttributedStringKey.font: Font.systemFont(ofSize: 12)], range: NSMakeRange(11, 3))
XCTAssertEqual(test,reference)
}
func testTagsWithNumbers() {
let test = "<b1>Hello World</b1>!!!".style(tags: Style("b1").font(.boldSystemFont(ofSize: 45)))
.styleAll(.font(.systemFont(ofSize: 12)))
.attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(0, 11))
reference.addAttributes([NSAttributedStringKey.font: Font.systemFont(ofSize: 12)], range: NSMakeRange(11, 3))
XCTAssertEqual(test,reference)
}
func testLines() {
let test = "<b>Hello\nWorld</b>!!!".style(tags: Style("b").font(.boldSystemFont(ofSize: 45)))
.styleAll(.font(.systemFont(ofSize: 12)))
.attributedString
let reference = NSMutableAttributedString(string: "Hello\nWorld!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(0, 11))
reference.addAttributes([NSAttributedStringKey.font: Font.systemFont(ofSize: 12)], range: NSMakeRange(11, 3))
XCTAssertEqual(test,reference)
}
func testEmpty() {
let test = "Hello World!!!".style().attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
XCTAssertEqual(test, reference)
}
func testParams() {
let a = "<a href=\"http://google.com\">Hello</a> World!!!".style()
let reference = NSMutableAttributedString(string: "Hello World!!!")
XCTAssertEqual(a.attributedString, reference)
XCTAssertEqual(a.detections[0].range, a.string.startIndex..<a.string.index(a.string.startIndex, offsetBy: 5))
if case .tag(let tag) = a.detections[0].type {
XCTAssertEqual(tag.name, "a")
XCTAssertEqual(tag.attributes, ["href":"http://google.com"])
}
}
func testBase() {
let test = "Hello World!!!".styleAll(Style.font(.boldSystemFont(ofSize: 45))).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!", attributes: [NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)])
XCTAssertEqual(test, reference)
}
func testManyTags() {
let test = "He<i>llo</i> <b>World</b>!!!".style(tags:
Style("b").font(.boldSystemFont(ofSize: 45)),
Style("i").font(.boldSystemFont(ofSize: 12))
).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 12)], range: NSMakeRange(2, 3))
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(6, 5))
XCTAssertEqual(test, reference)
}
func testManySameTags() {
let test = "He<b>llo</b> <b>World</b>!!!".style(tags:
Style("b").font(.boldSystemFont(ofSize: 45))
).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(2, 3))
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(6, 5))
XCTAssertEqual(test, reference)
}
func testTagsOverlap() {
let test = "Hello <b>W<red>orld</b>!!!</red>".style(tags:
Style("b").font(.boldSystemFont(ofSize: 45)),
Style("red").foregroundColor(.red)
).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(6, 5))
reference.addAttributes([NSAttributedStringKey.foregroundColor: Color.red], range: NSMakeRange(7, 7))
XCTAssertEqual(test, reference)
}
func testBr() {
let test = "Hello<br>World!!!".style(tags: []).attributedString
let reference = NSMutableAttributedString(string: "Hello\nWorld!!!")
XCTAssertEqual(test, reference)
}
func testNotClosedTag() {
let test = "Hello <b>World!!!".style(tags: Style("b").font(.boldSystemFont(ofSize: 45))).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
XCTAssertEqual(test, reference)
}
func testNotOpenedTag() {
let test = "Hello </b>World!!!".style(tags: Style("b").font(.boldSystemFont(ofSize: 45))).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
XCTAssertEqual(test, reference)
}
func testBadTag() {
let test = "Hello <World!!!".style(tags: Style("b").font(.boldSystemFont(ofSize: 45))).attributedString
let reference = NSMutableAttributedString(string: "Hello ")
XCTAssertEqual(test, reference)
}
func testTagsStack() {
let test = "Hello <b>Wo<red>rl<u>d</u></red></b>!!!"
.style(tags:
Style("b").font(.boldSystemFont(ofSize: 45)),
Style("red").foregroundColor(.red),
Style("u").underlineStyle(.styleSingle))
.attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(6, 5))
reference.addAttributes([NSAttributedStringKey.foregroundColor: Color.red], range: NSMakeRange(8, 3))
reference.addAttributes([NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue], range: NSMakeRange(10, 1))
XCTAssertEqual(test, reference)
}
func testHashCodes() {
let test = "#Hello @World!!!"
.styleHashtags(Style.font(.boldSystemFont(ofSize: 45)))
.styleMentions(Style.foregroundColor(.red))
.attributedString
let reference = NSMutableAttributedString(string: "#Hello @World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(0, 6))
reference.addAttributes([NSAttributedStringKey.foregroundColor: Color.red], range: NSMakeRange(7, 6))
XCTAssertEqual(test, reference)
}
func testDataDetectorPhoneRaw() {
let test = "Call me (888)555-5512".style(textCheckingTypes: [.phoneNumber],
style: Style.font(.boldSystemFont(ofSize: 45)))
.attributedString
let reference = NSMutableAttributedString(string: "Call me (888)555-5512")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(8, 13))
XCTAssertEqual(test, reference)
}
func testDataDetectorLinkRaw() {
let test = "Check this http://google.com".style(textCheckingTypes: [.link],
style: Style.font(.boldSystemFont(ofSize: 45)))
.attributedString
let reference = NSMutableAttributedString(string: "Check this http://google.com")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(11, 17))
XCTAssertEqual(test, reference)
}
func testDataDetectorPhone() {
let test = "Call me (888)555-5512".stylePhoneNumbers(Style.font(.boldSystemFont(ofSize: 45)))
.attributedString
let reference = NSMutableAttributedString(string: "Call me (888)555-5512")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(8, 13))
XCTAssertEqual(test, reference)
}
func testDataDetectorLink() {
let test = "Check this http://google.com".styleLinks(Style.font(.boldSystemFont(ofSize: 45)))
.attributedString
let reference = NSMutableAttributedString(string: "Check this http://google.com")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(11, 17))
XCTAssertEqual(test, reference)
}
func testIssue1() {
let bad = "<b>Save $1.00</b> on <b>any</b> order!".style(tags:
Style("b").font(.boldSystemFont(ofSize: 14))
)
.styleAll(Style.font(.systemFont(ofSize: 14)).foregroundColor(.red))
.attributedString
let badReference = NSMutableAttributedString(string: "Save $1.00 on any order!", attributes: [NSAttributedStringKey.font: Font.systemFont(ofSize: 14), NSAttributedStringKey.foregroundColor: Color.red])
badReference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 14)], range: NSMakeRange(0, 10))
badReference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 14)], range: NSMakeRange(14, 3))
XCTAssertEqual(bad, badReference)
let good = "Save <b>$1.00</b> on <b>any</b> order!".style(tags:
Style("b").font(.boldSystemFont(ofSize: 14)))
.styleAll(Style.font(.systemFont(ofSize: 14)).foregroundColor(.red))
.attributedString
let goodReference = NSMutableAttributedString(string: "Save $1.00 on any order!", attributes: [NSAttributedStringKey.font: Font.systemFont(ofSize: 14), NSAttributedStringKey.foregroundColor: Color.red])
goodReference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 14)], range: NSMakeRange(5, 5))
goodReference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 14)], range: NSMakeRange(14, 3))
XCTAssertEqual(good, goodReference)
}
func testRange() {
let str = "Hello World!!!"
let test = "Hello World!!!".style(range: str.startIndex..<str.index(str.startIndex, offsetBy: 5), style: Style("b").font(.boldSystemFont(ofSize: 45))).attributedString
let reference = NSMutableAttributedString(string: "Hello World!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(0, 5))
XCTAssertEqual(test, reference)
}
func testEmojis() {
let test = "Hello <b>W🌎rld</b>!!!".style(tags:
Style("b").font(.boldSystemFont(ofSize: 45))
).attributedString
let reference = NSMutableAttributedString(string: "Hello W🌎rld!!!")
reference.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSMakeRange(6, 6))
XCTAssertEqual(test,reference)
}
func testTransformers() {
let transformers: [TagTransformer] = [
TagTransformer.brTransformer,
TagTransformer(tagName: "li", tagType: .start, replaceValue: "- "),
TagTransformer(tagName: "li", tagType: .end, replaceValue: "\n")
]
let li = Style("li").font(.systemFont(ofSize: 12))
let test = "TODO:<br><li>veni</li><li>vidi</li><li>vici</li>"
.style(tags: li, transformers: transformers)
.attributedString
let reference = NSMutableAttributedString(string: "TODO:\n- veni\n- vidi\n- vici\n")
reference.addAttributes([NSAttributedStringKey.font: Font.systemFont(ofSize: 12)], range: NSMakeRange(6, 6))
reference.addAttributes([NSAttributedStringKey.font: Font.systemFont(ofSize: 12)], range: NSMakeRange(13, 6))
reference.addAttributes([NSAttributedStringKey.font: Font.systemFont(ofSize: 12)], range: NSMakeRange(20, 6))
XCTAssertEqual(test,reference)
}
func testOL() {
var counter = 0
let transformers: [TagTransformer] = [
TagTransformer.brTransformer,
TagTransformer(tagName: "ol", tagType: .start) { _ in
counter = 0
return ""
},
TagTransformer(tagName: "li", tagType: .start) { _ in
counter += 1
return "\(counter). "
},
TagTransformer(tagName: "li", tagType: .end) { _ in
return "\n"
}
]
let test = "<div><ol type=\"\"><li>Coffee</li><li>Tea</li><li>Milk</li></ol><ol type=\"\"><li>Coffee</li><li>Tea</li><li>Milk</li></ol></div>".style(tags: [], transformers: transformers).string
let reference = "1. Coffee\n2. Tea\n3. Milk\n1. Coffee\n2. Tea\n3. Milk\n"
XCTAssertEqual(test,reference)
}
func testStyleBuilder() {
let s = Style
.font(.boldSystemFont(ofSize: 12), .normal)
.font(.systemFont(ofSize: 12), .highlighted)
.font(.boldSystemFont(ofSize: 13), .normal)
.foregroundColor(.red, .normal)
.foregroundColor(.green, .highlighted)
let ref = Style("", [.normal: [.font: Font.boldSystemFont(ofSize: 13) as Any, .foregroundColor: Color.red as Any],
.highlighted: [.font: Font.systemFont(ofSize: 12) as Any, .foregroundColor: Color.green as Any]])
XCTAssertEqual("test".styleAll(s).attributedString,"test".styleAll(ref).attributedString)
}
func testStyleBuilder2() {
let s = Style
.foregroundColor(.red, .normal)
.font(.boldSystemFont(ofSize: 12), .normal)
.font(.boldSystemFont(ofSize: 13), .normal)
.foregroundColor(.green, .highlighted)
.font(.systemFont(ofSize: 12), .highlighted)
let ref = Style("", [.normal: [.font: Font.boldSystemFont(ofSize: 13) as Any, .foregroundColor: Color.red as Any],
.highlighted: [.font: Font.systemFont(ofSize: 12) as Any, .foregroundColor: Color.green as Any]])
XCTAssertEqual("test".styleAll(s).attributedString,"test".styleAll(ref).attributedString)
}
func testHelloWithRHTMLTag() {
let test = "\r\n<a style=\"text-decoration:none\" href=\"http://www.google.com\">Hello World</a>".style(tags:
Style("a").font(.boldSystemFont(ofSize: 45))
).attributedString
let reference1 = NSMutableAttributedString.init(string: "Hello World")
XCTAssertEqual(reference1.length, 11)
XCTAssertEqual(reference1.string.count, 11)
let reference2 = NSMutableAttributedString.init(string: "\rHello World")
XCTAssertEqual(reference2.length, 12)
XCTAssertEqual(reference2.string.count, 12)
let reference3 = NSMutableAttributedString.init(string: "\r\nHello World")
XCTAssertEqual(reference3.length, 13)
XCTAssertEqual(reference3.string.count, 12)
reference3.addAttributes([NSAttributedStringKey.font: Font.boldSystemFont(ofSize: 45)], range: NSRange(reference3.string.range(of: "Hello World")!, in: reference3.string) )
XCTAssertEqual(test, reference3)
}
func testTagAttributes() {
let test = "Hello <a class=\"big\" target=\"\" href=\"http://foo.com\">world</a>!"
let (string, tags) = test.detectTags()
XCTAssertEqual(string, "Hello world!")
XCTAssertEqual(tags[0].tag.attributes["class"], "big")
XCTAssertEqual(tags[0].tag.attributes["target"], "")
XCTAssertEqual(tags[0].tag.attributes["href"], "http://foo.com")
}
}
#if os(Linux)
extension AtributikaTests {
static var allTests : [(String, (AtributikaTests) -> () throws -> Void)] {
return [
("testExample", testExample),
]
}
}
#endif
| 42.089888 | 210 | 0.617459 |
fbbee634fe498f69c9b6b56917860081a70b9b76 | 1,202 | //
// Copyright © 2022 Schibsted.
// Licensed under the terms of the MIT license. See LICENSE in the project root.
//
import Foundation
enum StoreErrorReason: Equatable {
case keychainError(status: OSStatus)
case invalidData(reason: String)
}
enum KeychainStorageError: Error, Equatable {
case storeError(reason: StoreErrorReason)
case operationError
case deleteError
case itemEncodingError
case entitlementMissing
}
extension KeychainStorageError: LocalizedError {
public var errorDescription: String? {
switch self {
case .storeError(let reason):
return NSLocalizedString("Unable to store the secret, reason: \(reason)", comment: "")
case .operationError:
return NSLocalizedString("Unable to fulfill the keychain query", comment: "")
case .deleteError:
return NSLocalizedString("Unable to delete the secret", comment: "")
case .itemEncodingError:
return NSLocalizedString("Failed to JSON encode user tokens for storage", comment: "")
case .entitlementMissing:
return NSLocalizedString("Entitlement missing for access group", comment: "")
}
}
}
| 32.486486 | 98 | 0.688852 |
9b7b00ff41f333bb9db62f558e44b67df7b024f2 | 929 | //
// TipCalculatorTests.swift
// TipCalculatorTests
//
// Created by Modest Juarez on 9/14/20.
// Copyright © 2020 Modest Juarez. All rights reserved.
//
import XCTest
@testable import TipCalculator
class TipCalculatorTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.542857 | 111 | 0.663079 |
91a74cf64f30e5e48c0a053edb0e2049e1eda66d | 2,294 | //
// SceneDelegate.swift
// PitchPerfect
//
// Created by Hung Truong on 11/19/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.283019 | 147 | 0.713165 |
ef856abac0d1c873141cfc980581be413ad91e0c | 3,685 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import Foundation
import AWSSDKSwiftCore
extension EC2InstanceConnect {
public struct SendSSHPublicKeyRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "AvailabilityZone", required: true, type: .string),
AWSShapeMember(label: "InstanceId", required: true, type: .string),
AWSShapeMember(label: "InstanceOSUser", required: true, type: .string),
AWSShapeMember(label: "SSHPublicKey", required: true, type: .string)
]
/// The availability zone the EC2 instance was launched in.
public let availabilityZone: String
/// The EC2 instance you wish to publish the SSH key to.
public let instanceId: String
/// The OS user on the EC2 instance whom the key may be used to authenticate as.
public let instanceOSUser: String
/// The public key to be published to the instance. To use it after publication you must have the matching private key.
public let sSHPublicKey: String
public init(availabilityZone: String, instanceId: String, instanceOSUser: String, sSHPublicKey: String) {
self.availabilityZone = availabilityZone
self.instanceId = instanceId
self.instanceOSUser = instanceOSUser
self.sSHPublicKey = sSHPublicKey
}
public func validate(name: String) throws {
try validate(availabilityZone, name:"availabilityZone", parent: name, max: 32)
try validate(availabilityZone, name:"availabilityZone", parent: name, min: 6)
try validate(availabilityZone, name:"availabilityZone", parent: name, pattern: "^(\\w+-){2,3}\\d+\\w+$")
try validate(instanceId, name:"instanceId", parent: name, max: 32)
try validate(instanceId, name:"instanceId", parent: name, min: 10)
try validate(instanceId, name:"instanceId", parent: name, pattern: "^i-[a-f0-9]+$")
try validate(instanceOSUser, name:"instanceOSUser", parent: name, max: 32)
try validate(instanceOSUser, name:"instanceOSUser", parent: name, min: 1)
try validate(instanceOSUser, name:"instanceOSUser", parent: name, pattern: "^[A-Za-z_][A-Za-z0-9\\@\\._-]{0,30}[A-Za-z0-9\\$_-]?$")
try validate(sSHPublicKey, name:"sSHPublicKey", parent: name, max: 4096)
try validate(sSHPublicKey, name:"sSHPublicKey", parent: name, min: 256)
}
private enum CodingKeys: String, CodingKey {
case availabilityZone = "AvailabilityZone"
case instanceId = "InstanceId"
case instanceOSUser = "InstanceOSUser"
case sSHPublicKey = "SSHPublicKey"
}
}
public struct SendSSHPublicKeyResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "RequestId", required: false, type: .string),
AWSShapeMember(label: "Success", required: false, type: .boolean)
]
/// The request ID as logged by EC2 Connect. Please provide this when contacting AWS Support.
public let requestId: String?
/// Indicates request success.
public let success: Bool?
public init(requestId: String? = nil, success: Bool? = nil) {
self.requestId = requestId
self.success = success
}
private enum CodingKeys: String, CodingKey {
case requestId = "RequestId"
case success = "Success"
}
}
}
| 48.486842 | 158 | 0.643962 |
e4f3a5b7f6c56dc3f9a6b363a8b393874703c434 | 2,296 | //
// DefaultGraphQLAPIClient.swift
// Swift-Base
//
// Created by Анастасия Леонтьева on 20/05/2021.
// Copyright © 2021 Flatstack. All rights reserved.
//
import Foundation
import Apollo
import Combine
@available(iOS 13.0, *)
class DefaultGraphQLAPIClient: GraphQLAPIClient {
// MARK: - GraphQLAPIClient Properties
static let shared: GraphQLAPIClient = DefaultGraphQLAPIClient(accessManager: DefaultManagersModule().accessManager)
// MARK: -
private let accessManager: AccessManager
// MARK: - Instance Properties
private lazy var client: ApolloClient = {
let cache = InMemoryNormalizedCache()
let store = ApolloStore(cache: cache)
let interceptorProvider = NetworkInterceptorProvider(accessManager: self.accessManager, store: store, isUpdateToken: false)
let requestChainNetworkTransport = RequestChainNetworkTransport(interceptorProvider: interceptorProvider, endpointURL: Configuration.graphQLURL)
return ApolloClient(networkTransport: requestChainNetworkTransport, store: store)
}()
// MARK: - Initializers
init(accessManager: AccessManager) {
self.accessManager = accessManager
}
// MARK: - GraphQLAPIClient Methods
func fetchPublisher<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy, queue: DispatchQueue, contextIdentifier: UUID? = nil) -> Publishers.ApolloFetch<Query> {
let config = Publishers.ApolloFetchConfiguration(client: self.client, query: query, cachePolicy: cachePolicy, contextIdentifier: contextIdentifier, queue: queue)
return Publishers.ApolloFetch(with: config)
}
func performPublisher<Mutation: GraphQLMutation>(mutation: Mutation, queue: DispatchQueue) -> Publishers.ApolloPerform<Mutation> {
let config = Publishers.ApolloPerformConfiguration(client: self.client, mutation: mutation, queue: queue)
return Publishers.ApolloPerform(with: config)
}
func uploadPublisher<Operation: GraphQLOperation>(operation: Operation, queue: DispatchQueue, files: [GraphQLFile]) -> Publishers.ApolloUpload<Operation> {
let config = Publishers.ApolloUploadConfiguration(client: self.client, operation: operation, files: files, queue: queue)
return Publishers.ApolloUpload(with: config)
}
}
| 40.280702 | 173 | 0.746516 |
f44cf3ac793d5e1a391ad03f6690fae99c0dfa9b | 1,634 | //
// SettingsController.swift
// Everyday_Commit
//
// Created by 서보경 on 2020/11/11.
//
import UIKit
import WidgetKit
class SettingsController: UIViewController {
var themeDataManager = ThemeDataManager()
override func viewDidLoad() {
super.viewDidLoad()
setLightModeOnly()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let color = UserDefaults.shared?.string(forKey: "color") {
view.backgroundColor = themeDataManager.themeColorDict[color]
self.tabBarController?.tabBar.tintColor = themeDataManager.themeColorDict[color]
}
}
@IBAction func logout(_ sender: Any) {
let alert = UIAlertController(title: "알림", message: "로그아웃하시겠습니까?", preferredStyle: .alert)
let cancel = UIAlertAction(title: "취소", style: .cancel, handler: nil)
let logout = UIAlertAction(title: "로그아웃", style: .destructive) { action in
UserDefaults.shared?.removeObject(forKey: "token")
UserDefaults.shared?.removeObject(forKey: "userID")
WidgetCenter.shared.reloadAllTimelines()
// 화면 이동하기
guard let loginVC = UIStoryboard(name: "LoginController", bundle: nil).instantiateViewController(withIdentifier: "LoginVC") as? LoginController else { return }
loginVC.modalPresentationStyle = .fullScreen
self.present(loginVC, animated: true, completion: nil)
}
alert.addAction(cancel)
alert.addAction(logout)
self.present(alert, animated: true, completion: nil)
}
}
| 34.765957 | 171 | 0.652999 |
ab5545b1317f2ea62221869f0802c34ae669e8dc | 393 | //
// Settings.swift
// Clima
//
// Created by Tarokh on 8/6/20.
// Copyright © 2020 Tarokh. All rights reserved.
//
import Foundation
class GlobalSetting {
static let shared = GlobalSetting()
let apikey = "YOUR API KEY HERE"
}
struct Routes {
static let s = GlobalSetting.shared
static let baseURL = "http://api.openweathermap.org/data/2.5/weather?appid=\(s.apikey)"
}
| 19.65 | 91 | 0.676845 |
8a92d40397e41d76c100e11ae27eb1213b620d09 | 2,146 | //
// RegistrationViewController.swift
// InstaVig
//
// Created by Alex Vig on 09/03/2019.
// Copyright © 2019 Alex Vig. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
class RegistrationViewController: UIViewController {
var ref: DatabaseReference!
@IBOutlet weak var fullNameOutlet: UITextField!
@IBOutlet weak var emailOutlet: UITextField!
@IBOutlet weak var passwordOutlet: UITextField!
@IBOutlet weak var verifyOutlet: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
}
@IBAction func register(_ sender: Any) {
let fullNameText = fullNameOutlet.text ?? ""
let passwordText = passwordOutlet.text ?? ""
let emailText = emailOutlet.text ?? ""
if (fullNameText == "" || emailText == "" || passwordText == "" || verifyOutlet.text?.isEmpty ?? true)
{
Utilities.showAlert("Please fill all the details", self)
}
else if (passwordOutlet.text != verifyOutlet.text)
{
Utilities.showAlert("Passwords do not match", self)
}
else {
Utilities.showSpinner(onView: self.view)
//let user = User(_id: "", _fullName: fullNameOutlet.text ?? "", _description: "", _profilePicture: "", _lastUpdate: 0)
//self.ref.child("users").childByAutoId().setValue(user.toJson())
Auth.auth().createUser(withEmail: emailText, password: passwordText) { authResult, error in
if let userId = authResult?.user.uid {
let user = User(_id: userId, _fullName: fullNameText, _description: "", _profilePicture: "", _lastUpdate: 0)
self.ref.child("users").childByAutoId().setValue(user.toJson())
} else {
Utilities.showAlert("User creation has failed!", self)
}
}
Utilities.removeSpinner()
dismiss(animated: true, completion: nil)
}
}
}
| 34.063492 | 131 | 0.583411 |
18ced70551b20f5f0ff3d88ba2669d9dacf909f2 | 17,061 | //
// AgoraAlertView.swift
// AgoraEduSDK
//
// Created by SRS on 2021/2/13.
//
import AgoraUIEduBaseViews.AgoraFiles.AgoraAnimatedImage
import AgoraUIBaseViews
@objcMembers public class AgoraAlertImageModel: NSObject {
public var name: String = ""
public var width: CGFloat = 0
public var height: CGFloat = 0
}
@objcMembers public class AgoraAlertLabelModel: NSObject {
public var text: String = ""
public var textColor: UIColor = UIColor.clear
public var textFont: UIFont = UIFont.systemFont(ofSize:12)
}
@objcMembers public class AgoraAlertButtonModel: NSObject {
public var titleLabel: AgoraAlertLabelModel?
public var tapActionBlock: ((_ index: Int) -> ())? = nil
}
@objcMembers public class AgoraAlertModel: NSObject {
public var style: AgoraAlertView.AgoraAlertStyle = .Alert
public var backgoundColor: UIColor = UIColor.clear
public var titleLabel: AgoraAlertLabelModel?
public var titleImage: AgoraAlertImageModel?
public var messageLabel: AgoraAlertLabelModel?
public var buttons: [AgoraAlertButtonModel]?
}
@objcMembers public class AgoraAlertView: AgoraBaseUIView {
public var styleModel: AgoraAlertModel? {
didSet {
self.updateView()
}
}
// 0.1
public var process: Float = 0 {
didSet {
if self.styleModel?.style == AgoraAlertView.AgoraAlertStyle.LineLoading {
let pView = self.lineProgressView.viewWithTag(ProgressTag) as! UIProgressView
if pView.progress >= self.process {
return
}
pView.setProgress(self.process, animated: true)
let pLabel = self.lineProgressView.viewWithTag(LabelTag) as! AgoraBaseUILabel
pLabel.text = "\(Int(self.process * 100))%"
}
}
}
fileprivate let LabelTag = 99
fileprivate let ProgressTag = 100
fileprivate lazy var bgView: AgoraBaseUIView = {
let v = AgoraBaseUIView()
v.backgroundColor = UIColor.black.withAlphaComponent(0.6)
return v
}()
fileprivate lazy var contentView: AgoraBaseUIView = {
let v = AgoraBaseUIView()
v.layer.backgroundColor = UIColor.white.cgColor
v.layer.cornerRadius = 20
v.layer.masksToBounds = true
v.clipsToBounds = false
v.layer.shadowColor = UIColor(rgb: 0x0E1F2F, alpha: 0.15).cgColor
v.layer.shadowOffset = CGSize(width: 0, height: 4)
v.layer.shadowOpacity = 1
v.layer.shadowRadius = 12
return v
}()
fileprivate lazy var titleLabel: AgoraBaseUILabel = {
let label = AgoraBaseUILabel()
label.textAlignment = .center
label.isHidden = true
return label
}()
fileprivate lazy var cycleView: AgoraCycleView = {
let v = AgoraCycleView(frame: .zero)
v.isHidden = true
return v
}()
fileprivate lazy var gifView: AgoraFLAnimatedImageView = {
var animatedImage: AgoraFLAnimatedImage?
if let bundle = Bundle.agoraUIEduBaseBundle() {
if let url = bundle.url(forResource: "loading", withExtension: "gif") {
let imgData = try? Data(contentsOf: url)
animatedImage = AgoraFLAnimatedImage.init(animatedGIFData: imgData)
}
}
let v = AgoraFLAnimatedImageView()
v.animatedImage = animatedImage
v.isHidden = true
return v
}()
fileprivate lazy var messageLabel: AgoraBaseUILabel = {
let label = AgoraBaseUILabel()
label.textAlignment = .center
label.isHidden = true
label.numberOfLines = 0
return label
}()
fileprivate lazy var lineProgressView: AgoraBaseUIView = {
let v = AgoraBaseUIView()
v.backgroundColor = UIColor.clear
v.isHidden = true
let label = AgoraBaseUILabel()
label.text = "0%"
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: AgoraKitDeviceAssistant.OS.isPad ? 14 : 12)
label.textColor = UIColor(rgb: 0x5471FE)
label.adjustsFontSizeToFitWidth = true
label.tag = LabelTag
v.addSubview(label)
label.agora_y = 0
label.agora_right = 0
if AgoraKitDeviceAssistant.OS.isPad {
label.agora_resize(30, 16)
} else {
label.agora_resize(28, 14)
}
let pView = UIProgressView(progressViewStyle: .bar)
pView.progressTintColor = UIColor(rgb: 0x5471FE)
pView.trackTintColor = UIColor(rgb: 0xF0F2F4)
pView.tag = ProgressTag
v.addSubview(pView)
pView.translatesAutoresizingMaskIntoConstraints = false
pView.agora_y = (label.agora_height - pView.frame.size.height) * 0.5
pView.agora_right = label.agora_right + label.agora_width + 8
pView.agora_x = 0
pView.agora_height = pView.frame.size.height
return v
}()
fileprivate lazy var btnView: AgoraBaseUIView = {
let v = AgoraBaseUIView()
v.backgroundColor = UIColor.clear
v.isHidden = true
return v
}()
public override init(frame: CGRect) {
super.init(frame: frame)
self.initView()
self.initLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func show(in view: UIView) {
self.contentView.alpha = 0
let transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
self.contentView.transform = transform
view.addSubview(self)
translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: view.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
view.layoutIfNeeded()
UIView.animate(withDuration: 0.55, delay: 0.2, usingSpringWithDamping: 0.3, initialSpringVelocity: 1.0, options: .curveEaseInOut) {[weak self] in
self?.contentView.alpha = 1
self?.contentView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
view.layoutIfNeeded()
} completion: { (_) in
}
}
// MARK: Touch
@objc fileprivate func buttonTap(_ btn: AgoraBaseUIButton) {
guard let btnModels = self.styleModel?.buttons, btn.tag < btnModels.count else {
return
}
UIView.animate(withDuration: 0.25) {
self.alpha = 0
} completion: { (_) in
self.removeFromSuperview()
btnModels[btn.tag].tapActionBlock?(btn.tag)
}
}
}
// MARK: Private
extension AgoraAlertView {
fileprivate func updateView() {
guard let model = self.styleModel else {
return
}
self.bgView.backgroundColor = model.backgoundColor
let ratio: CGFloat = 1.2
if model.style == .CircleLoading || model.style == .GifLoading {
self.contentView.agora_width = AgoraKitDeviceAssistant.OS.isPad ? 120 * ratio : 120
} else if model.style == .LineLoading {
self.contentView.agora_width = AgoraKitDeviceAssistant.OS.isPad ? 210 * ratio : 210
} else if model.style == .Alert {
self.contentView.agora_width = AgoraKitDeviceAssistant.OS.isPad ? 270 * ratio : 270
}
let SideVGap: CGFloat = self.titleLabel.agora_y
let SideHGap: CGFloat = self.titleLabel.agora_x
let MessageVGap: CGFloat = AgoraKitDeviceAssistant.OS.isPad ? 18 : 13
let LoadingViewSize = AgoraKitDeviceAssistant.OS.isPad ? CGSize(width: 60 * ratio, height: 60 * ratio) : CGSize(width: 60, height: 60)
// titleLabel
// default value for no title
var TitleBottom: CGFloat = SideVGap
self.titleLabel.isHidden = true
self.cycleView.isHidden = true
self.gifView.isHidden = true
if model.style == .CircleLoading {
self.cycleView.isHidden = false
self.cycleView.agora_y = SideVGap
self.cycleView.agora_center_x = 0
self.cycleView.agora_resize(model.titleImage?.width ?? LoadingViewSize.width, model.titleImage?.height ?? LoadingViewSize.height)
self.cycleView.progressTintColor(UIColor(rgb: 0xF0F2F4), to: UIColor(rgb: 0x5471FE))
self.cycleView.startAnimation()
TitleBottom = self.cycleView.agora_y + self.cycleView.agora_height + MessageVGap
} else if model.style == .GifLoading {
self.gifView.isHidden = false
let gitW = model.titleImage?.width ?? LoadingViewSize.width
let gitH = model.titleImage?.height ?? LoadingViewSize.height
let gitX = (self.contentView.agora_width - gitW) * 0.5
let gitY = SideVGap
self.gifView.frame = CGRect(x: gitX, y: gitY, width: gitW, height: gitH)
TitleBottom = gitY + gitH
} else if (model.titleImage != nil || model.titleLabel != nil) {
self.titleLabel.isHidden = false
var labelHeight: CGFloat = 0
var textArt: NSAttributedString?
if let labelModel = model.titleLabel {
self.titleLabel.font = labelModel.textFont
self.titleLabel.textColor = labelModel.textColor
let size = labelModel.text.agoraKitSize(font: labelModel.textFont, height: 25)
labelHeight = size.height
textArt = NSAttributedString(string: labelModel.text)
}
let attr = NSMutableAttributedString()
if let titleImage = model.titleImage {
let imageAttachment = NSTextAttachment()
let image = AgoraKitImage(titleImage.name)
imageAttachment.image = image
imageAttachment.bounds = CGRect(x: 0, y: -4, width: titleImage.width, height: titleImage.height)
let imgAttr = NSAttributedString(attachment: imageAttachment)
attr.append(imgAttr)
labelHeight = max(labelHeight, titleImage.height)
}
if let art = textArt {
attr.append(NSAttributedString(string: " "))
attr.append(art)
}
self.titleLabel.attributedText = attr
self.titleLabel.agora_height = labelHeight
TitleBottom = self.titleLabel.agora_y + self.titleLabel.agora_height + MessageVGap
}
// message
var MessageBottom: CGFloat = TitleBottom
self.messageLabel.isHidden = true
if let messageLabelModel = model.messageLabel {
self.messageLabel.isHidden = false
self.messageLabel.font = messageLabelModel.textFont
self.messageLabel.textColor = messageLabelModel.textColor
self.messageLabel.text = messageLabelModel.text
let size = messageLabelModel.text.agoraKitSize(font: messageLabelModel.textFont,
width: contentView.agora_width - SideHGap * 2)
self.messageLabel.agora_y = TitleBottom
self.messageLabel.agora_height = size.height
MessageBottom = self.messageLabel.agora_y + self.messageLabel.agora_height + MessageVGap
}
// lineLoading
var LineLoadingBottom: CGFloat = MessageBottom
self.lineProgressView.isHidden = true
if model.style == .LineLoading {
self.lineProgressView.isHidden = false
self.lineProgressView.agora_y = MessageBottom
if (model.buttons?.count ?? 0) > 0 {
LineLoadingBottom = self.lineProgressView.agora_y + self.lineProgressView.agora_height + MessageVGap
} else {
LineLoadingBottom = self.lineProgressView.agora_y + self.lineProgressView.agora_height + SideVGap
}
}
// btn & line
var btnViewBottom: CGFloat = LineLoadingBottom
self.btnView.isHidden = true
if let btnModels = model.buttons {
let btnSubs = self.btnView.subviews
btnSubs.forEach { (v) in
v.removeFromSuperview()
}
self.btnView.isHidden = false
self.btnView.agora_height = AgoraKitDeviceAssistant.OS.isPad ? 50 : 45
self.btnView.agora_y = btnViewBottom
btnViewBottom = LineLoadingBottom + self.btnView.agora_height
// line
let hLineV = AgoraBaseUIView()
hLineV.backgroundColor = UIColor(rgb: 0xEDEDED)
self.btnView.addSubview(hLineV)
hLineV.agora_move(0, 0)
hLineV.agora_right = 0
hLineV.agora_height = 1
// btns
let btnWidth: CGFloat = self.contentView.agora_width / CGFloat(btnModels.count)
for (index, btnModel) in btnModels.enumerated() {
let btn = AgoraBaseUIButton(type: .custom)
btn.tag = index
btn.addTarget(self, action: #selector(buttonTap(_ :)), for: .touchUpInside)
self.btnView.addSubview(btn)
btn.agora_move(CGFloat(index) * btnWidth, hLineV.agora_height)
btn.agora_width = btnWidth
btn.agora_bottom = 0
if (index != btnModels.count - 1) {
let vLineV = AgoraBaseUIView()
vLineV.backgroundColor = UIColor(rgb: 0xEDEDED)
self.btnView.addSubview(vLineV)
vLineV.agora_move(btn.agora_x + btn.agora_width - 1, 0)
vLineV.agora_width = 1
vLineV.agora_bottom = 0
}
if let btnTitleLabelModle = btnModel.titleLabel {
btn.setTitle(btnTitleLabelModle.text, for: .normal)
btn.setTitleColor(btnTitleLabelModle.textColor, for: .normal)
btn.titleLabel?.font = btnTitleLabelModle.textFont
} else {
continue
}
}
}
if model.style == .CircleLoading || model.style == .GifLoading {
self.contentView.agora_height = self.contentView.agora_width
} else {
self.contentView.agora_height = btnViewBottom
}
}
}
// MARK: Private--Init
extension AgoraAlertView {
fileprivate func initView() {
backgroundColor = .clear
self.addSubview(self.bgView)
self.addSubview(self.contentView)
self.contentView.addSubview(self.cycleView)
self.contentView.addSubview(self.gifView)
self.contentView.addSubview(self.titleLabel)
self.contentView.addSubview(self.messageLabel)
self.contentView.addSubview(self.lineProgressView)
self.contentView.addSubview(self.btnView)
}
fileprivate func initLayout() {
self.bgView.agora_move(0, 0)
self.bgView.agora_right = 0
self.bgView.agora_bottom = 0
self.contentView.agora_center_x = 0
self.contentView.agora_center_y = -30
self.contentView.agora_width = 1000
self.contentView.agora_height = 1000
let SideVGap: CGFloat = 25
let SideHGap: CGFloat = 10
let LineProgressHGap: CGFloat = 28
self.titleLabel.agora_x = SideHGap
self.titleLabel.agora_y = SideVGap
self.titleLabel.agora_height = 0
self.titleLabel.agora_right = SideHGap
self.messageLabel.agora_x = SideHGap
self.messageLabel.agora_right = SideHGap
self.messageLabel.agora_y = 0
self.messageLabel.agora_height = 0
let label = self.lineProgressView.viewWithTag(LabelTag) as! AgoraBaseUILabel
self.lineProgressView.agora_x = LineProgressHGap
self.lineProgressView.agora_right = LineProgressHGap
self.lineProgressView.agora_y = 0
self.lineProgressView.agora_height = label.agora_height
self.btnView.agora_x = 0
self.btnView.agora_right = 0
self.btnView.agora_height = 0
self.btnView.agora_y = 0
}
}
extension AgoraAlertView {
@objc public enum AgoraAlertStyle: Int {
/// UI类型:`加载`
case CircleLoading
/// UI类型:`加载`
case GifLoading
/// UI类型: `加载`
case LineLoading
/// UI类型:`有点击按钮的alert`
case Alert
}
}
| 37.08913 | 153 | 0.600199 |
64f9ab2e459c639091d869268a84f2d5b8f8732e | 976 | //
// Array.swift
// Steganographer
//
// Created by Łukasz Stachnik on 28/10/2021.
//
import Foundation
extension Array where Element: Equatable {
/// Replaces given element in array with new one
/// - Parameters:
/// - element: Element in array to replace
/// - new: New Element to which old will be replaced
///
/// **Example Usage**:
///
/// ```
/// let array = ["Apple", "Orange", "Banana"]
/// let replaced = array.replace("Apple", "Swift") // will change array to ["Swift", "Orange", "Banana"]
/// print(replaced) // will print True
/// ```
///
/// - Returns: True if replaced and False if not
@discardableResult
public mutating func replace(_ element: Element, with new: Element) -> Bool {
if let first = self.firstIndex(where: { $0 == element}) {
self[first] = new
return true
}
return false
}
}
| 27.885714 | 119 | 0.544057 |
8781bb58b3c5bca3b779c8fdb00c8f4e8c1a67e7 | 837 | //
// TYPEPersistenceStrategy.swift
//
import AmberBase
import Foundation
public class Dictionary_C_AffineTransform_Calendar_D_PersistenceStrategy: PersistenceStrategy
{
public var types: Types
{
return Types.generic("Dictionary", [Types.type("AffineTransform"), Types.type("Calendar")])
}
public func save(_ object: Any) throws -> Data
{
guard let typedObject = object as? Dictionary<AffineTransform, Calendar> else
{
throw AmberError.wrongTypes(self.types, AmberBase.types(of: object))
}
let encoder = JSONEncoder()
return try encoder.encode(typedObject)
}
public func load(_ data: Data) throws -> Any
{
let decoder = JSONDecoder()
return try decoder.decode(Dictionary<AffineTransform, Calendar>.self, from: data)
}
} | 27 | 99 | 0.673835 |
1e26dd60fa751d7e9796d50983ecfe3005a32aec | 448 | //
// OptimoveNotificationHandling.swift
// OptimoveSDK
import Foundation
import UserNotifications
protocol OptimoveNotificationHandling {
func didReceiveRemoteNotification(userInfo: [AnyHashable: Any],
didComplete:@escaping (UIBackgroundFetchResult) -> Void)
func didReceive(response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping (() -> Void))
}
| 29.866667 | 94 | 0.698661 |
f92ee0af24f3c97927230d4dfbf807381bd3ac9d | 12,693 | //
// KeyboardLabelButtonViewModel.swift
// FontasticKeyboard
//
// Created by Timofey Surkov on 27.09.2021.
//
import UIKit
// MARK: - Protocol
public enum KeyboardButtonContent {
case text(contentString: String?, displayString: String)
case systemIcon(normalIconName: String, highilightedIconName: String?)
}
public protocol KeyboardButtonViewModelProtocol {
var content: KeyboardButtonContent { get }
var didTapEvent: Event<KeyboardButtonContent> { get }
var shouldUpdateContentEvent: Event<Void> { get }
}
// MARK: - Implementations
public class DefaultKeyboardButtonVM: KeyboardButtonViewModelProtocol {
// MARK: - Public Instance Properties
public let content: KeyboardButtonContent
public let didTapEvent = Event<KeyboardButtonContent>()
public let shouldUpdateContentEvent = Event<Void>()
// MARK: - Initializers
public init(symbol: String) {
self.content = .text(contentString: symbol, displayString: symbol)
}
public init(symbol: String, displayString: String) {
self.content = .text(contentString: symbol, displayString: displayString)
}
public init(normalIconName: String, highlightedIconName: String?) {
self.content = .systemIcon(normalIconName: normalIconName, highilightedIconName: highlightedIconName)
}
}
public class CapitalizableKeyboardButtonVM: KeyboardButtonViewModelProtocol {
// MARK: - Public Instance Properties
public let didTapEvent = Event<KeyboardButtonContent>()
public let shouldUpdateContentEvent = Event<Void>()
public var content: KeyboardButtonContent { isCapitalized ? capitalizedContent : uncapitalizedContent }
// MARK: - Private Instance Properties
private let uncapitalizedContent: KeyboardButtonContent
private let capitalizedContent: KeyboardButtonContent
private var isCapitalized: Bool = false
// MARK: - Initializers
public init(
uncapitalizedSymbol: String,
capitalizedSymbol: String,
capitalizationSource: FonttasticTools.Event<Bool>
) {
self.uncapitalizedContent = .text(contentString: uncapitalizedSymbol, displayString: uncapitalizedSymbol)
self.capitalizedContent = .text(contentString: capitalizedSymbol, displayString: capitalizedSymbol)
capitalizationSource.subscribe(self) { [weak self] isCapitalized in
guard let self = self else { return }
self.isCapitalized = isCapitalized
self.shouldUpdateContentEvent.onNext(())
}
}
}
public class LatinSpaceKeyboardButtonVM: DefaultKeyboardButtonVM {
public init() {
super.init(symbol: " ", displayString: "space")
}
}
public class LatinReturnKeyboardButtonVM: DefaultKeyboardButtonVM {
public init() {
super.init(symbol: "\n", displayString: "return")
}
}
public class BackspaceKeyboardButtonVM: DefaultKeyboardButtonVM {
public init(shouldDeleteSymbolEvent: Event<Void>) {
super.init(normalIconName: "delete.left", highlightedIconName: "delete.left.fill")
self.didTapEvent.subscribe(shouldDeleteSymbolEvent) { [weak shouldDeleteSymbolEvent] _ in
shouldDeleteSymbolEvent?.onNext(())
}
}
}
public class AdvanceToNextInputButtonVM: DefaultKeyboardButtonVM {
public init(advanceToNextInputEvent: Event<Void>) {
super.init(normalIconName: "globe", highlightedIconName: "globe")
self.didTapEvent.subscribe(advanceToNextInputEvent) { [weak advanceToNextInputEvent] _ in
advanceToNextInputEvent?.onNext(())
}
}
}
public class CaseChangeKeyboardButtonVM: KeyboardButtonViewModelProtocol {
// MARK: - Nested Types
public enum State {
case lowercase
case uppercase
case uppercaseLocked
// MARK: - Instance Properties
var isCapitalized: Bool {
switch self {
case .lowercase:
return false
case .uppercase, .uppercaseLocked:
return true
}
}
}
// MARK: - Public Instance Properties
public var content: KeyboardButtonContent {
switch state {
case .lowercase:
return lowercaseContent
case .uppercase:
return uppercaseContent
case .uppercaseLocked:
return uppercaseLockedContent
}
}
public let didTapEvent = Event<KeyboardButtonContent>()
public let shouldUpdateContentEvent = Event<Void>()
public let isCapitalizedEvent = HotEvent<Bool>(value: false)
public var state: State = .lowercase {
didSet {
isCapitalizedEvent.onNext(state.isCapitalized)
shouldUpdateContentEvent.onNext(())
}
}
// MARK: - Private Instance Properties
private var shouldTurnIntoLockedStateWorkItem: DispatchWorkItem?
private var shouldTurnIntoLockedState: Bool = false
private let lowercaseContent: KeyboardButtonContent = .systemIcon(
normalIconName: "arrow.up",
highilightedIconName: "arrow.up"
)
private let uppercaseContent: KeyboardButtonContent = .systemIcon(
normalIconName: "arrow.up",
highilightedIconName: "arrow.up"
)
private let uppercaseLockedContent: KeyboardButtonContent = .systemIcon(
normalIconName: "arrow.up.to.line",
highilightedIconName: "arrow.up.to.line"
)
// MARK: - Initializers
public init(capitalizationSource: Event<Bool>, textInsertedSource: Event<String>) {
isCapitalizedEvent.subscribe(capitalizationSource) { [weak capitalizationSource] isCapitalized in
capitalizationSource?.onNext(isCapitalized)
}
textInsertedSource.subscribe(self) { [weak self] _ in
guard let self = self else { return }
if self.state == .uppercase {
self.state = .lowercase
}
}
didTapEvent.subscribe(self) { [weak self] _ in
guard let self = self else { return }
if let workItem = self.shouldTurnIntoLockedStateWorkItem {
workItem.cancel()
self.shouldTurnIntoLockedStateWorkItem = nil
}
let targetState: State
switch self.state {
case .lowercase:
targetState = .uppercase
self.shouldTurnIntoLockedState = true
let workItem = DispatchWorkItem { [weak self] in
self?.shouldTurnIntoLockedState = false
self?.shouldTurnIntoLockedStateWorkItem = nil
}
self.shouldTurnIntoLockedStateWorkItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + Constants.uppercaseLockTimeout, execute: workItem)
case .uppercase:
targetState = self.shouldTurnIntoLockedState ? .uppercaseLocked : .lowercase
self.shouldTurnIntoLockedState = false
case .uppercaseLocked:
targetState = .lowercase
self.shouldTurnIntoLockedState = false
}
self.state = targetState
}
}
}
public class PunctuationSetToggleKeyboardButtonVM: KeyboardButtonViewModelProtocol {
// MARK: - Public Instance Properties
public let didTapEvent = Event<KeyboardButtonContent>()
public let shouldUpdateContentEvent = Event<Void>()
public let content: KeyboardButtonContent
// MARK: - Initializers
public init(punctuationSet: KeyboardType.PunctuationSet, punctuationSetToggleEvent: Event<Void>) {
switch punctuationSet {
case .default:
self.content = .text(contentString: nil, displayString: "#+=")
case .alternative:
self.content = .systemIcon(normalIconName: "textformat.123", highilightedIconName: nil)
}
didTapEvent.subscribe(punctuationSetToggleEvent) { [weak punctuationSetToggleEvent] _ in
punctuationSetToggleEvent?.onNext(())
}
}
}
public class LanguageToggleKeyboardButtonVM: KeyboardButtonViewModelProtocol {
// MARK: - Public Instance Properties
public let didTapEvent = Event<KeyboardButtonContent>()
public let shouldUpdateContentEvent = Event<Void>()
public var content: KeyboardButtonContent {
switch lastUsedLanguage {
case .latin:
return latinLanguageContent
case .cyrillic:
return cyrillicLanguageContent
}
}
// MARK: - Private Instance Properties
private let latinLanguageContent = KeyboardButtonContent.text(contentString: nil, displayString: "EN")
private let cyrillicLanguageContent = KeyboardButtonContent.text(contentString: nil, displayString: "RU")
private var lastUsedLanguage: KeyboardType.Language = DefaultFontsService.shared.lastUsedLanguage
// MARK: - Initializers
public init(
lastUsedLanguageSource: Event<KeyboardType.Language>,
languageToggleEvent: Event<Void>
) {
didTapEvent.subscribe(languageToggleEvent) { [weak languageToggleEvent] _ in
languageToggleEvent?.onNext(())
}
lastUsedLanguageSource.subscribe(self) { [weak self] language in
guard let self = self else { return }
self.lastUsedLanguage = language
self.shouldUpdateContentEvent.onNext(())
}
}
}
// swiftlint:disable:next type_name
public class LanguagePunctuationToggleKeyboardButtonVM: KeyboardButtonViewModelProtocol {
// MARK: - Public Instance Properties
public let didTapEvent = Event<KeyboardButtonContent>()
public let shouldUpdateContentEvent = Event<Void>()
public let content: KeyboardButtonContent
// MARK: - Initializers
public init(keyboardType: KeyboardType, languagePunctuationToggleEvent: Event<Void>) {
switch keyboardType {
case .language:
self.content = .systemIcon(normalIconName: "textformat.123", highilightedIconName: nil)
case .punctuation:
self.content = .systemIcon(normalIconName: "abc", highilightedIconName: nil)
}
didTapEvent.subscribe(languagePunctuationToggleEvent) { [weak languagePunctuationToggleEvent] _ in
languagePunctuationToggleEvent?.onNext(())
}
}
}
public class TextAlignmentChangeButtonViewModel: KeyboardButtonViewModelProtocol {
// MARK: - Public Instance Properties
public var content: KeyboardButtonContent {
switch self.textAlignment {
case .center:
return centerAlignmentContent
case .left:
return leftAlignmentContent
case .right:
return rightAlignmentContent
default:
return centerAlignmentContent
}
}
public let didTapEvent = Event<KeyboardButtonContent>()
public let shouldUpdateContentEvent = Event<Void>()
public lazy var didChangeTextAligmentEvent = HotEvent<NSTextAlignment>(value: textAlignment)
public var textAlignment: NSTextAlignment {
didSet {
shouldUpdateContentEvent.onNext(())
didChangeTextAligmentEvent.onNext(textAlignment)
}
}
// MARK: - Private Instance Properties
private var shouldTurnIntoLockedStateWorkItem: DispatchWorkItem?
private var shouldTurnIntoLockedState: Bool = false
private let leftAlignmentContent: KeyboardButtonContent = .systemIcon(
normalIconName: "text.alignleft",
highilightedIconName: nil
)
private let centerAlignmentContent: KeyboardButtonContent = .systemIcon(
normalIconName: "text.aligncenter",
highilightedIconName: nil
)
private let rightAlignmentContent: KeyboardButtonContent = .systemIcon(
normalIconName: "text.alignright",
highilightedIconName: nil
)
// MARK: - Initializers
public init(textAlignment: NSTextAlignment) {
self.textAlignment = textAlignment
didTapEvent.subscribe(self) { [weak self] _ in
guard let self = self else { return }
let targetTextAlignment: NSTextAlignment
switch self.textAlignment {
case .center:
targetTextAlignment = .left
case .left:
targetTextAlignment = .right
case .right:
targetTextAlignment = .center
default:
targetTextAlignment = Constants.defaultTextAlignment
}
self.textAlignment = targetTextAlignment
}
}
}
private enum Constants {
static let defaultTextAlignment: NSTextAlignment = .center
static let uppercaseLockTimeout: TimeInterval = 0.3
}
| 31.653367 | 115 | 0.673363 |
39154492aa083e388eb9e8d09c81c274b471f40c | 10,456 | //
// ViewController.swift
// SVSwiftHelpers
//
// Created by sudhakar on 04/08/2021.
// Copyright (c) 2021 sudhakar. All rights reserved.
//
import UIKit
import SVSwiftHelpers
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK:- Colour
func colorExtensionExample() {
print(UIColor(r:255, g:255, b:255, a:255))
print(UIColor(hexString: "#00FF00") ?? .white)
navigationBarColor = .randomColour
}
//MARK:- ViewController
func viewControllerExtensionExample() {
/// Alert
showAlert("Title","Alert message", "OK")
/// Alert style can be alert or actionSheet for iPhone
showAlertMoreThanOneButton("Title", "message", style: .actionSheet, actions:
action("OK", preferredStyle: .default, action: { (action) in
print("Cicked OK")
}),
action("Cancel", preferredStyle: .cancel, action: { (action) in
print("Cicked Cancel")
}),
action("Delete", preferredStyle: .destructive, action: { (action) in
print("Cicked delete")
})
)
/// Alert style can be alert or actionSheet for ipad
showAlertMoreThanOneButton("Title", "message", style: .actionSheet, sender:button ,actions:
action("OK", preferredStyle: .default, action: { (action) in
print("Cicked OK")
}),
action("Cancel", preferredStyle: .cancel, action: { (action) in
print("Cicked Cancel")
}),
action("Delete", preferredStyle: .destructive, action: { (action) in
print("Cicked delete")
})
)
/// Navigation bar
self.navigationItem.leftBarButtonItem = leftBarButton
print(tabBarHeight)
print(navigationBarHeight)
/// Can use in any view controller
navigationTitleView(withTitle: "Title",titleFont: UIFont.systemFont(ofSize: 14))
navigationTitleView(withTitle: "Title",textColor: .blue)
navigationTitleView(withTitle: "Title", subTitle: "Sub Title")
navigationTitleView(withTitle: "Title", subTitle: "Sub Title",textColor :.red,titleFont: UIFont.systemFont(ofSize: 14))
/// Set navigation bar colour
navigationBarColor = .randomColour
presentVC(ViewController())
pushVC(ViewController())
popVC()
popToRootVC()
dismissVC { }
/// Activity IndicatorView can be show in any view controller
startActivityIndicator()
/// can Show at any point in view
startActivityIndicator(CGPoint(x: 10, y: 10))
stopActivityIndicator()
/// Open Safari
openSFSafariVC(WithURL: "http://www.google.com")
openSFSafariVC(WithURL: "http://www.google.com", barTint: .green)
}
//MARK:- Array
func arrayExtensionExample() {
let array = [1,2,3]
print(array.get(at: 1) ?? "")
print(array.random() ?? "")
print(array.repeated(count: 1))
}
//MARK:- String
func stringExtensionExample() {
print("sudhakar".base64)
print("sudhakar".length)
print("9899898898".isValidMobileNumber)
print("[email protected]".isValidEmail)
print("http://www.google.com".isValidUrl)
print("sudhakar ".trim)
print("<null>".validateEmptyString)
print("sudhakar http://www.google.com , http://www.facebook.com".extractURLs)
print("hello/there".split("/"))
print("sudhakar".countofWords)
print("sudhakar kjdh ksadh lash dljhal kda".countofParagraphs)
print("sudhakar".countofWords)
print("20".toInt ?? "")
print("20".toFloat ?? "")
print("20".toDouble ?? "")
print("true".toBool ?? "")
print("sudhakar".getIndexOf("a") ?? "")
print("sudhakar".bold)
print("sudhakar".italic)
print("sudhakar".underline)
print("sudhakar".height(view.frame.size.width, font: .systemFont(ofSize: 14), lineBreakMode: .byWordWrapping))
print("sudhakar".color(.red))
print("sudhakar Dasari".colorSubString("Dasari", color: .blue))
print("http://www.google.com ".urlEncoded)
}
//MARK:- Date
func dateExtensionExample() {
let stringToDate = Date(fromString: "10-11-2020")
print(stringToDate ?? Date())
let httpsStringToDate = Date(httpDateString: "10-11-2020")
print(httpsStringToDate ?? Date())
let dateToString = Date().toString(format: "yyyy-MM-dd")
print(dateToString)
print(httpsStringToDate?.timeAgoSinceDate ?? "")
print(httpsStringToDate?.daysInBetweenDate(Date()) ?? "")
print(httpsStringToDate?.hoursInBetweenDate(Date()) ?? "")
print(httpsStringToDate?.minutesInBetweenDate(Date()) ?? "")
print(httpsStringToDate?.secondsInBetweenDate(Date()) ?? "")
print(httpsStringToDate?.hoursInBetweenDate(Date()) ?? "")
print(httpsStringToDate?.years(from: Date()) ?? "")
print(httpsStringToDate?.months(from: Date()) ?? "")
print(httpsStringToDate?.weeks(from: Date()) ?? "")
print(httpsStringToDate?.days(from: Date()) ?? "")
print(httpsStringToDate?.hours(from: Date()) ?? "")
print(httpsStringToDate?.minutes(from: Date()) ?? "")
print(httpsStringToDate?.seconds(from: Date()) ?? "")
print(httpsStringToDate?.offset(from: Date()) ?? "")
print(httpsStringToDate?.timeAgoSinceDate ?? "")
print(httpsStringToDate?.isFuture ?? false)
print(httpsStringToDate?.isPast ?? false)
print(httpsStringToDate?.isToday ?? false)
print(httpsStringToDate?.isYesterday ?? false)
print(httpsStringToDate?.isTomorrow ?? false)
print(httpsStringToDate?.isThisMonth ?? false)
print(httpsStringToDate?.isThisWeek ?? false)
print(httpsStringToDate?.isPast ?? false)
print(httpsStringToDate?.isPast ?? false)
print(httpsStringToDate?.isPast ?? false)
print(httpsStringToDate?.era ?? "")
print(httpsStringToDate?.year ?? "")
print(httpsStringToDate?.month ?? "")
print(httpsStringToDate?.day ?? "")
print(httpsStringToDate?.hour ?? "")
print(httpsStringToDate?.minute ?? "")
print(httpsStringToDate?.second ?? "")
print(httpsStringToDate?.nanosecond ?? "")
print(httpsStringToDate?.weekday ?? "")
print(httpsStringToDate?.monthAsString ?? "")
print(Date().changeDaysBy(days: 5))
print(Date().from(year: 1, month: 1, day: 1) ?? "")
}
//MARK:- App
func appHelperExample() {
/// Get all your app details
print(App.macAddress ?? "")
print(App.name ?? "")
print(App.version ?? "")
print(App.formattedNameAndVersion ?? "")
print(App.systemVersion ?? "")
}
//MARK:- UIView
func viewExtensionExample() {
let sampleView = UIView(x: 1, y: 1, w: 1, h: 1)
sampleView.addSubviews([UIView(),UIView()])
print(sampleView.x) // get
sampleView.x = 10 // set
sampleView.roundView()
sampleView.roundCorners([.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner], radius: 1.0)
sampleView.setCornerRadius(radius: 3.0)
sampleView.addShadow(offset: CGSize(width: 0, height: 1.0), radius: 1.0, color: .black, opacity: 1.0)
sampleView.addBorder(width: 1.0, color: .red)
sampleView.drawCircle(fillColor: .white, strokeColor: .red, strokeWidth: 0.5)
sampleView.drawStroke(width: 1.0, color: .red)
}
//MARK:- UserDefaults
func userdefaultsExtensionExample() {
//setter
UserDefaults.standard["sudhakar"] = "name"
// Getter
let name = UserDefaults.standard["name"]
print(name!)
if UserDefaults.standard.valueExists(forKey: "name") {
print("value exits")
}
UserDefaults.standard.archive(object: [:], forKey: "data")
print(UserDefaults.standard.unarchivedObject(forKey: "data") as? [String:Any] ?? [:])
}
//MARK:- UITextField
func textFieldExtensionExample() {
let textField = UITextField(x: 10, y: 150, w: 100, h: 44, fontSize: 16)
textField.borderStyle = .roundedRect
self.view.addSubview(textField)
textField.addLeftTextPadding(5.0)
textField.addLeftIcon(nil, frame: CGRect(x: 10, y: 10, width: 10, height: 10), imageSize: CGSize(width: 10, height: 10))
textField.addRightIcon(nil, frame: CGRect(x: 10, y: 10, width: 10, height: 10), imageSize: CGSize(width: 10, height: 10))
textField.enablePasswordToggle()
}
//MARK:- UILabel
func labelExtensionExample() {
let label = UILabel(x: 0, y: 0, w: 100, h: 200)
label.set(image: UIImage(named: "image")!, with: "Hello world")
}
//MARK:- UIImageView
func imageViewExtensionExample() {
let imageView = UIImageView(x: 0, y: 0, w: 120, h: 100)
imageView.image = imageView.changeImageColor(color: .red)
}
//MARK:- UIFont
func fontExtensionExample() {
let font = UIFont.Font(name: .Helvetica, type: .Light, size: 14)
print(font)
let customFont = UIFont.customFont(name: "fontname", type: .Light, size: 12)
print(customFont)
}
}
| 35.808219 | 135 | 0.553845 |
d727021acd04d4ac31904b2b0a208c7e46f81b33 | 2,522 | //
// GYNoticeViewCell.swift
// RollingNotice-Swift
//
// Created by qm on 2017/12/14.
// Copyright © 2017年 qm. All rights reserved.
//
import UIKit
let GYRollingDebugLog = false
open class GYNoticeViewCell: UIView {
open private(set) lazy var contentView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
self.addSubview(view)
isAddedContentView = true
return view
}()
open private(set) lazy var textLabel: UILabel = {
let lab = UILabel()
self.contentView.addSubview(lab)
return lab
}()
@objc open private(set) var reuseIdentifier: String?
fileprivate var isAddedContentView = false
/// leading >= 0
open var textLabelLeading: CGFloat
/// trailing >= 0
open var textLabelTrailing: CGFloat
public required init(reuseIdentifier: String?, textLabelLeading: CGFloat = 10, textLabelTrailing: CGFloat = 10){
self.textLabelLeading = textLabelLeading
self.textLabelTrailing = textLabelTrailing
self.reuseIdentifier = reuseIdentifier
super.init(frame: .zero)
if GYRollingDebugLog {
print(String(format: "init a cell from code: %p", self))
}
setupInitialUI()
}
public required init?(coder aDecoder: NSCoder){
self.textLabelLeading = 10
self.textLabelTrailing = 10
super.init(coder: aDecoder)
if GYRollingDebugLog {
print(String(format: "init a cell from xib: %p", self))
}
}
override open func layoutSubviews() {
super.layoutSubviews()
if isAddedContentView {
self.contentView.frame = self.bounds
var lead = textLabelLeading
if lead < 0 {
lead = 0
}
var trai = textLabelTrailing
if trai < 0 {
trai = 0
}
var width = self.frame.size.width - lead - trai
if width < 0 {
width = 0
}
self.textLabel.frame = CGRect(x: lead, y: 0, width: width, height: self.frame.size.height)
}
}
deinit {
if GYRollingDebugLog {
print(String(format: "cell deinit %p", self))
}
}
}
extension GYNoticeViewCell{
fileprivate func setupInitialUI() {
self.backgroundColor = UIColor.white
}
}
| 24.72549 | 116 | 0.559873 |
ef75ec60a155442e98f44756d7da636116d68a0a | 41 | enum Secrets {
static let apiKey = ""
}
| 10.25 | 23 | 0.634146 |
1659bb2a43cf941fa8d77fa2696d9eae3bc4fb05 | 3,152 | //
// ConstraintsHelper.swift
// TestCollectionView
//
// Created by Alex K. on 05/05/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
struct ConstraintInfo {
var attribute: NSLayoutAttribute = .Left
var secondAttribute: NSLayoutAttribute = .NotAnAttribute
var constant: CGFloat = 0
var identifier: String?
var relation: NSLayoutRelation = .Equal
}
infix operator >>>- { associativity left precedence 150 }
func >>>- <T: UIView> (left: (T, T), @noescape block: (inout ConstraintInfo) -> ()) -> NSLayoutConstraint {
var info = ConstraintInfo()
block(&info)
info.secondAttribute = info.secondAttribute == .NotAnAttribute ? info.attribute : info.secondAttribute
let constraint = NSLayoutConstraint(item: left.1,
attribute: info.attribute,
relatedBy: info.relation,
toItem: left.0,
attribute: info.secondAttribute,
multiplier: 1,
constant: info.constant)
constraint.identifier = info.identifier
left.0.addConstraint(constraint)
return constraint
}
func >>>- <T: UIView> (left: T, @noescape block: (inout ConstraintInfo) -> ()) -> NSLayoutConstraint {
var info = ConstraintInfo()
block(&info)
let constraint = NSLayoutConstraint(item: left,
attribute: info.attribute,
relatedBy: info.relation,
toItem: nil,
attribute: info.attribute,
multiplier: 1,
constant: info.constant)
constraint.identifier = info.identifier
left.addConstraint(constraint)
return constraint
}
func >>>- <T: UIView> (left: (T, T, T), @noescape block: (inout ConstraintInfo) -> ()) -> NSLayoutConstraint {
var info = ConstraintInfo()
block(&info)
info.secondAttribute = info.secondAttribute == .NotAnAttribute ? info.attribute : info.secondAttribute
let constraint = NSLayoutConstraint(item: left.1,
attribute: info.attribute,
relatedBy: info.relation,
toItem: left.2,
attribute: info.secondAttribute,
multiplier: 1,
constant: info.constant)
constraint.identifier = info.identifier
left.0.addConstraint(constraint)
return constraint
}
// MARK: UIView
extension UIView {
func addScaleToFillConstratinsOnView(view: UIView) {
[NSLayoutAttribute.Left, .Right, .Top, .Bottom].forEach { attribute in
(self, view) >>>- { $0.attribute = attribute }
}
}
func getConstraint(attributes: NSLayoutAttribute) -> NSLayoutConstraint? {
return constraints.filter {
if $0.firstAttribute == attributes && $0.secondItem == nil {
return true
}
return false
}.first
}
}
| 34.26087 | 110 | 0.560596 |
bb8d5306bbb475c62a6bc9cdb96d9a1ebbdcb2fe | 6,530 | /// Converts `Data` to `[String: URLEncodedFormData]`.
internal struct URLEncodedFormParser {
let omitEmptyValues: Bool
let omitFlags: Bool
/// Create a new form-urlencoded data parser.
init(omitEmptyValues: Bool = false, omitFlags: Bool = false) {
self.omitEmptyValues = omitEmptyValues
self.omitFlags = omitFlags
}
func parse(_ encoded: String) throws -> [String: URLEncodedFormData] {
guard let data = encoded.replacingOccurrences(of: "+", with: " ").removingPercentEncoding else {
throw URLEncodedFormError(identifier: "percentDecoding", reason: "Could not percent decode string value: \(encoded)")
}
var decoded: [String: URLEncodedFormData] = [:]
for pair in data.split(separator: "&") {
let data: URLEncodedFormData
let key: URLEncodedFormEncodedKey
/// Allow empty subsequences
/// value= => "value": ""
/// value => "value": true
let token = pair.split(
separator: "=",
maxSplits: 1, // max 1, `foo=a=b` should be `"foo": "a=b"`
omittingEmptySubsequences: false
)
guard let rawKey = token.first else {
throw URLEncodedFormError(
identifier: "percentDecoding",
reason: "Could not percent decode string key: \(token[0])"
)
}
let rawValue = token.last
if token.count == 2 {
if omitEmptyValues && token[1].count == 0 {
continue
}
guard let decodedValue = rawValue?.removingPercentEncoding else {
throw URLEncodedFormError(identifier: "percentDecoding", reason: "Could not percent decode string value: \(token[1])")
}
key = try parseKey(string: rawKey)
data = .string(decodedValue)
} else if token.count == 1 {
if omitFlags {
continue
}
key = try parseKey(string: rawKey)
data = "true"
} else {
throw URLEncodedFormError(
identifier: "malformedData",
reason: "Malformed form-urlencoded data encountered"
)
}
let resolved: URLEncodedFormData
if !key.path.isEmpty {
var current = decoded[key.name] ?? .dictionary([:])
self.set(¤t, to: data, at: key.path)
resolved = current
} else {
resolved = data
}
decoded[key.name] = resolved
}
return decoded
}
/// Parses a `URLEncodedFormEncodedKey` from `Data`.
private func parseKey(string: Substring) throws -> URLEncodedFormEncodedKey {
let name: Substring
let path: [URLEncodedFormEncodedSubKey]
// check if the key has `key[]` or `key[5]`
if string.hasSuffix("]") {
// split on the `[`
// a[b][c][d][hello] => a, b], c], d], hello]
let slices = string.split(separator: "[")
guard slices.count > 0 else {
throw URLEncodedFormError(identifier: "malformedKey", reason: "Malformed form-urlencoded key encountered.")
}
name = slices[0]
path = slices[1...].map { subKey in
if subKey.first == "]" {
return .array
} else {
return .dictionary(subKey.dropLast().removingPercentEncoding!)
}
}
} else {
name = string
path = []
}
return URLEncodedFormEncodedKey(name: name.removingPercentEncoding!, path: path)
}
/// Sets mutable form-urlencoded input to a value at the given `[URLEncodedFormEncodedSubKey]` path.
private func set(_ base: inout URLEncodedFormData, to data: URLEncodedFormData, at path: [URLEncodedFormEncodedSubKey]) {
guard path.count >= 1 else {
base = data
return
}
let first = path[0]
var child: URLEncodedFormData
switch path.count {
case 1:
child = data
case 2...:
switch first {
case .array:
/// always append to the last element of the array
child = base.array?.last ?? .array([])
set(&child, to: data, at: Array(path[1...]))
case .dictionary(let key):
child = base.dictionary?[key] ?? .dictionary([:])
set(&child, to: data, at: Array(path[1...]))
}
default: fatalError()
}
switch first {
case .array:
if case .array(var arr) = base {
/// always append
arr.append(child)
base = .array(arr)
} else {
base = .array([child])
}
case .dictionary(let key):
if case .dictionary(var dict) = base {
dict[key] = child
base = .dictionary(dict)
} else {
base = .dictionary([key: child])
}
}
}
}
// MARK: Key
/// Represents a key in a URLEncodedForm.
private struct URLEncodedFormEncodedKey {
let name: String
let path: [URLEncodedFormEncodedSubKey]
}
/// Available subkeys.
private enum URLEncodedFormEncodedSubKey {
case array
case dictionary(String)
}
// MARK: Utilities
//
//private extension Data {
// /// UTF8 decodes a Stirng or throws an error.
// func utf8DecodedString() throws -> String {
// guard let string = String(data: self, encoding: .utf8) else {
// throw URLEncodedFormError(identifier: "utf8Decoding", reason: "Failed to utf8 decode string: \(self)")
// }
//
// return string
// }
//}
//
//private extension Data {
// /// Percent decodes a String or throws an error.
// func percentDecodedString() throws -> String {
// let utf8 = try utf8DecodedString()
//
// guard let decoded = utf8.replacingOccurrences(of: "+", with: " ").removingPercentEncoding else {
// throw URLEncodedFormError(
// identifier: "percentDecoding",
// reason: "Failed to percent decode string: \(self)"
// )
// }
//
// return decoded
// }
//}
| 33.834197 | 138 | 0.52343 |
796213c077f5e76e52ad710d5d290535091ed936 | 3,739 | //
// EthereumLog.swift
// web3swift
//
// Created by Matt Marshall on 09/03/2018.
// Copyright © 2018 Argent Labs Limited. All rights reserved.
//
import Foundation
import BigInt
public struct EthereumLog: Equatable {
public let logIndex: BigUInt?
public let transactionIndex: BigUInt?
public let transactionHash: String?
public let blockHash: String?
public let blockNumber: EthereumBlock
public let address: EthereumAddress
public var data: String
public var topics: [String]
public let removed: Bool?
}
extension EthereumLog: Codable {
enum CodingKeys: String, CodingKey {
case removed // Bool
case logIndex // Quantity or null
case transactionIndex // Quantity or null
case transactionHash // Data or null
case blockHash // Data or null
case blockNumber // Data or null
case address // Data
case data // Data
case topics // Array of Data
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.removed = try values.decodeIfPresent(Bool.self, forKey: .removed)
self.address = try values.decode(EthereumAddress.self, forKey: .address)
self.data = try values.decode(String.self, forKey: .data)
self.topics = try values.decode([String].self, forKey: .topics)
if let logIndexString = try? values.decode(String.self, forKey: .logIndex), let logIndex = BigUInt(hex: logIndexString) {
self.logIndex = logIndex
} else {
self.logIndex = nil
}
if let transactionIndexString = try? values.decode(String.self, forKey: .transactionIndex), let transactionIndex = BigUInt(hex: transactionIndexString) {
self.transactionIndex = transactionIndex
} else {
self.transactionIndex = nil
}
self.transactionHash = try? values.decode(String.self, forKey: .transactionHash)
self.blockHash = try? values.decode(String.self, forKey: .blockHash)
if let blockNumberString = try? values.decode(String.self, forKey: .blockNumber) {
self.blockNumber = EthereumBlock(rawValue: blockNumberString)
} else {
self.blockNumber = EthereumBlock.Earliest
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(self.removed, forKey: .removed)
if let bytes = self.logIndex?.web3.bytes {
try? container.encode(String(bytes: bytes).web3.withHexPrefix, forKey: .logIndex)
}
if let bytes = self.transactionIndex?.web3.bytes {
try? container.encode(String(bytes: bytes).web3.withHexPrefix, forKey: .transactionIndex)
}
try? container.encode(self.transactionHash, forKey: .transactionHash)
try? container.encode(self.blockHash, forKey: .blockHash)
try container.encode(self.blockNumber.stringValue, forKey: .blockNumber)
try container.encode(self.address, forKey: .address)
try container.encode(self.data, forKey: .data)
try container.encode(self.topics, forKey: .topics)
}
}
extension EthereumLog: Comparable {
public static func < (lhs: EthereumLog, rhs: EthereumLog) -> Bool {
if lhs.blockNumber == rhs.blockNumber,
let lhsIndex = lhs.logIndex,
let rhsIndex = rhs.logIndex {
return lhsIndex < rhsIndex
}
return lhs.blockNumber < rhs.blockNumber
}
}
| 37.019802 | 161 | 0.634394 |
d9264b62b541bd9488b7fe84a063c11d2d013b61 | 2,888 | //
// VBaseButtonDemoView.swift
// VComponentsDemo
//
// Created by Vakhtang Kontridze on 12/23/20.
//
import SwiftUI
import VComponents
// MARK:- V Base Button Demo View
struct VBaseButtonDemoView: View {
// MARK: Properties
static let navBarTitle: String = "Base Buton"
@State private var clickState: ClickState = .prompt
@State private var pressState: PressState = .none
}
// MARK:- Body
extension VBaseButtonDemoView {
var body: some View {
VBaseView(title: Self.navBarTitle, content: {
DemoView(component: component)
})
}
private func component() -> some View {
ZStack(content: {
textView(title: clickState.promptDescription, color: ColorBook.primary)
.frame(maxHeight: .infinity, alignment: .top)
.padding(.top, 15)
VStack(spacing: 20, content: {
textView(title: clickState.description, color: ColorBook.secondary)
VBaseButton(isEnabled: true, action: action, onPress: pressAction, content: {
Circle()
.frame(dimension: 200)
.foregroundColor(Color.pink.opacity(pressState.buttonOpacity))
})
textView(title: pressState.description, color: ColorBook.secondary)
})
})
}
private func textView(title: String, color: Color) -> some View {
VText(
type: .oneLine,
font: .system(size: 16, weight: .semibold),
color: color,
title: title
)
.frame(height: 20)
}
}
// MARK:- Actions
private extension VBaseButtonDemoView {
func action() {
clickState = .clicked
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { clickState = .prompt })
}
func pressAction(isPressed: Bool) {
switch isPressed {
case false: pressState = .none
case true: pressState = .pressed
}
}
}
// MARK:- Helpers
private enum ClickState {
case prompt
case clicked
var promptDescription: String {
"Click on circle"
}
var description: String {
switch self {
case .prompt: return ""
case .clicked: return "You clicked on circle"
}
}
}
private enum PressState {
case none
case pressed
var description: String {
switch self {
case .none: return ""
case .pressed: return "You are pressing on circle"
}
}
var buttonOpacity: Double {
switch self {
case .none: return 1
case .pressed: return 0.75
}
}
}
// MARK:- Preview
struct VBaseButtonDemoView_Previews: PreviewProvider {
static var previews: some View {
VBaseButtonDemoView()
}
}
| 24.896552 | 94 | 0.567521 |
cc9c23a6d669d3692d92cf736e8917c0f7059526 | 2,566 | //
// AdaptyProduct.swift
// RNAdapty
//
// Created by Ivan on 12.07.2021.
//
import Adapty
import Foundation
struct AdaptyProductIos: Encodable {
let discounts: [AdaptyProductDiscount]
let isFamilyShareable: Bool
let promotionalOfferId: String?
let subscriptionGroupIdentifier: String?
let localizedSubscriptionPeriod: String?
let regionCode: String?
let promotionalOfferEligibility: Bool
}
struct AdaptyProduct: Encodable {
let vendorProductId: String
let variationId: String?
let introductoryOfferEligibility: Bool
let paywallABTestName: String?
let paywallName: String?
let localizedDescription: String
let localizedTitle: String
let price: Decimal
let currencyCode: String?
let currencySymbol: String?
let regionCode: String?
let subscriptionPeriod: AdaptySubscriptionPeriod?
let introductoryDiscount: AdaptyProductDiscount?
let localizedPrice: String?
let ios: AdaptyProductIos
init(_ product: ProductModel, _ paywallVariationId: String?) {
vendorProductId = product.vendorProductId
introductoryOfferEligibility = product.introductoryOfferEligibility
paywallABTestName = product.paywallABTestName
paywallName = product.paywallName
localizedDescription = product.localizedDescription
localizedTitle = product.localizedTitle
price = product.price
currencyCode = product.currencyCode
currencySymbol = product.currencySymbol
regionCode = product.regionCode
localizedPrice = product.localizedPrice
variationId = paywallVariationId
if let productSubscriptionPeriod = product.subscriptionPeriod {
subscriptionPeriod = AdaptySubscriptionPeriod.init(productSubscriptionPeriod)
} else {
subscriptionPeriod = nil
}
if let productIntroDiscount = product.introductoryDiscount {
introductoryDiscount = AdaptyProductDiscount.init(productIntroDiscount)
} else {
introductoryDiscount = nil
}
ios = AdaptyProductIos(
discounts: product.discounts.map {AdaptyProductDiscount.init($0) },
isFamilyShareable: product.isFamilyShareable,
promotionalOfferId: product.promotionalOfferId,
subscriptionGroupIdentifier: product.subscriptionGroupIdentifier,
localizedSubscriptionPeriod: product.localizedSubscriptionPeriod,
regionCode: product.regionCode,
promotionalOfferEligibility: product.promotionalOfferEligibility
)
}
}
| 32.897436 | 92 | 0.72915 |
db292a57feb58c2e6841398412e477c4cd56eb8e | 985 | //
// WelcomeViewController.swift
// GifMaker_Swift_Template
//
// Created by Admin on 2018/11/13.
// Copyright © 2018 Gabrielle Miller-Messner. All rights reserved.
//
import UIKit
class WelcomeViewController: UIViewController {
@IBOutlet weak var gifImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let testGifImage = UIImage.gif(name:"tinaFeyHiFive")
gifImageView.image = testGifImage
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 25.921053 | 106 | 0.678173 |
5b881cb632652377148f57635f884e49305c5f55 | 1,534 | //
// GDAXChange.swift
// GDAXSocketSwift
//
// Created by Hani Shabsigh on 10/29/17.
// Copyright © 2017 Hani Shabsigh. All rights reserved.
//
import Foundation
open class GDAXChange: GDAXProductSequenceTimeMessage {
public let orderId: String
public let newSize: Double?
public let oldSize: Double?
public let newFunds: Double?
public let oldFunds: Double?
public let price: Double
public let side: GDAXSide
public required init(json: [String: Any]) throws {
guard let orderId = json["order_id"] as? String else {
throw GDAXError.responseParsingFailure("order_id")
}
let newSize = Double(json["new_size"] as? String ?? "")
let oldSize = Double(json["old_size"] as? String ?? "")
let newFunds = Double(json["new_funds"] as? String ?? "")
let oldFunds = Double(json["old_funds"] as? String ?? "")
guard let price = Double(json["price"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("price")
}
guard let side = GDAXSide(rawValue: json["side"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("side")
}
self.orderId = orderId
self.newSize = newSize
self.oldSize = oldSize
self.newFunds = newFunds
self.oldFunds = oldFunds
self.price = price
self.side = side
try super.init(json: json)
}
}
| 28.407407 | 81 | 0.584094 |
90b9070b6c2802ffc35ff1de71a96b30912675b8 | 1,275 | //
// AWSDKError_Server.swift
// AWError
//
// Copyright © 2016 VMware, Inc. All rights reserved. This product is protected
// by copyright and intellectual property laws in the United States and other
// countries as well as by international treaties. VMware products are covered
// by one or more patents listed at http://www.vmware.com/go/patents.
//
import Foundation
public extension AWError.SDK {
enum Server: AWSDKErrorType {
case pageNotFound
case unavailable
case unexpectedServerResponse
case responseBodyMissing
case serverResponseError
}
}
public extension AWError.SDK.Server {
var code: Int {
switch self {
case .pageNotFound:
return 404
case .unavailable:
return 503
default:
return _code
}
}
var errorDescription: String {
switch self {
case .pageNotFound: return "http response code 404"
case .unavailable: return "http response code 503"
case .unexpectedServerResponse: return "i.e. not a 200"
case .responseBodyMissing: return "error in response body"
default: return String(describing: self)
}
}
}
| 28.977273 | 80 | 0.624314 |
f558a51ecaad7b1d63b184534ab09554c85976aa | 9,054 | //
// IAPDialogCell.swift
// IAPKit
//
// Copyright (c) 2018 Black Pixel.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class IAPDialogCell: UICollectionViewCell {
// MARK: Static Properties
static var identifier: String { return String(describing: self) }
// MARK: Outlets
@IBOutlet private weak var cellBackground: UIView!
@IBOutlet private weak var cellBorder: UIView!
@IBOutlet private weak var cellDescription: UILabel!
@IBOutlet private weak var cellPrice: UILabel!
@IBOutlet private weak var cellTitle: UILabel!
@IBOutlet private weak var titleStackView: UIStackView!
// MARK: Constraints
@IBOutlet private weak var cellDescriptionTopToPriceConstraint: NSLayoutConstraint!
@IBOutlet private weak var descriptionBottomConstraint: NSLayoutConstraint!
@IBOutlet private weak var titleStackTopConstraint: NSLayoutConstraint!
// MARK: Private Constants
fileprivate static let descriptionToPricePaddingRegular = CGFloat(8)
fileprivate static let descriptionToPricePaddingCompact = CGFloat(2)
fileprivate static let descriptionBottomPaddingRegular = CGFloat(30.0)
fileprivate static let descriptionBottomPaddingCompact = CGFloat(20.0)
fileprivate static let iPhoneLandscapeCellSize = CGSize(width: 375, height: 172)
fileprivate static let titleStackViewSpacingCompact = CGFloat(10.0)
fileprivate static let titleStackViewSpacingRegular = CGFloat(12.0)
fileprivate static let textSidePadding = CGFloat(25.0)
fileprivate static let titleTopPaddingRegular = CGFloat(28.0)
fileprivate static let titleTopPaddingCompact = CGFloat(20.0)
// MARK: Public Computed Properties
var selectedColor: IAPColor? {
didSet {
cellBorder.backgroundColor = selectedColor
}
}
// MARK: Public Properties
var selectedTitleColor: IAPColor?
// MARK: Public Property Overrides
override var isSelected: Bool {
didSet {
if !isSelected {
cellBorder.alpha = 0
cellTitle.textColor = .labelColor
} else {
cellBorder.alpha = 1
let titleColor = selectedTitleColor ?? .baseColor
cellTitle.textColor = titleColor
}
}
}
// MARK: Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
}
// MARK: - Class
extension IAPDialogCell {
class func registerNib(withCollectionView collection: UICollectionView) {
let bundle = Bundle(identifier: "com.blackpixel.IAP-iOS")
let nib = UINib(nibName: identifier, bundle: bundle)
collection.register(nib, forCellWithReuseIdentifier: identifier)
}
class func size(forStoreProduct product: StoreProduct, collectionWidth width: CGFloat) -> CGSize {
let showLandscapeCellSize = UIApplication.isLandscape() && !UIApplication.isIPad()
let isCompact = UIApplication.shouldShowCompactView
guard !showLandscapeCellSize else { return IAPDialogCell.iPhoneLandscapeCellSize }
let gutter = isCompact ? IAPDialogViewController.gutterPaddingCompact : IAPDialogViewController.gutterPaddingRegular
let cellWidth = width - (gutter * 2)
let textSize = CGSize(width: cellWidth - (IAPDialogCell.textSidePadding * 2), height: CGFloat.greatestFiniteMagnitude)
let title = NSAttributedString(string: product.skProduct.localizedTitle, attributes: [NSAttributedString.Key.font: UIFont.titleFont])
let titleHeight = ceil(title.boundingRect(with: textSize, options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil).height)
let description = NSAttributedString(string: product.marketingMessage, attributes: [NSAttributedString.Key.font: UIFont.descriptionFont])
let descriptionHeight = ceil(description.boundingRect(with: textSize, options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil).height)
guard isCompact else {
let cellHeight = IAPDialogCell.titleTopPaddingRegular + titleHeight + IAPDialogCell.descriptionToPricePaddingRegular + descriptionHeight + IAPDialogCell.descriptionBottomPaddingRegular
return CGSize(width: cellWidth, height: cellHeight)
}
let price = NSAttributedString(string: product.skProduct.price.stringValue, attributes: [NSAttributedString.Key.font: UIFont.priceFont])
let priceHeight = ceil(price.boundingRect(with: textSize, options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil).height)
let cellHeight = IAPDialogCell.titleTopPaddingRegular + titleHeight + IAPDialogCell.titleStackViewSpacingCompact + priceHeight + IAPDialogCell.descriptionToPricePaddingCompact + descriptionHeight + IAPDialogCell.descriptionBottomPaddingCompact
return CGSize(width: cellWidth, height: cellHeight)
}
}
// MARK: - Layout
extension IAPDialogCell {
override func layoutSubviews() {
super.layoutSubviews()
updateUI()
}
}
// MARK: - Private
private extension IAPDialogCell {
func setup() {
styleUI()
}
func styleUI() {
backgroundColor = .clear
clipsToBounds = false
cellBorder.layer.cornerRadius = 14
cellBorder.layer.masksToBounds = true
cellBorder.alpha = 0.0
cellBackground.backgroundColor = .white
cellBackground.layer.cornerRadius = 10.0
cellBackground.layer.borderColor = UIColor.unselectedColor.cgColor
cellBackground.layer.borderWidth = 0.5
cellBackground.layer.shadowColor = UIColor.shadowColor.cgColor
cellBackground.layer.shadowRadius = 3
cellBackground.layer.shadowOffset = CGSize(width: 0, height: 2)
cellBackground.layer.shadowOpacity = 1
cellTitle.font = .titleFont
cellTitle.textColor = .labelColor
cellPrice.font = .priceFont
cellPrice.textColor = .labelColor
cellDescription.font = .descriptionFont
cellDescription.textColor = .labelColor
}
func updateUI() {
if UIApplication.shouldShowCompactView {
titleStackView.axis = .vertical
titleStackView.spacing = IAPDialogCell.titleStackViewSpacingCompact
titleStackTopConstraint.constant = IAPDialogCell.titleTopPaddingCompact
cellDescriptionTopToPriceConstraint.constant = IAPDialogCell.descriptionToPricePaddingCompact
descriptionBottomConstraint.constant = IAPDialogCell.descriptionBottomPaddingCompact
} else {
titleStackView.axis = .horizontal
titleStackView.spacing = IAPDialogCell.titleStackViewSpacingRegular
titleStackTopConstraint.constant = IAPDialogCell.titleTopPaddingRegular
cellDescriptionTopToPriceConstraint.constant = IAPDialogCell.descriptionToPricePaddingRegular
descriptionBottomConstraint.constant = IAPDialogCell.descriptionBottomPaddingRegular
}
layoutIfNeeded()
}
}
// MARK: - Public
extension IAPDialogCell {
final func configureCell(withProduct product: StoreProduct, selectedColor: IAPColor, selectedTitleColor: IAPColor) {
self.selectedColor = selectedColor
self.selectedTitleColor = selectedTitleColor
cellTitle.text = product.marketingTitle
cellDescription.text = product.marketingMessage
// It's important that we let the StoreKit product dicate how
// the currency should be displayed
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = product.skProduct.priceLocale
let formattedString = formatter.string(from: product.skProduct.price)
cellPrice.text = formattedString
}
}
| 37.413223 | 251 | 0.703225 |
bf1094314484aa5b07d0f5f9d6497b8cd222491b | 2,154 | //
// AppDelegate.swift
// IRLive
//
// Created by Phil on 2018/8/15.
// Copyright © 2018年 Phil. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UITabBar.appearance().tintColor = UIColor.orange
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:.
}
}
| 44.875 | 285 | 0.750696 |
e65d4dd8621919cdbe147e53e30ea411be92abd3 | 3,189 | //
// Helpers.swift
// MeetingBar
//
// Created by Andrii Leitsius on 12.06.2020.
// Copyright © 2020 Andrii Leitsius. All rights reserved.
//
import Cocoa
import EventKit
func getMatch(text: String, regex: NSRegularExpression) -> String? {
let resultsIterator = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))
let resultsMap = resultsIterator.map { String(text[Range($0.range, in: text)!]) }
if !resultsMap.isEmpty {
let meetLink = resultsMap[0]
return meetLink
}
return nil
}
func openLinkInChrome(_ link: URL) {
let configuration = NSWorkspace.OpenConfiguration()
let chromeUrl = URL(fileURLWithPath: "/Applications/Google Chrome.app")
NSWorkspace.shared.open([link], withApplicationAt: chromeUrl, configuration: configuration) { app, error in
if app != nil {
NSLog("Open \(link) in Chrome")
} else {
NSLog("Can't open \(link) in Chrome: \(String(describing: error?.localizedDescription))")
sendNotification("Oops! Unable to open the link in Chrome", "Make sure you have Chrome installed, or change the browser in the preferences.")
_ = openLinkInDefaultBrowser(link)
}
}
}
func openLinkInDefaultBrowser(_ link: URL) -> Bool {
let result = NSWorkspace.shared.open(link)
if result {
NSLog("Open \(link) in default browser")
} else {
NSLog("Can't open \(link) in default browser")
}
return result
}
func cleanUpNotes(_ notes: String) -> String {
let zoomSeparator = "\n──────────"
let meetSeparator = "-::~:~::~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~::~:~::-"
let cleanNotes = notes.components(separatedBy: zoomSeparator)[0].components(separatedBy: meetSeparator)[0]
return cleanNotes
}
func generateTitleSample(_ titleFormat: EventTitleFormat, _ offset: Int) -> String {
var title: String
switch titleFormat {
case .show:
title = "An event with an excessively sizeable 55-character title"
let index = title.index(title.startIndex, offsetBy: offset, limitedBy: title.endIndex)
title = String(title[...(index ?? title.endIndex)])
if offset < (title.count - 1) {
title += "..."
}
case .dot:
title = "•"
}
return "\(title) in 1h 25m"
}
func getRegexForService(_ service: MeetingServices) -> NSRegularExpression? {
let regexes = LinksRegex()
let mirror = Mirror(reflecting: regexes)
for child in mirror.children {
if child.label == String(describing: service) {
return (child.value as! NSRegularExpression)
}
}
return nil
}
func getGmailAccount(_ event: EKEvent) -> String? {
// Hacky and likely to break, but should work until Apple changes something
let regex = GoogleRegex.emailAddress
let text = event.calendar.source.description
let resultsIterator = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))
let resultsMap = resultsIterator.map { String(text[Range($0.range(at: 1), in: text)!]) }
if !resultsMap.isEmpty {
return resultsMap.first
}
return nil
}
| 35.043956 | 153 | 0.637504 |
1a2369b0789bcaf61ae4f80485b3470388b69837 | 8,289 | //
// SettingsViewController.swift
// App
//
// Created by Priscila Zucato on 19/05/20.
// Copyright © 2020 Joao Flores. All rights reserved.
//
import UIKit
import os.log
class SettingsViewController: UIViewController {
@IBOutlet weak var optionsTableView: UITableView!
let notificationService = NotificationService.shared
var dataSource: [SettingsHeaders] = []
/// This property dictates if notification switch is on/off, as well as if should show/hide notification settings cell.
var isNotificationEnabled: Bool = false {
didSet {
notificationEnabledDidChange()
}
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.isNotificationEnabled = self.notificationService.isNotificationEnabled
setupTableView()
}
// MARK: - Methods
func setupTableView() {
optionsTableView.delegate = self
optionsTableView.dataSource = self
}
fileprivate func notificationEnabledDidChange() {
dataSource = [.tools(isNotificationEnabled), .tutorials, .about]
DispatchQueue.main.async {
if self.isNotificationEnabled {
// This if clause make sure we are not inserting the cell if it already exists.
if self.optionsTableView.numberOfRows(inSection: 0) < 3 {
self.optionsTableView.insertRows(at: [IndexPath(row: 2, section: 0)], with: .automatic)
}
} else {
// This if clause avoid crashes if table view hasn't inserted the row we want to delete here.
if self.optionsTableView.cellForRow(at: IndexPath(row: 2, section: 0)) != nil {
self.optionsTableView.deleteRows(at: [IndexPath(row: 2, section: 0)], with: .automatic)
}
}
}
notificationService.setIsEnabled(isNotificationEnabled)
}
func alertToSettings() -> UIAlertController {
let alertController = UIAlertController(title: "Alerta", message: "Para ativar as notificações, vá às configurações do seu celular.", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Configurações", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
}
}
let cancelAction = UIAlertAction(title: "Cancelar", style: .default, handler: nil)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
return alertController
}
// MARK: - Prepare for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Implementar as segues para cada tipo de célula, quando necessário.
switch segue.identifier {
case SettingsCells.shareResults.segueId:
if let destinationVC = segue.destination as? MealHistoryViewController {
destinationVC.receivedDates = Date().getAllDaysForWeek()
destinationVC.shouldShareWhenPresented = true
}
default:
return
}
}
// MARK: - Actions
@objc func notificationSwitchChanged(_ sender: UISwitch) {
self.notificationService.notificationCenter.getNotificationSettings(completionHandler: { (settings) in
if settings.authorizationStatus == .notDetermined {
self.isNotificationEnabled = false
DispatchQueue.main.async {
self.optionsTableView.reloadData()
let alert = self.alertToSettings()
self.present(alert, animated: true, completion: nil)
}
} else if settings.authorizationStatus == .denied {
self.isNotificationEnabled = false
DispatchQueue.main.async {
self.optionsTableView.reloadData()
let alert = self.alertToSettings()
self.present(alert, animated: true, completion: nil)
}
} else if settings.authorizationStatus == .authorized {
DispatchQueue.main.async {
self.isNotificationEnabled = sender.isOn
}
}
})
}
}
// MARK: - Table View delegate and data source
extension SettingsViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = dataSource[section]
return section.cells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let section = dataSource[indexPath.section]
let settingCell = section.cells[indexPath.row]
cell.textLabel?.text = settingCell.title
if settingCell == .enableNotifications {
let switchView = UISwitch(frame: .zero)
switchView.setOn(isNotificationEnabled, animated: false)
switchView.addTarget(self, action: #selector(self.notificationSwitchChanged(_:)), for: .valueChanged)
cell.accessoryView = switchView
cell.selectionStyle = .none
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let section = dataSource[section]
return section.title
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = dataSource[indexPath.section]
let settingCell = section.cells[indexPath.row]
if let segueID = settingCell.segueId {
performSegue(withIdentifier: segueID, sender: nil)
}
return
}
}
// MARK: - Enums to serve as data source for settings table view.
enum SettingsHeaders {
case tools(Bool)
case tutorials
case about
var cells: [SettingsCells] {
switch self {
case .tools(let isNotificationOn):
if isNotificationOn {
return [.shareResults, .enableNotifications, .notificationSettings]
} else {
return [.shareResults, .enableNotifications]
}
case .tutorials:
return [.howToUse, .healthyMeal]
case .about:
return [.about]
}
}
var title: String {
switch self {
case .tools:
return "Ferramentas"
case .tutorials:
return "Tutoriais"
case .about:
return "Sobre"
}
}
}
enum SettingsCells {
case shareResults
case enableNotifications
case notificationSettings
case howToUse
case healthyMeal
case about
var title: String {
switch self {
case .shareResults:
return "Compartilhar resultados"
case .enableNotifications:
return "Ativar notificações"
case .notificationSettings:
return "Horários de notificações"
case .howToUse:
return "Como utilizar"
case .healthyMeal:
return "Alimentação saudável"
case .about:
return "Sobre o aplicativo"
}
}
var segueId: String? {
switch self {
case .shareResults:
return R.segue.settingsViewController.toMealHistory.identifier
case .notificationSettings:
return R.segue.settingsViewController.toNotificationSettings.identifier
case .healthyMeal:
return R.segue.settingsViewController.toAboutMeal.identifier
case .howToUse:
return R.segue.settingsViewController.toHowToUse.identifier
case .about:
return R.segue.settingsViewController.toCredits.identifier
default:
return nil
}
}
}
| 34.394191 | 165 | 0.612257 |
ab7927f31c253064e32c86087c69689c3133dd00 | 1,010 | //
// CNNetworkingQueryParamEncoder.swift
// ConfusedNetworking
//
// Created by Harshal Neelkamal on 2/12/19.
// Copyright © 2019 BrightApps. All rights reserved.
//
import Foundation
internal class CNNetworkingQueryParamEncoder:CNRequestEncoder{
typealias ParameterTypes = [String:Any]
static func encodeRequest(request: inout URLRequest, withParameters parameters: [String : Any]) {
var component = URLComponents.init(url: request.url!, resolvingAgainstBaseURL: false)
for (key,value) in parameters {
let item = URLQueryItem.init(name: key, value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))
component?.queryItems?.append(item)
}
request.url = component?.url
if request.value(forHTTPHeaderField: "Content-Type") == nil {
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
}
}
| 31.5625 | 132 | 0.660396 |
f9a4a073b4a8a9846a67b33fa7b98e25a445501f | 6,767 | //
// 🦠 Corona-Warn-App
//
import UIKit
class DynamicTableViewConsentCell: UITableViewCell {
// MARK: - View elements.
lazy var subTitleLabel = ENALabel(frame: .zero)
lazy var descriptionPart1Label = ENALabel(frame: .zero)
lazy var descriptionPart2Label = ENALabel(frame: .zero)
lazy var seperatorView1 = UIView()
lazy var seperatorView2 = UIView()
lazy var flagIconsLabel = ENALabel(frame: .zero)
lazy var flagCountriesLabel = ENALabel(frame: .zero)
lazy var descriptionPart3Label = ENALabel(frame: .zero)
lazy var descriptionPart4Label = ENALabel(frame: .zero)
lazy var consentView = UIView(frame: .zero)
lazy var consentStackView = UIStackView(frame: .zero)
lazy var countriesStackView = UIStackView(frame: .zero)
// MARK: - Init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
isAccessibilityElement = false
// MARK: - General cell setup.
selectionStyle = .none
backgroundColor = .enaColor(for: .background)
// MARK: - Add consent view
consentView.backgroundColor = .enaColor(for: .cellBackground3)
consentView.layer.cornerRadius = 16.0
contentView.addSubview(consentView)
// MARK: - Stackview adjustment.
consentStackView.axis = .vertical
consentStackView.spacing = 20
consentStackView.distribution = .fill
consentView.addSubview(consentStackView)
UIView.translatesAutoresizingMaskIntoConstraints(for: [
consentView, consentStackView
], to: false)
// MARK: - Title adjustment.
subTitleLabel.style = .headline
subTitleLabel.textColor = .enaColor(for: .textPrimary1)
subTitleLabel.lineBreakMode = .byWordWrapping
subTitleLabel.numberOfLines = 0
// MARK: - Description1 Body adjustment.
descriptionPart1Label.style = .headline
descriptionPart1Label.textColor = .enaColor(for: .textPrimary1)
descriptionPart1Label.lineBreakMode = .byWordWrapping
descriptionPart1Label.numberOfLines = 0
// MARK: - Description2 Body adjustment.
descriptionPart2Label.style = .headline
descriptionPart2Label.textColor = .enaColor(for: .textPrimary1)
descriptionPart2Label.lineBreakMode = .byWordWrapping
descriptionPart2Label.numberOfLines = 0
// MARK: - Description3 Body adjustment.
descriptionPart3Label.style = .headline
descriptionPart3Label.textColor = .enaColor(for: .textPrimary1)
descriptionPart3Label.lineBreakMode = .byWordWrapping
descriptionPart3Label.numberOfLines = 0
// MARK: - Description4 Body adjustment.
descriptionPart4Label.style = .body
descriptionPart4Label.textColor = .enaColor(for: .textPrimary1)
descriptionPart4Label.lineBreakMode = .byWordWrapping
descriptionPart4Label.numberOfLines = 0
// MARK: - Countries StackView Body adjustment.
countriesStackView.axis = .vertical
countriesStackView.spacing = 8
countriesStackView.isLayoutMarginsRelativeArrangement = true
countriesStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
// MARK: - Flag Icons Label adjustment.
flagIconsLabel.lineBreakMode = .byWordWrapping
flagIconsLabel.numberOfLines = 0
countriesStackView.addArrangedSubview(flagIconsLabel)
// MARK: - Flag Countries Label adjustment.
flagCountriesLabel.style = .body
flagCountriesLabel.textColor = .enaColor(for: .textPrimary1)
flagCountriesLabel.lineBreakMode = .byWordWrapping
flagCountriesLabel.numberOfLines = 0
countriesStackView.addArrangedSubview(flagCountriesLabel)
// MARK: - Seperator View1 adjustment.
seperatorView1.backgroundColor = .enaColor(for: .hairline)
// MARK: - Seperator View2 Body adjustment.
seperatorView2.backgroundColor = .enaColor(for: .hairline)
[subTitleLabel, descriptionPart1Label, descriptionPart2Label, seperatorView1, countriesStackView, seperatorView2, descriptionPart3Label, descriptionPart4Label].forEach {
consentStackView.addArrangedSubview($0)
}
consentStackView.setCustomSpacing(16, after: seperatorView1)
consentStackView.setCustomSpacing(16, after: flagCountriesLabel)
consentStackView.setNeedsUpdateConstraints()
accessibilityElements = [subTitleLabel, descriptionPart1Label, descriptionPart2Label, flagCountriesLabel, descriptionPart3Label, descriptionPart4Label]
}
private func setupConstraints() {
let marginGuide = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
consentView.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor),
consentView.topAnchor.constraint(equalTo: marginGuide.topAnchor),
consentView.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor),
consentView.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor),
consentStackView.topAnchor.constraint(equalTo: consentView.topAnchor, constant: 20),
consentStackView.trailingAnchor.constraint(equalTo: consentView.trailingAnchor, constant: -16),
consentStackView.leadingAnchor.constraint(equalTo: consentView.leadingAnchor, constant: 16),
consentStackView.bottomAnchor.constraint(equalTo: consentView.bottomAnchor, constant: -20),
seperatorView1.heightAnchor.constraint(equalToConstant: 1),
seperatorView2.heightAnchor.constraint(equalToConstant: 1)
])
}
func configure(
subTitleLabel: NSMutableAttributedString,
descriptionPart1Label: NSMutableAttributedString,
descriptionPart2Label: NSMutableAttributedString,
countries: [Country],
descriptionPart3Label: NSMutableAttributedString,
descriptionPart4Label: NSMutableAttributedString
) {
self.subTitleLabel.attributedText = subTitleLabel
self.descriptionPart1Label.attributedText = descriptionPart1Label
self.descriptionPart2Label.attributedText = descriptionPart2Label
self.descriptionPart3Label.attributedText = descriptionPart3Label
self.descriptionPart4Label.attributedText = descriptionPart4Label
self.flagCountriesLabel.text = countries.map { $0.localizedName }.joined(separator: ", ")
let flagString = NSMutableAttributedString()
countries
.compactMap { $0.flag?.withRenderingMode(.alwaysOriginal) }
.forEach { flag in
let imageAttachment = NSTextAttachment()
imageAttachment.image = flag
imageAttachment.setImageHeight(height: 17)
let imageString = NSAttributedString(attachment: imageAttachment)
flagString.append(imageString)
flagString.append(NSAttributedString(string: " "))
}
let style = NSMutableParagraphStyle()
style.lineSpacing = 10
flagString.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: flagString.length))
flagIconsLabel.attributedText = flagString
}
}
| 38.231638 | 171 | 0.786168 |
f527c40549b144402ae7b6f30fad9472378b86a1 | 1,335 | //
// RadialGradientView.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-29.
// Copyright © 2021 Sumcoin Wallet All rights reserved.
//
import UIKit
class RadialGradientView : UIView {
//MARK: - Public
init(backgroundColor: UIColor, offset: CGFloat = 0.0) {
self.offset = offset
super.init(frame: .zero)
self.backgroundColor = backgroundColor
}
//MARK: - Private
private let offset: CGFloat
override func draw(_ rect: CGRect) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let startColor = UIColor.transparentWhite.cgColor
let endColor = UIColor(white: 1.0, alpha: 0.0).cgColor
let colors = [startColor, endColor] as CFArray
let locations: [CGFloat] = [0.0, 1.0]
guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) else { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
let center = CGPoint(x: rect.midX, y: rect.midY + offset)
let endRadius = rect.height
context.drawRadialGradient(gradient, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: [])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.375 | 137 | 0.665918 |
117bf83adb582c9a4d3ad1cd578edc28763184a9 | 3,446 | //
// Constants.swift
// ExponeaSDK
//
// Created by Ricardo Tokashiki on 05/04/2018.
// Copyright © 2018 Exponea. All rights reserved.
//
import Foundation
/// enum with constants used through the SDK
public enum Constants {
/// Network
public enum Repository {
public static let baseUrl = "https://api.exponea.com"
static let contentType = "application/json"
static let headerContentType = "content-type"
static let headerAccept = "accept"
static let headerContentLenght = "content-length"
static let headerAuthorization = "authorization"
}
/// Keys for plist files and userdefaults
enum Keys {
static let token = "exponeaProjectIdKey"
static let authorization = "exponeaAuthorization"
static let installTracked = "installTracked"
static let sessionStarted = "sessionStarted"
static let sessionEnded = "sessionEnded"
static let timeout = "sessionTimeout"
static let autoSessionTrack = "automaticSessionTrack"
static let appVersion = "CFBundleShortVersionString"
static let baseUrl = "exponeaBaseURL"
}
/// SDK Info
enum DeviceInfo {
static let osName = "iOS"
static let osVersion = UIDevice.current.systemVersion
static let sdk = "Exponea iOS SDK"
static let deviceModel = UIDevice.current.model
}
/// Type of customer events
enum EventTypes {
static let installation = "installation"
static let sessionEnd = "session_end"
static let sessionStart = "session_start"
static let payment = "payment"
static let pushOpen = "campaign"
static let pushDelivered = "campaign"
static let campaignClick = "campaign_click"
static let banner = "banner"
}
/// Error messages
enum ErrorMessages {
static let sdkNotConfigured = "Exponea SDK isn't configured. " +
"Before any calls to SDK functions, please configure the SDK " +
"with Exponea.shared.config() according to the documentation " +
"https://github.com/exponea/exponea-ios-sdk/blob/develop/Documentation/CONFIG.md#configuring-the-sdk"
}
/// Success messages
enum SuccessMessages {
static let sessionStart = "Session succesfully started"
static let sessionEnd = "Session succesfully ended"
static let paymentDone = "Payment was succesfully tracked!"
}
/// Default session values represented in seconds
public enum Session {
public static let defaultTimeout = 6.0
public static let maxRetries = 5
static let sessionUpdateThreshold = 3.0
}
enum Tracking {
// To be able to amend session tracking with campaign data, we have to delay immediate event flushing a bit
static let immediateFlushDelay = 3.0
}
/// General constants
enum General {
static let iTunesStore = "iTunes Store"
static let userDefaultsSuite = "ExponeaSDK"
static let deliveredPushUserDefaultsKey = "EXPONEA_DELIVERED_PUSH_TRACKING"
static let savedCampaignClickEvent = "EXPONEA_SAVED_CAMPAIGN_CLICK"
static let inAppMessageDisplayStatusUserDefaultsKey = "EXPONEA_IN_APP_MESSAGE_DISPLAY_STATUS"
static let lastKnownConfiguration = "EXPONEA_LAST_KNOWN_CONFIGURATION"
static let lastKnownCustomerIds = "EXPONEA_LAST_KNOWN_CUSTOMER_IDS"
}
}
| 36.659574 | 115 | 0.678468 |
2153c4ada55e8650813dbc14d67cc1c15e6d52f7 | 1,779 | /*
* Copyright 2015-present the original author or authors.
*
* 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.
*/
/// Request a completable stream in both directions
internal struct RequestChannelFrameBody: Hashable, FragmentableFrameBody {
/// If true, this is a fragment and at least another payload frame will follow
internal var fragmentFollows: Bool = false
/// If the channel is already completed
internal var isCompleted: Bool
/**
The initial number of items to request
Value MUST be > `0`.
*/
internal var initialRequestN: Int32
/// Identification of the service being requested along with parameters for the request
internal var payload: Payload
}
extension RequestChannelFrameBody: FrameBodyBoundToStream {
func body() -> FrameBody { .requestChannel(self) }
func header(withStreamId streamId: StreamID) -> FrameHeader {
var flags = FrameFlags()
if payload.metadata != nil {
flags.insert(.metadata)
}
if isCompleted {
flags.insert(.requestChannelComplete)
}
if fragmentFollows {
flags.insert(.fragmentFollows)
}
return FrameHeader(streamId: streamId, type: .requestChannel, flags: flags)
}
}
| 34.211538 | 91 | 0.695334 |
267d4aa529d64732ac1dc215f5e1660907e496cc | 4,089 | // Copyright 2017 Onix-Systems
// 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
import SwiftyDropbox
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
FIRApp.configure()
GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
DropboxClientsManager.setupWithAppKey(Keys.dropboxAppKey)
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
handleDropbox(openURL: url)
return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
handleDropbox(openURL: url)
return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation)
}
fileprivate func handleDropbox(openURL url: URL) {
if let authResult = DropboxClientsManager.handleRedirectURL(url) {
switch authResult {
case .success(let token):
print("Success! User is logged into Dropbox with token: \(token)")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: DropboxDidLoginNotification.Name), object: nil, userInfo: [DropboxDidLoginNotification.TokenKey : token])
case .error(let error, let description):
NotificationCenter.default.post(name: NSNotification.Name(rawValue: DropboxDidLoginNotification.Name), object: nil, userInfo: [DropboxDidLoginNotification.ErrorDescriptionKey : description])
print("Error \(error): \(description)")
case .cancel:
NotificationCenter.default.post(name: NSNotification.Name(rawValue: DropboxDidLoginNotification.Name), object: nil, userInfo: [DropboxDidLoginNotification.ErrorDescriptionKey : "User cancelled"])
}
}
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| 51.1125 | 211 | 0.734409 |
fff918d083cd6a851e0fa412ecce5f26127f976c | 11,939 | import Commandant
import Dispatch
import Foundation
import SourceKittenFramework
import SwiftLintFramework
private let indexIncrementerQueue = DispatchQueue(label: "io.realm.swiftlint.indexIncrementer")
private func scriptInputFiles() -> Result<[SwiftLintFile], CommandantError<()>> {
func getEnvironmentVariable(_ variable: String) -> Result<String, CommandantError<()>> {
let environment = ProcessInfo.processInfo.environment
if let value = environment[variable] {
return .success(value)
}
return .failure(.usageError(description: "Environment variable not set: \(variable)"))
}
let count: Result<Int, CommandantError<()>> = {
let inputFileKey = "SCRIPT_INPUT_FILE_COUNT"
guard let countString = ProcessInfo.processInfo.environment[inputFileKey] else {
return .failure(.usageError(description: "\(inputFileKey) variable not set"))
}
if let count = Int(countString) {
return .success(count)
}
return .failure(.usageError(description: "\(inputFileKey) did not specify a number"))
}()
return count.flatMap { count in
return .success((0..<count).compactMap { fileNumber in
switch getEnvironmentVariable("SCRIPT_INPUT_FILE_\(fileNumber)") {
case let .success(path):
if path.bridge().isSwiftFile() {
return SwiftLintFile(pathDeferringReading: path)
}
return nil
case let .failure(error):
queuedPrintError(String(describing: error))
return nil
}
})
}
}
#if os(Linux)
private func autoreleasepool<T>(block: () -> T) -> T { return block() }
#endif
extension Configuration {
func visitLintableFiles(with visitor: LintableFilesVisitor, storage: RuleStorage)
-> Result<[SwiftLintFile], CommandantError<()>> {
return getFiles(with: visitor)
.flatMap { groupFiles($0, visitor: visitor) }
.map { linters(for: $0, visitor: visitor) }
.map { ($0, $0.duplicateFileNames) }
.map { collect(linters: $0.0, visitor: visitor, storage: storage, duplicateFileNames: $0.1) }
.map { visit(linters: $0.0, visitor: visitor, storage: storage, duplicateFileNames: $0.1) }
}
private func groupFiles(_ files: [SwiftLintFile],
visitor: LintableFilesVisitor)
-> Result<[Configuration: [SwiftLintFile]], CommandantError<()>> {
if files.isEmpty && !visitor.allowZeroLintableFiles {
let errorMessage = "No lintable files found at paths: '\(visitor.paths.joined(separator: ", "))'"
return .failure(.usageError(description: errorMessage))
}
var groupedFiles = [Configuration: [SwiftLintFile]]()
for file in files {
// Files whose configuration specifies they should be excluded will be skipped
let fileConfiguration = configuration(for: file)
let fileConfigurationRootPath = (fileConfiguration.rootPath ?? "").bridge()
let shouldSkip = fileConfiguration.excluded.contains { excludedRelativePath in
let excludedPath = fileConfigurationRootPath.appendingPathComponent(excludedRelativePath)
let filePathComponents = file.path?.bridge().pathComponents ?? []
let excludedPathComponents = excludedPath.bridge().pathComponents
return filePathComponents.starts(with: excludedPathComponents)
}
if !shouldSkip {
groupedFiles[fileConfiguration, default: []].append(file)
}
}
return .success(groupedFiles)
}
private func outputFilename(for path: String, duplicateFileNames: Set<String>) -> String {
let basename = path.bridge().lastPathComponent
if !duplicateFileNames.contains(basename) {
return basename
}
var pathComponents = path.bridge().pathComponents
let root = self.rootPath ?? FileManager.default.currentDirectoryPath.bridge().standardizingPath
for component in root.bridge().pathComponents where pathComponents.first == component {
pathComponents.removeFirst()
}
return pathComponents.joined(separator: "/")
}
private func linters(for filesPerConfiguration: [Configuration: [SwiftLintFile]],
visitor: LintableFilesVisitor) -> [Linter] {
let fileCount = filesPerConfiguration.reduce(0) { $0 + $1.value.count }
var linters = [Linter]()
linters.reserveCapacity(fileCount)
for (config, files) in filesPerConfiguration {
let newConfig: Configuration
if visitor.cache != nil {
newConfig = config.withPrecomputedCacheDescription()
} else {
newConfig = config
}
linters += files.map { visitor.linter(forFile: $0, configuration: newConfig) }
}
return linters
}
private func collect(linters: [Linter],
visitor: LintableFilesVisitor,
storage: RuleStorage,
duplicateFileNames: Set<String>) -> ([CollectedLinter], Set<String>) {
var collected = 0
let total = linters.filter({ $0.isCollecting }).count
let collect = { (linter: Linter) -> CollectedLinter? in
let skipFile = visitor.shouldSkipFile(atPath: linter.file.path)
if !visitor.quiet, linter.isCollecting, let filePath = linter.file.path {
let outputFilename = self.outputFilename(for: filePath, duplicateFileNames: duplicateFileNames)
let increment = {
collected += 1
if skipFile {
queuedPrintError("""
Skipping '\(outputFilename)' (\(collected)/\(total)) \
because its compiler arguments could not be found
""")
} else {
queuedPrintError("Collecting '\(outputFilename)' (\(collected)/\(total))")
}
}
if visitor.parallel {
indexIncrementerQueue.sync(execute: increment)
} else {
increment()
}
}
guard !skipFile else {
return nil
}
return autoreleasepool {
linter.collect(into: storage)
}
}
let collectedLinters = visitor.parallel ?
linters.parallelCompactMap(transform: collect) :
linters.compactMap(collect)
return (collectedLinters, duplicateFileNames)
}
private func visit(linters: [CollectedLinter],
visitor: LintableFilesVisitor,
storage: RuleStorage,
duplicateFileNames: Set<String>) -> [SwiftLintFile] {
var visited = 0
let visit = { (linter: CollectedLinter) -> SwiftLintFile in
if !visitor.quiet, let filePath = linter.file.path {
let outputFilename = self.outputFilename(for: filePath, duplicateFileNames: duplicateFileNames)
let increment = {
visited += 1
queuedPrintError("\(visitor.action) '\(outputFilename)' (\(visited)/\(linters.count))")
}
if visitor.parallel {
indexIncrementerQueue.sync(execute: increment)
} else {
increment()
}
}
autoreleasepool {
visitor.block(linter)
}
return linter.file
}
return visitor.parallel ? linters.parallelMap(transform: visit) : linters.map(visit)
}
fileprivate func getFiles(with visitor: LintableFilesVisitor) -> Result<[SwiftLintFile], CommandantError<()>> {
if visitor.useSTDIN {
let stdinData = FileHandle.standardInput.readDataToEndOfFile()
if let stdinString = String(data: stdinData, encoding: .utf8) {
return .success([SwiftLintFile(contents: stdinString)])
}
return .failure(.usageError(description: "stdin isn't a UTF8-encoded string"))
} else if visitor.useScriptInputFiles {
return scriptInputFiles()
.map { files in
guard visitor.forceExclude else {
return files
}
let scriptInputPaths = files.compactMap { $0.path }
return filterExcludedPaths(in: scriptInputPaths)
.map(SwiftLintFile.init(pathDeferringReading:))
}
}
if !visitor.quiet {
let filesInfo: String
if visitor.paths.isEmpty {
filesInfo = "in current working directory"
} else {
filesInfo = "at paths \(visitor.paths.joined(separator: ", "))"
}
queuedPrintError("\(visitor.action) Swift files \(filesInfo)")
}
return .success(visitor.paths.flatMap {
self.lintableFiles(inPath: $0, forceExclude: visitor.forceExclude)
})
}
private static func rootPath(from paths: [String]) -> String? {
// We don't know the root when more than one path is passed (i.e. not useful if the root of 2 paths is ~)
return paths.count == 1 ? paths.first?.absolutePathStandardized() : nil
}
// MARK: LintOrAnalyze Command
init(options: LintOrAnalyzeOptions) {
let cachePath = options.cachePath.isEmpty ? nil : options.cachePath
self.init(path: options.configurationFile, rootPath: type(of: self).rootPath(from: options.paths),
optional: isConfigOptional(), quiet: options.quiet, enableAllRules: options.enableAllRules,
cachePath: cachePath)
}
func visitLintableFiles(options: LintOrAnalyzeOptions, cache: LinterCache? = nil, storage: RuleStorage,
visitorBlock: @escaping (CollectedLinter) -> Void)
-> Result<[SwiftLintFile], CommandantError<()>> {
return LintableFilesVisitor.create(options,
cache: cache,
allowZeroLintableFiles: allowZeroLintableFiles,
block: visitorBlock).flatMap({ visitor in
visitLintableFiles(with: visitor, storage: storage)
})
}
// MARK: AutoCorrect Command
init(options: AutoCorrectOptions) {
let cachePath = options.cachePath.isEmpty ? nil : options.cachePath
self.init(path: options.configurationFile, rootPath: type(of: self).rootPath(from: options.paths),
optional: isConfigOptional(), quiet: options.quiet, cachePath: cachePath)
}
// MARK: Rules command
init(options: RulesOptions) {
self.init(path: options.configurationFile, optional: isConfigOptional())
}
}
private func isConfigOptional() -> Bool {
return !CommandLine.arguments.contains("--config")
}
private struct DuplicateCollector {
var all = Set<String>()
var duplicates = Set<String>()
}
private extension Collection where Element == Linter {
var duplicateFileNames: Set<String> {
let collector = reduce(into: DuplicateCollector()) { result, linter in
if let filename = linter.file.path?.bridge().lastPathComponent {
if result.all.contains(filename) {
result.duplicates.insert(filename)
}
result.all.insert(filename)
}
}
return collector.duplicates
}
}
| 41.454861 | 115 | 0.585225 |
f5ca44fe3478d76e847ef5842c4dcc5cf12bf1b9 | 1,110 | //
// LatestAPIModel.swift
// TripKit
//
// Created by Adrian Schönig on 11/8/21.
// Copyright © 2021 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
extension TKAPI {
struct LatestResponse: Codable {
let services: [LatestService]
}
struct LatestService: Codable {
let code: String
@OptionalISO8601OrSecondsSince1970 public var startTime: Date?
@OptionalISO8601OrSecondsSince1970 public var endTime: Date?
let primaryVehicle: Vehicle?
@DefaultEmptyArray var alternativeVehicles: [Vehicle]
@DefaultEmptyArray var alerts: [Alert]
@DefaultEmptyArray var stops: [LatestStop]
private enum CodingKeys: String, CodingKey {
case code = "serviceTripID"
case startTime
case endTime
case stops
case primaryVehicle = "realtimeVehicle"
case alternativeVehicles = "realtimeVehicleAlternatives"
case alerts
}
}
struct LatestStop: Codable {
let stopCode: String
@OptionalISO8601OrSecondsSince1970 var arrival: Date?
@OptionalISO8601OrSecondsSince1970 var departure: Date?
}
}
| 23.617021 | 66 | 0.702703 |
b9480c7717a07718d2ca90fd883b23cb8493d572 | 3,224 | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import Foundation
import Amplify
import amplify_core
struct FlutterUploadFileRequest {
var uuid: String
var key: String
var file: URL
var options: StorageUploadFileRequest.Options?
init(request: Dictionary<String, AnyObject>) {
self.uuid = request["uuid"] as! String
self.key = request["key"] as! String
self.file = NSURL(fileURLWithPath: request["path"] as! String) as URL
self.options = setOptions(request: request)
}
static func validate(request: Dictionary<String, AnyObject>) throws {
let validationErrorMessage = "UploadFile request malformed."
if !(request["uuid"] is String) {
throw InvalidRequestError.storage(comment: validationErrorMessage,
suggestion: String(format: ErrorMessages.missingAttribute, "uuid"))
}
if !(request["key"] is String) {
throw InvalidRequestError.storage(comment: validationErrorMessage,
suggestion: String(format: ErrorMessages.missingAttribute, "key"))
}
if !(request["path"] is String) {
throw InvalidRequestError.storage(comment: validationErrorMessage,
suggestion: String(format: ErrorMessages.missingAttribute, "path"))
}
}
private func setOptions(request: Dictionary<String, AnyObject>) -> StorageUploadFileRequest.Options? {
if(request["options"] != nil) {
let requestOptions = request["options"] as! Dictionary<String, AnyObject>
//Default options
var accessLevel = StorageAccessLevel.guest
var targetIdentityId: String? = nil
var metadata: [String: String]? = nil
var contentType: String? = nil
for(key,value) in requestOptions {
switch key {
case "accessLevel":
accessLevel = StorageAccessLevel(rawValue: value as! String) ?? accessLevel
case "targetIdentityId":
targetIdentityId = value as? String
case "metadata":
metadata = value as? [String: String]
case "contentType":
contentType = value as? String
default:
print("Received unexpected option: \(key)")
}
}
return StorageUploadFileRequest.Options(accessLevel: accessLevel, targetIdentityId: targetIdentityId, metadata: metadata, contentType: contentType)
}
return nil
}
}
| 41.333333 | 159 | 0.611352 |
3aeaa5dc048a6a16f50b82592209852b35b03b7a | 8,831 | //
// MapVC.swift
// PirateWalla
//
// Created by Kevin Lohman on 2/5/16.
// Copyright © 2016 Logic High. All rights reserved.
//
import UIKit
import MapKit
class MapVC : PWVC, MKMapViewDelegate {
@IBOutlet var target : UIImageView?
@IBOutlet var searchButton : UIBarButtonItem?
@IBOutlet var resetButton : UIBarButtonItem?
@IBOutlet var mapView : MKMapView?
let itemLock = dispatch_queue_create("ItemLock", nil)
var savedItems = [ Int : SBSavedItem ]()
var pouchItems = [ Int : SBSavedItem ]()
var mixReverseLookup = [ Int : SBItemType ]()
var user : SBUser?
let bee = sharedBee
var zoomed = false
var recheck = false
var places = Set<SBPlace>()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
alwaysShow = true
}
override func viewDidLoad() {
reset()
super.viewDidLoad()
}
@IBAction func reset() {
searchButton!.enabled = false
resetButton!.enabled = false
recheck = true
dispatch_sync(self.itemLock, { () -> Void in
self.savedItems.removeAll()
self.pouchItems.removeAll()
self.mixReverseLookup.removeAll()
})
let activity = "Resetting"
startedActivity(activity)
ActionTVC.login(self) { (user) -> Void in
defer { self.stoppedActivity(activity) }
self.user = user
ActionTVC.getSavedItems(user, watcher: self, completion: { (error, savedItems) -> Void in
if let error = error {
self.errored(error)
return
}
let savedItems = savedItems!
dispatch_sync(self.itemLock, { () -> Void in
self.savedItems = savedItems
})
ActionTVC.addMixRequirements(self, savedItems: savedItems, itemLock: self.itemLock, completion: { (error, mixReverseLookup) -> Void in
if let mixReverseLookup = mixReverseLookup {
self.mixReverseLookup = mixReverseLookup
}
})
})
ActionTVC.getPouch(user, watcher: self, completion: { (error, pouchItems) -> Void in
if let error = error {
self.errored(error)
return
}
let pouchItems = pouchItems!
dispatch_sync(self.itemLock, { () -> Void in
self.pouchItems = pouchItems
})
})
}
}
override func didCompleteAllActivities() {
if !NSThread.isMainThread() {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.didCompleteAllActivities()
})
return
}
super.didCompleteAllActivities()
searchButton!.enabled = true
resetButton!.enabled = true
if recheck {
let mapView = self.mapView!
let annotations = mapView.annotations
mapView.removeAnnotations(annotations)
mapView.addAnnotations(annotations)
recheck = false
}
}
func errored(error : NSError) {
searchButton!.enabled = true
resetButton!.enabled = true
AppDelegate.handleError(error, button: "Retry", title: "Error", completion: {
self.reset()
})
}
@IBAction func search() {
let searchButton = self.searchButton!, mapView = self.mapView!, target = self.target!
searchButton.enabled = false
let coordinate = mapView.convertPoint(target.center, toCoordinateFromView: target.superview)
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
let activity = "Searching! ARRR!"
startedActivity(activity)
bee.priorityMode = true
bee.nearby(location) { (error, places) -> Void in
defer { self.stoppedActivity(activity) }
if let error = error {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
searchButton.enabled = true
})
AppDelegate.handleError(error, button: "OK", title: "Error", completion: nil)
return
}
let places = places!
var maxDistance : CLLocationDistance = 0
for place in places {
let placeCoordinate = place.location
let placeLocation = CLLocation(latitude: placeCoordinate.latitude, longitude: placeCoordinate.longitude)
maxDistance = max(maxDistance,location.distanceFromLocation(placeLocation))
}
let circle = MKCircle(centerCoordinate: coordinate, radius: maxDistance)
let newPlaces = Set<SBPlace>(places).subtract(self.places)
var annotations = [MKAnnotation]()
for place in newPlaces {
annotations.append(PlaceAnnotation(place: place, watcher: self))
}
self.places.unionInPlace(newPlaces)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
mapView.addOverlay(circle)
searchButton.enabled = true
mapView.setVisibleMapRect(circle.boundingMapRect, animated: true)
if annotations.count > 0 {
mapView.addAnnotations(annotations)
}
})
}
bee.priorityMode = false
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? PlaceAnnotation {
guard let items = annotation.items else {
let hiddenView = MKAnnotationView(annotation: annotation, reuseIdentifier: "hidden")
hiddenView.hidden = true
return hiddenView
}
var placeObjects = PlaceObjects()
ActionTVC.placeObjects(items, place: annotation.place, savedItems: savedItems, pouchItemTypes: pouchItems, mixReverseLookup: mixReverseLookup, placeObjects: &placeObjects)
var n = 1
while let type = FoundItemType(rawValue: n)
{
if let typeObjects = placeObjects[type], let _ = typeObjects[annotation.place] {
let av = MKAnnotationView(annotation: annotation, reuseIdentifier: type.name)
av.image = UIImage(named: type.name)
return av
}
n++
}
let hiddenView = MKAnnotationView(annotation: annotation, reuseIdentifier: "hidden")
hiddenView.hidden = true
return hiddenView
}
return nil
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
if zoomed { return }
zoomed = true
mapView.setRegion(MKCoordinateRegion(center: userLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)), animated: true)
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
if let overlay = overlay as? MKCircle {
let renderer = MKCircleRenderer(overlay: overlay)
renderer.fillColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.15)
return renderer
}
return MKOverlayRenderer(overlay: overlay)
}
}
class PlaceAnnotation : NSObject, MKAnnotation {
let place : SBPlace
var items : [SBItem]?
init(place : SBPlace, watcher : MapVC) {
self.place = place
super.init()
let activity = "Searching \(place.name)"
watcher.startedActivity(activity)
place.items { (error, items) -> Void in
defer { watcher.stoppedActivity(activity) }
if let error = error {
print(error)
return
}
if let items = items {
self.items = items
if NSThread.isMainThread() {
watcher.mapView!.removeAnnotation(self)
watcher.mapView!.addAnnotation(self)
}
else
{
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
watcher.mapView!.removeAnnotation(self)
watcher.mapView!.addAnnotation(self)
})
}
}
}
}
var coordinate : CLLocationCoordinate2D {
get {
return place.location
}
}
var title : String? {
get {
return place.name
}
}
}
| 37.419492 | 183 | 0.56279 |
e8c589ecfb80ace4a8aacdc2242f94514900b815 | 503 | //
// ImageWithDescription.swift
// refapa
//
// Created by Abraham Haros on 17/04/21.
//
import UIKit
class ImageWithDescription: NSObject, Codable {
var imgDescription : String!
let imgFoto : String?
init(imgDescription: String, imgFoto: String?) {
self.imgDescription = imgDescription
self.imgFoto = imgFoto
}
func getImage() -> UIImage? {
if imgFoto != nil {
return UIImage(named: imgFoto!)
}
return nil
}
}
| 19.346154 | 52 | 0.600398 |
5bd3cbcf09de74940bbfe12a077c96da514f8c6d | 2,273 | //
// UITableViewCell+Rx.swift
// RxHeartRateMonitors
//
// Created by Leandro Perez on 12/13/17.
// Copyright © 2017 Leandro Perez. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
//taken from https://github.com/ReactiveX/RxSwift/issues/821
private var prepareForReuseBag: Int8 = 0
extension Reactive where Base: UITableViewCell {
public var prepareForReuse: Observable<Void> {
return Observable.of(sentMessage(#selector(UITableViewCell.prepareForReuse)).map { _ in () }, deallocated).merge()
}
public var disposeBag: DisposeBag {
MainScheduler.ensureExecutingOnScheduler()
if let bag = objc_getAssociatedObject(base, &prepareForReuseBag) as? DisposeBag {
return bag
}
let bag = DisposeBag()
objc_setAssociatedObject(base, &prepareForReuseBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
_ = sentMessage(#selector(UITableViewCell.prepareForReuse))
.subscribe(onNext: { [weak base] _ in
let newBag = DisposeBag()
objc_setAssociatedObject(base as Any, &prepareForReuseBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
})
return bag
}
}
extension Reactive where Base: UITableViewHeaderFooterView {
public var prepareForReuse: Observable<Void> {
return Observable.of(sentMessage(#selector(UITableViewHeaderFooterView.prepareForReuse)).map { _ in () }, deallocated).merge()
}
public var disposeBag: DisposeBag {
MainScheduler.ensureExecutingOnScheduler()
if let bag = objc_getAssociatedObject(base, &prepareForReuseBag) as? DisposeBag {
return bag
}
let bag = DisposeBag()
objc_setAssociatedObject(base, &prepareForReuseBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
_ = sentMessage(#selector(UITableViewHeaderFooterView.prepareForReuse))
.subscribe(onNext: { [weak base] _ in
let newBag = DisposeBag()
objc_setAssociatedObject(base as Any, &prepareForReuseBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
})
return bag
}
}
| 34.969231 | 134 | 0.670919 |
284a028b039a089a8054b4326f030fe531168874 | 2,614 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Windows)
import ucrt
#else
import Glibc
#endif
/// logSumExp(_:_:)
///
/// Specialized logSumExp for 2 float.
@differentiable
public func logSumExp(_ lhs: Float, _ rhs: Float) -> Float {
let maxVal = max(lhs, rhs)
let sumExp = exp(lhs - maxVal) + exp(rhs - maxVal)
return maxVal + log(sumExp)
}
@derivative(of: logSumExp)
public func vjpLogSumExp(_ lhs: Float, _ rhs: Float) -> (
value: Float,
pullback: (Float) -> (Float, Float)
) {
func pb(v: Float) -> (Float, Float) {
let maxVal = max(lhs, rhs)
let sumExp = exp(lhs - maxVal) + exp(rhs - maxVal)
return (v * exp(lhs - maxVal) / sumExp, v * exp(rhs - maxVal) / sumExp)
}
return (logSumExp(lhs, rhs), pb)
}
/// SemiRing
///
/// Represents a SemiRing
public struct SemiRing: Differentiable {
public var logp: Float
public var logr: Float
@differentiable
public init(logp: Float, logr: Float) {
self.logp = logp
self.logr = logr
}
static var zero: SemiRing { SemiRing(logp: -Float.infinity, logr: -Float.infinity) }
static var one: SemiRing { SemiRing(logp: 0.0, logr: -Float.infinity) }
}
@differentiable
func * (_ lhs: SemiRing, _ rhs: SemiRing) -> SemiRing {
return SemiRing(
logp: lhs.logp + rhs.logp,
logr: logSumExp(lhs.logp + rhs.logr, rhs.logp + lhs.logr))
}
@differentiable
func + (_ lhs: SemiRing, _ rhs: SemiRing) -> SemiRing {
return SemiRing(
logp: logSumExp(lhs.logp, rhs.logp),
logr: logSumExp(lhs.logr, rhs.logr))
}
extension SemiRing {
var shortDescription: String {
"(\(logp), \(logr))"
}
}
/// SE-0259-esque equality with tolerance
extension SemiRing {
// TODO(abdulras) see if we can use ulp as a default tolerance
@inlinable
public func isAlmostEqual(to other: Self, tolerance: Float) -> Bool {
return self.logp.isAlmostEqual(to: other.logp, tolerance: tolerance)
&& self.logr.isAlmostEqual(to: other.logr, tolerance: tolerance)
}
}
| 28.413043 | 86 | 0.682862 |
1e1e4f3767fec0231b8fb610bb6bd9d4e4d6e10c | 1,354 | //
// DetailViewController.swift
// Example
//
// Created by Dat Ng on 6/10/19.
// Copyright © 2019 datnm ([email protected]). All rights reserved.
//
import Foundation
import UIKit
import LHCoreRxRealmApiJWTExts
import RxCocoa
import RxSwift
import SwiftyJSON
import RealmSwift
import RxRealm
class RxDetailViewController: BaseViewController {
let disposeBag = DisposeBag()
var userId: Int64 = 0
var userViewModel: SampleDetailViewModel?
@IBOutlet weak var mImageView: UIImageView!
@IBOutlet weak var mLabelFirstName: UILabel!
@IBOutlet weak var mLabelLastName: UILabel!
@IBOutlet weak var mLabelEmail: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
userViewModel = SampleDetailViewModel(id: userId)
self.bindData()
userViewModel?.fetch()
}
func bindData() {
userViewModel?.avatarString.subscribe(onNext: { [weak self] (avatar) in
self?.mImageView.alamofireSetImage(avatar)
}).disposed(by: disposeBag)
userViewModel?.firstName.asDriver().drive(mLabelFirstName.rx.text).disposed(by: disposeBag)
userViewModel?.lastName.asDriver().drive(mLabelLastName.rx.text).disposed(by: disposeBag)
userViewModel?.email.asDriver().drive(mLabelEmail.rx.text).disposed(by: disposeBag)
}
}
| 29.434783 | 99 | 0.700148 |
098fce0870726b320c047c835906de84601bb193 | 880 | import Foundation
protocol NetSocketCompatible {
var inputBuffer: Data { get set }
var timeout: Int { get set }
var totalBytesIn: Int64 { get }
var totalBytesOut: Int64 { get }
var queueBytesOut: Int64 { get }
var connected: Bool { get }
var securityLevel: StreamSocketSecurityLevel { get set }
var qualityOfService: DispatchQoS { get set }
var inputHandler: (() -> Void)? { get set }
var timeoutHandler: (() -> Void)? { get set }
var didSetTotalBytesIn: ((Int64) -> Void)? { get set }
var didSetTotalBytesOut: ((Int64) -> Void)? { get set }
var didSetConnected: ((Bool) -> Void)? { get set }
func deinitConnection(isDisconnected: Bool)
func connect(withName: String, port: Int)
func close(isDisconnected: Bool)
@discardableResult
func doOutput(data: Data, locked: UnsafeMutablePointer<UInt32>?) -> Int
}
| 35.2 | 75 | 0.664773 |
ef21d70aa4088b97cb99b15dc4d9fc3720f2333c | 747 | //
// ViewController.swift
// Remember
//
// Created by Songbai Yan on 14/11/2016.
// Copyright © 2016 Songbai Yan. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setUI()
}
private func setUI() {
self.title = "丁丁记事"
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func pushToAboutPage(_ sender: UIBarButtonItem) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 22.636364 | 85 | 0.649264 |
14eb784eb94a29ebb32c15ba5d437e18bdaca922 | 336 | //
// RouteError.swift
// CarsApp
//
// Created by Joachim Kret on 29/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
enum RouteError: Error {
case notFound(LocationType)
case invalidArguments(LocationType)
case invalidPayload(LocationType)
case unknown(LocationType, Error)
}
| 19.764706 | 55 | 0.720238 |
2f8717c213c4cb34676e2f9f20d0d74313470489 | 1,269 | // REQUIRES: objc_interop
// REQUIRES: OS=macosx
// RUN: rm -rf %t && mkdir -p %t/stats-pre && mkdir -p %t/stats-post
//
// Prime module cache
// RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -typecheck -primary-file %s %S/Inputs/NamedLazyMembers/NamedLazyMembersExt.swift
//
// Check that named-lazy-member-loading reduces the number of Decls deserialized
// RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -disable-named-lazy-member-loading -stats-output-dir %t/stats-pre -primary-file %s %S/Inputs/NamedLazyMembers/NamedLazyMembersExt.swift
// RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers -stats-output-dir %t/stats-post -primary-file %s %S/Inputs/NamedLazyMembers/NamedLazyMembersExt.swift
// RUN: %{python} %utils/process-stats-dir.py --evaluate-delta 'NumTotalClangImportedEntities < -10' %t/stats-pre %t/stats-post
import NamedLazyMembers
public func bar(d: SimpleDoerSubclass) {
let _ = d.simplyDoVeryImportantWork(speed: 10, motivation: 42)
}
public func foo(d: SimpleDoer) {
let _ = d.simplyDoSomeWork()
let _ = d.simplyDoSomeWork(withSpeed:10)
let _ = d.simplyDoVeryImportantWork(speed:10, thoroughness:12)
let _ = d.simplyDoSomeWorkWithSpeed(speed:10, levelOfAlacrity:12)
}
| 50.76 | 207 | 0.758865 |
e4a399e72d99f34398dbc9185b626ee4f6f260f4 | 8,393 | // Copyright 2018 Esri.
//
// 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 ArcGIS
class ViewshedLocationViewController: UIViewController, AGSGeoViewTouchDelegate, UIAdaptivePresentationControllerDelegate, ViewshedSettingsVCDelegate {
@IBOutlet weak var sceneView: AGSSceneView!
@IBOutlet weak var setObserverOnTapInstruction: UILabel!
@IBOutlet weak var updateObserverOnDragInstruction: UILabel!
private var viewshed: AGSLocationViewshed!
private var analysisOverlay: AGSAnalysisOverlay!
private var canMoveViewshed:Bool = false {
didSet {
setObserverOnTapInstruction.isHidden = canMoveViewshed
updateObserverOnDragInstruction.isHidden = !canMoveViewshed
}
}
private let ELEVATION_SERVICE_URL = URL(string: "https://scene.arcgis.com/arcgis/rest/services/BREST_DTM_1M/ImageServer")!
private let SCENE_LAYER_URL = URL(string: "https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Buildings_Brest/SceneServer/layers/0")!
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ViewshedLocationViewController", "ViewshedSettingsVC"]
// initialize the scene with an imagery basemap
let scene = AGSScene(basemap: AGSBasemap.imagery())
// assign the scene to the scene view
sceneView.scene = scene
// initialize the camera and set the viewpoint specified by the camera position
let camera = AGSCamera(lookAt: AGSPoint(x: -4.50, y: 48.4, z: 100.0, spatialReference: AGSSpatialReference.wgs84()), distance: 200, heading: 20, pitch: 70, roll: 0)
sceneView.setViewpointCamera(camera)
// initialize the elevation source with the service URL and add it to the base surface of the scene
let elevationSrc = AGSArcGISTiledElevationSource(url: ELEVATION_SERVICE_URL)
scene.baseSurface?.elevationSources.append(elevationSrc)
// initialize the scene layer with the scene layer URL and add it to the scene
let buildings = AGSArcGISSceneLayer(url: SCENE_LAYER_URL)
scene.operationalLayers.add(buildings)
// initialize a viewshed analysis object with arbitrary location (the location will be defined by the user), heading, pitch, view angles, and distance range (in meters) from which visibility is calculated from the observer location
viewshed = AGSLocationViewshed(location: AGSPoint(x: 0.0, y: 0.0, z: 0.0, spatialReference: AGSSpatialReference.wgs84()), heading: 20, pitch: 70, horizontalAngle: 45, verticalAngle: 90, minDistance: 50, maxDistance: 1000)
// create an analysis overlay for the viewshed and to add it to the scene view
analysisOverlay = AGSAnalysisOverlay()
analysisOverlay.analyses.add(viewshed)
sceneView.analysisOverlays.add(analysisOverlay)
//set touch delegate on scene view as self
sceneView.touchDelegate = self
}
// MARK: - UIAdaptivePresentationControllerDelegate
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
// for popover or non modal presentation
return UIModalPresentationStyle.none
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "settingsVCSegue" {
// set viewshed settings view controller
let viewshedSettingsVC = segue.destination as! ViewshedSettingsVC
viewshedSettingsVC.delegate = self
// pop over settings
viewshedSettingsVC.presentationController?.delegate = self
viewshedSettingsVC.popoverPresentationController?.passthroughViews = [sceneView]
// preferred content size
if traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular {
viewshedSettingsVC.preferredContentSize = CGSize(width: 375, height: 340)
}
else {
viewshedSettingsVC.preferredContentSize = CGSize(width: 375, height: 240)
}
}
}
// MARK: - AGSGeoViewTouchDelegate
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
canMoveViewshed = true
// update the observer location from which the viewshed is calculated
viewshed.location = mapPoint
}
func geoView(_ geoView: AGSGeoView, didTouchDownAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint, completion: @escaping (Bool) -> Void) {
// tell the ArcGIS Runtime if we are going to handle interaction
canMoveViewshed ? completion(true) : completion(false)
}
func geoView(_ geoView: AGSGeoView, didTouchDragToScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
// update the observer location from which the viewshed is calculated
viewshed.location = mapPoint
}
// MARK: - ViewshedSettingsVCDelegate
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateFrustumOutlineVisibility frustumOutlineVisibility:Bool) {
viewshed.isFrustumOutlineVisible = frustumOutlineVisibility
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateAnalysisOverlayVisibility analysisOverlayVisibility:Bool) {
analysisOverlay.isVisible = analysisOverlayVisibility
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateObstructedAreaColor obstructedAreaColor:UIColor) {
// sets the color with which non-visible areas of all viewsheds will be rendered (default: red color). This setting is applied to all viewshed analyses in the view.
AGSViewshed.setObstructedColor(obstructedAreaColor.withAlphaComponent(0.5))
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateVisibleAreaColor visibleAreaColor:UIColor) {
// sets the color with which visible areas of all viewsheds will be rendered (default: green color). This setting is applied to all viewshed analyses in the view.
AGSViewshed.setVisibleColor(visibleAreaColor.withAlphaComponent(0.5))
}
func viewshedSettingsVC(_ viewshedSettingsVC: ViewshedSettingsVC, didUpdateFrustumOutlineColor frustumOutlineColor: UIColor) {
// sets the color used to render the frustum outline (default: blue color). This setting is applied to all viewshed analyses in the view.
AGSViewshed.setFrustumOutlineColor(frustumOutlineColor)
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateHeading heading:Double) {
viewshed.heading = heading
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdatePitch pitch:Double) {
viewshed.pitch = pitch
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateHorizontalAngle horizontalAngle:Double) {
viewshed.horizontalAngle = horizontalAngle
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateVerticalAngle verticalAngle:Double) {
viewshed.verticalAngle = verticalAngle
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateMinDistance minDistance:Double) {
viewshed.minDistance = minDistance
}
func viewshedSettingsVC(_ viewshedSettingsVC:ViewshedSettingsVC, didUpdateMaxDistance maxDistance:Double) {
viewshed.maxDistance = maxDistance
}
}
| 48.235632 | 239 | 0.721196 |
01fa7b03cbc9dadf5640b9375d01291d640d0ad3 | 1,089 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "FHIRModels",
platforms: [
.macOS(.v10_13),
.iOS(.v11),
.watchOS(.v4),
.tvOS(.v11),
],
products: [
.library(name: "ModelsDSTU2", targets: ["ModelsDSTU2"]),
.library(name: "ModelsSTU3", targets: ["ModelsSTU3"]),
.library(name: "ModelsR4", targets: ["ModelsR4"]),
.library(name: "ModelsBuild", targets: ["ModelsBuild"]),
],
targets: [
.target(name: "FMCore"),
.target(name: "ModelsDSTU2", dependencies: ["FMCore"]),
.target(name: "ModelsSTU3", dependencies: ["FMCore"]),
.target(name: "ModelsR4", dependencies: ["FMCore"]),
.target(name: "ModelsBuild", dependencies: ["FMCore"]),
.testTarget(name: "CoreTests", dependencies: ["FMCore"]),
.testTarget(name: "DateTimeTests", dependencies: ["ModelsR4"]),
.testTarget(name: "ModelTests",
dependencies: [
"ModelsDSTU2",
"ModelsSTU3",
"ModelsR4",
"ModelsBuild",
]),
.testTarget(name: "PrimitiveTests", dependencies: ["ModelsR4"]),
]
)
| 30.25 | 66 | 0.608815 |
0ecca9be6e815afdb7c574fb6b5a66fee9e94a7f | 36,222 | //
// ListView.swift
// ListableUI
//
// Created by Kyle Van Essen on 6/16/19.
//
import UIKit
public final class ListView : UIView, KeyboardObserverDelegate
{
//
// MARK: Initialization
//
public init(frame: CGRect = .zero, appearance : Appearance = Appearance())
{
// Create all default values.
self.appearance = appearance
self.behavior = Behavior()
self.autoScrollAction = .none
self.scrollIndicatorInsets = .zero
self.storage = Storage()
self.environment = .empty
self.sourcePresenter = SourcePresenter(initial: StaticSource.State(), source: StaticSource())
self.dataSource = DataSource()
self.delegate = Delegate()
let initialLayout = CollectionViewLayout(
delegate: self.delegate,
layoutDescription: .table(),
appearance: self.appearance,
behavior: self.behavior
)
self.collectionView = UICollectionView(
frame: CGRect(origin: .zero, size: frame.size),
collectionViewLayout: initialLayout
)
self.layoutManager = LayoutManager(
layout: initialLayout,
collectionView: self.collectionView
)
self.liveCells = LiveCells()
self.visibleContent = VisibleContent()
self.keyboardObserver = KeyboardObserver.shared
KeyboardObserver.logKeyboardSetupWarningIfNeeded()
self.stateObserver = ListStateObserver()
self.collectionView.isPrefetchingEnabled = false
self.collectionView.dataSource = self.dataSource
self.collectionView.delegate = self.delegate
// Super init.
super.init(frame: frame)
// Associate ourselves with our child objects.
self.dataSource.presentationState = self.storage.presentationState
self.dataSource.environment = self.environment
self.dataSource.liveCells = self.liveCells
self.delegate.view = self
self.delegate.presentationState = self.storage.presentationState
self.keyboardObserver.add(delegate: self)
// Register supplementary views.
SupplementaryKind.allCases.forEach {
SupplementaryContainerView.register(in: self.collectionView, for: $0.rawValue)
}
// Size and update views.
self.collectionView.frame = self.bounds
self.addSubview(self.collectionView)
self.applyAppearance()
self.applyBehavior()
self.updateScrollViewInsets()
}
deinit
{
self.keyboardObserver.remove(delegate: self)
/**
Even though these are zeroing weak references in UIKIt as of iOS 9.0,
We still want to nil these out, because _our_ `delegate` and `dataSource`
objects have unowned references back to us (`ListView`). We do not want
any `delegate` or `dataSource` callbacks to trigger referencing
that unowned reference (eg, in `scrollViewDidScroll:`).
*/
self.collectionView.delegate = nil
self.collectionView.dataSource = nil
}
@available(*, unavailable)
required init?(coder: NSCoder) { listableFatal() }
//
// MARK: Internal Properties
//
let storage : Storage
let collectionView : UICollectionView
let delegate : Delegate
let layoutManager : LayoutManager
let liveCells : LiveCells
var collectionViewLayout : CollectionViewLayout {
self.layoutManager.collectionViewLayout
}
var performsContentCallbacks : Bool = true {
didSet {
self.storage.presentationState.performsContentCallbacks = self.performsContentCallbacks
}
}
private(set) var visibleContent : VisibleContent
//
// MARK: Private Properties
//
private var sourcePresenter : AnySourcePresenter
private var autoScrollAction : AutoScrollAction
private let dataSource : DataSource
private let keyboardObserver : KeyboardObserver
//
// MARK: Debugging
//
public var debuggingIdentifier : String? = nil
//
// MARK: Appearance
//
public var appearance : Appearance {
didSet {
guard oldValue != self.appearance else {
return
}
self.applyAppearance()
}
}
private func applyAppearance()
{
// Appearance
self.collectionViewLayout.appearance = self.appearance
self.backgroundColor = self.appearance.backgroundColor
// Scroll View
self.updateCollectionViewWithCurrentLayoutProperties()
}
//
// MARK: Layout
//
public var scrollPositionInfo : ListScrollPositionInfo {
let visibleItems = Set(self.visibleContent.items.map { item in
item.item.anyModel.identifier
})
return ListScrollPositionInfo(
scrollView: self.collectionView,
visibleItems: visibleItems,
isFirstItemVisible: self.content.firstItem.map { visibleItems.contains($0.identifier) } ?? false,
isLastItemVisible: self.content.lastItem.map { visibleItems.contains($0.identifier) } ?? false
)
}
public var layout : LayoutDescription {
get { self.collectionViewLayout.layoutDescription }
set { self.set(layout: newValue, animated: false) }
}
public func set(layout : LayoutDescription, animated : Bool = false, completion : @escaping () -> () = {})
{
self.layoutManager.set(layout: layout, animated: animated, completion: completion)
}
public var contentSize : CGSize {
return self.collectionViewLayout.layout.content.contentSize
}
//
// MARK: Behavior
//
public var behavior : Behavior {
didSet {
guard oldValue != self.behavior else {
return
}
self.applyBehavior()
}
}
private func applyBehavior()
{
self.collectionViewLayout.behavior = self.behavior
self.collectionView.keyboardDismissMode = self.behavior.keyboardDismissMode
self.collectionView.canCancelContentTouches = self.behavior.canCancelContentTouches
self.collectionView.delaysContentTouches = self.behavior.delaysContentTouches
self.updateCollectionViewWithCurrentLayoutProperties()
self.updateCollectionViewSelectionMode()
self.updateScrollViewInsets()
}
private func updateCollectionViewWithCurrentLayoutProperties()
{
self.collectionViewLayout.layout.scrollViewProperties.apply(
to: self.collectionView,
behavior: self.behavior,
direction: self.collectionViewLayout.layout.direction,
showsScrollIndicators: self.appearance.showsScrollIndicators
)
}
private func updateCollectionViewSelectionMode()
{
let view = self.collectionView
switch self.behavior.selectionMode {
case .none:
view.allowsSelection = false
view.allowsMultipleSelection = false
case .single:
view.allowsSelection = true
view.allowsMultipleSelection = false
case .multiple:
view.allowsSelection = true
view.allowsMultipleSelection = true
}
}
//
// MARK: Scroll Insets
//
public var scrollIndicatorInsets : UIEdgeInsets {
didSet {
guard oldValue != self.scrollIndicatorInsets else {
return
}
self.updateScrollViewInsets()
}
}
private func updateScrollViewInsets()
{
let (contentInsets, scrollIndicatorInsets) = self.calculateScrollViewInsets(
with: self.keyboardObserver.currentFrame(in: self)
)
if self.collectionView.contentInset != contentInsets {
self.collectionView.contentInset = contentInsets
}
if self.collectionView.scrollIndicatorInsets != scrollIndicatorInsets {
self.collectionView.scrollIndicatorInsets = scrollIndicatorInsets
}
}
func calculateScrollViewInsets(with keyboardFrame : KeyboardObserver.KeyboardFrame?) -> (UIEdgeInsets, UIEdgeInsets)
{
let keyboardBottomInset : CGFloat = {
guard let keyboardFrame = keyboardFrame else {
return 0.0
}
switch self.behavior.keyboardAdjustmentMode {
case .none:
return 0.0
case .adjustsWhenVisible:
switch keyboardFrame {
case .nonOverlapping:
return 0.0
case .overlapping(let frame):
return (self.bounds.size.height - frame.origin.y) - self.safeAreaInsets.bottom
}
}
}()
let scrollIndicatorInsets = modified(self.scrollIndicatorInsets) {
$0.bottom = max($0.bottom, keyboardBottomInset)
}
let contentInsets = modified(self.collectionView.contentInset) {
$0.bottom = keyboardBottomInset
}
return (contentInsets, scrollIndicatorInsets)
}
//
// MARK: KeyboardObserverDelegate
//
private var lastKeyboardFrame : KeyboardObserver.KeyboardFrame? = nil
func keyboardFrameWillChange(for observer: KeyboardObserver, animationDuration: Double, options: UIView.AnimationOptions) {
guard let frame = self.keyboardObserver.currentFrame(in: self) else {
return
}
guard self.lastKeyboardFrame != frame else {
return
}
self.lastKeyboardFrame = frame
UIView.animate(withDuration: animationDuration, delay: 0.0, options: options, animations: {
self.updateScrollViewInsets()
})
}
//
// MARK: List State Observation
//
/// A state observer allows you to receive callbacks when varying types
/// of changes occur within the list's state, such as scroll events,
/// content change events, frame change events, or item visibility changes.
///
/// See the `ListStateObserver` for more info.
public var stateObserver : ListStateObserver
/// Allows registering a `ListActions` object associated
/// with the list view that allows you to perform actions such as scrolling to
/// items, or controlling view appearance transitions.
private var actions : ListActions? {
didSet {
oldValue?.listView = nil
self.actions?.listView = self
}
}
//
// MARK: Public - Scrolling To Sections & Items
//
public typealias ScrollCompletion = (Bool) -> ()
///
/// Scrolls to the provided item, with the provided positioning.
/// If the item is contained in the list, true is returned. If it is not, false is returned.
///
@discardableResult
public func scrollTo(
item : AnyItem, position : ScrollPosition,
animation: ViewAnimation = .none,
completion : @escaping ScrollCompletion = { _ in }
) -> Bool
{
self.scrollTo(
item: item.identifier,
position: position,
animation: animation,
completion: completion
)
}
///
/// Scrolls to the item with the provided identifier, with the provided positioning.
/// If there is more than one item with the same identifier, the list scrolls to the first.
/// If the item is contained in the list, true is returned. If it is not, false is returned.
///
@discardableResult
public func scrollTo(
item : AnyIdentifier,
position : ScrollPosition,
animation: ViewAnimation = .none,
completion : @escaping ScrollCompletion = { _ in }
) -> Bool
{
// Make sure the item identifier is valid.
guard let toIndexPath = self.storage.allContent.firstIndexPath(for: item) else {
return false
}
return self.preparePresentationStateForScroll(to: toIndexPath) {
let isAlreadyVisible: Bool = {
let frame = self.collectionViewLayout.frameForItem(at: toIndexPath)
return self.collectionView.contentFrame.contains(frame)
}()
// If the item is already visible and that's good enough, return.
if isAlreadyVisible && position.ifAlreadyVisible == .doNothing {
return
}
animation.perform(
animations: {
self.collectionView.scrollToItem(
at: toIndexPath,
at: position.position.UICollectionViewScrollPosition,
animated: false
)
},
completion: completion
)
}
}
/// Scrolls to the very top of the list, which includes displaying the list header.
@discardableResult
public func scrollToTop(
animation: ViewAnimation = .none,
completion : @escaping ScrollCompletion = { _ in }
) -> Bool {
// The rect we scroll to must have an area – an empty rect will result in no scrolling.
let rect = CGRect(origin: .zero, size: CGSize(width: 1.0, height: 1.0))
return self.preparePresentationStateForScroll(to: IndexPath(item: 0, section: 0)) {
animation.perform(
animations: {
self.collectionView.scrollRectToVisible(rect, animated: false)
},
completion: completion
)
}
}
/// Scrolls to the last item in the list. If the list contains no items, no action is performed.
@discardableResult
public func scrollToLastItem(
animation: ViewAnimation = .none,
completion : @escaping ScrollCompletion = { _ in }
) -> Bool {
// Make sure we have a valid last index path.
guard let toIndexPath = self.storage.allContent.lastIndexPath() else {
return false
}
// Perform scrolling.
return self.preparePresentationStateForScroll(to: toIndexPath) {
let contentHeight = self.collectionViewLayout.collectionViewContentSize.height
let contentFrameHeight = self.collectionView.contentFrame.height
guard contentHeight > contentFrameHeight else {
return
}
let contentOffsetY = contentHeight - contentFrameHeight - self.collectionView.adjustedContentInset.top
let contentOffset = CGPoint(x: self.collectionView.contentOffset.x, y: contentOffsetY)
animation.perform(
animations: {
self.collectionView.setContentOffset(contentOffset, animated: false)
},
completion: completion
)
}
}
//
// MARK: Setting & Getting Content
//
public var environment : ListEnvironment {
didSet {
self.dataSource.environment = self.environment
}
}
public var content : Content {
get { return self.storage.allContent }
set { self.setContent(animated: false, newValue) }
}
public func setContent(animated : Bool = false, _ content : Content)
{
self.set(
source: StaticSource(with: content),
initial: StaticSource.State(),
animated: animated
)
}
private var sourceChangedTimer : ReloadTimer? = nil
@discardableResult
public func set<Source:ListViewSource>(source : Source, initial : Source.State, animated : Bool = false) -> StateAccessor<Source.State>
{
self.sourcePresenter.discard()
let sourcePresenter = SourcePresenter(initial: initial, source: source, didChange: { [weak self] in
guard let self = self else { return }
guard self.sourceChangedTimer == nil else { return }
self.sourceChangedTimer = ReloadTimer {
self.sourceChangedTimer = nil
self.setContentFromSource(animated: true)
}
})
self.sourcePresenter = sourcePresenter
self.setContentFromSource(animated: animated)
return StateAccessor(get: {
sourcePresenter.state
}, set: {
sourcePresenter.state = $0
})
}
public func configure(with configure : ListProperties.Configure)
{
let description = ListProperties(
animatesChanges: true,
layout: self.layout,
appearance: self.appearance,
scrollIndicatorInsets: self.scrollIndicatorInsets,
behavior: self.behavior,
autoScrollAction: self.autoScrollAction,
accessibilityIdentifier: self.collectionView.accessibilityIdentifier,
debuggingIdentifier: self.debuggingIdentifier,
configure: configure
)
self.configure(with: description)
}
public func configure(with properties : ListProperties)
{
let animated = properties.animatesChanges
self.appearance = properties.appearance
self.behavior = properties.behavior
self.autoScrollAction = properties.autoScrollAction
self.scrollIndicatorInsets = properties.scrollIndicatorInsets
self.collectionView.accessibilityIdentifier = properties.accessibilityIdentifier
self.debuggingIdentifier = properties.debuggingIdentifier
self.actions = properties.actions
self.stateObserver = properties.stateObserver
self.environment = properties.environment
self.set(layout: properties.layout, animated: animated)
self.setContent(animated: animated, properties.content)
}
private func setContentFromSource(animated : Bool = false)
{
let oldIdentifier = self.storage.allContent.identifier
self.storage.allContent = self.sourcePresenter.reloadContent()
let newIdentifier = self.storage.allContent.identifier
let identifierChanged = oldIdentifier != newIdentifier
self.updatePresentationState(for: .contentChanged(animated: animated, identifierChanged: identifierChanged))
}
//
// MARK: UIView
//
@available(*, unavailable, message: "sizeThatFits does not re-measure the size of the list. Use ListView.contentSize(in:for:) instead.")
public override func sizeThatFits(_ size: CGSize) -> CGSize {
super.sizeThatFits(size)
}
@available(*, unavailable, message: "intrinsicContentSize does not re-measure the size of the list. Use ListView.contentSize(in:for:) instead.")
public override var intrinsicContentSize: CGSize {
super.intrinsicContentSize
}
public override var frame: CGRect {
didSet {
self.frameDidChange(from: oldValue, to: self.frame)
}
}
public override var bounds: CGRect {
get { super.bounds }
set {
let oldValue = self.frame
super.bounds = newValue
self.frameDidChange(from: oldValue, to: self.frame)
}
}
private func frameDidChange(from old : CGRect, to new : CGRect) {
/// Set the frame explicitly, so that the layout can occur
/// within performBatchUpdates. Waiting for layoutSubviews() is too late.
self.collectionView.frame = self.bounds
/// If nothing has changed, there's no work here – return early.
guard old != new else {
return
}
/// Once the view actually has a size, we can provide content.
///
/// There's no value in having content with no view size, as we cannot size cells otherwise.
let fromEmpty = old.size.isEmpty && new.size.isEmpty == false
let toEmpty = old.size.isEmpty == false && new.size.isEmpty
if fromEmpty {
self.updatePresentationState(for: .transitionedToBounds(isEmpty: false))
} else if toEmpty {
self.updatePresentationState(for: .transitionedToBounds(isEmpty: true))
}
/// Our frame changed, update the keyboard inset in case the inset should now be different.
self.updateScrollViewInsets()
ListStateObserver.perform(self.stateObserver.onFrameChanged, "Frame Changed", with: self) { actions in
ListStateObserver.FrameChanged(
actions: actions,
positionInfo: self.scrollPositionInfo,
old: old,
new: new
)
}
}
public override var backgroundColor: UIColor? {
didSet {
self.collectionView.backgroundColor = self.backgroundColor
}
}
public override func didMoveToWindow()
{
super.didMoveToWindow()
if self.window != nil {
self.updateScrollViewInsets()
}
}
public override func didMoveToSuperview()
{
super.didMoveToSuperview()
if self.superview != nil {
self.updateScrollViewInsets()
}
}
override public func layoutSubviews()
{
super.layoutSubviews()
self.collectionView.frame = self.bounds
/// Our layout changed, update the keyboard inset in case the inset should now be different.
self.updateScrollViewInsets()
}
//
// MARK: Internal - Updating Content
//
internal func setPresentationStateItemPositions()
{
self.storage.presentationState.forEachItem { indexPath, item in
item.itemPosition = self.collectionViewLayout.positionForItem(at: indexPath)
}
}
private func updateCollectionViewSelections(animated : Bool)
{
let oldSelected : Set<IndexPath> = Set(self.collectionView.indexPathsForSelectedItems ?? [])
let newSelected : Set<IndexPath> = Set(self.storage.presentationState.selectedIndexPaths)
let removed = oldSelected.subtracting(newSelected)
let added = newSelected.subtracting(oldSelected)
let view = self.collectionView
let state = self.storage.presentationState
removed.forEach {
let item = state.item(at: $0)
view.deselectItem(at: $0, animated: animated)
item.applyToVisibleCell(with: self.environment)
}
added.forEach {
let item = state.item(at: $0)
view.selectItem(at: $0, animated: animated, scrollPosition: [])
item.applyToVisibleCell(with: self.environment)
}
}
//
// MARK: Internal - Updating Presentation State
//
internal func updatePresentationState(
for reason : PresentationState.UpdateReason,
completion callerCompletion : @escaping (Bool) -> () = { _ in }
) {
SignpostLogger.log(.begin, log: .updateContent, name: "List Update", for: self)
let completion = { (completed : Bool) in
callerCompletion(completed)
SignpostLogger.log(.end, log: .updateContent, name: "List Update", for: self)
}
let indexPaths = self.collectionView.indexPathsForVisibleItems
let indexPath = indexPaths.first
let presentationStateTruncated = self.storage.presentationState.containsAllItems == false
switch reason {
case .scrolledDown:
let needsUpdate = self.collectionView.isScrolledNearBottom() && presentationStateTruncated
if needsUpdate {
self.updatePresentationStateWith(firstVisibleIndexPath: indexPath, for: reason, completion: completion)
} else {
completion(true)
}
case .contentChanged:
self.updatePresentationStateWith(firstVisibleIndexPath: indexPath, for: reason, completion: completion)
case .didEndDecelerating:
if presentationStateTruncated {
self.updatePresentationStateWith(firstVisibleIndexPath: indexPath, for: reason, completion: completion)
} else {
completion(true)
}
case .scrolledToTop:
if presentationStateTruncated {
self.updatePresentationStateWith(firstVisibleIndexPath: IndexPath(item: 0, section: 0), for: reason, completion: completion)
} else {
completion(true)
}
case .transitionedToBounds(_):
self.updatePresentationStateWith(firstVisibleIndexPath: indexPath, for: reason, completion: completion)
case .programaticScrollDownTo(let scrollToIndexPath):
self.updatePresentationStateWith(firstVisibleIndexPath: scrollToIndexPath, for: reason, completion: completion)
}
}
private func updatePresentationStateWith(
firstVisibleIndexPath indexPath: IndexPath?,
for reason : PresentationState.UpdateReason,
completion callerCompletion : @escaping (Bool) -> ()
) {
// Figure out visible content.
let presentationState = self.storage.presentationState
let indexPath = indexPath ?? IndexPath(item: 0, section: 0)
let visibleSlice = self.newVisibleSlice(to: indexPath)
let diff = SignpostLogger.log(log: .updateContent, name: "Diff Content", for: self) {
ListView.diffWith(old: presentationState.sectionModels, new: visibleSlice.content.sections)
}
let updateCallbacks = UpdateCallbacks(.queue)
let updateBackingData = {
let dependencies = ItemStateDependencies(
reorderingDelegate: self,
coordinatorDelegate: self,
environmentProvider: { [weak self] in self?.environment ?? .empty }
)
presentationState.update(
with: diff,
slice: visibleSlice,
dependencies: dependencies,
updateCallbacks: updateCallbacks,
loggable: self
)
}
// Update Refresh Control
/**
Update Refresh Control
Note: Must be called *OUTSIDE* of CollectionView's `performBatchUpdates:`, otherwise
we trigger a bug where updated indexes are calculated incorrectly.
*/
presentationState.updateRefreshControl(with: visibleSlice.content.refreshControl, in: self.collectionView)
// Update Collection View
self.performBatchUpdates(with: diff, animated: reason.animated, updateBackingData: updateBackingData, completion: callerCompletion)
// Perform any needed auto scroll actions.
self.performAutoScrollAction(with: diff.changes.addedItemIdentifiers, animated: reason.animated)
// Update info for new contents.
self.updateCollectionViewSelections(animated: reason.animated)
// Notify updates.
updateCallbacks.perform()
// Notify state reader the content updated.
if case .contentChanged(_, _) = reason {
ListStateObserver.perform(self.stateObserver.onContentUpdated, "Content Updated", with: self) { actions in
ListStateObserver.ContentUpdated(
hadChanges: diff.changes.isEmpty == false,
insertionsAndRemovals: .init(diff: diff),
actions: actions,
positionInfo: self.scrollPositionInfo
)
}
}
}
private func newVisibleSlice(to indexPath : IndexPath) -> Content.Slice
{
if self.bounds.isEmpty {
return Content.Slice()
} else {
switch self.autoScrollAction {
case .scrollToItem(let insertInfo):
guard let autoScrollIndexPath = self.storage.allContent.firstIndexPath(for: insertInfo.insertedIdentifier) else {
fallthrough
}
let greaterIndexPath = max(autoScrollIndexPath, indexPath)
return self.storage.allContent.sliceTo(indexPath: greaterIndexPath)
case .none:
return self.storage.allContent.sliceTo(indexPath: indexPath)
}
}
}
private func performAutoScrollAction(with addedItems : Set<AnyIdentifier>, animated : Bool)
{
switch self.autoScrollAction {
case .none:
return
case .scrollToItem(let info):
let wasInserted = addedItems.contains(info.insertedIdentifier)
if wasInserted && info.shouldPerform(self.scrollPositionInfo) {
/// Only animate the scroll if both the update **and** the scroll action are animated.
let animation = info.animation.and(with: animated)
if let destination = info.destination.destination(with: self.content) {
self.scrollTo(item: destination, position: info.position, animation: animation) { _ in
info.didPerform(self.scrollPositionInfo)
}
}
}
}
}
private func preparePresentationStateForScroll(to toIndexPath: IndexPath, scroll: @escaping () -> Void) -> Bool {
// Make sure we have a last loaded index path.
guard let lastLoadedIndexPath = self.storage.presentationState.lastIndexPath else {
return false
}
// Update presentation state if needed, then scroll.
if lastLoadedIndexPath < toIndexPath {
self.updatePresentationState(for: .programaticScrollDownTo(toIndexPath)) { _ in
scroll()
}
} else {
scroll()
}
return true
}
private func performBatchUpdates(
with diff : SectionedDiff<Section, AnyIdentifier, AnyItem, AnyIdentifier>,
animated: Bool,
updateBackingData : @escaping () -> (),
completion callerCompletion : @escaping (Bool) -> ()
)
{
SignpostLogger.log(.begin, log: .updateContent, name: "Update UICollectionView", for: self)
let completion = { (completed : Bool) in
callerCompletion(completed)
SignpostLogger.log(.end, log: .updateContent, name: "Update UICollectionView", for: self)
}
let view = self.collectionView
let changes = CollectionViewChanges(sectionChanges: diff.changes)
let batchUpdates = {
updateBackingData()
// Sections
view.deleteSections(IndexSet(changes.deletedSections.map { $0.oldIndex }))
view.insertSections(IndexSet(changes.insertedSections.map { $0.newIndex }))
changes.movedSections.forEach {
view.moveSection($0.oldIndex, toSection: $0.newIndex)
}
// Items
view.deleteItems(at: changes.deletedItems.map { $0.oldIndex })
view.insertItems(at: changes.insertedItems.map { $0.newIndex })
changes.movedItems.forEach {
view.moveItem(at: $0.oldIndex, to: $0.newIndex)
}
self.visibleContent.updateVisibleViews(with: self.environment)
}
if changes.hasIndexAffectingChanges {
self.cancelInteractiveMovement()
}
self.collectionViewLayout.setShouldAskForItemSizesDuringLayoutInvalidation()
if animated {
view.performBatchUpdates(batchUpdates, completion: completion)
} else {
UIView.performWithoutAnimation {
view.performBatchUpdates(batchUpdates, completion: completion)
}
}
}
private static func diffWith(old : [Section], new : [Section]) -> SectionedDiff<Section, AnyIdentifier, AnyItem, AnyIdentifier>
{
return SectionedDiff(
old: old,
new: new,
configuration: SectionedDiff.Configuration(
section: .init(
identifier: { $0.info.anyIdentifier },
items: { $0.items },
movedHint: { $0.info.anyWasMoved(comparedTo: $1.info) }
),
item: .init(
identifier: { $0.identifier },
updated: { $0.anyIsEquivalent(to: $1) == false },
movedHint: { $0.anyWasMoved(comparedTo: $1) }
)
)
)
}
}
public extension ListView
{
///
/// Call this method to force an immediate, synchronous re-render of the list
/// and its content when writing unit or snapshot tests. This avoids needing to
/// spin the runloop or needing to use test expectations to wait for content
/// to be rendered asynchronously.
///
/// **WARNING**: You must **not** call this method outside of tests. Doing so will cause a fatal error.
///
func testing_forceLayoutUpdateNow()
{
guard NSClassFromString("XCTestCase") != nil else {
fatalError("You must not call testing_forceLayoutUpdateNow outside of an XCTest environment.")
}
self.collectionView.reloadData()
}
}
extension ListView : ItemContentCoordinatorDelegate
{
func coordinatorUpdated(for : AnyItem)
{
self.collectionViewLayout.setNeedsRelayout()
self.collectionView.layoutIfNeeded()
}
}
extension ListView : ReorderingActionsDelegate
{
//
// MARK: Internal - Moving Items
//
func beginInteractiveMovementFor(item : AnyPresentationItemState) -> Bool
{
guard let indexPath = self.storage.presentationState.indexPath(for: item) else {
return false
}
return self.collectionView.beginInteractiveMovementForItem(at: indexPath)
}
func updateInteractiveMovementTargetPosition(with recognizer : UIPanGestureRecognizer)
{
let position = recognizer.location(in: self.collectionView)
self.collectionView.updateInteractiveMovementTargetPosition(position)
}
func endInteractiveMovement()
{
self.collectionView.endInteractiveMovement()
}
func cancelInteractiveMovement()
{
self.collectionView.cancelInteractiveMovement()
}
}
extension ListView : SignpostLoggable
{
var signpostInfo : SignpostLoggingInfo {
SignpostLoggingInfo(
identifier: self.debuggingIdentifier,
instanceIdentifier: String(format: "%p", unsafeBitCast(self, to: Int.self))
)
}
}
fileprivate extension UIScrollView
{
func isScrolledNearBottom() -> Bool
{
let viewHeight = self.bounds.size.height
// We are within one half view height from the bottom of the content.
return self.contentOffset.y + (viewHeight * 1.5) > self.contentSize.height
}
}
| 32.750452 | 148 | 0.597786 |
89d5d6090f3019bf6ae0f905862dc3fa9016c1bb | 345 | // Copyright SIX DAY LLC. All rights reserved.
//This struct sets the amount of gas units to consume
import Foundation
import BigInt
public struct GasLimitConfiguration {
static let defaultGasLimit = BigInt(90_000)
static let minGasLimit = BigInt(21_000) // ETH transfers are always 21k
static let maxGasLimit = BigInt(1_000_000)
}
| 31.363636 | 75 | 0.768116 |
2f7fc3fed06e8bdb6390c2f79b97c98f0269532f | 11,431 | import XCTest
@testable import InstanaAgent
class HTTPMarkerTests: InstanaTestCase {
func test_marker_defaultValues() {
// Given
let url: URL = .random
let start = Date().millisecondsSince1970
// When
let marker = HTTPMarker(url: url, method: "GET", trigger: .automatic, delegate: Delegate())
// Then
XCTAssertEqual(marker.url, url)
XCTAssertEqual(marker.method, "GET")
XCTAssertEqual(marker.trigger, .automatic)
XCTAssertTrue(marker.startTime >= start)
}
func test_marker_viewname() {
// Given
let viewName = URL.random.absoluteString
// When
let marker = HTTPMarker(url: .random, method: "GET", trigger: .automatic, delegate: nil, viewName: viewName)
// Then
XCTAssertEqual(marker.viewName, viewName)
}
func test_set_HTTP_Sizes_for_task_and_transactionMetrics() {
// Given
let response = MockHTTPURLResponse(url: URL.random, mimeType: "text/plain", expectedContentLength: 1024, textEncodingName: "txt")
response.stubbedAllHeaderFields = ["KEY": "VALUE"]
let headerMetric = MockURLSessionTaskTransactionMetrics(stubbedCountOfResponseHeaderBytesReceived: 512)
let bodyMetric = MockURLSessionTaskTransactionMetrics(stubbedCountOfResponseBodyBytesReceived: 1024)
let decodedMetric = MockURLSessionTaskTransactionMetrics(stubbedCountOfResponseBodyBytesAfterDecoding: 2000)
let marker = HTTPMarker(url: URL.random, method: "GET", trigger: .automatic, delegate: Delegate())
let responseSize = HTTPMarker.Size(response: response, transactionMetrics: [headerMetric, bodyMetric, decodedMetric])
// When
marker.set(responseSize: responseSize)
// Then
XCTAssertEqual(marker.responseSize?.bodyBytes, 1024)
if #available(iOS 13.0, *) {
XCTAssertEqual(marker.responseSize?.headerBytes, 512)
XCTAssertEqual(marker.responseSize?.bodyBytesAfterDecoding, 2000)
}
}
func test_set_HTTP_Sizes_for_task() {
// Given
let url = URL(string: "https://www.some.com")!
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: ["KEY": "VALUE"])!
let marker = HTTPMarker(url: url, method: "GET", trigger: .automatic, delegate: Delegate())
let responseSize = HTTPMarker.Size(response)
let excpectedHeaderSize = Instana.Types.Bytes(NSKeyedArchiver.archivedData(withRootObject: response.allHeaderFields).count)
// When
marker.set(responseSize: responseSize)
// Then
AssertEqualAndNotZero(excpectedHeaderSize, 273)
AssertEqualAndNotZero(marker.responseSize?.headerBytes ?? 0, excpectedHeaderSize)
}
func test_finish_200() {
// Given
let backendTracingID = "d2f7aebc1ee0813c"
let delegate = Delegate()
let response = HTTPURLResponse(url: .random, statusCode: 200, httpVersion: nil, headerFields: ["Server-Timing": "intid;desc=\(backendTracingID)"])
let marker = HTTPMarker(url: .random, method: "GET", trigger: .automatic, delegate: delegate, viewName: "SomeView")
// When
marker.finish(response: response, error: nil)
// Then
XCTAssertEqual(marker.viewName, "SomeView")
XCTAssertEqual(marker.trigger, .automatic)
XCTAssertEqual(delegate.didFinishCount, 1)
XCTAssertEqual(marker.backendTracingID, backendTracingID)
if case let .finished(responseCode) = marker.state {
XCTAssertEqual(responseCode, 200)
} else {
XCTFail("Wrong marker state: \(marker.state)")
}
}
func test_marker_shouldNotRetainDelegate() {
// Given
let url: URL = .random
var delegate: Delegate = Delegate()
weak var weakDelegate = delegate
let sut = HTTPMarker(url: url, method: "b", trigger: .automatic, delegate: delegate)
delegate = Delegate()
// Then
XCTAssertNil(weakDelegate)
XCTAssertEqual(sut.url, url) // random test, so maker is not deallocated and no warning is shown
}
func test_unfished_MarkerDuration_shouldBeZero() {
// Given
let sut = HTTPMarker(url: .random, method: "b", trigger: .automatic, delegate: Delegate())
// Then
XCTAssertEqual(sut.duration, 0)
}
func test_finish_Marker_withSuccess_shouldRetainOriginalValues() {
// Given
let delegate = Delegate()
let responseSize = HTTPMarker.Size.random
let marker = HTTPMarker(url: .random, method: "b", trigger: .automatic, delegate: delegate)
// When
wait(0.1)
marker.set(responseSize: responseSize)
marker.finish(response: createMockResponse(200), error: nil)
marker.finish(response: createMockResponse(200), error: nil)
marker.cancel()
// Then
XCTAssertEqual(delegate.didFinishCount, 1)
XCTAssertEqual(marker.responseSize, responseSize)
XCTAssertTrue(marker.duration > 0)
if case let .finished(responseCode) = marker.state {
XCTAssertEqual(responseCode, 200)
} else {
XCTFail("Wrong marker state: \(marker.state)")
}
}
func test_finishing_Marker_withError_shouldRetainOriginalValues() {
// Given
let delegate = Delegate()
let marker = HTTPMarker(url: .random, method: "b", trigger: .automatic, delegate: delegate)
let error = CocoaError(CocoaError.coderValueNotFound)
let responseSize = HTTPMarker.Size.random
// When
wait(0.1)
marker.set(responseSize: responseSize)
marker.finish(response: createMockResponse(200), error: error)
marker.finish(response: createMockResponse(200), error: CocoaError(CocoaError.coderInvalidValue))
marker.finish(response: createMockResponse(300), error: nil)
// Then
XCTAssertEqual(delegate.didFinishCount, 1)
XCTAssertEqual(marker.responseSize, responseSize)
XCTAssertTrue(marker.duration > 0)
if case let .failed(e) = marker.state {
XCTAssertEqual(e as? CocoaError, error)
} else {
XCTFail("Wrong marker state: \(marker.state)")
}
}
func test_finishing_Marker_withCancel_shouldRetainOriginalValues() {
// Given
let delegate = Delegate()
let responseSize = HTTPMarker.Size.random
let marker = HTTPMarker(url: .random, method: "b", trigger: .automatic, delegate: delegate)
// When
wait(0.1)
marker.set(responseSize: responseSize)
marker.cancel()
marker.cancel()
marker.finish(response: createMockResponse(300), error: nil)
// Then
XCTAssertEqual(delegate.didFinishCount, 1)
XCTAssertEqual(marker.responseSize, responseSize)
XCTAssertTrue(marker.duration > 0)
if case .canceled = marker.state {} else {
XCTFail("Wrong marker state: \(marker.state)")
}
}
// MARK: CreateBeacon
func test_createBeacon_freshMarker() {
// Given
let url: URL = .random
let marker = HTTPMarker(url: url, method: "c", trigger: .automatic, delegate: Delegate())
// When
guard let beacon = marker.createBeacon() as? HTTPBeacon else {
XCTFail("Beacon type missmatch"); return
}
// Then
XCTAssertTrue(beacon.id.uuidString.count > 0)
XCTAssertEqual(beacon.timestamp, marker.startTime)
XCTAssertEqual(beacon.duration, 0)
XCTAssertEqual(beacon.method, "c")
XCTAssertEqual(beacon.url, url)
XCTAssertEqual(beacon.responseCode, -1)
XCTAssertNil(beacon.responseSize)
XCTAssertNil(beacon.error)
}
func test_createBeacon_finishedMarker() {
// Given
let url: URL = .random
let viewName = URL.random.absoluteString
let responseSize = HTTPMarker.Size.random
let marker = HTTPMarker(url: url, method: "m", trigger: .automatic, delegate: Delegate(), viewName: viewName)
// When
marker.set(responseSize: responseSize)
marker.finish(response: createMockResponse(204), error: nil)
guard let beacon = marker.createBeacon() as? HTTPBeacon else {
XCTFail("Beacon type missmatch"); return
}
// Then
XCTAssertEqual(beacon.viewName, viewName)
XCTAssertTrue(beacon.id.uuidString.count > 0)
XCTAssertEqual(beacon.timestamp, marker.startTime)
XCTAssertEqual(beacon.duration, marker.duration)
XCTAssertEqual(beacon.method, "m")
XCTAssertEqual(beacon.url, url)
XCTAssertEqual(beacon.responseCode, 204)
XCTAssertEqual(beacon.responseSize, responseSize)
XCTAssertNil(beacon.error)
}
func test_createBeacon_failedMarker() {
// Given
let url: URL = .random
let responseSize = HTTPMarker.Size.random
let marker = HTTPMarker(url: url, method: "t", trigger: .automatic, delegate: Delegate())
let error = NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil)
// When
marker.set(responseSize: responseSize)
marker.finish(response: createMockResponse(409), error: error)
guard let beacon = marker.createBeacon() as? HTTPBeacon else {
XCTFail("Beacon type missmatch"); return
}
// Then
XCTAssertTrue(beacon.id.uuidString.count > 0)
XCTAssertEqual(beacon.timestamp, marker.startTime)
XCTAssertEqual(beacon.duration, marker.duration)
XCTAssertEqual(beacon.method, "t")
XCTAssertEqual(beacon.url, url)
XCTAssertEqual(beacon.responseCode, -1)
AssertEqualAndNotNil(beacon.responseSize, responseSize)
AssertEqualAndNotNil(beacon.responseSize?.headerBytes, responseSize.headerBytes)
AssertEqualAndNotNil(beacon.responseSize?.bodyBytes, responseSize.bodyBytes)
AssertEqualAndNotNil(beacon.responseSize?.bodyBytesAfterDecoding, responseSize.bodyBytesAfterDecoding)
XCTAssertEqual(beacon.error, HTTPError.unknown(error))
}
func test_createBeacon_canceledMarker() {
// Given
let url: URL = .random
let marker = HTTPMarker(url: url, method: "c", trigger: .automatic, delegate: Delegate())
marker.cancel()
// When
guard let beacon = marker.createBeacon() as? HTTPBeacon else {
XCTFail("Beacon type missmatch"); return
}
// Then
XCTAssertTrue(beacon.id.uuidString.count > 0)
XCTAssertEqual(beacon.timestamp, marker.startTime)
XCTAssertEqual(beacon.duration, marker.duration)
XCTAssertEqual(beacon.method, "c")
XCTAssertEqual(beacon.url, url)
XCTAssertEqual(beacon.responseCode, -1)
XCTAssertNil(beacon.responseSize)
XCTAssertEqual(beacon.error, HTTPError.cancelled)
}
// MARK: Helper
func createMockResponse(_ statusCode: Int) -> HTTPURLResponse {
HTTPURLResponse(url: .random, statusCode: statusCode, httpVersion: nil, headerFields: nil)!
}
}
extension HTTPMarkerTests {
class Delegate: HTTPMarkerDelegate {
var didFinishCount: Int = 0
func httpMarkerDidFinish(_ marker: HTTPMarker) {
didFinishCount += 1
}
}
}
| 38.103333 | 154 | 0.655673 |
87b71773933d97eee62ee333042768d513c67227 | 24,523 | import Foundation
import Combine
extension String {
func rmPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
}
}
@objc(CloudStoreModule)
class CloudStoreModule : RCTEventEmitter {
private let domain = "iCloudModule"
private var hasListeners = false
private var iCloudURL: URL? {
FileManager.default.url(forUbiquityContainerIdentifier: nil)
}
@available(iOS 13.0, *)
private lazy var subscriberContainer = Set<AnyCancellable>()
@available(iOS 13.0, *)
private lazy var queryContainer = Set<NSMetadataQuery>()
override init() {
super.init()
// kv event
NotificationCenter.default.addObserver(forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: NSUbiquitousKeyValueStore.default, queue: nil) { [self] u in
onICloudKVStoreRemoteChanged(notification: u)
}
}
override func supportedEvents() -> [String]! {
return ["onICloudKVStoreRemoteChanged", "onICloudDocumentsStartGathering", "onICloudDocumentsGathering", "onICloudDocumentsFinishGathering", "onICloudDocumentsUpdateGathering"]
}
override func constantsToExport() -> [AnyHashable : Any] {
return ["iCloudContainerPath": iCloudURL?.path ?? ""]
}
@objc
override static func requiresMainQueueSetup() -> Bool {
return false
}
@objc
override func startObserving() {
hasListeners = true
}
@objc
override func stopObserving() {
hasListeners = false
}
// make sure iCloud exists before doing extra things
private func assertICloud(ifNil reject: RCTPromiseRejectBlock) -> Bool {
guard iCloudURL != nil else {
reject("ERR_PATH_NOT_EXIST", "iCloud container path not exists, maybe you did not enable iCloud documents capability, please check https://react-native-cloud-store.vercel.app/docs/get-started for details", NSError(domain: domain, code: 101, userInfo: nil))
return false
}
return true
}
private func createDirIfNotExists(_ dirURL: URL, ifFail reject: RCTPromiseRejectBlock) {
do {
if(!FileManager.default.fileExists(atPath: dirURL.path)) {
try FileManager.default.createDirectory(at: dirURL, withIntermediateDirectories: true, attributes: nil)
}
} catch {
reject("ERR_CREATE_DIR", error.localizedDescription, NSError(domain: "iCloudModule", code: 102, userInfo: nil))
return
}
}
private func getFullICloudURL(_ relativePath: String, isDirectory dir: Bool = false) -> URL {
return iCloudURL!.appendingPathComponent(relativePath.rmPrefix("/"), isDirectory: dir)
}
}
// MARK: kv
extension CloudStoreModule {
@objc
func onICloudKVStoreRemoteChanged(notification:Notification) {
if hasListeners {
sendEvent(withName: "onICloudKVStoreRemoteChanged", body: notification.userInfo)
}
}
@objc
func kvSync(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
let success = NSUbiquitousKeyValueStore.default.synchronize()
if(success) {
resolve(nil)
} else {
reject("ERR_KV_SYNC", "key-value sync failed, maybe caused by: 1.You did not enable key-value storage capability, please check https://react-native-cloud-store.vercel.app/docs/get-started for details. 2.User's iCloud not available.", NSError(domain: domain, code: 701, userInfo: nil))
}
}
@objc
func kvSetItem(_ key: String, and value: String,resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
NSUbiquitousKeyValueStore.default.set(value, forKey: key)
resolve(nil)
}
@objc
func kvGetItem(_ key: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
let res = NSUbiquitousKeyValueStore.default.string(forKey: key)
resolve(res)
}
@objc
func kvRemoveItem(_ key: String,resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
NSUbiquitousKeyValueStore.default.removeObject(forKey: key)
resolve(nil)
}
@objc
func kvGetAllItems(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
resolve(NSUbiquitousKeyValueStore.default.dictionaryRepresentation)
}
}
// MARK: helpers
extension CloudStoreModule {
@objc
func isICloudAvailable(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
let token = FileManager.default.ubiquityIdentityToken
resolve(token != nil)
}
}
// MARK: file
extension CloudStoreModule {
@objc
func writeFile(_ relativeFilePath: String, withContent content: String, withOptions options: NSDictionary,resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil: reject) else { return }
let override: Bool = (options["override"] as? Bool) ?? false
let fileURL = getFullICloudURL(relativeFilePath)
createDirIfNotExists(fileURL.deletingLastPathComponent(), ifFail: reject)
if(FileManager.default.fileExists(atPath: fileURL.path) && !override) {
reject("ERR_FILE_EXISTS", "file \(fileURL.path) already exists and override is false, so not create file", NSError(domain: domain, code: 201, userInfo: nil))
return
}
do {
try content.data(using: .utf8)?.write(to: fileURL)
resolve(nil)
return
} catch {
reject("ERR_WRITE_FILE", error.localizedDescription, NSError(domain: domain, code: 202, userInfo: nil))
return
}
}
@objc
func readFile(_ relativeFilePath: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil:reject) else { return }
let fileURL = getFullICloudURL(relativeFilePath)
if(!FileManager.default.fileExists(atPath: fileURL.path)) {
reject("ERR_FILE_NOT_EXISTS", "file \(fileURL.path) not exists", NSError(domain: domain, code: 401, userInfo: nil))
return
}
do {
let content = try String(contentsOf: fileURL, encoding: .utf8)
resolve(content)
} catch {
reject("ERR_READ_FILE", error.localizedDescription, NSError(domain: domain, code: 402, userInfo: nil))
}
}
}
// MARK: dir
extension CloudStoreModule {
@objc
func readDir(_ relativePath: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil: reject) else { return }
let dirURL = getFullICloudURL(relativePath)
if(!FileManager.default.fileExists(atPath: dirURL.path)) {
reject("ERR_DIR_NOT_EXISTS", "dir \(dirURL.path) not exists", NSError(domain: domain, code: 501, userInfo: nil))
return
}
do {
let contents = try FileManager.default.contentsOfDirectory(at: dirURL, includingPropertiesForKeys: nil)
resolve(contents.map {
$0.relativePath
})
} catch {
reject("ERR_LIST_FILES", error.localizedDescription, NSError(domain: domain, code: 502, userInfo: nil))
return
}
}
@objc
func createDir(_ relativePath: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil: reject) else { return }
let url = getFullICloudURL(relativePath, isDirectory: true)
createDirIfNotExists(url, ifFail: reject)
resolve(nil)
}
@objc
func moveDir(_ relativeFromPath: String, to relativeToPath: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil: reject) else { return }
do {
let srcDirURL = getFullICloudURL(relativeFromPath)
let destDirURL = getFullICloudURL(relativeToPath)
try FileManager.default.moveItem(at: srcDirURL, to: destDirURL)
resolve(nil)
} catch {
reject("ERR_MOVE_DIR", error.localizedDescription, NSError(domain: domain, code: 801, userInfo: nil))
return
}
}
}
enum ICloudGatheringFileType:String{
case upload = "upload"
case persist = "persist"
}
struct ICloudGatheringFile {
let type: ICloudGatheringFileType
let path: String
let progress: Float?
let isDir: Bool?
var dictionary: [String: Any] {
return [
"type": type.rawValue, // cannot use swift enum here, will be null in js side
"path": path,
"progress": progress as Any,
"isDir": isDir as Any
]
}
var nsDictionary: NSDictionary {
return dictionary as NSDictionary
}
}
// https://stackoverflow.com/questions/39176196/how-to-provide-a-localized-description-with-an-error-type-in-swift
enum MyError: LocalizedError {
case notExists(path: String)
public var errorDescription: String? {
switch self {
case .notExists(let path):
return "dest folder \"\(path)\" not exists, you need create it first"
}
}
}
// MARK: file or dir
extension CloudStoreModule {
// The error message of `copyItem` is misleading: when dest path folder not exists, error message is src file not exists which is not the right error message, so here I handled this bad behavior
private func copyItem(at: URL, to: URL) throws {
let parentURL = to.deletingLastPathComponent()
if FileManager.default.fileExists(atPath: parentURL.path) {
try FileManager.default.copyItem(at: at, to: to)
} else {
throw MyError.notExists(path: parentURL.path)
}
}
@objc
func copy(_ srcRelativePath: String, to destRelativePath: String, with options: NSDictionary, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil:reject) else { return }
let override = options["override"] as? Bool ?? false
let srcURL = getFullICloudURL(srcRelativePath)
let destURL = getFullICloudURL(destRelativePath)
let destExists = FileManager.default.fileExists(atPath: destURL.path)
do {
if(destExists) {
if(override) {
let _ = try FileManager.default.replaceItemAt(destURL, withItemAt: srcURL, options: .withoutDeletingBackupItem)
resolve(nil)
return
} else {
reject("ERR_DEST_EXISTS", "file or dir \"\(destURL.path)\" already exists", NSError(domain: domain, code: 303, userInfo: nil))
return
}
} else {
try copyItem(at: srcURL, to: destURL)
resolve(nil)
return
}
}
catch {
reject("ERR_COPY", error.localizedDescription, NSError(domain: domain, code: 304, userInfo: nil))
return
}
}
@objc
func unlink(_ relativePath: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil: reject) else { return }
let url = getFullICloudURL(relativePath, isDirectory: relativePath.hasSuffix("/"))
if(!FileManager.default.fileExists(atPath: url.path)) {
resolve(nil)
return;
}
do {
try FileManager.default.removeItem(at: url)
} catch {
reject("ERR_UNLINK", error.localizedDescription, NSError(domain: domain, code: 601, userInfo: nil))
return
}
resolve(nil)
}
@objc
func exist(_ relativePath: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil:reject) else { return }
let fileFullUrl = getFullICloudURL(relativePath)
resolve(FileManager.default.fileExists(atPath: fileFullUrl.path))
}
@objc
func stat(_ relativePath: String, resolver resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil:reject) else { return }
let url = getFullICloudURL(relativePath)
if(!FileManager.default.fileExists(atPath: url.path)) {
reject("ERR_NOT_EXISTS", "file \(url.path) not exists", NSError(domain: domain, code: 401, userInfo: nil))
return
}
do {
let resources = try url.resourceValues(forKeys: [
.isUbiquitousItemKey,
.ubiquitousItemContainerDisplayNameKey,
.ubiquitousItemDownloadRequestedKey,
.ubiquitousItemIsDownloadingKey,
.ubiquitousItemDownloadingStatusKey,
.ubiquitousItemDownloadingErrorKey,
.ubiquitousItemIsUploadedKey,
.ubiquitousItemIsUploadingKey,
.ubiquitousItemUploadingErrorKey,
.ubiquitousItemHasUnresolvedConflictsKey,
.contentModificationDateKey,
.creationDateKey,
.nameKey,
.localizedNameKey
])
let dict = NSMutableDictionary()
dict["isInICloud"] = resources.isUbiquitousItem
dict["containerDisplayName"] = resources.ubiquitousItemContainerDisplayName
dict["isDownloading"] = resources.ubiquitousItemIsDownloading
dict["hasCalledDownload"] = resources.ubiquitousItemDownloadRequested
dict["downloadStatus"] = resources.ubiquitousItemDownloadingStatus
dict["downloadError"] = resources.ubiquitousItemDownloadingError?.localizedDescription
dict["isUploaded"] = resources.ubiquitousItemIsUploaded
dict["isUploading"] = resources.ubiquitousItemIsUploading
dict["uploadError"] = resources.ubiquitousItemUploadingError?.localizedDescription
dict["hasUnresolvedConflicts"] = resources.ubiquitousItemHasUnresolvedConflicts
if let modifyDate = resources.contentModificationDate {
dict["modifyTimestamp"] = modifyDate.timeIntervalSince1970 * 1000
} else {
dict["modifyTimestamp"] = nil
}
if let createDate = resources.contentModificationDate {
dict["createTimestamp"] = createDate.timeIntervalSince1970 * 1000
} else {
dict["createTimestamp"] = nil
}
dict["name"] = resources.name
dict["localizedName"] = resources.localizedName
resolve(dict)
} catch {
reject("ERR_STAT", error.localizedDescription, NSError(domain: domain, code: 402, userInfo: nil))
}
}
@available(iOS 13.0, *)
private func initAndStartQuery(iCloudURL url: URL, resolver resolve: @escaping RCTPromiseResolveBlock, using enumQuery: @escaping (_ query: NSMetadataQuery) -> (NSMutableArray,Bool)) {
func getChangedItems(_ notif: Notification) -> NSDictionary {
// https://developer.apple.com/documentation/coreservices/file_metadata/mdquery/query_result_change_keys
let dict = NSMutableDictionary()
dict["added"] = (notif.userInfo?["kMDQueryUpdateAddedItems"] as? [NSMetadataItem] ?? []).map{ (i) in
return i.value(forAttribute: NSMetadataItemPathKey)
}
dict["changed"] = (notif.userInfo?["kMDQueryUpdateChangedItems"] as? [NSMetadataItem] ?? []).map{ (i) in
return i.value(forAttribute: NSMetadataItemPathKey)
}
dict["removed"] = (notif.userInfo?["kMDQueryUpdateRemovedItems"] as? [NSMetadataItem] ?? []).map{ (i) in
return i.value(forAttribute: NSMetadataItemPathKey)
}
return dict
}
let query = NSMetadataQuery()
query.operationQueue = .main
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope, NSMetadataQueryUbiquitousDataScope]
query.predicate = NSPredicate(format: "%K CONTAINS %@", NSMetadataItemPathKey,url.path)
query.notificationBatchingInterval = 0.2
// TODO: we use publisher here is for future JSI to better support such as upload('/path',{ onProgress: fn, onError: fn}) instead of listening global listeners
var startSub: AnyCancellable?
startSub = NotificationCenter.default.publisher(for: NSNotification.Name.NSMetadataQueryDidStartGathering, object: query).prefix(1).sink{ [self] n in
print("☹️start results:")
let (res, _) = enumQuery(query)
if hasListeners {
sendEvent(withName: "onICloudDocumentsStartGathering", body: NSDictionary(dictionary: [
"info": getChangedItems(n),
"detail": res
]))
}
}
startSub?.store(in: &subscriberContainer)
var gatherSub: AnyCancellable?
gatherSub = NotificationCenter.default.publisher(for: NSNotification.Name.NSMetadataQueryGatheringProgress, object: query).prefix(1).sink{ [self] n in
print("😑gather results:")
let (res, _) = enumQuery(query)
if hasListeners {
sendEvent(withName: "onICloudDocumentsGathering", body: NSDictionary(dictionary: [
"info": getChangedItems(n),
"detail": res
]))
}
}
gatherSub?.store(in: &subscriberContainer)
var finishSub: AnyCancellable?
finishSub = NotificationCenter.default.publisher(for: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: query).prefix(1).sink{ [self] n in
print("😶finish results:")
let (res, _) = enumQuery(query)
if hasListeners {
sendEvent(withName: "onICloudDocumentsFinishGathering", body: NSDictionary(dictionary: [
"info": getChangedItems(n),
"detail": res
]))
}
}
finishSub?.store(in: &subscriberContainer)
var updateSub: AnyCancellable?
updateSub = NotificationCenter.default.publisher(for: NSNotification.Name.NSMetadataQueryDidUpdate, object: query).sink{ [self] n in
print("🤠update results:")
let (res, ended) = enumQuery(query)
if ended {
print("persist query stopped")
query.stop()
updateSub?.cancel()
queryContainer.remove(query)
}
if hasListeners {
sendEvent(withName: "onICloudDocumentsUpdateGathering", body: NSDictionary(dictionary: [
"info": getChangedItems(n),
"detail": res
]))
}
}
updateSub?.store(in: &subscriberContainer)
queryContainer.insert(query)
let _ = query.start()
resolve(nil)
}
@objc
func upload(_ fullLocalPath: String, to relativePath: String, resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil: reject) else { return }
let localURL = URL(string: fullLocalPath)
guard let localURL = localURL else {
reject("ERR_INVALID_PATH", "local path \"\(fullLocalPath)\" is invalid", NSError(domain: domain, code: 801, userInfo: nil))
return
}
let iCloudURL = getFullICloudURL(relativePath)
do {
try copyItem(at: localURL, to: iCloudURL)
} catch {
reject("ERR_COPY_TO_ICLOUD", error.localizedDescription, NSError(domain: domain, code: 304, userInfo: nil))
return
}
guard #available(iOS 13, *) else {
reject("ERR_VERSION_UNSUPPORTED", "upload events only support IOS 13+",NSError(domain: domain, code: -1, userInfo: nil))
return
}
initAndStartQuery(iCloudURL: iCloudURL, resolver: resolve) { (query) in
query.disableUpdates()
var arr: [ICloudGatheringFile] = []
var ended = false
for item in query.results {
let item = item as! NSMetadataItem
let fileItemURL = item.value(forAttribute: NSMetadataItemURLKey) as! URL
let values = try? fileItemURL.resourceValues(forKeys: [.isDirectoryKey, .ubiquitousItemIsUploadingKey])
let isDir = values?.isDirectory
let isUploading = values?.ubiquitousItemIsUploading
let uploadProgress = item.value(forAttribute: NSMetadataUbiquitousItemPercentUploadedKey) as? Float
arr.append(ICloudGatheringFile(type: .upload, path: fileItemURL.path, progress: uploadProgress, isDir: isDir))
if isUploading == false && uploadProgress == 100 {
ended = true
}
print(fileItemURL," upload info: uploadProgress-\(String(describing: uploadProgress))")
}
let m: NSMutableArray = NSMutableArray()
m.addObjects(from: arr.map{$0.nsDictionary})
if !ended {
query.enableUpdates()
}
return (m, ended)
}
}
@objc
func persist(_ relativePath: String, resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
guard assertICloud(ifNil: reject) else { return }
let iCloudURL = getFullICloudURL(relativePath)
do {
// TODO: if url is a directory, this only download dir but not files under it, need to manually handle it, check https://github.com/farnots/iCloudDownloader/blob/master/iCloudDownlader/Downloader.swift for inspiration
try FileManager.default.startDownloadingUbiquitousItem(at: iCloudURL)
} catch {
reject("ERR_DOWNLOAD_ICLOUD_FILE", error.localizedDescription, NSError(
domain: domain, code: 801, userInfo: nil))
return
}
guard #available(iOS 13, *) else {
reject("ERR_VERSION_UNSUPPORTED", "persist events only support IOS 13+",NSError(domain: domain, code: -1, userInfo: nil))
return
}
initAndStartQuery(iCloudURL: iCloudURL, resolver: resolve) { query in
query.disableUpdates()
var arr: [ICloudGatheringFile] = []
var ended = false
for item in query.results {
let item = item as! NSMetadataItem
let fileItemURL = item.value(forAttribute: NSMetadataItemURLKey) as! URL
let values = try? fileItemURL.resourceValues(forKeys: [.isDirectoryKey, .ubiquitousItemDownloadingStatusKey, .ubiquitousItemIsDownloadingKey])
let isDir = values?.isDirectory
let downloadingStatus = values?.ubiquitousItemDownloadingStatus
let downloading = values?.ubiquitousItemIsDownloading
let downloadingProgress = item.value(forAttribute: NSMetadataUbiquitousItemPercentDownloadedKey) as? Float
arr.append(ICloudGatheringFile(type: .persist, path: fileItemURL.path, progress: downloadingProgress, isDir: isDir))
// stop query when one file progress is 100
if downloading == false && downloadingProgress == 100 {
ended = true
}
print(fileItemURL," download info: isDownloading-\(String(describing: downloading)),status-\(String(describing: downloadingStatus)),progress-\(String(describing: downloadingProgress))")
}
if !ended {
query.enableUpdates()
}
let m: NSMutableArray = NSMutableArray()
m.addObjects(from: arr.map{$0.nsDictionary})
return (m,ended)
}
}
}
| 40.400329 | 296 | 0.627289 |
9b8959ffc671cb4d250a902a4f0849cdfb611f18 | 416 | //
// PlantFormPresenter.swift
// Water Me
//
// Created by Karim Alweheshy on 09.09.19.
// Copyright © 2019 Karim. All rights reserved.
//
import Foundation
protocol PlantFormPresenter {
func numberOfSections() -> Int
func numberOfRows(in: Int) -> Int
func didSelectCell(at: IndexPath)
func title(for section: Int) -> String?
func cellViewModel(at: IndexPath) -> PlantFormCellViewModel
}
| 21.894737 | 63 | 0.699519 |
fbd1efb5fbbcb2e486ea612429849aebe6701eee | 1,247 | //
// theGramUITests.swift
// theGramUITests
//
// Created by macbookair11 on 3/14/16.
// Copyright © 2016 Broulaye Doumbia. All rights reserved.
//
import XCTest
class theGramUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.702703 | 182 | 0.663994 |
9c6abecc99de9153069ebeebc2af63f6eb4c21a7 | 26,202 | /* Copyright 2018 JDCLOUD.COM
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.
媒体处理相关接口
多媒体处理服务API,包括截图、转码、媒体处理消息通知等操作。本文档详细说明了媒体处理API及用法,适合开发人员阅读。
OpenAPI spec version: v1
Contact:
NOTE: This class is auto generated by the jdcloud code generator program.
*/
import Foundation
/// styleDelimiterConf
public class StyleDelimiterConf:NSObject,Codable{
/// 图片样式分隔符配置(JSON数组);支持的分隔符包含:["-", "_", "/", "!"]
/// Required:true
var delimiters:[String?]?
public init(delimiters:[String?]?){
self.delimiters = delimiters
}
enum StyleDelimiterConfCodingKeys: String, CodingKey {
case delimiters
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: StyleDelimiterConfCodingKeys.self)
self.delimiters = try decoderContainer.decode([String?]?.self, forKey: .delimiters)
}
}
public extension StyleDelimiterConf{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: StyleDelimiterConfCodingKeys.self)
try encoderContainer.encode(delimiters, forKey: .delimiters)
}
}
/// imageStyleCount
public class ImageStyleCount:NSObject,Codable{
/// 图片样式总数
var styleCount:Int?
public override init(){
super.init()
}
enum ImageStyleCountCodingKeys: String, CodingKey {
case styleCount
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ImageStyleCountCodingKeys.self)
if decoderContainer.contains(.styleCount)
{
self.styleCount = try decoderContainer.decode(Int?.self, forKey: .styleCount)
}
}
}
public extension ImageStyleCount{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ImageStyleCountCodingKeys.self)
try encoderContainer.encode(styleCount, forKey: .styleCount)
}
}
/// imageStyleID
public class ImageStyleID:NSObject,Codable{
/// 图片样式ID
var id:Int64?
public override init(){
super.init()
}
enum ImageStyleIDCodingKeys: String, CodingKey {
case id
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ImageStyleIDCodingKeys.self)
if decoderContainer.contains(.id)
{
self.id = try decoderContainer.decode(Int64?.self, forKey: .id)
}
}
}
public extension ImageStyleID{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ImageStyleIDCodingKeys.self)
try encoderContainer.encode(id, forKey: .id)
}
}
/// imageStyleQueryResult
public class ImageStyleQueryResult:NSObject,Codable{
/// 按样式名称查询
var styleName:String?
/// 数据页码
var pageNumber:Int?
/// 每页数据的条数
var pageSize:Int?
/// 图片样式列表
var imageStyleList:[ImageStyle?]?
public override init(){
super.init()
}
enum ImageStyleQueryResultCodingKeys: String, CodingKey {
case styleName
case pageNumber
case pageSize
case imageStyleList
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ImageStyleQueryResultCodingKeys.self)
if decoderContainer.contains(.styleName)
{
self.styleName = try decoderContainer.decode(String?.self, forKey: .styleName)
}
if decoderContainer.contains(.pageNumber)
{
self.pageNumber = try decoderContainer.decode(Int?.self, forKey: .pageNumber)
}
if decoderContainer.contains(.pageSize)
{
self.pageSize = try decoderContainer.decode(Int?.self, forKey: .pageSize)
}
if decoderContainer.contains(.imageStyleList)
{
self.imageStyleList = try decoderContainer.decode([ImageStyle?]?.self, forKey: .imageStyleList)
}
}
}
public extension ImageStyleQueryResult{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ImageStyleQueryResultCodingKeys.self)
try encoderContainer.encode(styleName, forKey: .styleName)
try encoderContainer.encode(pageNumber, forKey: .pageNumber)
try encoderContainer.encode(pageSize, forKey: .pageSize)
try encoderContainer.encode(imageStyleList, forKey: .imageStyleList)
}
}
/// imageStyle
public class ImageStyle:NSObject,Codable{
/// 图片样式id(readOnly)
var id:Int64?
/// 用户id(readOnly)
var userId:String?
/// 图片样式名称
var styleName:String?
/// 图片样式参数
var params:String?
/// 图片样式参数别名
var paramAlias:String?
/// 所属区域(readOnly)
var regionId:String?
/// 所属Bucket(readOnly)
var bucketName:String?
/// 图片样式状态(readOnly)
var status:Int?
/// 修改时间(readOnly)
var modifyTime:String?
/// 创建时间(readOnly)
var createdTime:String?
public override init(){
super.init()
}
enum ImageStyleCodingKeys: String, CodingKey {
case id
case userId
case styleName
case params
case paramAlias
case regionId
case bucketName
case status
case modifyTime
case createdTime
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ImageStyleCodingKeys.self)
if decoderContainer.contains(.id)
{
self.id = try decoderContainer.decode(Int64?.self, forKey: .id)
}
if decoderContainer.contains(.userId)
{
self.userId = try decoderContainer.decode(String?.self, forKey: .userId)
}
if decoderContainer.contains(.styleName)
{
self.styleName = try decoderContainer.decode(String?.self, forKey: .styleName)
}
if decoderContainer.contains(.params)
{
self.params = try decoderContainer.decode(String?.self, forKey: .params)
}
if decoderContainer.contains(.paramAlias)
{
self.paramAlias = try decoderContainer.decode(String?.self, forKey: .paramAlias)
}
if decoderContainer.contains(.regionId)
{
self.regionId = try decoderContainer.decode(String?.self, forKey: .regionId)
}
if decoderContainer.contains(.bucketName)
{
self.bucketName = try decoderContainer.decode(String?.self, forKey: .bucketName)
}
if decoderContainer.contains(.status)
{
self.status = try decoderContainer.decode(Int?.self, forKey: .status)
}
if decoderContainer.contains(.modifyTime)
{
self.modifyTime = try decoderContainer.decode(String?.self, forKey: .modifyTime)
}
if decoderContainer.contains(.createdTime)
{
self.createdTime = try decoderContainer.decode(String?.self, forKey: .createdTime)
}
}
}
public extension ImageStyle{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ImageStyleCodingKeys.self)
try encoderContainer.encode(id, forKey: .id)
try encoderContainer.encode(userId, forKey: .userId)
try encoderContainer.encode(styleName, forKey: .styleName)
try encoderContainer.encode(params, forKey: .params)
try encoderContainer.encode(paramAlias, forKey: .paramAlias)
try encoderContainer.encode(regionId, forKey: .regionId)
try encoderContainer.encode(bucketName, forKey: .bucketName)
try encoderContainer.encode(status, forKey: .status)
try encoderContainer.encode(modifyTime, forKey: .modifyTime)
try encoderContainer.encode(createdTime, forKey: .createdTime)
}
}
/// 视频截图规则参数
public class ThumbnailTaskRule:NSObject,Codable{
/// 截图模式 单张: single 多张: multi 平均: average default: single
var mode:String?
/// 是否开启关键帧截图 default: true
var keyFrame:Bool?
/// 生成截图的开始时间, mode=average 时不可选. default:0
var startTimeInSecond:Int?
/// 生成截图的结束时间, mode=single/average时不可选, 且不得小于startTimeInSecond. default:-1(代表视频时长)
var endTimeInSecond:Int?
/// 截图数量, mode=single时不可选. default:1
var count:Int?
public override init(){
super.init()
}
enum ThumbnailTaskRuleCodingKeys: String, CodingKey {
case mode
case keyFrame
case startTimeInSecond
case endTimeInSecond
case count
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ThumbnailTaskRuleCodingKeys.self)
if decoderContainer.contains(.mode)
{
self.mode = try decoderContainer.decode(String?.self, forKey: .mode)
}
if decoderContainer.contains(.keyFrame)
{
self.keyFrame = try decoderContainer.decode(Bool?.self, forKey: .keyFrame)
}
if decoderContainer.contains(.startTimeInSecond)
{
self.startTimeInSecond = try decoderContainer.decode(Int?.self, forKey: .startTimeInSecond)
}
if decoderContainer.contains(.endTimeInSecond)
{
self.endTimeInSecond = try decoderContainer.decode(Int?.self, forKey: .endTimeInSecond)
}
if decoderContainer.contains(.count)
{
self.count = try decoderContainer.decode(Int?.self, forKey: .count)
}
}
}
public extension ThumbnailTaskRule{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ThumbnailTaskRuleCodingKeys.self)
try encoderContainer.encode(mode, forKey: .mode)
try encoderContainer.encode(keyFrame, forKey: .keyFrame)
try encoderContainer.encode(startTimeInSecond, forKey: .startTimeInSecond)
try encoderContainer.encode(endTimeInSecond, forKey: .endTimeInSecond)
try encoderContainer.encode(count, forKey: .count)
}
}
/// 视频截图源文件参数
public class ThumbnailTaskSource:NSObject,Codable{
/// 输入视频信息的 bucket
/// Required:true
var bucket:String
/// 输入视频信息的 Key
/// Required:true
var key:String
public init(bucket:String,key:String){
self.bucket = bucket
self.key = key
}
enum ThumbnailTaskSourceCodingKeys: String, CodingKey {
case bucket
case key
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ThumbnailTaskSourceCodingKeys.self)
self.bucket = try decoderContainer.decode(String.self, forKey: .bucket)
self.key = try decoderContainer.decode(String.self, forKey: .key)
}
}
public extension ThumbnailTaskSource{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ThumbnailTaskSourceCodingKeys.self)
try encoderContainer.encode(bucket, forKey: .bucket)
try encoderContainer.encode(key, forKey: .key)
}
}
/// thumbnailStatus
public class ThumbnailStatus:NSObject,Codable{
/// 状态 (SUCESS, ERROR, PENDDING, RUNNING)
/// Required:true
var status:String
/// 错误码
var errorCode:Int?
/// 成功时生成的截图文件个数
var count:Int?
public init(status:String){
self.status = status
}
enum ThumbnailStatusCodingKeys: String, CodingKey {
case status
case errorCode
case count
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ThumbnailStatusCodingKeys.self)
self.status = try decoderContainer.decode(String.self, forKey: .status)
if decoderContainer.contains(.errorCode)
{
self.errorCode = try decoderContainer.decode(Int?.self, forKey: .errorCode)
}
if decoderContainer.contains(.count)
{
self.count = try decoderContainer.decode(Int?.self, forKey: .count)
}
}
}
public extension ThumbnailStatus{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ThumbnailStatusCodingKeys.self)
try encoderContainer.encode(status, forKey: .status)
try encoderContainer.encode(errorCode, forKey: .errorCode)
try encoderContainer.encode(count, forKey: .count)
}
}
/// notification
public class Notification:NSObject,Codable{
/// 是否启用通知
/// Required:true
var enabled:Bool
/// 通知endpoint, 当前支持http://和https://
var endpoint:String?
/// 触发通知的事件集合 (mpsTranscodeComplete, mpsThumbnailComplete)
var events:[String?]?
/// 重试策略, BACKOFF_RETRY: 退避重试策略, 重试 3 次, 每次重试的间隔时间是 10秒 到 20秒 之间的随机值; EXPONENTIAL_DECAY_RETRY: 指数衰减重试, 重试 176 次, 每次重试的间隔时间指数递增至 512秒, 总计重试时间为1天; 每次重试的具体间隔为: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 512 ... 512 秒(共167个512)
var notifyStrategy:String?
/// 描述了向 Endpoint 推送的消息格式, JSON: 包含消息正文和消息属性, SIMPLIFIED: 消息体即用户发布的消息, 不包含任何属性信息
var notifyContentFormat:String?
public init(enabled:Bool){
self.enabled = enabled
}
enum NotificationCodingKeys: String, CodingKey {
case enabled
case endpoint
case events
case notifyStrategy
case notifyContentFormat
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: NotificationCodingKeys.self)
self.enabled = try decoderContainer.decode(Bool.self, forKey: .enabled)
if decoderContainer.contains(.endpoint)
{
self.endpoint = try decoderContainer.decode(String?.self, forKey: .endpoint)
}
if decoderContainer.contains(.events)
{
self.events = try decoderContainer.decode([String?]?.self, forKey: .events)
}
if decoderContainer.contains(.notifyStrategy)
{
self.notifyStrategy = try decoderContainer.decode(String?.self, forKey: .notifyStrategy)
}
if decoderContainer.contains(.notifyContentFormat)
{
self.notifyContentFormat = try decoderContainer.decode(String?.self, forKey: .notifyContentFormat)
}
}
}
public extension Notification{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: NotificationCodingKeys.self)
try encoderContainer.encode(enabled, forKey: .enabled)
try encoderContainer.encode(endpoint, forKey: .endpoint)
try encoderContainer.encode(events, forKey: .events)
try encoderContainer.encode(notifyStrategy, forKey: .notifyStrategy)
try encoderContainer.encode(notifyContentFormat, forKey: .notifyContentFormat)
}
}
/// thumbnailTask
public class ThumbnailTask:NSObject,Codable{
/// 任务ID (readonly)
var taskID:String?
/// 状态 (SUCCESS, ERROR, PENDDING, RUNNING) (readonly)
var status:String?
/// 错误码 (readonly)
var errorCode:Int?
/// 任务创建时间 时间格式(GMT): yyyy-MM-dd’T’HH:mm:ss.SSS’Z’ (readonly)
var createdTime:String?
/// 任务创建时间 时间格式(GMT): yyyy-MM-dd’T’HH:mm:ss.SSS’Z’ (readonly)
var lastUpdatedTime:String?
/// Source
/// Required:true
var source:ThumbnailTaskSource
/// Target
/// Required:true
var target:ThumbnailTaskTarget
/// Rule
var rule:ThumbnailTaskRule?
public init(source:ThumbnailTaskSource,target:ThumbnailTaskTarget){
self.source = source
self.target = target
}
enum ThumbnailTaskCodingKeys: String, CodingKey {
case taskID
case status
case errorCode
case createdTime
case lastUpdatedTime
case source
case target
case rule
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ThumbnailTaskCodingKeys.self)
if decoderContainer.contains(.taskID)
{
self.taskID = try decoderContainer.decode(String?.self, forKey: .taskID)
}
if decoderContainer.contains(.status)
{
self.status = try decoderContainer.decode(String?.self, forKey: .status)
}
if decoderContainer.contains(.errorCode)
{
self.errorCode = try decoderContainer.decode(Int?.self, forKey: .errorCode)
}
if decoderContainer.contains(.createdTime)
{
self.createdTime = try decoderContainer.decode(String?.self, forKey: .createdTime)
}
if decoderContainer.contains(.lastUpdatedTime)
{
self.lastUpdatedTime = try decoderContainer.decode(String?.self, forKey: .lastUpdatedTime)
}
self.source = try decoderContainer.decode(ThumbnailTaskSource.self, forKey: .source)
self.target = try decoderContainer.decode(ThumbnailTaskTarget.self, forKey: .target)
if decoderContainer.contains(.rule)
{
self.rule = try decoderContainer.decode(ThumbnailTaskRule?.self, forKey: .rule)
}
}
}
public extension ThumbnailTask{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ThumbnailTaskCodingKeys.self)
try encoderContainer.encode(taskID, forKey: .taskID)
try encoderContainer.encode(status, forKey: .status)
try encoderContainer.encode(errorCode, forKey: .errorCode)
try encoderContainer.encode(createdTime, forKey: .createdTime)
try encoderContainer.encode(lastUpdatedTime, forKey: .lastUpdatedTime)
try encoderContainer.encode(source, forKey: .source)
try encoderContainer.encode(target, forKey: .target)
try encoderContainer.encode(rule, forKey: .rule)
}
}
/// 视频截图目标文件参数
public class ThumbnailTaskTarget:NSObject,Codable{
/// 输入存放目标文件的 bucket
/// Required:true
var destBucket:String
/// 目标截图的Key的前缀, '前缀-taskID-%04d(num).(format)', 默认: sourceKey
var destKeyPrefix:String?
/// 目标截图的格式 default: jpg
var format:String?
/// 目标截图的宽, 如果视频实际分辨率低于目标分辨率则按照实际分辨率输出 default: 0 代表源视频高 其他[8, 4096]
var widthInPixel:Int?
/// 目标截图的高, 如果视频实际分辨率低于目标分辨率则按照实际分辨率输出 default: 0 代表源视频高 其他[8, 4096]
var heightInPixel:Int?
/// 目标截图的Key的集合 (readonly)
var keys:[String?]?
public init(destBucket:String){
self.destBucket = destBucket
}
enum ThumbnailTaskTargetCodingKeys: String, CodingKey {
case destBucket
case destKeyPrefix
case format
case widthInPixel
case heightInPixel
case keys
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ThumbnailTaskTargetCodingKeys.self)
self.destBucket = try decoderContainer.decode(String.self, forKey: .destBucket)
if decoderContainer.contains(.destKeyPrefix)
{
self.destKeyPrefix = try decoderContainer.decode(String?.self, forKey: .destKeyPrefix)
}
if decoderContainer.contains(.format)
{
self.format = try decoderContainer.decode(String?.self, forKey: .format)
}
if decoderContainer.contains(.widthInPixel)
{
self.widthInPixel = try decoderContainer.decode(Int?.self, forKey: .widthInPixel)
}
if decoderContainer.contains(.heightInPixel)
{
self.heightInPixel = try decoderContainer.decode(Int?.self, forKey: .heightInPixel)
}
if decoderContainer.contains(.keys)
{
self.keys = try decoderContainer.decode([String?]?.self, forKey: .keys)
}
}
}
public extension ThumbnailTaskTarget{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ThumbnailTaskTargetCodingKeys.self)
try encoderContainer.encode(destBucket, forKey: .destBucket)
try encoderContainer.encode(destKeyPrefix, forKey: .destKeyPrefix)
try encoderContainer.encode(format, forKey: .format)
try encoderContainer.encode(widthInPixel, forKey: .widthInPixel)
try encoderContainer.encode(heightInPixel, forKey: .heightInPixel)
try encoderContainer.encode(keys, forKey: .keys)
}
}
/// thumbnailQuery
public class ThumbnailQuery:NSObject,Codable{
/// 状态 (SUCCESS, ERROR, PENDDING, RUNNING)
var status:String?
/// 查询开始时间 时间格式(GMT): yyyy-MM-dd’T’HH:mm:ss.SSS’Z’
var begin:String?
/// 查询结束时间 时间格式(GMT): yyyy-MM-dd’T’HH:mm:ss.SSS’Z’
var end:String?
/// 本次请求的marker, 标记查询的起始位置, 此处为taskID
var marker:String?
/// 本次请求返回的任务列表的最大元素个数, 有效值: [1-1000],默认值: 1000
var limit:Int?
/// 获取下一页所需要传递的marker值(此处为taskID), 仅当isTruncated为true时(数据未全部返回)出现 (readonly)
var nextMarker:String?
/// 指明返回数据是否被截断. true表示本页后面还有数据, 即数据未全部返回; false表示已是最后一页, 即数据已全部返回 (readonly)
var truncated:Bool?
/// 返回的task列表 (readonly)
var taskList:[ThumbnailTask?]?
public override init(){
super.init()
}
enum ThumbnailQueryCodingKeys: String, CodingKey {
case status
case begin
case end
case marker
case limit
case nextMarker
case truncated
case taskList
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ThumbnailQueryCodingKeys.self)
if decoderContainer.contains(.status)
{
self.status = try decoderContainer.decode(String?.self, forKey: .status)
}
if decoderContainer.contains(.begin)
{
self.begin = try decoderContainer.decode(String?.self, forKey: .begin)
}
if decoderContainer.contains(.end)
{
self.end = try decoderContainer.decode(String?.self, forKey: .end)
}
if decoderContainer.contains(.marker)
{
self.marker = try decoderContainer.decode(String?.self, forKey: .marker)
}
if decoderContainer.contains(.limit)
{
self.limit = try decoderContainer.decode(Int?.self, forKey: .limit)
}
if decoderContainer.contains(.nextMarker)
{
self.nextMarker = try decoderContainer.decode(String?.self, forKey: .nextMarker)
}
if decoderContainer.contains(.truncated)
{
self.truncated = try decoderContainer.decode(Bool?.self, forKey: .truncated)
}
if decoderContainer.contains(.taskList)
{
self.taskList = try decoderContainer.decode([ThumbnailTask?]?.self, forKey: .taskList)
}
}
}
public extension ThumbnailQuery{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ThumbnailQueryCodingKeys.self)
try encoderContainer.encode(status, forKey: .status)
try encoderContainer.encode(begin, forKey: .begin)
try encoderContainer.encode(end, forKey: .end)
try encoderContainer.encode(marker, forKey: .marker)
try encoderContainer.encode(limit, forKey: .limit)
try encoderContainer.encode(nextMarker, forKey: .nextMarker)
try encoderContainer.encode(truncated, forKey: .truncated)
try encoderContainer.encode(taskList, forKey: .taskList)
}
}
/// transcodeStatus
public class TranscodeStatus:NSObject,Codable{
/// 状态 (SUCESS, ERROR, PENDDING, RUNNING)
/// Required:true
var status:String
/// 错误码
var errorCode:Int?
/// 通知消息, 由work调用, 暂时方案
var notifyMessage:String?
public init(status:String){
self.status = status
}
enum TranscodeStatusCodingKeys: String, CodingKey {
case status
case errorCode
case notifyMessage
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: TranscodeStatusCodingKeys.self)
self.status = try decoderContainer.decode(String.self, forKey: .status)
if decoderContainer.contains(.errorCode)
{
self.errorCode = try decoderContainer.decode(Int?.self, forKey: .errorCode)
}
if decoderContainer.contains(.notifyMessage)
{
self.notifyMessage = try decoderContainer.decode(String?.self, forKey: .notifyMessage)
}
}
}
public extension TranscodeStatus{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: TranscodeStatusCodingKeys.self)
try encoderContainer.encode(status, forKey: .status)
try encoderContainer.encode(errorCode, forKey: .errorCode)
try encoderContainer.encode(notifyMessage, forKey: .notifyMessage)
}
}
/// thumbnailTaskID
public class ThumbnailTaskID:NSObject,Codable{
/// TaskID
var taskID:String?
public override init(){
super.init()
}
enum ThumbnailTaskIDCodingKeys: String, CodingKey {
case taskID
}
required public init(from decoder: Decoder) throws {
let decoderContainer = try decoder.container(keyedBy: ThumbnailTaskIDCodingKeys.self)
if decoderContainer.contains(.taskID)
{
self.taskID = try decoderContainer.decode(String?.self, forKey: .taskID)
}
}
}
public extension ThumbnailTaskID{
func encode(to encoder: Encoder) throws {
var encoderContainer = encoder.container(keyedBy: ThumbnailTaskIDCodingKeys.self)
try encoderContainer.encode(taskID, forKey: .taskID)
}
}
| 33.506394 | 223 | 0.662354 |
11ff5473479fae709808336ec41b0ff149fb9e00 | 1,272 | //
// SharedAlertsForViewControllers.swift
// Voice Magic
//
// Created by Daniel Pratt on 2/2/17.
// Copyright © 2017 Daniel Pratt. All rights reserved.
//
import UIKit
extension UIViewController {
struct Alerts {
static let DismissAlert = "Dismiss"
static let RecordingDisabledTitle = "Recording Disabled"
static let RecordingDisabledMessage = "You've disabled this app from recording your microphone. Change this in Settings -> Privacy -> Microphone"
static let RecordingFailedTitle = "Recording Failed"
static let RecordingFailedMessage = "Something went wrong with your recording."
static let AudioRecorderError = "Audio Recorder Error"
static let AudioSessionError = "Audio Session Error"
static let AudioRecordingError = "Audio Recording Error"
static let AudioFileError = "Audio File Error"
static let AudioEngineError = "Audio Engine Error"
}
func showAlert(_ title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Alerts.DismissAlert, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| 39.75 | 153 | 0.703616 |
fcc8778ffeb0161fc5c840309cd54f36f90b1d5c | 696 | //
// Operator.swift
// NStackSDK
//
// Created by Peter Bødskov on 29/07/2019.
// Copyright © 2019 Nodes ApS. All rights reserved.
//
import Foundation
infix operator <=>
/*
OK so we wan't to return the value from the translation manager, unless a local proposal exists
and we wan't to do so for the selected language
So label.text <=> tr.myvalue.myvalue = give me the string for "tr.myvalue.myvalue" for the current language
*/
public func <=> (left: NStackLocalizable, right: String) {
left.localize(for: right)
}
public func <=> (left: NStackLocalizable, right: TranslationIdentifier) {
NStack.sharedInstance.translationsManager?.localize(component: left, for: right)
}
| 25.777778 | 108 | 0.722701 |
e5f9dffb3acdc49652a91ccb3017595c35abb9ae | 523 | //
// User.swift
// First Test
//
// Created by Jesse Ruiz on 9/22/20.
// Copyright © 2020 Jesse Ruiz. All rights reserved.
//
import Foundation
struct User {
static let upgradeNotification = Notification.Name("UserUpgraded")
func upgrade(using center: NotificationCenter = NotificationCenter.default) {
DispatchQueue.global().async {
Thread.sleep(forTimeInterval: 1)
center.post(name: User.upgradeNotification, object: nil, userInfo: ["level": "gold"])
}
}
}
| 24.904762 | 97 | 0.655832 |
791e8e489d797e2b64dd40503516bacff5f2386f | 1,024 | //
// TimesyncCommonMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// Time synchronization message.
public struct Timesync {
/// Time sync timestamp 1
public let tc1: Int64
/// Time sync timestamp 2
public let ts1: Int64
}
extension Timesync: Message {
public static let id = UInt8(111)
public static var typeName = "TIMESYNC"
public static var typeDescription = "Time synchronization message."
public static var fieldDefinitions: [FieldDefinition] = [("tc1", 0, "Int64", 0, "Time sync timestamp 1"), ("ts1", 8, "Int64", 0, "Time sync timestamp 2")]
public init(data: Data) throws {
tc1 = try data.number(at: 0)
ts1 = try data.number(at: 8)
}
public func pack() throws -> Data {
var payload = Data(count: 16)
try payload.set(tc1, at: 0)
try payload.set(ts1, at: 8)
return payload
}
}
| 26.25641 | 158 | 0.675781 |
61480155b3bdbfdb4b9830420415df02724a8303 | 4,867 | //
// TaskBase.swift
// Overdrive
//
// Created by Said Sikira on 9/11/16.
// Copyright © 2016 Said Sikira. All rights reserved.
//
import class Foundation.NSObject
import class Foundation.Operation
import class Foundation.DispatchQueue
extension Operation {
/// Enqueue methods changes task state to `pending`. Default implementation
/// defined in `Operation` extension does nothing. Subclasses should override
/// this method to define how they are enqueued.
///
/// - Parameter suspended: Task queue suspended state
func enqueue(suspended: Bool) {
}
}
/// Base class of `Task<T>`, responsible for state management.
open class TaskBase: Operation {
/**
Internal task state
*/
enum State: Int, Comparable {
/// Task state is `Initialized`
case initialized
/// Task state is `Pending` and ready to evaluate conditions
case pending
/// Task is ready to execute
case ready
/// Task is executing
case executing
/// Task is finished
case finished
/**
Check if current state can be changed to other state.
You need to perform this check because task state can only occur
in already defined way.
- Parameter state: Target state
- Parameter isCancelled: Current cancelled state
- Returns: Boolean value indicating whether state change is possible
*/
func canTransition(to state: State, isCancelled cancelled: Bool) -> Bool {
switch (self, state) {
case (.initialized, .pending):
return true
case (.initialized, .finished):
return cancelled
case (.pending, .ready):
return true
case (.pending, .finished):
return cancelled
case (.ready, .executing):
return true
case (.ready, .finished):
return true
case (.executing, .finished):
return true
default:
return false
}
}
//MARK: - Comparable implementation
static func < (lhs: State, rhs: State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
static func > (lhs: State, rhs: State) -> Bool {
return lhs.rawValue > rhs.rawValue
}
}
// MARK: Dispatch queue
/// Private queue used in task state machine
let queue = DispatchQueue(label: "overdrive.task", attributes: [])
// MARK: Task state management
/// Internal task state
///
/// - warning: Setting the state directly using this property will result
/// in unexpected behaviour. Always use the `state` property to set and retrieve
/// current state.
fileprivate var internalState: State = .initialized
/// Main task state object. Any state change triggers internal `Foundation.Operation`
/// KVO observers.
///
/// - note: You can change state from any thread.
///
/// - seealso: State
var state: State {
get {
return queue.sync { return internalState }
}
set(newState) {
// Notify internal `Foundation.Operation` observers that task state will be changed
willChangeValue(forKey: "state")
queue.sync {
assert(internalState.canTransition(to: newState, isCancelled: isCancelled),
"Invalid state transformation from \(internalState) to \(newState)")
internalState = newState
}
// Notifity internal `Foundation.Operation` observers that task state is changed
didChangeValue(forKey: "state")
}
}
override func enqueue(suspended: Bool) {
if !suspended && !isCancelled { state = .pending }
}
// MARK: `Foundation.Operation` Key value observation
/// Called by `Foundation.Operation` KVO mechanisms to check if task is ready
@objc class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> {
return ["state" as NSObject]
}
/// Called by `Foundation.Operation` KVO mechanisms to check if task is executing
@objc class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state" as NSObject]
}
/// Called by `Foundation.Operation` KVO mechanisms to check if task is finished
@objc class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state" as NSObject]
}
@objc class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> {
return ["state" as NSObject]
}
}
| 31.603896 | 95 | 0.585165 |
e91c86f23e7cac3d5a98e4aa2ab8465b7371fc84 | 2,370 | //
// UserView.swift
// SwiftUIDemo
//
// Created by Le Phuong Tien on 3/22/21.
//
import SwiftUI
struct UserView: View {
typealias Action = (String) -> Void
var name: String
var action: Action?
@State var redValue: Double = 0.5
@State var blueValue: Double = 0.5
@State var greenValue: Double = 0.5
init(name: String, action: @escaping Action) {
self.name = name
self.action = action
}
var body: some View {
VStack {
HStack {
VStack {
MyAvatar(name: name, redValue: $redValue, blueValue: $blueValue, greenValue: $greenValue)
}
.frame(height: 350, alignment: .center)
VStack {
Image(systemName: "person.crop.square")
.resizable()
.aspectRatio(1.0, contentMode: .fit)
.foregroundColor(Color(red: redValue, green: greenValue, blue: blueValue, opacity: 1.0))
Text(name)
.fontWeight(.bold)
.multilineTextAlignment(.center)
Button(action: {
print("Select: \(name)")
if let action = action {
action(name)
}
redValue = Double.random(in: 0...1)
blueValue = Double.random(in: 0...1)
greenValue = Double.random(in: 0...1)
}) {
Text("Tap me!")
}
}
.frame(height: 350, alignment: .center)
}
VStack {
MyColorUISlider(color: .red, value: $redValue)
.frame(maxWidth: .infinity)
MyColorUISlider(color: .blue, value: $blueValue)
.frame(maxWidth: .infinity)
MyColorUISlider(color: .systemGreen, value: $greenValue)
.frame(maxWidth: .infinity)
}
}
.padding()
//.navigationBarTitle("Profile", displayMode: .inline)
}
}
struct UserView_Previews: PreviewProvider {
static var previews: some View {
UserView(name: "Fx Studio", action: { _ in })
}
}
| 31.6 | 112 | 0.461181 |
9ccacd65a3f1646ab3f4b7ccec2ba4d6b52d8402 | 1,002 | //
// SleepControllerTests.swift
// BoltTests
//
// Created by Robert Walker on 1/26/18.
// Copyright © 2018 Robert Walker. All rights reserved.
//
import Cocoa
import XCTest
@testable import Bolt
class SleepControllerTests: XCTestCase {
func testKeepAwake() {
let sleepController = SleepController()
sleepController.preventSleep()
XCTAssertEqual(sleepController.sleepState, .preventSleepIndefinitely)
}
func testAllowSleep() {
let sleepController = SleepController()
sleepController.allowSleep()
XCTAssertEqual(sleepController.sleepState, .allowSleep)
}
func testPerformanceKeepAwake() {
self.measure() {
let sleepController = SleepController()
sleepController.preventSleep()
XCTAssertEqual(sleepController.sleepState, .preventSleepIndefinitely)
sleepController.allowSleep()
XCTAssertEqual(sleepController.sleepState, .allowSleep)
}
}
}
| 27.833333 | 81 | 0.679641 |
486f806b4fd786d098eccf20d2f4aafd96b89b69 | 299 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<d where B : a {
}
let g : (Any) -> (e: BooleanType>: A<T> Void>()
let h = B
| 27.181818 | 87 | 0.688963 |
bbc592d023fde6a4fc7d41c69b3a9fe64647cf98 | 1,217 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//419. Battleships in a Board
//Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:
//You receive a valid board, made of only battleships or empty slots.
//Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
//At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
//Example:
//X..X
//...X
//...X
//In the above board there are 2 battleships.
//Invalid Example:
//...X
//XXXX
//...X
//This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
//Follow up:
//Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
//class Solution {
// func countBattleships(_ board: [[Character]]) -> Int {
// }
//}
// Time Is Money | 43.464286 | 189 | 0.734593 |
010633f1bd62732249f665ed5d88e2a109a752f0 | 1,296 | import UIKit
class RockMapNavigationController: UINavigationController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
}
override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience init(
rootVC: UIViewController,
naviBarClass: AnyClass?,
toolbarClass: AnyClass? = nil
) {
self.init(navigationBarClass: naviBarClass, toolbarClass: toolbarClass)
self.viewControllers = [rootVC]
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
let previousVcIndex = viewControllers.count - 1
guard
let previousVc = viewControllers.any(at: previousVcIndex)
else {
return
}
previousVc.navigationItem.backButtonDisplayMode = .minimal
super.pushViewController(viewController, animated: animated)
}
}
| 30.857143 | 90 | 0.690586 |
e2113dcf3320e4232f8eee5c1079af658e520942 | 774 | /* Copyright Airship and Contributors */
import Foundation
import AirshipKit
class InboxDelegate : NSObject, UAInboxDelegate {
var tabBarController : UITabBarController;
var messageCenterViewController : MessageCenterViewController;
init(rootViewController:UIViewController) {
self.tabBarController = rootViewController as! UITabBarController
self.messageCenterViewController = self.tabBarController.viewControllers![2] as! MessageCenterViewController;
}
func showInbox() {
DispatchQueue.main.async {
self.tabBarController.selectedIndex = 2
}
}
func showMessage(forID messageID: String) {
self.showInbox()
self.messageCenterViewController.displayMessageForID(messageID)
}
}
| 26.689655 | 117 | 0.731266 |
29ab439834a0dc25d165b9d4e8b6cece71f3db29 | 426 | //
// CandleList.swift
// ExchangeKit
//
// Created by Brendan Taylor on 9/16/17.
// Copyright © 2017 Brendan Taylor. All rights reserved.
//
import Foundation
import ObjectMapper
struct CandleList: Mappable {
fileprivate(set) var candles: [[Any]] = [[Any]]()
init?(map: Map) {
}
mutating func mapping(map: Map) {
candles <- map["response"]
}
}
| 15.777778 | 57 | 0.561033 |
1838e30695baeafc9cb3b704954725458a620a6b | 414 | //
// TYSHomeADModel.swift
// SwiftTools
//
// Created by 张书孟 on 2018/4/9.
// Copyright © 2018年 ZSM. All rights reserved.
//
import Foundation
import HandyJSON
struct TYSHomeADModel: HandyJSON {
var link_type: String? // 跳转连接类型 1html跳转
var img_path: String? // 图片地址
var link_path: String? // 连接地址
var id: String? // 数据ID
var position: String? // 位置 HOME 首页
var title: String? // 标题
}
| 20.7 | 47 | 0.65942 |
696f5feece9a950f4d16214615e35330c517d235 | 441 | //
// RepoOwner.swift
// GHCollection
//
// Created by Piotr Bogdan on 28/05/2019.
// Copyright © 2019 Piotr Bogdan. All rights reserved.
//
import UIKit
struct RepoOwner: Codable, RepoOwnerRepresenting {
let login: String
let avatarAddress: String
let profileAddress: String
enum CodingKeys: String, CodingKey {
case login
case avatarAddress = "avatar_url"
case profileAddress = "url"
}
}
| 20.045455 | 55 | 0.671202 |
ed8dee74b1dfa6eb591b93d7894c93cdef00d1de | 3,914 | //
// DZButtonMenuAttributes.swift
// DarkEggKit
//
// Created by Yuhua Hu on 2019/03/07.
//
import UIKit
public class DZButtonMenuAttributes: NSObject {
internal var padding: CGFloat = 10.0
internal var buttonDiameter: CGFloat = 40.0
internal var buttonPadding: CGFloat = 8.0
internal var labelHeight: CGFloat = 22.0
internal var animationDuration: TimeInterval = 0.3
internal var mainButtonTag: Int {
get { return 10000 }
}
internal var closedColor: UIColor = RGBA(47, 47, 47, 0.7)
private var _initialFrame: CGRect = .zero
internal var initialFrame: CGRect {
get {
return _initialFrame
}
}
public class func `default`() -> DZButtonMenuAttributes {
return DZButtonMenuAttributes()
}
public override init() {
if #available(iOS 13, *) {
closedColor = UIColor.label.withAlphaComponent(0.7)
}
else {
closedColor = RGBA(47, 47, 47, 0.7)
}
}
}
extension DZButtonMenuAttributes {
internal func initialLocation(of index: Int) -> CGPoint {
let point: CGPoint = .zero
return point
}
}
extension DZButtonMenuAttributes {
internal func mainFrameOf(location: DZButtonMenu.Location, inView: UIView) -> CGRect {
var rect: CGRect = .zero
rect.size = CGSize(width: buttonDiameter, height: buttonDiameter)
if (location.rawValue & 0b001) > 0 {
rect.origin.x = padding
}
else {
rect.origin.x = inView.frame.size.width - buttonDiameter - padding
}
if (location.rawValue & 0b010) > 0 {
let topPadding: CGFloat = DZUtility.safeAreaInsetsOf(inView).top
rect.origin.y = topPadding + padding
}
else {
let bottomPadding: CGFloat = DZUtility.safeAreaInsetsOf(inView).bottom
rect.origin.y = inView.frame.size.height - bottomPadding - padding - buttonDiameter
}
self._initialFrame = rect
return rect
}
internal func openFrameOf(configuration: DZButtonMenuConfiguration, buttonsCount: Int = 1, inView: UIView) -> CGRect {
var rect: CGRect = .zero
rect.size = CGSize(width: buttonDiameter, height: buttonDiameter)
if (configuration.location.rawValue & 0b001) > 0 {
rect.origin.x = padding
}
else {
rect.origin.x = inView.frame.size.width - buttonDiameter - padding
}
if (configuration.location.rawValue & 0b010) > 0 {
let topPadding: CGFloat = { return DZUtility.safeAreaInsetsOf(inView).top }()
rect.origin.y = topPadding + padding
}
else {
let bottomPadding: CGFloat = { return DZUtility.safeAreaInsetsOf(inView).bottom }()
rect.origin.y = inView.frame.size.height - bottomPadding - padding - buttonDiameter
}
let count = CGFloat(buttonsCount)
switch configuration.direction {
case .left:
rect.origin.x = rect.origin.x - (self.buttonDiameter + self.buttonPadding) * count
rect.size.width = (self.buttonDiameter + self.buttonPadding) * count + self.buttonDiameter
break
case .right:
rect.size.width = (self.buttonDiameter + self.buttonPadding) * count + self.buttonDiameter
break
case .up:
rect.origin.y = rect.origin.y - (self.buttonDiameter + self.buttonPadding) * count
rect.size.height = (self.buttonDiameter + self.buttonPadding) * count + self.buttonDiameter
break
case .down:
rect.size.height = (self.buttonDiameter + self.buttonPadding) * count + self.buttonDiameter
break
}
Logger.debug("location: \(configuration.location), rect: \(rect)")
return rect
}
}
| 34.034783 | 122 | 0.607563 |
3905d00417cf2e49b31ca59c898b06e2ca01a5f7 | 7,312 | //
// ViewController.swift
// Smear
//
// Created by Adam Jensen on 6/7/17.
//
import Cocoa
import AVFoundation
class ViewController: NSViewController {
@IBOutlet weak var sourcePathControl: NSPathControl!
@IBOutlet weak var shredButton: NSButtonCell!
@IBOutlet weak var collectionView: NSCollectionView!
fileprivate var avcMonkey: AVCMonkey?
fileprivate var sourceAsset: AVAsset?
fileprivate var sourceVideoTrack: AVAssetTrack?
fileprivate var frameTimes: [Int: CMTime]?
fileprivate var keyFrameIndices: [Int]?
fileprivate var imageGenerator: AVAssetImageGenerator?
override func viewDidLoad() {
super.viewDidLoad()
let nib = NSNib(nibNamed: "NSCollectionViewItem", bundle: nil)
collectionView.register(nib, forItemWithIdentifier: "FrameViewItem")
sourcePathControl.url = URL(string: NSString(string: "~/Desktop").expandingTildeInPath)
}
@IBAction func sourcePathChanged(_ sender: Any) {
guard let url = URL(string: sourcePathControl.stringValue) else {
print("Couldn't parse source URL")
return
}
let asset = AVAsset(url: url)
guard let videoTrack = asset.tracks(withMediaType: AVMediaTypeVideo).first else {
print("Couldn't find video track in asset")
return
}
let sourceFilePath = sourcePathControl.stringValue.replacingOccurrences(of: "file://", with: "")
print("Demuxing source video")
try? FileManager.default.removeItem(atPath: "/tmp/smear.h264")
try? FileManager.default.removeItem(atPath: "/tmp/smear.aac")
"/usr/local/bin/mp4box -raw 1 \(sourceFilePath) -out /tmp/smear.h264".runForSideEffects()
"/usr/local/bin/mp4box -raw 2 \(sourceFilePath) -out /tmp/smear.aac".runForSideEffects()
do {
print("Parsing video track")
if let avcMonkey = try AVCMonkey(path: "/tmp/smear.h264") {
self.avcMonkey = avcMonkey
imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator?.maximumSize = CGSize(width: 50, height: 50)
sourceAsset = asset
sourceVideoTrack = videoTrack
frameTimes = asset.frameTimesForTrack(track: videoTrack)
print("Found \(frameTimes!.count) frames")
keyFrameIndices = avcMonkey.frameNumbersForIDRFrames()
print("Found \(keyFrameIndices!.count) key frames")
collectionView.reloadData()
shredButton.isEnabled = true
}
} catch let error {
print(error)
return
}
}
@IBAction func shredButtonClicked(_ sender: Any) {
guard let keyFrameIndices = keyFrameIndices else {
assert(false, "No key frame indices available")
return
}
guard var avcMonkey = avcMonkey else {
assert(false, "No AVCMonkey instance")
return
}
let rawIndicesForKeyFrames = collectionView.selectionIndexPaths.map { keyFrameIndices[$0.item] }
rawIndicesForKeyFrames.forEach { index in
avcMonkey.removeFrame(at: index)
}
avcMonkey.write(toFilePath: "/tmp/smear-new.h264")
let panel = NSSavePanel()
panel.nameFieldStringValue = "output.mp4"
panel.begin { result in
if result == NSFileHandlingPanelOKButton, let url = panel.url {
let destinationPath = url.absoluteString.replacingOccurrences(of: "file://", with: "")
if FileManager.default.fileExists(atPath: destinationPath) {
try! FileManager.default.removeItem(atPath: destinationPath)
}
print("Writing to \(destinationPath)")
"/usr/local/bin/mp4box -add /tmp/smear-new.h264 -add /tmp/smear.aac \(destinationPath)".runForSideEffects()
}
}
}
}
extension ViewController: NSCollectionViewDataSource {
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let viewItem = collectionView.makeItem(withIdentifier: "FrameViewItem", for: indexPath)
if let frameTimes = frameTimes, let keyFrameIndices = keyFrameIndices, let nearestTimeToFrame = frameTimes[keyFrameIndices[indexPath.item]] {
// print("Request image for \(indexPath.item)")
if viewItem.imageView?.tag != indexPath.item {
viewItem.imageView?.tag = indexPath.item
imageGenerator?.generateCGImagesAsynchronously(forTimes: [NSValue(time: nearestTimeToFrame)], completionHandler: { (requestedTime, image, actualTime, resultCode, error) in
if error != nil {
print("Failed to get thumbnail at time \(requestedTime)")
} else {
// print("Got thumbnail at time \(requestedTime)")
}
DispatchQueue.main.async {
// print("Looking for \(indexPath) in \(collectionView.selectionIndexPaths)")
if collectionView.selectionIndexPaths.contains(indexPath) {
viewItem.view.layer?.backgroundColor = CGColor.black
} else {
viewItem.view.layer?.backgroundColor = CGColor.clear
}
if let imageView = viewItem.imageView, imageView.tag == indexPath.item {
if let image = image {
imageView.image = NSImage(cgImage: image, size: CGSize(width: 100, height: 100))
} else {
imageView.image = nil
}
}
}
})
}
} else {
viewItem.imageView?.tag = -1
viewItem.imageView?.image = nil
}
return viewItem
}
func numberOfSections(in collectionView: NSCollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return keyFrameIndices?.count ?? 0
}
}
extension ViewController: NSCollectionViewDelegate {
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
if let item = collectionView.item(at: indexPath) {
item.view.layer?.backgroundColor = NSColor.alternateSelectedControlColor.cgColor
}
}
}
func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
for indexPath in indexPaths {
if let item = collectionView.item(at: indexPath) {
item.view.layer?.backgroundColor = CGColor.clear
}
}
}
}
| 40.39779 | 187 | 0.581647 |
214d563e2005c8908315533d38923b9c6fb6e460 | 393 | //
// City.swift
// PrevisaoDoTempo
//
// Created by Ricardo Gehrke Filho on 03/02/16.
// Copyright © 2016 Ricardo Gehrke Filho. All rights reserved.
//
import Foundation
class City {
var id: Int
var name: String
var state: String
init(id: Int, name: String, state: String) {
self.id = id
self.name = name
self.state = state
}
} | 17.086957 | 63 | 0.587786 |
f5acf93a6196b435aab89bb8371664857244894e | 3,418 | /*-
* ---license-start
* eu-digital-green-certificates / dgca-wallet-app-ios
* ---
* Copyright (C) 2021 T-Systems International GmbH and all other 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.
* ---license-end
*/
//
// CertificateViewer.swift
// DGCAWallet
//
// Created by Yannick Spreen on 4/19/21.
//
import Foundation
import UIKit
import FloatingPanel
import SwiftDGC
class CertificateViewerVC: UIViewController {
@IBOutlet weak var headerBackground: UIView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var dismissButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var cancelButtonConstraint: NSLayoutConstraint!
var hCert: HCert!
var tan: String?
var childDismissedDelegate: CertViewerDelegate?
public var isSaved = true
func draw() {
nameLabel.text = hCert.fullName
if !isSaved {
dismissButton.setTitle(l10n("btn.save"), for: .normal)
}
headerBackground.backgroundColor = isSaved ? .blue : .grey10
nameLabel.textColor = isSaved ? .white : .black
cancelButton.alpha = isSaved ? 0 : 1
cancelButtonConstraint.priority = .init(isSaved ? 997 : 999)
view.layoutIfNeeded()
}
override func viewDidLoad() {
super.viewDidLoad()
draw()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
return
}
var newCertAdded = false
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Brightness.reset()
childDismissedDelegate?.childDismissed(newCertAdded)
}
@IBAction
func closeButtonClick() {
if isSaved {
return dismiss(animated: true, completion: nil)
}
saveCert()
}
@IBAction
func cancelButtonClick() {
dismiss(animated: true, completion: nil)
}
func saveCert() {
showInputDialog(
title: l10n("tan.confirm.title"),
subtitle: l10n("tan.confirm.text"),
inputPlaceholder: l10n("tan.confirm.placeholder")
) { [weak self] in
guard let cert = self?.hCert else {
return
}
GatewayConnection.claim(cert: cert, with: $0) { success, newTan in
if success {
guard let cert = self?.hCert else {
return
}
LocalData.add(cert, with: newTan)
self?.newCertAdded = true
self?.showAlert(
title: l10n("tan.confirm.success.title"),
subtitle: l10n("tan.confirm.success.text")
) { _ in
self?.dismiss(animated: true, completion: nil)
}
} else {
self?.showAlert(
title: l10n("tan.confirm.fail.title"),
subtitle: l10n("tan.confirm.fail.text")
)
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let child = segue.destination as? CertPagesVC {
child.embeddingVC = self
}
}
}
| 26.913386 | 77 | 0.658572 |
e2c3c3e7101fb405e99d973c0f498ad9eeaf3fb6 | 2,876 | import Foundation
import WatchKit
class UIUtils {
// Caller may not be running in Main thread
static func showAlert(presenter: WKInterfaceController, title: String, message: String, done: (() -> Void)?) {
// We are not always on the main thread so present dialog on main thread to prevent crashes
DispatchQueue.main.async {
let dismissText = NSLocalizedString("Dismiss", comment: "")
let action1 = WKAlertAction(title: dismissText, style: WKAlertActionStyle.default, handler: {
// Execute done block on dismiss
done?()
})
presenter.presentAlert(withTitle: title, message: message, preferredStyle: .alert, actions: [action1])
}
}
// Caller MUST be running in Main thread
static func showConfirm(presenter: WKInterfaceController, message: String, yes: @escaping () -> Void, no: (() -> Void)?) {
let yesText = NSLocalizedString("Yes", comment: "")
let action1 = WKAlertAction(title: yesText, style: WKAlertActionStyle.default, handler: {
yes()
})
let noText = NSLocalizedString("No", comment: "")
let action2 = WKAlertAction(title: noText, style: WKAlertActionStyle.cancel, handler: {
no?()
})
let confirmTitle = NSLocalizedString("Confirm", comment: "")
presenter.presentAlert(withTitle: confirmTitle, message: message, preferredStyle: .alert, actions: [action1, action2])
}
/// Return estimated complection date based on number of estimated seconds to completion
/// - parameter seconds: estimated number of seconds to complection
static func secondsToETA(seconds: Int) -> String {
if seconds == 0 {
return ""
} else if seconds < 0 {
// Should never happen but an OctoPrint plugin is returning negative values
// so return 'Unknown' when this happens
return NSLocalizedString("Unknown", comment: "ETA is Unknown")
}
let calendar = Calendar.current
let now = Date()
if let etaDate = calendar.date(byAdding: .second, value: seconds, to: now) {
let formatter = DateFormatter()
if Calendar.current.isDate(now, inSameDayAs:etaDate) {
// Same day so just show hour
formatter.dateStyle = .none
formatter.timeStyle = .short
} else {
// Show short version of date and hour
formatter.dateStyle = .short
formatter.timeStyle = .short
}
return formatter.string(from: etaDate)
} else {
NSLog("Failed to create ETA date")
return ""
}
}
static func isHLS(url: String) -> Bool {
return url.hasSuffix(".m3u8")
}
}
| 40.507042 | 126 | 0.59701 |
1e986c07d7ae5e290b0f2c155f96fa6099db3f6a | 2,315 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s -DINT=i%target-ptrsize
protocol A {}
protocol B {
associatedtype AA: A
func foo()
}
@objc protocol O {}
protocol C {
associatedtype OO: O
func foo()
}
struct SA: A {}
struct SB: B {
typealias AA = SA
func foo() {}
}
// CHECK-LABEL: @"$s34witness_table_objc_associated_type2SBVAA1BAAWP" = hidden constant [4 x i8*] [
// CHECK: i8* bitcast (i8** ()* @"$s34witness_table_objc_associated_type2SAVAA1AAAWa" to i8*)
// CHECK: i8* bitcast (%swift.metadata_response ([[INT]])* @"$s34witness_table_objc_associated_type2SAVMa" to i8*)
// CHECK: i8* bitcast {{.*}} @"$s34witness_table_objc_associated_type2SBVAA1BA2aDP3fooyyFTW"
// CHECK: ]
class CO: O {}
struct SO: C {
typealias OO = CO
func foo() {}
}
// CHECK-LABEL: @"$s34witness_table_objc_associated_type2SOVAA1CAAWP" = hidden constant [3 x i8*] [
// CHECK: i8* bitcast (%swift.metadata_response ([[INT]])* @"$s34witness_table_objc_associated_type2COCMa" to i8*)
// CHECK: i8* bitcast {{.*}} @"$s34witness_table_objc_associated_type2SOVAA1CA2aDP3fooyyFTW"
// CHECK: ]
// CHECK-LABEL: define hidden swiftcc void @"$s34witness_table_objc_associated_type0A25OffsetAfterAssociatedTypeyyxAA1BRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.B)
func witnessOffsetAfterAssociatedType<T: B>(_ x: T) {
// CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.B, i32 3
// CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]]
// CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]]
// CHECK: call swiftcc void [[FOO]]
x.foo()
}
// CHECK-LABEL: define hidden swiftcc void @"$s34witness_table_objc_associated_type0A29OffsetAfterAssociatedTypeObjCyyxAA1CRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.C) {{.*}} {
func witnessOffsetAfterAssociatedTypeObjC<T: C>(_ x: T) {
// CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.C, i32 2
// CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]]
// CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]]
// CHECK: call swiftcc void [[FOO]]
x.foo()
}
| 42.090909 | 204 | 0.653132 |
e89dc81e241d5b7c94d9f2d44bf0066b1f597a83 | 4,343 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 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 Swift project authors
*/
import PackageModel
import Workspace
import SPMBuildCore
import Basics
public extension Destination {
static func forKlepto(
diagnostics: DiagnosticsEngine,
dkp devkitproPath: String,
toolchain kleptoToolchainPath: String,
kleptoSpecsPath: String,
kleptoIsystem: [String],
kleptoIcuPaths: [String],
kleptoLlvmBinPath: String
) -> Destination? {
let ccFlags = [
"-Wno-gnu-include-next",
"-D__SWITCH__",
"-D__DEVKITA64__",
"-D__unix__",
"-D__linux__",
"-fPIE",
"-nostdinc",
"-nostdinc++",
"-D_POSIX_C_SOURCE=200809",
"-D_GNU_SOURCE",
// libnx already included in isystem
"-I\(devkitproPath)/portlibs/switch/include/",
"-fno-blocks",
"-mno-tls-direct-seg-refs",
"-Qunused-arguments",
"-Xclang", "-target-feature",
"-Xclang", "+read-tp-soft",
"-ftls-model=local-exec",
] + kleptoIsystem.map {"-isystem\($0)"}
var swiftcFlags = [
"-static-stdlib",
"-D", "__SWITCH__",
]
for ccFlag in ccFlags {
swiftcFlags += ["-Xcc", ccFlag]
}
let triple = try! Triple("aarch64-none-unknown-elf")
var destination = Destination(
target: triple,
sdk: AbsolutePath(kleptoToolchainPath),
binDir: AbsolutePath(kleptoToolchainPath).appending(components: "usr", "bin"),
extraCCFlags: ccFlags,
extraSwiftCFlags: swiftcFlags,
extraCPPFlags: ccFlags
)
destination.devkitproPath = devkitproPath
destination.kleptoSpecsPath = kleptoSpecsPath
destination.kleptoIcuPaths = kleptoIcuPaths
destination.kleptoLlvmBinPath = kleptoLlvmBinPath
destination.isKlepto = true
return destination
}
}
public extension ManifestLoader {
convenience init(
manifestResources: ManifestResourceProvider,
serializedDiagnostics: Bool = false,
isManifestSandboxEnabled: Bool = true,
cacheDir: AbsolutePath? = nil,
delegate: ManifestLoaderDelegate? = nil,
extraManifestFlags: [String] = [],
klepto: Bool
) {
self.init(
manifestResources: manifestResources,
serializedDiagnostics: serializedDiagnostics,
isManifestSandboxEnabled: isManifestSandboxEnabled,
cacheDir: cacheDir,
delegate: delegate,
extraManifestFlags: extraManifestFlags + (klepto ? ["-D", "__SWITCH__"] : [])
)
}
}
public func buildKleptoLinkArguments(
productType: ProductType,
devkitproPath: String,
binaryPath: String,
kleptoSpecsPath: String,
kleptoIcuPaths: [String],
kleptoLlvmBinPath: String
) throws -> [String] {
if productType == .nxApplication {
var args: [String] = []
let additional_args = [
"-Map", "\(binaryPath).map",
]
for arg in additional_args {
args += ["-Xlinker", arg]
}
args += ["-static-executable"]
args += ["-use-ld=\(devkitproPath)/devkitA64/bin"]
args += ["-tools-directory", kleptoLlvmBinPath]
args += ["-specs=\(kleptoSpecsPath)"]
for path in kleptoIcuPaths {
args += ["-Xlinker", "-L\(path)"]
}
args += ["-Xlinker", "-L\(devkitproPath)/libnx/lib"]
args += ["-Xlinker", "-L\(devkitproPath)/portlibs/switch/lib"]
args += ["-Xlinker", "-lnx"]
return args
}
else {
throw InternalError("product type not supported")
}
}
public func buildKleptoElf2NroArguments(
devkitproPath: String,
input: AbsolutePath,
output: AbsolutePath
) -> [String] {
return [
"\(devkitproPath)/tools/bin/elf2nro",
input.pathString,
output.pathString
]
}
| 29.147651 | 90 | 0.587382 |
4b4d84842ca6d68e8bd3aca09d99ee298c351adb | 2,964 | //
// NodeTrigger.swift
// VPL
//
// Created by Nathan Flurry on 3/28/18.
// Copyright © 2018 Nathan Flurry. All rights reserved.
//
public final class InputTrigger {
/// The node that owns this trigger.
public internal(set) weak var owner: Node!
/// The connected trigger.
public private(set) var target: OutputTrigger?
public init() {
}
/// Determines if two triggers can be connected.
public func canConnect(to newTarget: OutputTrigger) -> Bool {
return newTarget.canConnect(to: self)
}
/// Connects this trigger to another trigger.
public func connect(to newTarget: OutputTrigger) {
// Set the new target
target = newTarget
// Connect the other node
if newTarget.target !== self {
newTarget.connect(to: self)
}
}
/// Disconnects any targets this is connected to.
public func reset() {
// Remove the target
let tmpTarget = target
target = nil
// Remove other target if needed
if tmpTarget?.target != nil {
tmpTarget?.reset()
}
}
}
public final class OutputTrigger {
/// The node that owns this trigger
public internal(set) weak var owner: Node!
/// An identifier for this trigger.
public let id: String
/// Name for this trigger.
public let name: String
/// The connected trigger.
public private(set) var target: InputTrigger?
/// Variables availables to any other nodes further along the control flow.
public let exposedVariables: [NodeVariable]
public init(id: String, name: String, exposedVariables: [NodeVariable] = []) {
self.id = id
self.name = name
self.exposedVariables = exposedVariables
// Set owner on variables
for variable in exposedVariables {
variable.owner = self
}
}
public convenience init(exposedVariables: [NodeVariable] = []) {
self.init(id: "next", name: "Next", exposedVariables: exposedVariables)
}
/// Determines if two triggers can be connected.
public func canConnect(to newTarget: InputTrigger) -> Bool {
return owner !== newTarget.owner && target == nil && newTarget.target == nil
}
/// Connects this trigger to another trigger.
public func connect(to newTarget: InputTrigger) {
// Set the new target
target = newTarget
// Connect the other node
if newTarget.target !== self {
newTarget.connect(to: self)
}
}
/// Disconnects any targets this is connected to.
public func reset() {
// Remove the target
let tmpTarget = target
target = nil
// Remove other target if needed
if tmpTarget?.target != nil {
tmpTarget?.reset()
}
}
/// Assembles the code.
public func assemble() -> String {
return target?.owner.assemble() ?? ""
}
}
| 26.230088 | 84 | 0.608637 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.