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
714ead1312eeecda65ebb196947c466e5bdc3da9
8,561
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore /// Error enum for DAX public enum DAXErrorType: AWSErrorType { case clusterAlreadyExistsFault(message: String?) case clusterNotFoundFault(message: String?) case clusterQuotaForCustomerExceededFault(message: String?) case insufficientClusterCapacityFault(message: String?) case invalidARNFault(message: String?) case invalidClusterStateFault(message: String?) case invalidParameterCombinationException(message: String?) case invalidParameterGroupStateFault(message: String?) case invalidParameterValueException(message: String?) case invalidSubnet(message: String?) case invalidVPCNetworkStateFault(message: String?) case nodeNotFoundFault(message: String?) case nodeQuotaForClusterExceededFault(message: String?) case nodeQuotaForCustomerExceededFault(message: String?) case parameterGroupAlreadyExistsFault(message: String?) case parameterGroupNotFoundFault(message: String?) case parameterGroupQuotaExceededFault(message: String?) case serviceLinkedRoleNotFoundFault(message: String?) case subnetGroupAlreadyExistsFault(message: String?) case subnetGroupInUseFault(message: String?) case subnetGroupNotFoundFault(message: String?) case subnetGroupQuotaExceededFault(message: String?) case subnetInUse(message: String?) case subnetQuotaExceededFault(message: String?) case tagNotFoundFault(message: String?) case tagQuotaPerResourceExceeded(message: String?) } extension DAXErrorType { public init?(errorCode: String, message: String?) { var errorCode = errorCode if let index = errorCode.firstIndex(of: "#") { errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...]) } switch errorCode { case "ClusterAlreadyExistsFault": self = .clusterAlreadyExistsFault(message: message) case "ClusterNotFoundFault": self = .clusterNotFoundFault(message: message) case "ClusterQuotaForCustomerExceededFault": self = .clusterQuotaForCustomerExceededFault(message: message) case "InsufficientClusterCapacityFault": self = .insufficientClusterCapacityFault(message: message) case "InvalidARNFault": self = .invalidARNFault(message: message) case "InvalidClusterStateFault": self = .invalidClusterStateFault(message: message) case "InvalidParameterCombinationException": self = .invalidParameterCombinationException(message: message) case "InvalidParameterGroupStateFault": self = .invalidParameterGroupStateFault(message: message) case "InvalidParameterValueException": self = .invalidParameterValueException(message: message) case "InvalidSubnet": self = .invalidSubnet(message: message) case "InvalidVPCNetworkStateFault": self = .invalidVPCNetworkStateFault(message: message) case "NodeNotFoundFault": self = .nodeNotFoundFault(message: message) case "NodeQuotaForClusterExceededFault": self = .nodeQuotaForClusterExceededFault(message: message) case "NodeQuotaForCustomerExceededFault": self = .nodeQuotaForCustomerExceededFault(message: message) case "ParameterGroupAlreadyExistsFault": self = .parameterGroupAlreadyExistsFault(message: message) case "ParameterGroupNotFoundFault": self = .parameterGroupNotFoundFault(message: message) case "ParameterGroupQuotaExceededFault": self = .parameterGroupQuotaExceededFault(message: message) case "ServiceLinkedRoleNotFoundFault": self = .serviceLinkedRoleNotFoundFault(message: message) case "SubnetGroupAlreadyExistsFault": self = .subnetGroupAlreadyExistsFault(message: message) case "SubnetGroupInUseFault": self = .subnetGroupInUseFault(message: message) case "SubnetGroupNotFoundFault": self = .subnetGroupNotFoundFault(message: message) case "SubnetGroupQuotaExceededFault": self = .subnetGroupQuotaExceededFault(message: message) case "SubnetInUse": self = .subnetInUse(message: message) case "SubnetQuotaExceededFault": self = .subnetQuotaExceededFault(message: message) case "TagNotFoundFault": self = .tagNotFoundFault(message: message) case "TagQuotaPerResourceExceeded": self = .tagQuotaPerResourceExceeded(message: message) default: return nil } } } extension DAXErrorType: CustomStringConvertible { public var description: String { switch self { case .clusterAlreadyExistsFault(let message): return "ClusterAlreadyExistsFault: \(message ?? "")" case .clusterNotFoundFault(let message): return "ClusterNotFoundFault: \(message ?? "")" case .clusterQuotaForCustomerExceededFault(let message): return "ClusterQuotaForCustomerExceededFault: \(message ?? "")" case .insufficientClusterCapacityFault(let message): return "InsufficientClusterCapacityFault: \(message ?? "")" case .invalidARNFault(let message): return "InvalidARNFault: \(message ?? "")" case .invalidClusterStateFault(let message): return "InvalidClusterStateFault: \(message ?? "")" case .invalidParameterCombinationException(let message): return "InvalidParameterCombinationException: \(message ?? "")" case .invalidParameterGroupStateFault(let message): return "InvalidParameterGroupStateFault: \(message ?? "")" case .invalidParameterValueException(let message): return "InvalidParameterValueException: \(message ?? "")" case .invalidSubnet(let message): return "InvalidSubnet: \(message ?? "")" case .invalidVPCNetworkStateFault(let message): return "InvalidVPCNetworkStateFault: \(message ?? "")" case .nodeNotFoundFault(let message): return "NodeNotFoundFault: \(message ?? "")" case .nodeQuotaForClusterExceededFault(let message): return "NodeQuotaForClusterExceededFault: \(message ?? "")" case .nodeQuotaForCustomerExceededFault(let message): return "NodeQuotaForCustomerExceededFault: \(message ?? "")" case .parameterGroupAlreadyExistsFault(let message): return "ParameterGroupAlreadyExistsFault: \(message ?? "")" case .parameterGroupNotFoundFault(let message): return "ParameterGroupNotFoundFault: \(message ?? "")" case .parameterGroupQuotaExceededFault(let message): return "ParameterGroupQuotaExceededFault: \(message ?? "")" case .serviceLinkedRoleNotFoundFault(let message): return "ServiceLinkedRoleNotFoundFault: \(message ?? "")" case .subnetGroupAlreadyExistsFault(let message): return "SubnetGroupAlreadyExistsFault: \(message ?? "")" case .subnetGroupInUseFault(let message): return "SubnetGroupInUseFault: \(message ?? "")" case .subnetGroupNotFoundFault(let message): return "SubnetGroupNotFoundFault: \(message ?? "")" case .subnetGroupQuotaExceededFault(let message): return "SubnetGroupQuotaExceededFault: \(message ?? "")" case .subnetInUse(let message): return "SubnetInUse: \(message ?? "")" case .subnetQuotaExceededFault(let message): return "SubnetQuotaExceededFault: \(message ?? "")" case .tagNotFoundFault(let message): return "TagNotFoundFault: \(message ?? "")" case .tagQuotaPerResourceExceeded(let message): return "TagQuotaPerResourceExceeded: \(message ?? "")" } } }
49.773256
158
0.677374
f7d9e8d239041079f2fd9b77c673f565468919f3
3,012
// Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length // swiftlint:disable identifier_name line_length type_body_length internal enum L10n { internal enum Localizable { /// Some alert body there internal static let alertMessage = L10n.tr("Localizable", "alert_message") /// Title of the alert internal static let alertTitle = L10n.tr("Localizable", "alert_title") /// These are %3$@'s %1$d %2$@. internal static func objectOwnership(_ p1: Int, _ p2: String, _ p3: String) -> String { return L10n.tr("Localizable", "ObjectOwnership", p1, p2, p3) } /// Hello, my name is %@ and I'm %d internal static func `private`(_ p1: String, _ p2: Int) -> String { return L10n.tr("Localizable", "private", p1, p2) } /// You have %d apples internal static func applesCount(_ p1: Int) -> String { return L10n.tr("Localizable", "apples.count", p1) } /// Those %d bananas belong to %@. internal static func bananasOwner(_ p1: Int, _ p2: String) -> String { return L10n.tr("Localizable", "bananas.owner", p1, p2) } /// Some Reserved Keyword there internal static let settingsNavigationBarSelf = L10n.tr("Localizable", "settings.navigation-bar.self") /// DeepSettings internal static let settingsNavigationBarTitleDeeperThanWeCanHandleNoReallyThisIsDeep = L10n.tr("Localizable", "settings.navigation-bar.title.deeper.than.we.can.handle.no.really.this.is.deep") /// Settings internal static let settingsNavigationBarTitleEvenDeeper = L10n.tr("Localizable", "settings.navigation-bar.title.even.deeper") /// Here you can change some user profile settings. internal static let settingsUserProfileSectionFooterText = L10n.tr("Localizable", "settings.user_profile_section.footer_text") /// User Profile Settings internal static let settingsUserProfileSectionHEADERTITLE = L10n.tr("Localizable", "settings.user_profile_section.HEADER_TITLE") } internal enum LocMultiline { /// multi\nline internal static let multiline = L10n.tr("LocMultiline", "MULTILINE") /// test internal static let multiLineNKey = L10n.tr("LocMultiline", "multiLine\nKey") /// another\nmulti\n line internal static let multiline2 = L10n.tr("LocMultiline", "MULTILINE2") /// single line internal static let singleline = L10n.tr("LocMultiline", "SINGLELINE") /// another single line internal static let singleline2 = L10n.tr("LocMultiline", "SINGLELINE2") } } // swiftlint:enable identifier_name line_length type_body_length extension L10n { private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String { let format = NSLocalizedString(key, tableName: table, bundle: Bundle(for: BundleToken.self), comment: "") return String(format: format, locale: Locale.current, arguments: args) } } private final class BundleToken {}
46.338462
196
0.712815
e247742380e3d5f6a8826e647026aa14d88058c8
906
// // DoneViewController.swift // Agendawg // // Created by Sam Gehman on 9/2/17. // Copyright © 2017 Sam Gehman. All rights reserved. // import UIKit class DoneViewController: UIViewController { static let personalWebsiteURL = URL(string:"http://www.samgehman.com/")! static let icons8URL = URL(string:"https://icons8.com/icon/41662/News")! override func viewDidLoad() { super.viewDidLoad() } @IBAction func openPersonalWebsite(_ sender: Any) { UIApplication.shared.open(DoneViewController.personalWebsiteURL, options: [:], completionHandler: nil) } @IBAction func openIcons8Website(_ sender: Any) { UIApplication.shared.open(DoneViewController.icons8URL, options: [:], completionHandler: nil) } }
27.454545
76
0.590508
0ea3f26c3b81028fdab06e56cafd0305f4cc4aed
371
import UIKit /* A Very Big Sum ------------------------------------------------------------------------ difficulty: easy source: https://www.hackerrank.com/challenges/a-very-big-sum/problem */ // Sum of all elements in a Array using reduce func sumArrayReduce(array: [Double]) -> Double { return array.reduce(0, +) } print(sumArrayReduce(array: [1, 2, 3, 4, 5]))
28.538462
73
0.560647
f4a5ed9b58ce4db9594d1393b63033bafd0f74cf
1,271
// // MovieCell.swift // Flicks // // Created by Evelio Tarazona on 10/15/16. // Copyright © 2016 Evelio Tarazona. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var posterImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var voteView: VoteView! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) contentView.backgroundColor = selected ? Colors.main : Colors.background } override func prepareForReuse() { super.prepareForReuse() posterImageView.af_cancelImageRequest() posterImageView.layer.removeAllAnimations() posterImageView.image = nil } public func bind(_ movie: Movie) { titleLabel.text = movie.title overviewLabel.text = movie.overview voteView.voteAverage = movie.voteAverage ?? 0 posterImageView.af_setImage(withURL: movie.poster.mediumResolutionURL, placeholderImage: Placeholders.poster, imageTransition: .crossDissolve(0.2), runImageTransitionIfCached: false) } }
30.261905
190
0.693155
ff9600188b52d5bb965a9857816ecd6c0ff1e4a5
2,941
// // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // 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 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. // // For more information, please refer to <https://unlicense.org> // // // Then.swift // RamySDK // // Created by Ahmed Ramy on 10/1/20. // Copyright © 2020 Ahmed Ramy. All rights reserved. // import Foundation import UIKit public protocol Then {} extension Then where Self: Any { /// Makes it available to set properties with closures just after initializing and copying the value types. /// /// let frame = CGRect().with { /// $0.origin.x = 10 /// $0.size.width = 100 /// } public func with(_ block: (inout Self) throws -> Void) rethrows -> Self { var copy = self try block(&copy) return copy } /// Makes it available to execute something with closures. /// /// UserDefaults.standard.do { /// $0.set("devxoul", forKey: "username") /// $0.set("[email protected]", forKey: "email") /// $0.synchronize() /// } public func `do`(_ block: (Self) throws -> Void) rethrows { try block(self) } } extension Then where Self: AnyObject { /// Makes it available to set properties with closures just after initializing. /// /// let label = UILabel().then { /// $0.textAlignment = .center /// $0.textColor = UIColor.black /// $0.text = "Hello, World!" /// } public func then(_ block: (Self) throws -> Void) rethrows -> Self { try block(self) return self } } extension NSObject: Then {} extension CGPoint: Then {} extension CGRect: Then {} extension CGSize: Then {} extension CGVector: Then {} extension Array: Then {} extension Dictionary: Then {} extension Set: Then {} extension UIEdgeInsets: Then {} extension UIOffset: Then {} extension UIRectEdge: Then {}
31.287234
109
0.675621
e9f8a2fa2c2df8f8e9a9310d0fecc43ba0b42121
1,492
import AppArchitecture import ComposableArchitecture import PlacesLogic import Utility import Types let placesP: Reducer< AppState, AppAction, SystemEnvironment<AppEnvironment> > = placesReducer.pullback( state: placesStateAffine, action: placesActionPrism, environment: constant(()) ) private let placesStateAffine = /AppState.operational ** \.flow ** /AppFlow.main ** placesStateLens private let placesStateLens = Lens<MainState, PlacesState>( get: { s in .init(places: s.places, selected: s.selectedPlace, presentation: s.placesPresentation) }, set: { d in \.places *< d.places <> \.selectedPlace *< d.selected <> \.placesPresentation *< d.presentation } ) private let placesActionPrism = Prism<AppAction, PlacesAction>( extract: { a in switch a { case let .changePlacesPresentation(pp): return .changePlacesPresentation(pp) case let .placeCreatedWithSuccess(p): return .placeCreated(p) case let .placesUpdated(.success(ps)): return .placesUpdated(ps) case let .selectPlace(p): return .selectPlace(p) default: return nil } }, embed: { a in switch a { case let .changePlacesPresentation(pp): return .changePlacesPresentation(pp) case let .placeCreated(p): return .placeCreatedWithSuccess(p) case let .placesUpdated(ps): return .placesUpdated(.success(ps)) case let .selectPlace(p): return .selectPlace(p) } } )
31.083333
99
0.682306
11e6201ce16cba724f3639d41bb103cc654083d5
1,362
// // AbstractPaperkeyViewController.swift // VergeiOS // // Created by Swen van Zanten on 29-07-18. // Copyright © 2018 Verge Currency. All rights reserved. // import UIKit class AbstractPaperkeyViewController: UIViewController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white] self.navigationController?.navigationBar.tintColor = .white self.navigationController?.navigationBar.barStyle = .blackTranslucent } override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white] } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem } }
32.428571
127
0.717327
d9767ed5ad7abc3d85739bbf5ef11e202e3775d0
439
// // File.swift // Lecture3_TwitterClient // // Created by Truong Vo Duy Thuc on 10/29/16. // Copyright © 2016 thuctvd. All rights reserved. // import Foundation class Global { static let API_PATH = "https://api." static let API_KEY = "Sz6KQ6wwxhsMy149tp7BBqswr" static let API_SECRET = "DEzlIwwdYMBmCYpOlvRlxmzPH5RbNHfdyrpoTsUw8AIJvLu2Qw" static let NETWORK_ERROR_NOTICE = "There's a networking error!" }
23.105263
80
0.712984
3954127b72a183973d39fd75bd85a59f1d651955
260
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true{class a{struct A{class A{struct B<T where j:a{{}var a{if true{struct Q<T where f:l
43.333333
90
0.753846
9cd6742d4e19a7caf943085ba92cc06bebd743d5
6,365
// // ViewController.swift // Example // // Created by Krunoslav Zaher on 1/1/16. // Copyright © 2016 kzaher. All rights reserved. // import UIKit import RxDataSources import RxSwift import RxCocoa import CoreLocation class NumberCell : UICollectionViewCell { @IBOutlet private var value: UILabel? func configure(with value: String) { self.value?.text = value } } class NumberSectionView : UICollectionReusableView { @IBOutlet private weak var value: UILabel? func configure(value: String) { self.value?.text = value } } class PartialUpdatesViewController: UIViewController { @IBOutlet private weak var animatedTableView: UITableView! @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var animatedCollectionView: UICollectionView! @IBOutlet private weak var refreshButton: UIButton! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() //初始值 let initialRandomizedSections = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: initialValue()) //interval:每隔一段时间发出一个索引数 let ticks = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance).map { _ in () } let randomSections = Observable.of(ticks, refreshButton.rx.tap.asObservable()) //合并成一个 .merge() // .scan(initialRandomizedSections) { a, _ in return a.randomize() } .map { a in return a.sections } .share(replay: 1) let (configureCell, titleForSection) = PartialUpdatesViewController.tableViewDataSourceUI() //配置 let tvAnimatedDataSource = RxTableViewSectionedAnimatedDataSource<NumberSection>( configureCell: configureCell, titleForHeaderInSection: titleForSection ) //配置 let reloadDataSource = RxTableViewSectionedReloadDataSource<NumberSection>( configureCell: configureCell, titleForHeaderInSection: titleForSection ) //绑定 randomSections .bind(to: animatedTableView.rx.items(dataSource: tvAnimatedDataSource)) .disposed(by: disposeBag) //绑定 randomSections .bind(to: tableView.rx.items(dataSource: reloadDataSource)) .disposed(by: disposeBag) let (configureCollectionViewCell, configureSupplementaryView) = PartialUpdatesViewController.collectionViewDataSourceUI() //配置CollectionView let cvAnimatedDataSource = RxCollectionViewSectionedAnimatedDataSource( configureCell: configureCollectionViewCell, configureSupplementaryView: configureSupplementaryView ) //绑定 randomSections .bind(to: animatedCollectionView.rx.items(dataSource: cvAnimatedDataSource)) .disposed(by: disposeBag) // touches Observable.of( tableView.rx.modelSelected(IntItem.self), animatedTableView.rx.modelSelected(IntItem.self), animatedCollectionView.rx.modelSelected(IntItem.self) ) .merge() .subscribe(onNext: { item in print("Let me guess, it's .... It's \(item), isn't it? Yeah, I've got it.") }) .disposed(by: disposeBag) } } // MARK: Skinning extension PartialUpdatesViewController { //配置tableView static func tableViewDataSourceUI() -> ( TableViewSectionedDataSource<NumberSection>.ConfigureCell, TableViewSectionedDataSource<NumberSection>.TitleForHeaderInSection ) { return ( { _, tv, ip, i in let cell = tv.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style:.default, reuseIdentifier: "Cell") cell.textLabel!.text = "\(i)" return cell }, { ds, section -> String? in return ds[section].header } ) } static func collectionViewDataSourceUI() -> ( CollectionViewSectionedDataSource<NumberSection>.ConfigureCell, CollectionViewSectionedDataSource<NumberSection>.ConfigureSupplementaryView ) { return ( { _, cv, ip, i in let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: ip) as! NumberCell cell.configure(with: "\(i)") return cell }, { ds ,cv, kind, ip in let section = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Section", for: ip) as! NumberSectionView section.configure(value: "\(ds[ip.section].header)") return section } ) } // MARK: Initial value //初始值 func initialValue() -> [NumberSection] { #if true let nSections = 10 let nItems = 100 /* let nSections = 10 let nItems = 2 */ return (0 ..< nSections).map { (i: Int) in NumberSection(header: "Section \(i + 1)", numbers: `$`(Array(i * nItems ..< (i + 1) * nItems)), updated: Date()) } #else return _initialValue #endif } } let _initialValue: [NumberSection] = [ NumberSection(header: "section 1", numbers: `$`([1, 2, 3]), updated: Date()), NumberSection(header: "section 2", numbers: `$`([4, 5, 6]), updated: Date()), NumberSection(header: "section 3", numbers: `$`([7, 8, 9]), updated: Date()), NumberSection(header: "section 4", numbers: `$`([10, 11, 12]), updated: Date()), NumberSection(header: "section 5", numbers: `$`([13, 14, 15]), updated: Date()), NumberSection(header: "section 6", numbers: `$`([16, 17, 18]), updated: Date()), NumberSection(header: "section 7", numbers: `$`([19, 20, 21]), updated: Date()), NumberSection(header: "section 8", numbers: `$`([22, 23, 24]), updated: Date()), NumberSection(header: "section 9", numbers: `$`([25, 26, 27]), updated: Date()), NumberSection(header: "section 10", numbers: `$`([28, 29, 30]), updated: Date()) ] //函数 func `$`(_ numbers: [Int]) -> [IntItem] { return numbers.map { IntItem(number: $0, date: Date()) } }
34.781421
142
0.602514
5bc582fec2033b8479b229573e994a9302fe0437
922
// // SwiftUIMovieTests.swift // SwiftUIMovieTests // // Created by Jeevan-1382 on 17/04/20. // Copyright © 2020 Jeevan-1382. All rights reserved. // import XCTest @testable import SwiftUIMovie class SwiftUIMovieTests: 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.342857
111
0.660521
03670bb07b6a7bd5ab746326b7fafb223da6bb0d
6,800
// // Created by Tom Baranes on 28/06/16. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit @IBDesignable open class AnimatableScrollView: UIScrollView, CornerDesignable, FillDesignable, BorderDesignable, RotationDesignable, ShadowDesignable, BlurDesignable, TintDesignable, GradientDesignable, MaskDesignable, Animatable { // MARK: - CornerDesignable @IBInspectable open var cornerRadius = CGFloat.nan { didSet { configureCornerRadius() } } open var cornerSides: CornerSides = .allSides { didSet { configureCornerRadius() } } @IBInspectable var _cornerSides: String? { didSet { cornerSides = CornerSides(rawValue: _cornerSides) } } // MARK: - FillDesignable @IBInspectable open var fillColor: UIColor? { didSet { configureFillColor() } } open var predefinedColor: ColorType? { didSet { configureFillColor() } } @IBInspectable var _predefinedColor: String? { didSet { predefinedColor = ColorType(string: _predefinedColor) } } @IBInspectable open var opacity = CGFloat.nan { didSet { configureOpacity() } } // MARK: - BorderDesignable open var borderType: BorderType = .solid { didSet { configureBorder() } } @IBInspectable var _borderType: String? { didSet { borderType = BorderType(string: _borderType) } } @IBInspectable open var borderColor: UIColor? { didSet { configureBorder() } } /** The color of the border when it has content. This property applies a color to the lower edge of the control. The default value for this property is a clear color. */ @IBInspectable open var activeColor: UIColor? { didSet { configureBorder() } } @IBInspectable open var borderWidth = CGFloat.nan { didSet { configureBorder() } } open var borderSides: BorderSides = .AllSides { didSet { configureBorder() } } @IBInspectable var _borderSides: String? { didSet { borderSides = BorderSides(rawValue: _borderSides) } } // MARK: - RotationDesignable @IBInspectable open var rotate = CGFloat.nan { didSet { configureRotate() } } // MARK: - ShadowDesignable @IBInspectable open var shadowColor: UIColor? { didSet { configureShadowColor() } } @IBInspectable open var shadowRadius = CGFloat.nan { didSet { configureShadowRadius() } } @IBInspectable open var shadowOpacity = CGFloat.nan { didSet { configureShadowOpacity() } } @IBInspectable open var shadowOffset = CGPoint(x: CGFloat.nan, y: CGFloat.nan) { didSet { configureShadowOffset() } } // MARK: - BlurDesignable open var blurEffectStyle: UIBlurEffect.Style? { didSet { configureBlurEffectStyle() } } @IBInspectable var _blurEffectStyle: String? { didSet { blurEffectStyle = UIBlurEffect.Style(string: _blurEffectStyle) } } open var vibrancyEffectStyle: UIBlurEffect.Style? { didSet { configureBlurEffectStyle() } } @IBInspectable var _vibrancyEffectStyle: String? { didSet { vibrancyEffectStyle = UIBlurEffect.Style(string: _vibrancyEffectStyle) } } @IBInspectable open var blurOpacity = CGFloat.nan { didSet { configureBlurEffectStyle() } } // MARK: - TintDesignable @IBInspectable open var tintOpacity = CGFloat.nan @IBInspectable open var shadeOpacity = CGFloat.nan @IBInspectable open var toneColor: UIColor? @IBInspectable open var toneOpacity = CGFloat.nan // MARK: - GradientDesignable open var gradientMode: GradientMode = .linear @IBInspectable var _gradientMode: String? { didSet { gradientMode = GradientMode(string: _gradientMode) ?? .linear } } @IBInspectable open var startColor: UIColor? @IBInspectable open var endColor: UIColor? open var predefinedGradient: GradientType? @IBInspectable var _predefinedGradient: String? { didSet { predefinedGradient = GradientType(string: _predefinedGradient) } } open var startPoint: GradientStartPoint = .top @IBInspectable var _startPoint: String? { didSet { startPoint = GradientStartPoint(string: _startPoint, default: .top) } } // MARK: - MaskDesignable open var maskType: MaskType = .none { didSet { configureMask(previousMaskType: oldValue) configureBorder() } } /// The mask type used in Interface Builder. **Should not** use this property in code. @IBInspectable var _maskType: String? { didSet { maskType = MaskType(string: _maskType) } } // MARK: - Animatable open var animationType: AnimationType = .none @IBInspectable var _animationType: String? { didSet { animationType = AnimationType(string: _animationType) } } @IBInspectable open var autoRun: Bool = true @IBInspectable open var duration = Double.nan @IBInspectable open var delay = Double.nan @IBInspectable open var damping = CGFloat.nan @IBInspectable open var velocity = CGFloat.nan @IBInspectable open var force = CGFloat.nan @IBInspectable var _timingFunction: String = "" { didSet { timingFunction = TimingFunctionType(string: _timingFunction) } } open var timingFunction: TimingFunctionType = .none // MARK: - Lifecycle override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() configureInspectableProperties() } override open func awakeFromNib() { super.awakeFromNib() configureInspectableProperties() } override open func layoutSubviews() { super.layoutSubviews() configureAfterLayoutSubviews() autoRunAnimation() } // MARK: - Private fileprivate func configureInspectableProperties() { configureAnimatableProperties() configureTintedColor() } fileprivate func configureAfterLayoutSubviews() { configureMask(previousMaskType: maskType) configureCornerRadius() configureBorder() configureGradient() } }
24.460432
122
0.61
236623d8401590664eb97dfc0724b082077030a9
891
// // List.swift // UpcomingMoviesDomain // // Created by Alonso on 4/19/19. // Copyright © 2019 Alonso. All rights reserved. // public struct List: Equatable { public let id: String public let name: String public let description: String? public let backdropPath: String? public let averageRating: Double? public let runtime: Int? public let movieCount: Int public let movies: [Movie]? public init(id: String, name: String, description: String?, backdropPath: String?, averageRating: Double?, runtime: Int?, movieCount: Int, movies: [Movie]?) { self.id = id self.name = name self.description = description self.backdropPath = backdropPath self.averageRating = averageRating self.runtime = runtime self.movieCount = movieCount self.movies = movies } }
27
91
0.637486
d9c3da242c8c320193949416d8b064a8ca083f3a
2,246
// // Problem1.swift // Day36 // // Created by Manish Rathi on 06/02/2022. // import Foundation /* https://www.geeksforgeeks.org/next-smaller-element/ Next Smaller Element Given an array, print the Next Smaller Element (NSE) for every element. The NSE for an element x is the first smaller element on the right side of x in array. Elements for which no smaller element exist (on right side), consider NSE as -1. Examples: a) For any array, rightmost element always has NSE as -1. b) For an array which is sorted in increasing order, all elements have NSE as -1. c) For the input array [4, 8, 5, 2, 25}, the NSE for each element are as follows. Element NSE 4 --> 2 8 --> 5 5 --> 2 2 --> -1 25 --> -1 d) For the input array [13, 7, 6, 12}, the next smaller elements for each element are as follows. Element NSE 13 --> 7 7 --> 6 6 --> -1 12 --> -1 */ class Stack<T> { private var array: [T] = [] var isEmpty: Bool { return array.isEmpty } var peekElement: T? { return array.last } func push(element: T) { array.append(element) } func pop() { array.removeLast() } } protocol Solvable { func solve() } class Problem { private let inputArray: [Int] init(inputArray: [Int]) { self.inputArray = inputArray } } extension Problem: Solvable { func solve() { print("Input: \(inputArray)") let stack = Stack<Int>() var outputArray: [Int] = [] for currentElement in inputArray.reversed() { if let peekElement = stack.peekElement { if peekElement < currentElement { outputArray.append(peekElement) } else { while stack.isEmpty == false && stack.peekElement! >= currentElement { stack.pop() } if let peekElement = stack.peekElement, peekElement < currentElement { outputArray.append(peekElement) } else { outputArray.append(-1) } } } else { outputArray.append(-1) } stack.push(element: currentElement) } outputArray = outputArray.reversed() print("Output: \(outputArray)") } }
22.46
240
0.587711
ddd126acad5791e2431bb0adeb80a90a1e3b469a
1,214
// // PreworkTests.swift // PreworkTests // // Created by Winston Peng on 1/28/22. // import XCTest @testable import Prework class PreworkTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
32.810811
130
0.682043
62b5c9278480a95cb3ddeae61e127d0430a06a91
264
// // SerieCellViewModel.swift // LumAppsSeries // // Created by Jonathan Arnal on 17/12/2018. // Copyright © 2018 Jonathan Arnal. All rights reserved. // import Foundation struct SerieCellViewModel { var title: String? var thumbnailURL: URL? }
16.5
57
0.693182
14dddc19fe1c465c89e34a1408d91280f3a3b8c2
12,490
// // ParseRoleTests.swift // ParseSwift // // Created by Corey Baker on 1/18/21. // Copyright © 2021 Parse Community. All rights reserved. // import Foundation import XCTest @testable import ParseSwift class ParseRoleTests: XCTestCase { struct GameScore: ParseObject { //: Those are required for Object var objectId: String? var createdAt: Date? var updatedAt: Date? var ACL: ParseACL? //: Your own properties var score: Int var members = [String]() var levels: [String]? //custom initializers init(score: Int) { self.score = score } } struct User: ParseUser { //: Those are required for Object var objectId: String? var createdAt: Date? var updatedAt: Date? var ACL: ParseACL? // provided by User var username: String? var email: String? var emailVerified: Bool? var password: String? var authData: [String: [String: String]?]? // Your custom keys var customKey: String? } struct Role<RoleUser: ParseUser>: ParseRole { // required by ParseObject var objectId: String? var createdAt: Date? var updatedAt: Date? var ACL: ParseACL? // provided by Role var name: String init() { self.name = "roleMe" } } struct Level: ParseObject { //: Those are required for Object var objectId: String? var createdAt: Date? var updatedAt: Date? var ACL: ParseACL? //: Your own properties var level: Int var members = [String]() //custom initializers init(level: Int) { self.level = level } } override func setUpWithError() throws { try super.setUpWithError() guard let url = URL(string: "http://localhost:1337/1") else { XCTFail("Should create valid URL") return } ParseSwift.initialize(applicationId: "applicationId", clientKey: "clientKey", masterKey: "masterKey", serverURL: url, testing: true) } override func tearDownWithError() throws { try super.tearDownWithError() MockURLProtocol.removeAll() #if !os(Linux) && !os(Android) try KeychainStore.shared.deleteAll() #endif try ParseStorage.shared.deleteAll() } func testName() throws { XCTAssertNoThrow(try Role<User>(name: "Hello9_- ")) XCTAssertThrowsError(try Role<User>(name: "Hello9!")) XCTAssertNoThrow(try Role<User>(name: "Hello9_- ", acl: ParseACL())) XCTAssertThrowsError(try Role<User>(name: "Hello9!", acl: ParseACL())) } func testEndPoint() throws { var role = try Role<User>(name: "Administrator") role.objectId = "me" //This endpoint is at the ParseRole level XCTAssertEqual(role.endpoint.urlComponent, "/roles/me") } func testUserAddIncorrectClassKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let userRoles = role.users var level = Level(level: 1) level.objectId = "nice" XCTAssertThrowsError(try userRoles.add("users", objects: [level])) } func testUserAddIncorrectKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let userRoles = role.users var user = User() user.objectId = "heel" XCTAssertThrowsError(try userRoles.add("level", objects: [user])) } #if !os(Linux) && !os(Android) func testUserAddOperation() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let userRoles = role.users let expected = "{\"className\":\"_User\",\"__type\":\"Relation\"}" let encoded = try ParseCoding.jsonEncoder().encode(userRoles) let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8)) XCTAssertEqual(decoded, expected) XCTAssertEqual(userRoles.key, "users") var user = User() user.objectId = "heel" let operation = try userRoles.add([user]) // swiftlint:disable:next line_length let expected2 = "{\"users\":{\"objects\":[{\"__type\":\"Pointer\",\"className\":\"_User\",\"objectId\":\"heel\"}],\"__op\":\"AddRelation\"}}" let encoded2 = try ParseCoding.jsonEncoder().encode(operation) let decoded2 = try XCTUnwrap(String(data: encoded2, encoding: .utf8)) XCTAssertEqual(decoded2, expected2) } #endif func testUserRemoveIncorrectClassKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let userRoles = role.users var level = Level(level: 1) level.objectId = "nice" XCTAssertThrowsError(try userRoles.remove("users", objects: [level])) } func testUserRemoveIncorrectKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let userRoles = role.users var user = User() user.objectId = "heel" XCTAssertThrowsError(try userRoles.remove("level", objects: [user])) } #if !os(Linux) && !os(Android) func testUserRemoveOperation() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let userRoles = role.users let expected = "{\"className\":\"_User\",\"__type\":\"Relation\"}" let encoded = try ParseCoding.jsonEncoder().encode(userRoles) let decoded = String(data: encoded, encoding: .utf8) XCTAssertEqual(decoded, expected) XCTAssertEqual(userRoles.key, "users") var user = User() user.objectId = "heel" let operation = try userRoles.remove([user]) // swiftlint:disable:next line_length let expected2 = "{\"users\":{\"objects\":[{\"__type\":\"Pointer\",\"className\":\"_User\",\"objectId\":\"heel\"}],\"__op\":\"RemoveRelation\"}}" let encoded2 = try ParseCoding.jsonEncoder().encode(operation) let decoded2 = try XCTUnwrap(try XCTUnwrap(String(data: encoded2, encoding: .utf8))) XCTAssertEqual(decoded2, expected2) } #endif func testRoleAddIncorrectClassKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let roles = role.roles var level = Level(level: 1) level.objectId = "nice" XCTAssertThrowsError(try roles.add("roles", objects: [level])) } #if !os(Linux) && !os(Android) func testRoleAddIncorrectKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let roles = role.roles var newRole = try Role<User>(name: "Moderator", acl: acl) newRole.objectId = "heel" XCTAssertThrowsError(try roles.add("level", objects: [newRole])) } func testRoleAddOperation() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let roles = role.roles let expected = "{\"className\":\"_Role\",\"__type\":\"Relation\"}" let encoded = try ParseCoding.jsonEncoder().encode(roles) let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8)) XCTAssertEqual(decoded, expected) XCTAssertEqual(roles.key, "roles") var newRole = try Role<User>(name: "Moderator", acl: acl) newRole.objectId = "heel" let operation = try roles.add([newRole]) // swiftlint:disable:next line_length let expected2 = "{\"roles\":{\"objects\":[{\"__type\":\"Pointer\",\"className\":\"_Role\",\"objectId\":\"heel\"}],\"__op\":\"AddRelation\"}}" let encoded2 = try ParseCoding.jsonEncoder().encode(operation) let decoded2 = try XCTUnwrap(String(data: encoded2, encoding: .utf8)) XCTAssertEqual(decoded2, expected2) } #endif func testRoleRemoveIncorrectClassKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let roles = role.roles var level = Level(level: 1) level.objectId = "nice" XCTAssertThrowsError(try roles.remove("users", objects: [level])) } func testRoleRemoveIncorrectKeyError() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let roles = role.roles var user = User() user.objectId = "heel" XCTAssertThrowsError(try roles.remove("level", objects: [user])) } #if !os(Linux) && !os(Android) func testRoleRemoveOperation() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true let role = try Role<User>(name: "Administrator", acl: acl) let roles = role.roles let expected = "{\"className\":\"_Role\",\"__type\":\"Relation\"}" let encoded = try ParseCoding.jsonEncoder().encode(roles) let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8)) XCTAssertEqual(decoded, expected) XCTAssertEqual(roles.key, "roles") var newRole = try Role<User>(name: "Moderator", acl: acl) newRole.objectId = "heel" let operation = try roles.remove([newRole]) // swiftlint:disable:next line_length let expected2 = "{\"roles\":{\"objects\":[{\"__type\":\"Pointer\",\"className\":\"_Role\",\"objectId\":\"heel\"}],\"__op\":\"RemoveRelation\"}}" let encoded2 = try ParseCoding.jsonEncoder().encode(operation) let decoded2 = try XCTUnwrap(String(data: encoded2, encoding: .utf8)) XCTAssertEqual(decoded2, expected2) } func testUserQuery() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true var user = User() user.objectId = "heel" var userRoles = try Role<User>(name: "Administrator", acl: acl) userRoles.objectId = "yolo" let query = try userRoles.queryUsers(user) // swiftlint:disable:next line_length let expected = "{\"limit\":100,\"skip\":0,\"_method\":\"GET\",\"where\":{\"$relatedTo\":{\"key\":\"users\",\"object\":{\"__type\":\"Pointer\",\"className\":\"_Role\",\"objectId\":\"yolo\"}}}}" let encoded = try ParseCoding.jsonEncoder().encode(query) let decoded = try XCTUnwrap(String(data: encoded, encoding: .utf8)) XCTAssertEqual(decoded, expected) } func testRoleQuery() throws { var acl = ParseACL() acl.publicWrite = false acl.publicRead = true var role = try Role<User>(name: "Administrator", acl: acl) role.objectId = "yolo" var newRole = try Role<User>(name: "Moderator", acl: acl) newRole.objectId = "heel" guard let query = role.queryRoles else { XCTFail("Should unwrap, if it doesn't it an error occurred when creating query.") return } // swiftlint:disable:next line_length let expected2 = "{\"limit\":100,\"skip\":0,\"_method\":\"GET\",\"where\":{\"$relatedTo\":{\"key\":\"roles\",\"object\":{\"__type\":\"Pointer\",\"className\":\"_Role\",\"objectId\":\"yolo\"}}}}" let encoded2 = try ParseCoding.jsonEncoder().encode(query) let decoded2 = try XCTUnwrap(String(data: encoded2, encoding: .utf8)) XCTAssertEqual(decoded2, expected2) } #endif }
33.848238
201
0.592954
641826b4741b1a458483d58d87e75082b7854e9e
1,474
// // AnonymousSubscriber.swift // // Copyright (c) 2017 Jaesung Jung. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public class AnonymousSubscriber<StateType: State>: Subscriber { private let handler: (StateType) -> Void public init(_ handler: @escaping (StateType) -> Void) { self.handler = handler } public func newState(_ state: StateType) { handler(state) } }
39.837838
81
0.731343
ebf012f8fc10fa2246143545956d9877afbb0300
2,488
// // IFSettingModel.swift // InFace // // Created by lieon on 2020/11/30. // Copyright © 2020 Pinguo. All rights reserved. // import Foundation //import SimpleKeychain import RxDataSources enum IFSettingCellType { case vipOrNot(IFSettingVipStatus) case common(IFSettingCommonCellData) case debug var compareValue: String { switch self { case .vipOrNot(let status): switch status { case .notVip: return "notVip" case .vip: return "vip" } case .common: return "common" case .debug: return "debug" } } } //struct IFSettingSectionModel: SectionModel<String, IFSettingCellType> { } struct IFSettingCommonCellData { var icon: UIImage var title: String var arrow: UIImage var isHiddenLine: Bool = false } enum IFSettingVipStatus { case vip case notVip var data: IFSettingVipStatusData { switch self { case .vip: return IFSettingVipStatusData.vipData case .notVip: return IFSettingVipStatusData.notVipData } } } struct IFSettingVipStatusData { var title: String var subTitle: String static var notVipData: IFSettingVipStatusData { let title = "立即成为VIP"//.localized(nil) // var subTitle: String { // let plan = IFManager.getABPlan(.level_vip_sideEntranceTip).pid // switch plan { // case .plan_vip_sideEntranceTip0: // return "解锁全部功能".localized(nil) // case .plan_vip_sideEntranceTip1: // return "畅享所有功能".localized(nil) // case .plan_vip_sideEntranceTip2: // return "试用全部功能".localized(nil) // default: // return A0SimpleKeychain().string(forKey: "iap_product_id") == nil ? // "免费试用3天".localized(nil) // : // "解锁全部功能".localized(nil) // } // } let data = IFSettingVipStatusData(title: title, subTitle: "免费试用3天") return data } static var vipData: IFSettingVipStatusData { // let title = "欢迎您,Inface Vip".localized(nil) // let vipByTheTime = " \("尽情享受全部功能与素材".localized())\n \("有效期至:".localized())" + "2019年12月31号" let data = IFSettingVipStatusData(title: "欢迎你,VIP用户", subTitle: "尽情享受全部功能与素材 有效期至:2019年12月31号") return data } }
27.043478
104
0.579582
08669a1e1a95bfb2d18aff2fc9937edb12a366fe
2,282
import UIKit import SwiftUI import SwiftShogi class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { let game = Game(sfen: .default) let userData = UserData(game: game) let contentView = ContentView().environmentObject(userData) // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
45.64
141
0.701578
0aa73acecaf534950c614bb11b50cfe30490c82b
239
// // ColorPickMode.swift // AR-Graffiti // // Created by Bjarne Lundgren on 02/09/2017. // Copyright © 2017 Silicon.dk ApS. All rights reserved. // import UIKit enum ColorPickMode { case picked(color:UIColor) case picking }
15.933333
57
0.686192
7a1128b9fcf623450532cf177e8d6feb345e76d4
1,031
// // ParsingService.swift // TypographyKit // // Created by Ross Butler on 7/15/17. // // import AppKit protocol ParsingService { func parse(_ data: Data) -> ParsingServiceResult? } private enum CodingKeys { static let colorsEntry = "typography-colors" static let minimumPointSize = "minimum-point-size" static let maximumPointSize = "maximum-point-size" static let pointStepMultiplier = "point-step-multiplier" static let pointStepSize = "point-step-size" static let scalingMode = "scaling-mode" static let stylesEntry = "ui-font-text-styles" static let umbrellaEntry = "typography-kit" } typealias ColorEntries = [String: Any] extension ParsingService { func parse(_ configEntries: [String: Any]) -> ParsingServiceResult? { let colorEntries = configEntries[CodingKeys.colorsEntry] as? ColorEntries ?? [:] var colorParser = ColorParser(colors: colorEntries) let typographyColors = colorParser.parseColors() return typographyColors } }
27.131579
88
0.705141
f539cd888ab5e2170a7e84af320a621a7f8847fb
513
// // Model200Response.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation /** Model for testing model name starting with number */ public struct Model200Response: Codable { public var name: Int? public var _class: String? public init(name: Int?, _class: String?) { self.name = name self._class = _class } public enum CodingKeys: String, CodingKey { case name case _class = "class" } }
16.548387
56
0.641326
ebd8e9743ecd9894c76152f161fadf102fa73ebc
1,920
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore import HMGithub // ======================================================= class SingleRepoHeaderCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() self.titleLabel.text = "" self.descriptionLabel.text = "" } // ======================================================= internal func render(model model: GithubRepoModel) { self.backgroundColor = Theme.color(type: .CellBackgroundColor) let titleAttrString = NSAttributedString(string: model.name, attributes: [ NSFontAttributeName: Theme.font(type: .Bold(16.0)), NSForegroundColorAttributeName: Theme.color(type: .PrimaryTextColor) ]) self.titleLabel.attributedText = titleAttrString if model.repoDescription != "" { let descAttrString = NSAttributedString(string: model.repoDescription, attributes: [ NSFontAttributeName: Theme.font(type: .Regular(12.0)), NSForegroundColorAttributeName: Theme.color(type: .SecondaryTextColor) ]) self.descriptionLabel.attributedText = descAttrString } else { let descAttrString = NSAttributedString(string: "None Specified", attributes: [ NSFontAttributeName: Theme.font(type: .Italic(12.0)), NSForegroundColorAttributeName: Theme.color(type: .SecondaryTextColor) ]) self.descriptionLabel.attributedText = descAttrString } } }
32.542373
96
0.547396
ed62af6a9f4cff21bd91307cf081b0af4cbcd080
2,269
import Foundation import OneginiSDKiOS import OneginiCrypto import Flutter extension OneginiModuleSwift { public func authenticateDevice(_ scopes: [String]?, callback: @escaping FlutterResult) -> Void { bridgeConnector.toResourceFetchHandler.authenticateDevice(scopes) { (data, error) -> Void in error != nil ? callback(error?.flutterError()) : callback(data) } } public func resourceRequest(isImplicit: Bool, isAnonymousCall: Bool = true, parameters: [String: Any], callback: @escaping (Any?, FlutterError?) -> Void) { bridgeConnector.toResourceFetchHandler.resourceRequest(isImplicit: isImplicit, isAnonymousCall: isAnonymousCall, parameters: parameters, completion: { (data, error) -> Void in callback(data, error?.flutterError()) }) } public func fetchResources(_ path: String, type: String, parameters: [String: Any?], callback: @escaping FlutterResult) { switch type { case Constants.Routes.getImplicitResource: Logger.log("super path1 \(path)") Logger.log("super params1 \(parameters)") bridgeConnector.toResourceFetchHandler.fetchResourceWithImplicitResource(path, parameters: parameters, completion: callback) case Constants.Routes.getResourceAnonymous: Logger.log("super path2 \(path)") Logger.log("super params2 \(parameters)") bridgeConnector.toResourceFetchHandler.fetchAnonymousResource(path, parameters: parameters, completion: callback) case Constants.Routes.getResource: Logger.log("super path3 \(path)") Logger.log("super params3 \(parameters)") bridgeConnector.toResourceFetchHandler.fetchSimpleResources(path, parameters: parameters, completion: callback) case Constants.Routes.unauthenticatedRequest: Logger.log("super path4 \(path)") Logger.log("super params4 \(parameters)") bridgeConnector.toResourceFetchHandler.unauthenticatedRequest(path, parameters: parameters, callback: callback) default: callback(SdkError.convertToFlutter(SdkError(customType: .incrorrectResourcesAccess))) } } }
47.270833
158
0.679154
896714610cb510ea7dce8f8ee48ce4858afeaa0b
267
// RUN: not --crash %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 enum B{class a}import CoreData{func b<U:U.j
33.375
87
0.749064
33753b770c17c643b86a8ecc48919ea84f2474df
2,022
// // Scheduler.swift // SignalKit // // Created by Yanko Dimitrov on 3/5/16. // Copyright © 2016 Yanko Dimitrov. All rights reserved. // import Foundation public enum SchedulerQueue { case MainQueue case UserInteractiveQueue case UserInitiatedQueue case UtilityQueue case BackgroundQueue case CustomQueue(dispatch_queue_t) var dispatchQueue: dispatch_queue_t { switch self { case .MainQueue: return dispatch_get_main_queue() case .UserInteractiveQueue: return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) case .UserInitiatedQueue: return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) case .UtilityQueue: return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) case .BackgroundQueue: return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) case .CustomQueue(let customQueue): return customQueue } } } public struct Scheduler { private var debounceAction: (() -> Void)? = nil internal let queue: dispatch_queue_t public init(queue: SchedulerQueue) { self.queue = queue.dispatchQueue } public func async(block: dispatch_block_t) { dispatch_async(queue, block) } public func delay(seconds: Double, block: dispatch_block_t) { let when = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) dispatch_after(when, queue, block) } public mutating func debounce(seconds: Double, block: dispatch_block_t) { debounceAction?() var isCancelled = false delay(seconds) { if !isCancelled { block() } } debounceAction = { isCancelled = true } } }
24.071429
90
0.584075
cc67fcfa5787eb8a118dfd63ed73250dffebee35
22,200
// // MessageStreamImpl.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 08.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** Class that responsible for handling full set of events inside message stream. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ final class MessageStreamImpl { // MARK: - Properties private let accessChecker: AccessChecker private let currentChatMessageFactoriesMapper: MessageMapper private let locationSettingsHolder: LocationSettingsHolder private let messageComposingHandler: MessageComposingHandler private let messageHolder: MessageHolder private let sendingMessageFactory: SendingFactory private let serverURLString: String private let webimActions: WebimActions private var chat: ChatItem? private weak var chatStateListener: ChatStateListener? private var currentOperator: OperatorImpl? private var departmentList: [Department]? private weak var departmentListChangeListener: DepartmentListChangeListener? private weak var currentOperatorChangeListener: CurrentOperatorChangeListener? private var isChatIsOpening = false private var lastChatState: ChatItem.ChatItemState = .unknown private var lastOperatorTypingStatus: Bool? private weak var locationSettingsChangeListener: LocationSettingsChangeListener? private var operatorFactory: OperatorFactory private weak var operatorTypingListener: OperatorTypingListener? private var onlineStatus: OnlineStatusItem = .unknown private weak var onlineStatusChangeListener: OnlineStatusChangeListener? private var unreadByOperatorTimestamp: Date? private weak var unreadByOperatorTimestampChangeListener: UnreadByOperatorTimestampChangeListener? private var unreadByVisitorMessageCount: Int private weak var unreadByVisitorMessageCountChangeListener: UnreadByVisitorMessageCountChangeListener? private var unreadByVisitorTimestamp: Date? private weak var unreadByVisitorTimestampChangeListener: UnreadByVisitorTimestampChangeListener? private var visitSessionState: VisitSessionStateItem = .unknown private weak var visitSessionStateListener: VisitSessionStateListener? // MARK: - Initialization init(serverURLString: String, currentChatMessageFactoriesMapper: MessageMapper, sendingMessageFactory: SendingFactory, operatorFactory: OperatorFactory, accessChecker: AccessChecker, webimActions: WebimActions, messageHolder: MessageHolder, messageComposingHandler: MessageComposingHandler, locationSettingsHolder: LocationSettingsHolder) { self.serverURLString = serverURLString self.currentChatMessageFactoriesMapper = currentChatMessageFactoriesMapper self.sendingMessageFactory = sendingMessageFactory self.operatorFactory = operatorFactory self.accessChecker = accessChecker self.webimActions = webimActions self.messageHolder = messageHolder self.messageComposingHandler = messageComposingHandler self.locationSettingsHolder = locationSettingsHolder self.unreadByVisitorMessageCount = -1 } // MARK: - Methods func getWebimActions() -> WebimActions { return webimActions } func set(visitSessionState: VisitSessionStateItem) { let previousVisitSessionState = self.visitSessionState self.visitSessionState = visitSessionState isChatIsOpening = false visitSessionStateListener?.changed(state: publicState(ofVisitSessionState: previousVisitSessionState), to: publicState(ofVisitSessionState: visitSessionState)) } func set(onlineStatus: OnlineStatusItem) { self.onlineStatus = onlineStatus } func set(unreadByOperatorTimestamp: Date?) { let previousValue = self.unreadByOperatorTimestamp self.unreadByOperatorTimestamp = unreadByOperatorTimestamp if previousValue != unreadByOperatorTimestamp { unreadByOperatorTimestampChangeListener?.changedUnreadByOperatorTimestampTo(newValue: self.unreadByOperatorTimestamp) } } func set(unreadByVisitorTimestamp: Date?) { let previousValue = self.unreadByVisitorTimestamp self.unreadByVisitorTimestamp = unreadByVisitorTimestamp if previousValue != unreadByVisitorTimestamp { unreadByVisitorTimestampChangeListener?.changedUnreadByVisitorTimestampTo(newValue: self.unreadByVisitorTimestamp) } } func set(unreadByVisitorMessageCount: Int) { let previousValue = self.unreadByVisitorMessageCount self.unreadByVisitorMessageCount = unreadByVisitorMessageCount if previousValue != unreadByVisitorMessageCount { unreadByVisitorMessageCountChangeListener?.changedUnreadByVisitorMessageCountTo(newValue: self.unreadByVisitorMessageCount) } } func changingChatStateOf(chat: ChatItem?) { let previousChat = self.chat self.chat = chat messageHolder.receiving(newChat: self.chat, previousChat: previousChat, newMessages: (self.chat == nil) ? [MessageImpl]() : currentChatMessageFactoriesMapper.mapAll(messages: self.chat!.getMessages())) let newChatState = (self.chat == nil) ? .closed : self.chat!.getState() if let newChatState = newChatState { // Recieved chat state can be unsupported by the library. if lastChatState != newChatState { chatStateListener?.changed(state: publicState(ofChatState: lastChatState), to: publicState(ofChatState: newChatState)) } lastChatState = newChatState } let newOperator = operatorFactory.createOperatorFrom(operatorItem: self.chat?.getOperator()) if newOperator != currentOperator { let previousOperator = currentOperator currentOperator = newOperator currentOperatorChangeListener?.changed(operator: previousOperator, to: newOperator) } let operatorTypingStatus = ((chat != nil) && chat!.isOperatorTyping()) if lastOperatorTypingStatus != operatorTypingStatus { operatorTypingListener?.onOperatorTypingStateChanged(isTyping: operatorTypingStatus) } lastOperatorTypingStatus = operatorTypingStatus if let unreadByOperatorTimestamp = chat?.getUnreadByOperatorTimestamp() { set(unreadByOperatorTimestamp: Date(timeIntervalSince1970: unreadByOperatorTimestamp)) } if let unreadByVisitorMessageCount = chat?.getUnreadByVisitorMessageCount() { set(unreadByVisitorMessageCount: unreadByVisitorMessageCount) } if let unreadByVisitorTimestamp = chat?.getUnreadByVisitorTimestamp() { set(unreadByVisitorTimestamp: Date(timeIntervalSince1970: unreadByVisitorTimestamp)) } if chat?.getReadByVisitor() == true { set(unreadByVisitorTimestamp: nil) } } func saveLocationSettingsOn(fullUpdate: FullUpdate) { let hintsEnabled = (fullUpdate.getHintsEnabled() == true) let previousLocationSettings = locationSettingsHolder.getLocationSettings() let newLocationSettings = LocationSettingsImpl(hintsEnabled: hintsEnabled) let newLocationSettingsReceived = locationSettingsHolder.receiving(locationSettings: newLocationSettings) if newLocationSettingsReceived { locationSettingsChangeListener?.changed(locationSettings: previousLocationSettings, to: newLocationSettings) } } func onOnlineStatusChanged(to newOnlineStatus: OnlineStatusItem) { let previousPublicOnlineStatus = publicState(ofOnlineStatus: onlineStatus) let newPublicOnlineStatus = publicState(ofOnlineStatus: newOnlineStatus) if onlineStatus != newOnlineStatus { onlineStatusChangeListener?.changed(onlineStatus: previousPublicOnlineStatus, to: newPublicOnlineStatus) } onlineStatus = newOnlineStatus } func onReceiving(departmentItemList: [DepartmentItem]) { var departmentList = [Department]() let departmentFactory = DepartmentFactory(serverURLString: serverURLString) for departmentItem in departmentItemList { let department = departmentFactory.convert(departmentItem: departmentItem) departmentList.append(department) } self.departmentList = departmentList departmentListChangeListener?.received(departmentList: departmentList) } // MARK: Private methods private func publicState(ofChatState chatState: ChatItem.ChatItemState) -> ChatState { switch chatState { case .queue: return .QUEUE case .chatting: return .CHATTING case .chattingWithRobot: return .CHATTING_WITH_ROBOT case .closed: return .NONE case .closedByVisitor: return .CLOSED_BY_VISITOR case .closedByOperator: return .CLOSED_BY_OPERATOR case .invitation: return .INVITATION default: return .UNKNOWN } } private func publicState(ofOnlineStatus onlineStatus: OnlineStatusItem) -> OnlineStatus { switch onlineStatus { case .busyOffline: return .BUSY_OFFLINE case .busyOnline: return .BUSY_ONLINE case .offline: return .OFFLINE case .online: return .ONLINE default: return .UNKNOWN } } private func publicState(ofVisitSessionState visitSessionState: VisitSessionStateItem) -> VisitSessionState { switch visitSessionState { case .chat: return .CHAT case .departmentSelection: return .DEPARTMENT_SELECTION case .idle: return .IDLE case .idleAfterChat: return .IDLE_AFTER_CHAT case .offlineMessage: return .OFFLINE_MESSAGE default: return .UNKNOWN } } } // MARK: - MessageStream extension MessageStreamImpl: MessageStream { // MARK: - Methods func getVisitSessionState() -> VisitSessionState { return publicState(ofVisitSessionState: visitSessionState) } func getChatState() -> ChatState { return publicState(ofChatState: lastChatState) } func getUnreadByOperatorTimestamp() -> Date? { return unreadByOperatorTimestamp } func getUnreadByVisitorMessageCount() -> Int { return (unreadByVisitorMessageCount > 0) ? unreadByVisitorMessageCount : 0 } func getUnreadByVisitorTimestamp() -> Date? { return unreadByVisitorTimestamp } func getDepartmentList() -> [Department]? { return departmentList } func getLocationSettings() -> LocationSettings { return locationSettingsHolder.getLocationSettings() } func getCurrentOperator() -> Operator? { return currentOperator } func getLastRatingOfOperatorWith(id: String) -> Int { let rating = chat?.getOperatorIDToRate()?[id] return ((rating == nil) ? 0 : rating!.getRating()) } func rateOperatorWith(id: String?, byRating rating: Int, comletionHandler: RateOperatorCompletionHandler?) throws { guard rating >= 1, rating <= 5 else { WebimInternalLogger.shared.log(entry: "Rating must be within from 1 to 5 range. Passed value: \(rating)", verbosityLevel: .WARNING) return } try accessChecker.checkAccess() webimActions.rateOperatorWith(id: id, rating: (rating - 3), // Accepted range: (-2, -1, 0, 1, 2). completionHandler: comletionHandler) } func respondSentryCall(id: String) throws { try accessChecker.checkAccess() webimActions.respondSentryCall(id: id) } func startChat() throws { try startChat(departmentKey: nil, firstQuestion: nil) } func startChat(firstQuestion: String?) throws { try startChat(departmentKey: nil, firstQuestion: firstQuestion) } func startChat(departmentKey: String?) throws { try startChat(departmentKey: departmentKey, firstQuestion: nil) } func startChat(customFields:String?) throws { try startChat(departmentKey: nil, firstQuestion: nil, customFields: customFields) } func startChat(firstQuestion:String?, customFields: String?) throws { try startChat(departmentKey: nil, firstQuestion: firstQuestion, customFields: customFields) } func startChat(departmentKey: String?, customFields: String?) throws { try startChat(departmentKey: departmentKey, firstQuestion: nil, customFields: customFields) } func startChat(departmentKey: String?, firstQuestion: String?) throws { try startChat(departmentKey: departmentKey, firstQuestion: firstQuestion, customFields: nil) } func startChat(departmentKey: String?, firstQuestion: String?, customFields: String?) throws { try accessChecker.checkAccess() if (lastChatState.isClosed() || (visitSessionState == .offlineMessage)) && !isChatIsOpening { webimActions.startChat(withClientSideID: ClientSideID.generateClientSideID(), firstQuestion: firstQuestion, departmentKey: departmentKey, customFields: customFields) } } func closeChat() throws { try accessChecker.checkAccess() let chatIsOpen = ((lastChatState != .closedByVisitor) && (lastChatState != .closed)) && (lastChatState != .unknown) if chatIsOpen { webimActions.closeChat() } } func setVisitorTyping(draftMessage: String?) throws { try accessChecker.checkAccess() messageComposingHandler.setComposing(draft: draftMessage) } func send(message: String) throws -> String { return try sendMessageInternally(messageText: message) } func send(message: String, data: [String: Any]?, completionHandler: DataMessageCompletionHandler?) throws -> String { if let jsonData = try? JSONSerialization.data(withJSONObject: data as Any, options: []) { let jsonString = String(data: jsonData, encoding: .utf8) return try sendMessageInternally(messageText: message, dataJSONString: jsonString, dataMessageCompletionHandler: completionHandler) } else { return try sendMessageInternally(messageText: message) } } func send(message: String, isHintQuestion: Bool?) throws -> String { return try sendMessageInternally(messageText: message, isHintQuestion: isHintQuestion) } func send(file: Data, filename: String, mimeType: String, completionHandler: SendFileCompletionHandler?) throws -> String { try startChat() let messageID = ClientSideID.generateClientSideID() messageHolder.sending(message: sendingMessageFactory.createFileMessageToSendWith(id: messageID)) webimActions.send(file: file, filename: filename, mimeType: mimeType, clientSideID: messageID, completionHandler: SendFileCompletionHandlerWrapper(sendFileCompletionHandler: completionHandler, messageHolder: messageHolder)) return messageID } func setChatRead() throws { try accessChecker.checkAccess() webimActions.setChatRead() } func set(prechatFields: String) throws { try accessChecker.checkAccess() webimActions.set(prechatFields: prechatFields) } func newMessageTracker(messageListener: MessageListener) throws -> MessageTracker { try accessChecker.checkAccess() return try messageHolder.newMessageTracker(withMessageListener: messageListener) as MessageTracker } func set(visitSessionStateListener: VisitSessionStateListener) { self.visitSessionStateListener = visitSessionStateListener } func set(chatStateListener: ChatStateListener) { self.chatStateListener = chatStateListener } func set(currentOperatorChangeListener: CurrentOperatorChangeListener) { self.currentOperatorChangeListener = currentOperatorChangeListener } func set(operatorTypingListener: OperatorTypingListener) { self.operatorTypingListener = operatorTypingListener } func set(departmentListChangeListener: DepartmentListChangeListener) { self.departmentListChangeListener = departmentListChangeListener } func set(locationSettingsChangeListener: LocationSettingsChangeListener) { self.locationSettingsChangeListener = locationSettingsChangeListener } func set(onlineStatusChangeListener: OnlineStatusChangeListener) { self.onlineStatusChangeListener = onlineStatusChangeListener } func set(unreadByOperatorTimestampChangeListener: UnreadByOperatorTimestampChangeListener) { self.unreadByOperatorTimestampChangeListener = unreadByOperatorTimestampChangeListener } func set(unreadByVisitorMessageCountChangeListener: UnreadByVisitorMessageCountChangeListener) { self.unreadByVisitorMessageCountChangeListener = unreadByVisitorMessageCountChangeListener } func set(unreadByVisitorTimestampChangeListener: UnreadByVisitorTimestampChangeListener) { self.unreadByVisitorTimestampChangeListener = unreadByVisitorTimestampChangeListener } // MARK: Private methods private func sendMessageInternally(messageText: String, dataJSONString: String? = nil, isHintQuestion: Bool? = nil, dataMessageCompletionHandler: DataMessageCompletionHandler? = nil) throws -> String { try startChat() let messageID = ClientSideID.generateClientSideID() webimActions.send(message: messageText, clientSideID: messageID, dataJSONString: dataJSONString, isHintQuestion: isHintQuestion, dataMessageCompletionHandler: dataMessageCompletionHandler) messageHolder.sending(message: sendingMessageFactory.createTextMessageToSendWith(id: messageID, text: messageText)) return messageID } } // MARK: - fileprivate final class SendFileCompletionHandlerWrapper: SendFileCompletionHandler { // MARK: - Properties private let messageHolder: MessageHolder private weak var sendFileCompletionHandler: SendFileCompletionHandler? // MARK: - Initialization init(sendFileCompletionHandler: SendFileCompletionHandler?, messageHolder: MessageHolder) { self.sendFileCompletionHandler = sendFileCompletionHandler self.messageHolder = messageHolder } // MARK: - Methods func onSuccess(messageID: String) { sendFileCompletionHandler?.onSuccess(messageID: messageID) } func onFailure(messageID: String, error: SendFileError) { messageHolder.sendingCancelledWith(messageID: messageID) sendFileCompletionHandler?.onFailure(messageID: messageID, error: error) } }
38.947368
161
0.651847
fed191993ffbc9655c1d53584e13b10a094ef6c6
634
// // EmptyDataSource.swift // WeatherZone // // Created by Hardik on 18/02/18. // Copyright © 2018 Hardik Kothari. All rights reserved. // import UIKit class EmptyDataSource: NSObject { var placeholderMessage: String! = "" } extension EmptyDataSource : UITableViewDelegate { func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIViewFactory.getPlaceholderView(with: placeholderMessage, parentView: tableView) } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return tableView.frame.height } }
25.36
96
0.72082
3396e0475204de8773c15829e2fe920d037a07da
6,960
// // Installation.swift // LeanCloud // // Created by Tianyong Tang on 2018/10/12. // Copyright © 2018 LeanCloud. All rights reserved. // import Foundation /** LeanCloud installation type. */ public class LCInstallation: LCObject { /// The badge of installation. @objc dynamic public var badge: LCNumber? /// The time zone of installtion. @objc dynamic public var timeZone: LCString? /// The channels of installation, which contains client ID of IM. @objc dynamic public var channels: LCArray? /// The type of device. @objc dynamic public var deviceType: LCString? /// The device token used to push notification. @objc dynamic public private(set) var deviceToken: LCString? /// The device profile. You can use this property to select one from mutiple push certificates or configurations. @objc dynamic public var deviceProfile: LCString? /// The installation ID of device, it's mainly for Android device. @objc dynamic public var installationId: LCString? /// The APNs topic of installation. @objc dynamic public var apnsTopic: LCString? /// The APNs Team ID of installation. @objc dynamic public private(set) var apnsTeamId: LCString? public final override class func objectClassName() -> String { return "_Installation" } public required init() { super.init() self.timeZone = NSTimeZone.system.identifier.lcString if let bundleIdentifier = Bundle.main.bundleIdentifier { self.apnsTopic = bundleIdentifier.lcString } #if os(iOS) self.deviceType = "ios" #elseif os(macOS) self.deviceType = "macos" #elseif os(watchOS) self.deviceType = "watchos" #elseif os(tvOS) self.deviceType = "tvos" #endif } public required init(application: LCApplication) { super.init(application: application) self.timeZone = NSTimeZone.system.identifier.lcString if let bundleIdentifier = Bundle.main.bundleIdentifier { self.apnsTopic = bundleIdentifier.lcString } #if os(iOS) self.deviceType = "ios" #elseif os(macOS) self.deviceType = "macos" #elseif os(watchOS) self.deviceType = "watchos" #elseif os(tvOS) self.deviceType = "tvos" #endif } /** Set required properties for installation. - parameter deviceToken: The device token. - parameter deviceProfile: The device profile. - parameter apnsTeamId: The Team ID of your Apple Developer Account. */ public func set( deviceToken: LCDeviceTokenConvertible, apnsTeamId: LCStringConvertible) { self.deviceToken = deviceToken.lcDeviceToken self.apnsTeamId = apnsTeamId.lcString } override func preferredBatchRequest( method: HTTPClient.Method, path: String, internalId: String) throws -> [String : Any]? { switch method { case .post, .put: var request: [String: Any] = [:] request["method"] = HTTPClient.Method.post.rawValue request["path"] = try self.application.httpClient.getBatchRequestPath(object: self, method: .post) if var body = dictionary.lconValue as? [String: Any] { body["__internalId"] = internalId body.removeValue(forKey: "createdAt") body.removeValue(forKey: "updatedAt") body.removeValue(forKey: "__type") body.removeValue(forKey: "className") request["body"] = body } return request default: return nil } } override func validateBeforeSaving() throws { try super.validateBeforeSaving() guard let _ = deviceToken else { throw LCError(code: .inconsistency, reason: "Installation device token not found.") } guard let _ = apnsTeamId else { throw LCError(code: .inconsistency, reason: "Installation APNs team ID not found.") } } override func objectDidSave() { super.objectDidSave() if self === self.application._currentInstallation { LCInstallation.saveCurrentInstallation(self) } } } extension LCInstallation { // MARK: Cache struct CacheTable: Codable { let jsonString: String let applicationID: String enum CodingKeys: String, CodingKey { case jsonString = "json_string" case applicationID = "application_id" } } static func currentInstallation(application: LCApplication) -> LCInstallation? { do { guard let fileURL = application.currentInstallationFileURL, let context = application.localStorageContext, let table: CacheTable = try context.table(from: fileURL), table.applicationID == application.id, let data = table.jsonString.data(using: .utf8), let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } let dictionary = try LCDictionary( application: application, unsafeObject: jsonObject) return LCInstallation( application: application, dictionary: dictionary) } catch { Logger.shared.error(error) return nil } } static func saveCurrentInstallation(_ installation: LCInstallation) { let application = installation.application guard let context = application.localStorageContext, let fileURL = application.currentInstallationFileURL else { return } do { try context.save( table: CacheTable( jsonString: installation.jsonString, applicationID: application.id), to: fileURL) } catch { Logger.shared.error(error) } } } // MARK: Device Token Convertible public protocol LCDeviceTokenConvertible { var lcDeviceToken: LCString { get } } extension String: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { return lcString } } extension NSString: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { return (self as String).lcDeviceToken } } extension Data: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { let string = map { String(format: "%02.2hhx", $0) }.joined() return LCString(string) } } extension NSData: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { return (self as Data).lcDeviceToken } }
28.760331
117
0.608333
29f43c7364fcf7c778b8b651cac47235bd0f3d20
2,110
// // Copyright (c) 2016 Keun young Kim <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit #if !swift(>=3.0) class Person { var name: String = "" var birthDate: NSDate? var age: Int { get { if let date = birthDate { let calendar = NSCalendar.currentCalendar() let components = calendar.components(NSCalendarUnit.Year, fromDate: date, toDate: NSDate(), options: []) return components.year } return -1 } set { let calendar = NSCalendar.currentCalendar() birthDate = calendar.dateByAddingUnit([.Year], value: newValue * -1, toDate: NSDate(), options: []) } } } let calendar = NSCalendar.currentCalendar() let componets = NSDateComponents() componets.year = 1983 componets.month = 3 componets.day = 17 let james = Person() james.birthDate = calendar.dateFromComponents(componets) print(james.age) // 33 james.age = 10 print(james.birthDate) // 2006-05-03 … #endif
34.032258
120
0.682464
085707630864d9120bdb53fcfc991fd0600c5192
639
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "RxCoreData", platforms: [ .iOS(.v9), .macOS(.v10_12) ], products: [ .library(name: "RxCoreData", targets: ["RxCoreData"]), ], dependencies: [ .package(url: "https://github.com/ReactiveX/RxSwift.git", "6.0.0" ..< "7.0.0"), ], targets: [ .target( name: "RxCoreData", dependencies: [ .product(name: "RxSwift", package: "RxSwift"), .product(name: "RxCocoa", package: "RxSwift"), ], path: "Sources"), ] )
25.56
87
0.500782
9c1516251bfd415f92721106b5816d061c66a06f
1,568
import UIKit import SwiftyBeaver let log = SwiftyBeaver.self @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //let console = ConsoleDestination() // log to Xcode Console let file = FileDestination() // log to default swiftybeaver.log file - where is this file?????? let cloud = SBPlatformDestination(appID: Keys.sharedInstance.appID, appSecret: Keys.sharedInstance.appSecret, encryptionKey: Keys.sharedInstance.encryptionKey) cloud.analyticsUserName = "Tester1" cloud.showNSLog = false //log.addDestination(console) log.addDestination(file) log.addDestination(cloud) log.info("Log 1") // prio 3, INFO in green /* // log with different importance log.verbose("not so important") // prio 1, VERBOSE in silver log.debug("something to debug") // prio 2, DEBUG in blue log.info("a nice information") // prio 3, INFO in green log.warning("oh no, that won’t be good") // prio 4, WARNING in yellow log.error("ouch, an error did occur!") // prio 5, ERROR in red // log strings, ints, dates, etc. log.verbose(123) log.info(-123.45678) log.warning(NSDate()) log.error(["I", "like", "logs!"]) log.error(["name": "Mr Beaver", "address": "7 Beaver Lodge"]) */ return true } }
33.361702
169
0.646684
3aab906d6464b51223f50e770dbcf63a6a7fb510
3,662
// // ViewController.swift // TipCalculator // // Created by John Jakobsen on 9/3/20. // Copyright © 2020 Peggie Liang. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billAmountField: UITextField! @IBOutlet weak var tipPercentageLabel: UILabel! @IBOutlet weak var totalAmount: UILabel! @IBOutlet weak var tipSlider: UISlider! var tipSliderHidden: Bool! = false var symbol: String! let currencies = [ "$", "лв","₾", "₽", "₦", "R", "€", "¥", "元", "₹", "₩", "฿", "₫", ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. billAmountField.becomeFirstResponder() if UserDefaults.standard.object(forKey: "showTipSlider") != nil { tipSliderHidden = !UserDefaults.standard.bool(forKey: "showTipSlider") } // Resets after 5 minutes if UserDefaults.standard.object(forKey: "lastSaved") != nil && (UserDefaults.standard.object(forKey: "lastSaved") as! Date).distance(to: Date()) < 300 { billAmountField.text = UserDefaults.standard.string(forKey: "billAmount") ?? "" tipSlider.value = UserDefaults.standard.float(forKey: "tip") tipSlider.isHidden = !UserDefaults.standard.bool(forKey: "showTipSlider") tipSliderHidden = tipSlider.isHidden if UserDefaults.standard.object(forKey: "DefaultTip") != nil { tipSlider.value = UserDefaults.standard.float(forKey: "DefaultTip") } else { tipSlider.value = UserDefaults.standard.float(forKey: "tip") } billAmountChanged() } else { UserDefaults.standard.set("", forKey: "billAmount") UserDefaults.standard.set(0.0, forKey: "tip") } if UserDefaults.standard.object(forKey: "DefaultTip") != nil { tipSlider.value = UserDefaults.standard.float(forKey: "DefaultTip") } symbol = currencies[UserDefaults.standard.integer(forKey: "currRow") ?? 0] tipSliderChanged(tipSlider) totalAmount.text = symbol + String(totalAmount.text!.suffix(totalAmount.text!.count - 1)) UserDefaults.standard.set(Date(), forKey: "lastSaved") } @IBAction func tipSliderChanged(_ sender: Any) { tipSlider.value = round(tipSlider.value * 100) / 100 tipPercentageLabel.text = String(format: "%d %%", Int(round(tipSlider.value * 100))) billAmountChanged() } @IBAction func billAmountChanged(_ sender: Any) { UserDefaults.standard.set(billAmountField.text ?? 0, forKey: "billAmount") UserDefaults.standard.set(tipSlider.value, forKey: "tip") UserDefaults.standard.set(Date(), forKey: "lastSaved") billAmountChanged() } func billAmountChanged() { let billAmount: Float = Float(billAmountField.text!) ?? 0 totalAmount.text = String(format: "%@ %.2f",symbol ?? "$" ,billAmount * (tipSlider.value + 1.0)) } func setTip(tip: Float) { tipSlider.value = tip tipSliderChanged(tipSlider) } func tipVisibility(shown: Bool) { tipSlider.isHidden = !shown tipSliderHidden = !shown } func setCurr(sym: String) { symbol = sym totalAmount.text = symbol + String(totalAmount.text!.suffix(totalAmount.text!.count - 1)) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let settings = segue.destination as! SettingsViewController settings.mainController = self settings.tipSliderOn = !tipSliderHidden } }
40.688889
160
0.632714
d9edeeb80e80195974eeb311c43d0ae92217e8f2
789
// // PaddingLabel.swift // HouJia // // Created by JEROME on 2020/1/23. // import UIKit // 距離周邊有距離的 Label @IBDesignable public class PaddingLabel: UILabel { @IBInspectable var topInset: CGFloat = 5.0 @IBInspectable var bottomInset: CGFloat = 5.0 @IBInspectable var leftInset: CGFloat = 7.0 @IBInspectable var rightInset: CGFloat = 7.0 override public func drawText(in rect: CGRect) { let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset) super.drawText(in: rect.inset(by: insets)) } override public var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize(width: size.width + leftInset + rightInset, height: size.height + topInset + bottomInset) } }
27.206897
101
0.700887
46b6af4930348c3837abdf43bee00feb435fe5a5
875
// // MigratoryBirdsTests.swift // CodingChallengesTests // // Created by William Boles on 29/10/2021. // Copyright © 2021 Boles. All rights reserved. // import XCTest @testable import HackerRank class MigratoryBirdsTests: XCTestCase { // MARK: - Tests func test_A() { let birds = [1, 1, 2, 2, 3] let mostFrequent = MigratoryBirds.mostFrequentBird(from: birds) XCTAssertEqual(1, mostFrequent) } func test_B() { let birds = [1, 4, 4, 4, 5, 3] let mostFrequent = MigratoryBirds.mostFrequentBird(from: birds) XCTAssertEqual(4, mostFrequent) } func test_C() { let birds = [1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4] let mostFrequent = MigratoryBirds.mostFrequentBird(from: birds) XCTAssertEqual(3, mostFrequent) } }
21.341463
71
0.581714
fea6dfdad1f1cab0296854c102e2e323dadce2de
3,461
// // AppDelegate.swift // Warble // // Created by Vanna Phong on 2/25/17. // Copyright © 2017 Vanna Phong. All rights reserved. // import UIKit import AFNetworking import BDBOAuth1Manager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let storyboard = UIStoryboard(name: "Main", bundle: nil) if User.currentUser != nil { print("appDelegate.didFinishLaunching(): currentUser: \((User.currentUser?.screenname)! as String)") // set initial view to Tweets let vc = storyboard.instantiateViewController(withIdentifier: "tweetsNavigationController") window?.rootViewController = vc UIApplication.shared.statusBarStyle = .lightContent } else { print("there is NOT a user logged in") } // if user logs out NotificationCenter.default.addObserver(forName: User.userDidLogoutNotification, object: nil, queue: OperationQueue.main) { (notif: Notification) -> Void in // return to login view let vc = storyboard.instantiateInitialViewController() self.window?.rootViewController = vc } 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:. } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { TwitterClient.sharedInstance.handleOpenUrl(url: url) return true } }
42.207317
285
0.692863
fea83560efb25c9ee3dd8f0122435b3e5ac27d2a
1,546
// // UpdatedComponentsSection.swift // SwiftUIComponents // // Created by Rafal Padberg on 13/05/2021. // import SwiftUI struct UpdatedComponentsSection: View { var body: some View { Section(header: Text("Updated Components")) { NavigationLink(destination: ScrollViewReaderView()) { DoubleTextView(["ScrollView", ".scroll()"]) } NavigationLink(destination: PageTabViewStyleView()) { DoubleTextView(["TabView", "PageTabViewStyle()"]) } #if os(watchOS) NavigationLink(destination: CarouselTabViewStyleView()) { DoubleTextView(["TabView", "CarouselTabViewStyle()"]) } #endif NavigationLink(destination: ToggleView()) { DoubleTextView(["Toggle", "tint"]) } NavigationLink(destination: TextView()) { DoubleTextView(["Text", "date"]) } NavigationLink(destination: SFSymbolsView()) { DoubleTextView(["SFSymbols", "multicolor"]) } NavigationLink(destination: ListView()) { DoubleTextView(["List", "Style"])} } } } struct DoubleTextView: View { let textArray: [String] var body: some View { HStack { Text(textArray[0]) Text(textArray[1]) .font(.subheadline) .foregroundColor(.secondary) } } init(_ array: [String]) { textArray = array } } struct UpdatedComponentsSection_Previews: PreviewProvider { static var previews: some View { UpdatedComponentsSection() } }
30.92
125
0.608021
89f4a1f62790c7a2b884febf20b0e193c2db9c58
9,796
/* file: leader_directed_dimension.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY leader_directed_dimension SUBTYPE OF ( leader_directed_callout ); WHERE wr1: ( SIZEOF( QUERY ( con <* SELF.contents | ( 'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.' + 'LEADER_CURVE' IN TYPEOF( con ) ) ) ) = 1 ); END_ENTITY; -- leader_directed_dimension (line:18911 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) representation_item ATTR: name, TYPE: label -- EXPLICIT SUPER- ENTITY(2) geometric_representation_item ATTR: dim, TYPE: dimension_count -- DERIVED := dimension_of( SELF ) SUPER- ENTITY(3) draughting_callout ATTR: contents, TYPE: SET [1 : ?] OF draughting_callout_element -- EXPLICIT -- observed by ENTITY(1): annotation_placeholder_occurrence, ATTR: the_callout, TYPE: draughting_callout SUPER- ENTITY(4) leader_directed_callout (no local attributes) ENTITY(SELF) leader_directed_dimension (no local attributes) */ //MARK: - Partial Entity public final class _leader_directed_dimension : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eLEADER_DIRECTED_DIMENSION.self } //ATTRIBUTES // (no local attributes) public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //MARK: WHERE RULES (ENTITY) public static func WHERE_wr1(SELF: eLEADER_DIRECTED_DIMENSION?) -> SDAI.LOGICAL { guard let SELF = SELF else { return SDAI.UNKNOWN } let _TEMP1 = SELF.CONTENTS let _TEMP2 = _TEMP1.QUERY{ CON in let _TEMP1 = SDAI.TYPEOF(CON, IS: eLEADER_CURVE.self) return _TEMP1 } let _TEMP3 = SDAI.SIZEOF(_TEMP2) let _TEMP4 = _TEMP3 .==. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(1)) return _TEMP4 } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init() { super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 0 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } self.init( ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY leader_directed_dimension SUBTYPE OF ( leader_directed_callout ); WHERE wr1: ( SIZEOF( QUERY ( con <* SELF.contents | ( 'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.' + 'LEADER_CURVE' IN TYPEOF( con ) ) ) ) = 1 ); END_ENTITY; -- leader_directed_dimension (line:18911 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eLEADER_DIRECTED_DIMENSION : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _leader_directed_dimension.self } public let partialEntity: _leader_directed_dimension //MARK: SUPERTYPES public let super_eREPRESENTATION_ITEM: eREPRESENTATION_ITEM // [1] public let super_eGEOMETRIC_REPRESENTATION_ITEM: eGEOMETRIC_REPRESENTATION_ITEM // [2] public let super_eDRAUGHTING_CALLOUT: eDRAUGHTING_CALLOUT // [3] public let super_eLEADER_DIRECTED_CALLOUT: eLEADER_DIRECTED_CALLOUT // [4] public var super_eLEADER_DIRECTED_DIMENSION: eLEADER_DIRECTED_DIMENSION { return self } // [5] //MARK: SUBTYPES //MARK: ATTRIBUTES /// __EXPLICIT(OBSERVED)__ attribute /// - origin: SUPER( ``eDRAUGHTING_CALLOUT`` ) public var CONTENTS: SDAI.SET<sDRAUGHTING_CALLOUT_ELEMENT>/*[1:nil]*/ { get { return SDAI.UNWRAP( super_eDRAUGHTING_CALLOUT.partialEntity._contents ) } set(newValue) { let partial = super_eDRAUGHTING_CALLOUT.partialEntity partial._contents = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eREPRESENTATION_ITEM`` ) public var NAME: tLABEL { get { return SDAI.UNWRAP( super_eREPRESENTATION_ITEM.partialEntity._name ) } set(newValue) { let partial = super_eREPRESENTATION_ITEM.partialEntity partial._name = SDAI.UNWRAP(newValue) } } /// __DERIVE__ attribute /// - origin: SUPER( ``eGEOMETRIC_REPRESENTATION_ITEM`` ) public var DIM: tDIMENSION_COUNT? { get { if let cached = cachedValue(derivedAttributeName:"DIM") { return cached.value as! tDIMENSION_COUNT? } let origin = super_eGEOMETRIC_REPRESENTATION_ITEM let value = tDIMENSION_COUNT(origin.partialEntity._dim__getter(SELF: origin)) updateCache(derivedAttributeName:"DIM", value:value) return value } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_leader_directed_dimension.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eREPRESENTATION_ITEM.self) else { return nil } self.super_eREPRESENTATION_ITEM = super1 guard let super2 = complexEntity?.entityReference(eGEOMETRIC_REPRESENTATION_ITEM.self) else { return nil } self.super_eGEOMETRIC_REPRESENTATION_ITEM = super2 guard let super3 = complexEntity?.entityReference(eDRAUGHTING_CALLOUT.self) else { return nil } self.super_eDRAUGHTING_CALLOUT = super3 guard let super4 = complexEntity?.entityReference(eLEADER_DIRECTED_CALLOUT.self) else { return nil } self.super_eLEADER_DIRECTED_CALLOUT = super4 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: WHERE RULE VALIDATION (ENTITY) public override class func validateWhereRules(instance:SDAI.EntityReference?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] { guard let instance = instance as? Self else { return [:] } let prefix2 = prefix + " \(instance)" var result = super.validateWhereRules(instance:instance, prefix:prefix2) result[prefix2 + " .WHERE_wr1"] = _leader_directed_dimension.WHERE_wr1(SELF: instance) return result } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "LEADER_DIRECTED_DIMENSION", type: self, explicitAttributeCount: 0) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eREPRESENTATION_ITEM.self) entityDef.add(supertype: eGEOMETRIC_REPRESENTATION_ITEM.self) entityDef.add(supertype: eDRAUGHTING_CALLOUT.self) entityDef.add(supertype: eLEADER_DIRECTED_CALLOUT.self) entityDef.add(supertype: eLEADER_DIRECTED_DIMENSION.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "CONTENTS", keyPath: \eLEADER_DIRECTED_DIMENSION.CONTENTS, kind: .explicit, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "NAME", keyPath: \eLEADER_DIRECTED_DIMENSION.NAME, kind: .explicit, source: .superEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "DIM", keyPath: \eLEADER_DIRECTED_DIMENSION.DIM, kind: .derived, source: .superEntity, mayYieldEntityReference: false) return entityDef } } }
36.827068
185
0.710392
ff37050aa0e069778d6eaf113e1ac597bcd1be24
1,250
// // ViewController.swift // FullMaterialLoader // // Created by [email protected] on 02/14/2018. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit import FullMaterialLoader class ViewController: UIViewController { var indicator: MaterialLoadingIndicator! override func viewDidLoad() { super.viewDidLoad() self.configViews() } func configViews() { indicator = MaterialLoadingIndicator(frame: CGRect(x:0, y:0, width: 30, height: 30)) indicator.indicatorColor = [UIColor.red.cgColor, UIColor.blue.cgColor] indicator.center = self.view.center self.view.addSubview(indicator) indicator.startAnimating() } // ************ Not Using ***************** @IBAction func startLoader(_ sender: Any) { indicator.isHidden = false indicator.startAnimating() DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: { self.indicator.isHidden = true self.indicator.stopAnimating() }) } @IBAction func stopLoader(_ sender: Any) { indicator.stopAnimating() indicator.isHidden = true } }
24.038462
92
0.6152
fc50456ed857e96d4723ad8f55d44794446c6af5
1,938
// // Proteus.swift // Proteusific // // Created by Adam Jansch on 13/12/2020. // import AudioKit import CoreMIDI typealias BiDirectionalEndpointInfo = (source: EndpointInfo?, destination: EndpointInfo) final class Proteus: ObservableObject { // MARK: - PROPERTIES // MARK: Shared instance static let shared = Proteus() // MARK: Type properties private static let midiOperationQueueLabel = "MIDIOperationQueue" static let messageTimeoutDuration: TimeInterval = 1.0 static let midiOperationQueue = DispatchQueue(label: midiOperationQueueLabel, qos: .utility) // MARK: Wrapper properties @Published var midiSetupChanged = false // MARK: Stored properties var pendingSysExMessages: [SysExMessage] = [] var sysExResponseTimer: Timer? // MARK: Computed properties var currentDeviceID: MIDIByte { switch User.current?.currentDevice?.deviceID { case .some(let deviceID): return MIDIByte(deviceID) case .none: return SysExMessage.allBroadcastID } } // MARK: - METHODS // MARK: Initializers private init() {} deinit { MIDI.sharedInstance.removeListener(self) clearSysExResponseTimer() } // MARK: Configuration methods func configure() { let midi = MIDI.sharedInstance midi.clearListeners() midi.addListener(self) } // MARK: MIDI methods func changePreset(to preset: Preset, channel: MIDIChannel) { let midi = MIDI.sharedInstance let channel: MIDIChannel = channel let romChangeEvent = MIDIEvent(controllerChange: 0, value: MIDIByte(preset.romID), channel: channel) midi.sendEvent(romChangeEvent) let bankNumber = MIDIByte(preset.presetID / 128) let bankChangeEvent = MIDIEvent(controllerChange: 32, value: bankNumber, channel: channel) midi.sendEvent(bankChangeEvent) let presetNumber = MIDIByte(preset.presetID % 128) let programChangeEvent = MIDIEvent(programChange: presetNumber, channel: channel) midi.sendEvent(programChangeEvent) } }
25.84
102
0.747162
4bad77ae087e085517926f17fcb63ddea25a8762
5,254
// // AuthenticationWebviewController.swift // Xendit // // Created by Juan Gonzalez on 5/4/17. // // import Foundation import WebKit protocol AuthenticationProviderProtocol { func authenticate(fromViewController: UIViewController, URL: String, authentication: XenditAuthentication, completion: @escaping (XenditAuthentication?, XenditError?) -> Void) } class AuthenticationProvider: AuthenticationProviderProtocol { func authenticate(fromViewController: UIViewController, URL: String, authentication: XenditAuthentication, completion: @escaping (XenditAuthentication?, XenditError?) -> Void) { let webViewController = AuthenticationWebViewController(URL: URL) webViewController.authentication = authentication webViewController.authenticateCompletion = { updatedAuthentication, error in webViewController.dismiss(animated: true, completion: nil) completion(updatedAuthentication, error) } DispatchQueue.main.async { let navigationController = UINavigationController(rootViewController: webViewController) fromViewController.present(navigationController, animated: true, completion: nil) } } } class AuthenticationWebViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate { private var urlString : String! public var authentication : XenditAuthentication! var webView: WKWebView! var authenticateCompletion: (XenditAuthentication?, XenditError?) ->Void = { (authentication: XenditAuthentication?, error: XenditError?) -> Void in } // MARK: - Initializer init(URL: String) { super.init(nibName: nil, bundle: nil) urlString = URL } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = UIView(frame: UIScreen.main.bounds) view.backgroundColor = .white navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancelAuthentication)) let contentController = WKUserContentController(); contentController.add( self, name: "callbackHandler" ) let webConfiguration = WKWebViewConfiguration() webConfiguration.userContentController = contentController webView = WKWebView(frame: view.frame, configuration: webConfiguration) webView.navigationDelegate = self view.addSubview(webView) NSLayoutConstraint.activate([ NSLayoutConstraint(item: webView!, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView!, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView!, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView!, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0), ]) } override func viewDidLoad() { super.viewDidLoad() let HTMLString = WebViewConstants.templateHTMLWithAuthenticateURL.replacingOccurrences(of: "@xendit_src", with: urlString) webView.loadHTMLString(HTMLString, baseURL: nil) } @objc func cancelAuthentication() { authenticateCompletion(nil, XenditError(errorCode: "AUTHENTICATION_ERROR", message: "Authentication was cancelled")) } // MARK: - WKScriptMessageHandler func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { Log.shared.verbose("web auth: receive message \(message)") if let responseString = message.body as? String, let data = responseString.data(using: .utf8), let parsedData = try? JSONSerialization.jsonObject(with: data, options: []), let parsedDict = parsedData as? [String: Any] { handlePostMessageResponse(response: parsedDict) } else { Log.shared.logUnexpectedWebScriptMessage(url: urlString, message: message) authenticateCompletion(nil, XenditError(errorCode: "SERVER_ERROR", message: "Unable to parse server response")) } } func handlePostMessageResponse(response: [String:Any]) { let updatedAuthentication = XenditAuthentication(response: response) if updatedAuthentication != nil && authentication!.id == updatedAuthentication?.id { authenticateCompletion(updatedAuthentication, nil) } else { authenticateCompletion(nil, XenditError(errorCode: "SERVER_ERROR", message: "Incorrect webview post message format or wrong authentication id")) } } // MARK: - WKNavigationDelegate func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { Log.shared.verbose("web auth: navigation error \(error)") authenticateCompletion(nil, XenditError(errorCode: "WEBVIEW_ERROR", message: error.localizedDescription)) } }
41.370079
181
0.703083
bf105e36b60efab7e5800f479acbe9f255894067
927
// // Copyright © 2020 Apparata AB. All rights reserved. // import Foundation func replacing<T, U>(_ keyPath: WritableKeyPath<T, U>, on object: T, with value: U) -> T { var newObject = object newObject[keyPath: keyPath] = value return newObject } protocol KeyPathReplaceable { /// Example: /// /// ``` /// struct User: KeyPathReplaceable { /// var name: String /// var email: String /// } /// /// let user = User(name: "Luke", email: "[email protected]") /// let updatedUser = user.replacing(\.email, with: "[email protected]") /// ``` func replacing<LeafType>(_ keyPath: WritableKeyPath<Self, LeafType>, with value: LeafType) -> Self } extension KeyPathReplaceable { func replacing<LeafType>(_ keyPath: WritableKeyPath<Self, LeafType>, with value: LeafType) -> Self { SQLiteKit.replacing(keyPath, on: self, with: value) } }
27.264706
104
0.629989
09e3e2a84e460e8ac4da4e8c698939f53ee348c3
8,457
// // PoseMatchingViewController.swift // PoseEstimation-CoreML // // Created by Doyoung Gwak on 13/08/2019. // Copyright © 2019 tucan9389. All rights reserved. // import UIKit import CoreMedia import Vision class PoseMatchingViewController: UIViewController { // MARK: - UI Property @IBOutlet weak var videoPreview: UIView! @IBOutlet weak var jointView: DrawingJointView! @IBOutlet var capturedJointViews: [DrawingJointView]! @IBOutlet var capturedJointConfidenceLabels: [UILabel]! @IBOutlet var capturedJointBGViews: [UIView]! var capturedPointsArray: [[CapturedPoint?]?] = [] var capturedIndex = 0 // MARK: - AV Property var videoCapture: VideoCapture! // MARK: - ML Properties // Core ML model typealias EstimationModel = model_cpm // Preprocess and Inference var request: VNCoreMLRequest? var visionModel: VNCoreMLModel? // Postprocess var postProcessor: HeatmapPostProcessor = HeatmapPostProcessor() var mvfilters: [MovingAverageFilter] = [] override func viewDidLoad() { super.viewDidLoad() // setup the drawing views setUpCapturedJointView() // setup the model setUpModel() // setup camera setUpCamera() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.videoCapture.start() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.videoCapture.stop() } // MARK: - Setup Captured Joint View func setUpCapturedJointView() { postProcessor.onlyBust = true for capturedJointView in capturedJointViews { capturedJointView.layer.borderWidth = 2 capturedJointView.layer.borderColor = UIColor.gray.cgColor } capturedPointsArray = capturedJointViews.map { _ in return nil } for currentIndex in 0..<capturedPointsArray.count { // retrieving a value for a key if let data = UserDefaults.standard.data(forKey: "points-\(currentIndex)"), let capturedPoints = NSKeyedUnarchiver.unarchiveObject(with: data) as? [CapturedPoint?] { capturedPointsArray[currentIndex] = capturedPoints capturedJointViews[currentIndex].bodyPoints = capturedPoints.map { capturedPoint in if let capturedPoint = capturedPoint { return PredictedPoint(capturedPoint: capturedPoint) } else { return nil } } } } } // MARK: - Setup Core ML func setUpModel() { if let visionModel = try? VNCoreMLModel(for: EstimationModel().model) { self.visionModel = visionModel request = VNCoreMLRequest(model: visionModel, completionHandler: visionRequestDidComplete) request?.imageCropAndScaleOption = .centerCrop } else { fatalError("cannot load the ml model") } } // MARK: - SetUp Video func setUpCamera() { videoCapture = VideoCapture() videoCapture.delegate = self videoCapture.fps = 30 videoCapture.setUp(sessionPreset: .vga640x480, cameraPosition: .front) { success in if success { // add preview view on the layer if let previewLayer = self.videoCapture.previewLayer { self.videoPreview.layer.addSublayer(previewLayer) self.resizePreviewLayer() } // start video preview when setup is done self.videoCapture.start() } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() resizePreviewLayer() } func resizePreviewLayer() { videoCapture.previewLayer?.frame = videoPreview.bounds } // CAPTURE THE CURRENT POSE @IBAction func tapCapture(_ sender: Any) { let currentIndex = capturedIndex % capturedJointViews.count let capturedJointView = capturedJointViews[currentIndex] let predictedPoints = jointView.bodyPoints capturedJointView.bodyPoints = predictedPoints let capturedPoints: [CapturedPoint?] = predictedPoints.map { predictedPoint in guard let predictedPoint = predictedPoint else { return nil } return CapturedPoint(predictedPoint: predictedPoint) } capturedPointsArray[currentIndex] = capturedPoints let encodedData = NSKeyedArchiver.archivedData(withRootObject: capturedPoints) UserDefaults.standard.set(encodedData, forKey: "points-\(currentIndex)") print(UserDefaults.standard.synchronize()) capturedIndex += 1 } } // MARK: - VideoCaptureDelegate extension PoseMatchingViewController: VideoCaptureDelegate { func videoCapture(_ capture: VideoCapture, didCaptureVideoFrame pixelBuffer: CVPixelBuffer?, timestamp: CMTime) { // the captured image from camera is contained on pixelBuffer if let pixelBuffer = pixelBuffer { predictUsingVision(pixelBuffer: pixelBuffer) } } } extension PoseMatchingViewController { // MARK: - Inferencing func predictUsingVision(pixelBuffer: CVPixelBuffer) { guard let request = request else { fatalError() } // vision framework configures the input size of image following our model's input configuration automatically let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer) try? handler.perform([request]) } // MARK: - Postprocessing func visionRequestDidComplete(request: VNRequest, error: Error?) { guard let observations = request.results as? [VNCoreMLFeatureValueObservation], let heatmaps = observations.first?.featureValue.multiArrayValue else { return } /* =================================================================== */ /* ========================= post-processing ========================= */ /* ------------------ convert heatmap to point array ----------------- */ var predictedPoints = postProcessor.convertToPredictedPoints(from: heatmaps, isFlipped: true) /* --------------------- moving average filter ----------------------- */ if predictedPoints.count != mvfilters.count { mvfilters = predictedPoints.map { _ in MovingAverageFilter(limit: 3) } } for (predictedPoint, filter) in zip(predictedPoints, mvfilters) { filter.add(element: predictedPoint) } predictedPoints = mvfilters.map { $0.averagedValue() } /* =================================================================== */ let matchingRatios = capturedPointsArray .map { $0?.matchVector(with: predictedPoints) } .compactMap { $0 } /* =================================================================== */ /* ======================= display the results ======================= */ DispatchQueue.main.sync { [weak self] in guard let self = self else { return } // draw line self.jointView.bodyPoints = predictedPoints var topCapturedJointBGView: UIView? var maxMatchingRatio: CGFloat = 0 for (matchingRatio, (capturedJointBGView, capturedJointConfidenceLabel)) in zip(matchingRatios, zip(self.capturedJointBGViews, self.capturedJointConfidenceLabels)) { let text = String(format: "%.2f%", matchingRatio*100) capturedJointConfidenceLabel.text = text capturedJointBGView.backgroundColor = .clear if matchingRatio > 0.80 && maxMatchingRatio < matchingRatio { maxMatchingRatio = matchingRatio topCapturedJointBGView = capturedJointBGView } } topCapturedJointBGView?.backgroundColor = UIColor(red: 0.5, green: 1.0, blue: 0.5, alpha: 0.4) // print(matchingRatios) } /* =================================================================== */ } }
38.094595
177
0.593828
e2c66d1585c109e9ba22256895914c590a8e1825
277
// // Onboard.swift // paysplit // // Created by timofey makhlay on 4/27/20. // Copyright © 2020 dev. All rights reserved. // import UIKit /// Onboard will hold the raw data struct Onboard { let centerImgName: String let description: String let isGif: Bool }
16.294118
46
0.67148
62d5629f98260acc4b688ddd9601492a871ae9bb
156
import SwiftUI @main struct NeumorphicDesignSwiftUIApp: App { var body: some Scene { WindowGroup { ContentView() } } }
14.181818
40
0.576923
d97b2958612ea0f8e52cd2cc3f3f5758bb1c3fe3
1,227
import SwiftUI import UIKit import CropViewController struct AvatarCropView: UIViewControllerRepresentable { var model: AvatarPickerModel func makeUIViewController(context: Self.Context) -> CropViewController { let cropViewController = CropViewController(croppingStyle: .circular, image: model.pickedImage) cropViewController.delegate = context.coordinator return cropViewController } func updateUIViewController(_ uiViewController: CropViewController, context: Self.Context) {} func makeCoordinator() -> Coordinator { return Coordinator(self) } class Coordinator: NSObject, CropViewControllerDelegate { var parent: AvatarCropView init(_ parent: AvatarCropView) { self.parent = parent } func cropViewController(_ cropViewController: CropViewController, didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) { parent.model.cropped(image: image) } func cropViewController(_ cropViewController: CropViewController, didFinishCancelled cancelled: Bool) { parent.model.cancel() } } }
32.289474
111
0.672372
29301242469dcbd6b06a72c4ff7d9ad362ec0a39
4,099
import UIKit import FlexibleDiff class WordListViewController: UIViewController { let viewModel: WordListViewModel private var cachedCellViewModels: [Word] = [] private let tableView: UITableView init(viewModel: WordListViewModel) { tableView = UITableView() self.viewModel = viewModel super.init(nibName: nil, bundle: nil) viewModel.output = self } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = tableView tableView.register(WordCell.self, forCellReuseIdentifier: "WordCell") tableView.dataSource = self tableView.delegate = self tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension } override func viewDidLoad() { super.viewDidLoad() tableView.reloadData() viewModel.viewDidLoad() navigationItem.title = "Words" navigationItem.largeTitleDisplayMode = .never navigationItem.largeTitleDisplayMode = .automatic navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(userDidTapActionButton)) } @objc private func userDidTapActionButton() { viewModel.userDidTapActionButton() } override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { super.motionEnded(motion, with: event) if motion == .motionShake { viewModel.userDidShakeDevice() } } } extension WordListViewController: WordListViewModelOutput { func update(_ snapshot: Snapshot<[Word]>) { cachedCellViewModels = snapshot.current for offset in snapshot.changeset.mutations { let indexPath = IndexPath(row: offset, section: 0) guard let cell = tableView.cellForRow(at: indexPath) as! WordCell? else { continue } cell.configure(self.cachedCellViewModels[offset]) } for move in snapshot.changeset.moves where move.isMutated { let indexPath = IndexPath(row: move.source, section: 0) guard let cell = tableView.cellForRow(at: indexPath) as! WordCell? else { continue } cell.configure(self.cachedCellViewModels[move.destination]) } tableView.performBatchUpdates( { let inserted = snapshot.changeset.inserts.map { IndexPath(row: $0, section: 0) } let deleted = snapshot.changeset.removals.map { IndexPath(row: $0, section: 0) } tableView.insertRows(at: inserted, with: .top) tableView.deleteRows(at: deleted, with: .top) for move in snapshot.changeset.moves { tableView.moveRow(at: IndexPath(row: move.source, section: 0), to: IndexPath(row: move.destination, section: 0)) } }, completion: nil ) print(Date()) print(snapshot.changeset) print("") } } extension WordListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "WordCell", for: indexPath) as! WordCell let viewModel = cachedCellViewModels[indexPath.row] cell.configure(viewModel) return cell } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cachedCellViewModels.count } } extension WordListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { return UISwipeActionsConfiguration(actions: [ UIContextualAction(style: .destructive, title: "Delete") { [viewModel, cachedCellViewModels] _, _, completion in let isSuccessful = viewModel.deleteWord(cachedCellViewModels[indexPath.row]) completion(isSuccessful) }, UIContextualAction(style: .normal, title: "Edit") { [viewModel, cachedCellViewModels] _, _, completion in viewModel.editWord(cachedCellViewModels[indexPath.row], completion: completion) } ]) } }
31.530769
139
0.748475
fc612c7e36d37e1acb744b4896b63f9e8c640724
2,778
// // TransfornmLayerViewController.swift // CoreAnimation06 // // Created by roni on 2018/10/10. // Copyright © 2018 roni. All rights reserved. // import UIKit class TransfornmLayerViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() addContainerView() var pt = CATransform3DIdentity pt.m34 = -1 / 500.0 containerView.layer.sublayerTransform = pt var ct01 = CATransform3DIdentity ct01 = CATransform3DTranslate(ct01, -100, 0, 0) let cube01 = cube(withTransform: ct01) containerView.layer.addSublayer(cube01) var ct02 = CATransform3DIdentity ct02 = CATransform3DTranslate(ct02, 100, 0, 0) ct02 = CATransform3DRotate(ct02, -CGFloat.pi / 4, 1, 0, 0) ct02 = CATransform3DRotate(ct02, -CGFloat.pi / 4, 0, 1, 0) let cube02 = cube(withTransform: ct02) containerView.layer.addSublayer(cube02) } func face(with transform: CATransform3D) -> CALayer { let face = CALayer() face.frame = CGRect(x: -50, y: -50, width: 100, height: 100) let red = CGFloat.random(in: 0 ... 1) let green = CGFloat.random(in: 0 ... 1) let blue = CGFloat.random(in: 0 ... 1) face.backgroundColor = UIColor(displayP3Red: red, green: green, blue: blue, alpha: 1).cgColor face.transform = transform return face } func cube(withTransform: CATransform3D) -> CALayer { let cube = CATransformLayer() var transform = CATransform3DMakeTranslation(0, 0, 50) cube.addSublayer(face(with: transform)) transform = CATransform3DMakeTranslation(50, 0, 0) transform = CATransform3DRotate(transform, CGFloat.pi / 2, 0, 1, 0) cube.addSublayer(face(with: transform)) transform = CATransform3DMakeTranslation(0, -50, 0) transform = CATransform3DRotate(transform, CGFloat.pi / 2, 1, 0, 0) cube.addSublayer(face(with: transform)) transform = CATransform3DMakeTranslation(0, 50, 0) transform = CATransform3DRotate(transform, -CGFloat.pi / 2, 1, 0, 0) cube.addSublayer(face(with: transform)) transform = CATransform3DMakeTranslation(-50, 0, 0) transform = CATransform3DRotate(transform, -CGFloat.pi / 2, 0, 1, 0) cube.addSublayer(face(with: transform)) transform = CATransform3DMakeTranslation(0, 0, -50) transform = CATransform3DRotate(transform, CGFloat.pi, 0, 1, 0) cube.addSublayer(face(with: transform)) let containerSize = containerView.bounds.size cube.position = CGPoint(x: containerSize.width / 2, y: containerSize.height / 2) cube.transform = withTransform return cube } }
33.46988
101
0.644708
d58bf173f6f96b41d210604bab9f3199e801084f
206
// // NodeService1.swift // HHModule // // Created by Howie on 26/6/20. // Copyright © 2020 Beijing Bitstar Technology Co., Ltd. All rights reserved. // import UIKit class Service1Module: Module { }
14.714286
78
0.684466
bb60acfc49ee90bf31b3153fde48f96e52d39e8d
2,746
import XCTest import APNS class APNSTests: XCTestCase { var target: APNS! private let deviceToken: DeviceToken = "0c34a62170c1c0be603780e6458b20dc902730094805b87bef896e6f5ed9bbcb" func testSend_Code() throws { // Initialize from the config file target = try APNS(configPath: "/Users/mono/Documents/Config.plist") // Or from each argument // target = try APNS(keyPath: "YOUR_p8_KEY_PATH", // keyId: "YOUR_KEY_ID", // teamId: "YOUR_TEAM_ID", // environment: .sandbox, .production or .all) // environmentは省略可能 // All fields can be amitted let alert = Alert(title: "title", subtitle: "subtitle", body: "body", titleLocalizationKey: nil, titleLocalizationArguments: nil, actionLocalizationKey: nil, bodyLocalizationKey: nil, bodyLocalizationArguments: nil, launchImage: nil) let aps = Aps(alert: alert, badge: nil, // Can be omitted below sound: "Default", contentAvailable: nil, category: nil, threadId: nil) let payload = Payload(aps: aps, custom: Custom(test: "custom-value")) // Can be omitted let request = APNSRequest(topic: "com.mono0926.notification.example", payload: payload, apnsIdentifier: UUID(), // Can be omitted below priority: .immediately, expiration: Date().addingTimeInterval(3600), collapseIdentifier: "collapse-identifier") let results = try target.send(request: request, deviceTokens: [deviceToken]) results.forEach { print($0) } } func testSend_JSON() throws { target = try APNS(configPath: "/Users/mono/Documents/Config.plist") let payload = Payload(aps: try Aps(jsonPath: "/Users/mono/Documents/aps.json"), custom: try Custom(jsonPath: "/Users/mono/Documents/custom.json")) let request = APNSRequest(topic: "com.mono0926.notification.example", payload: payload) let results = try target.send(request: request, deviceTokens: [deviceToken]) results.forEach { print($0) } } } struct Custom: Codable, CustomPayload { let test: String }
41.606061
109
0.516023
62a2292a04186e6a3a72014a24d5ac1a7193f8e5
3,320
// // SceneDelegate.swift // Skyflow // // Created by Luis Zapata on 12-10-19. // Copyright © 2019 Luis Zapata. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Get the managed object context from the shared persistent container. let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = ContentView().environment(\.managedObjectContext, context) // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
46.111111
147
0.714157
75d847e4e1bfa0a296caf1373ccf3325593a2df0
1,021
// // ColorPickerViewController.swift // Mensagens // // Created by Rennan Bruno on 21/01/22. // Copyright © 2022 Eric Brito. All rights reserved. // import UIKit protocol ColorPickerDelegate: class { func applyColor(color: UIColor) } class ColorPickerViewController: UIViewController { @IBOutlet weak var viColor: UIView! @IBOutlet weak var slRed: UISlider! @IBOutlet weak var slGreen: UISlider! @IBOutlet weak var slBlue: UISlider! weak var delegate: ColorPickerDelegate? override func viewDidLoad() { super.viewDidLoad() } @IBAction func chooseColor(_ sender: UIButton) { delegate?.applyColor(color: viColor.backgroundColor!) dismiss(animated: true, completion: nil) } @IBAction func changeColor(_ sender: UISlider) { viColor.backgroundColor = UIColor(red: CGFloat(slRed.value), green:CGFloat(slGreen.value), blue: CGFloat(slBlue.value), alpha: 1.0) } }
22.688889
135
0.650343
28c189369c2a8de1746b10e39223831dbbba9f62
55
struct YOLOKitSwift { var text = "Hello, World!" }
13.75
30
0.636364
76b6b1cb362d502e8abbb6f4956fb93c8a6707fd
532
// // WatDocument.swift // Wasmic // // Created by kateinoigakukun on 2021/04/09. // import Foundation class WatDocument: TextDocument { init() { let tempDir = FileManager.default.temporaryDirectory let url = tempDir.appendingPathComponent("main.wat") super.init(fileURL: url) text = """ (module (export "_start" (func $_start)) (func $_start (result i32) (i32.const 0) ) ) """ } }
20.461538
60
0.509398
90a3eb1fdfba67df40a68eb4bcba9772f327044d
2,434
// // Constants.swift // RNShareMenu // // Created by Gustavo Parreira on 29/07/2020. // // MARK: Error Codes public let DISMISS_SHARE_EXTENSION_WITH_ERROR_CODE = 1 // MARK: Error Messages public let NO_URL_TYPES_ERROR_MESSAGE = "You have not defined CFBundleURLTypes in your Info.plist" public let NO_URL_SCHEMES_ERROR_MESSAGE = "You have not defined CFBundleURLSchemes in your Info.plist" public let NO_SCHEME_ERROR_MESSAGE = "You have not defined a scheme under CFBundleURLSchemes in your Info.plist" public let NO_APP_GROUP_ERROR = "Failed to get App Group User Defaults. Did you set up an App Group on your App and Share Extension?" public let NO_INFO_PLIST_INDENTIFIER_ERROR = "You haven't defined \(HOST_APP_IDENTIFIER_INFO_PLIST_KEY) in your Share Extension's Info.plist" public let NO_INFO_PLIST_URL_SCHEME_ERROR = "You haven't defined \(HOST_URL_SCHEME_INFO_PLIST_KEY) in your Share Extension's Info.plist" public let COULD_NOT_FIND_STRING_ERROR = "Couldn't find string" public let COULD_NOT_FIND_URL_ERROR = "Couldn't find url" public let COULD_NOT_FIND_IMG_ERROR = "Couldn't find image" public let COULD_NOT_PARSE_IMG_ERROR = "Couldn't parse image" public let COULD_NOT_SAVE_FILE_ERROR = "Couldn't save file on disk" public let NO_EXTENSION_CONTEXT_ERROR = "No extension context attached" public let NO_DELEGATE_ERROR = "No ReactShareViewDelegate attached" public let COULD_NOT_FIND_ITEM_ERROR = "Couldn't find item attached to this share" // MARK: Keys public let USER_DEFAULTS_KEY = "ShareMenuUserDefaults" public let USER_DEFAULTS_TEXT_KEY = "ShareMenuUserDefaultsText" public let USER_DEFAULTS_URL_KEY = "ShareMenuUserDefaultsUrl" public let USER_DEFAULTS_FILE_KEY = "ShareMenuUserDefaultsFile" public let USER_DEFAULTS_EXTRA_DATA_KEY = "ShareMenuUserDefaultsExtraData" public let URL_SCHEME_INFO_PLIST_KEY = "AppURLScheme" public let HOST_APP_IDENTIFIER_INFO_PLIST_KEY = "HostAppBundleIdentifier" public let HOST_URL_SCHEME_INFO_PLIST_KEY = "HostAppURLScheme" public let REACT_SHARE_VIEW_BACKGROUND_COLOR_KEY = "ReactShareViewBackgroundColor" public let COLOR_RED_KEY = "Red" public let COLOR_GREEN_KEY = "Green" public let COLOR_BLUE_KEY = "Blue" public let COLOR_ALPHA_KEY = "Alpha" public let COLOR_TRANSPARENT_KEY = "Transparent" public let MIME_TYPE_KEY = "mimeType" public let DATA_KEY = "data" public let EXTRA_DATA_KEY = "extraData" // MARK: Events public let NEW_SHARE_EVENT = "NewShareEvent"
45.924528
141
0.820049
56fecd6895fe0cf9beca9ce71c333b740c14f435
61,380
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module /** URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated. Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system. As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located. */ public struct URLResourceValues { fileprivate var _values: [URLResourceKey: Any] fileprivate var _keys: Set<URLResourceKey> public init() { _values = [:] _keys = [] } fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) { _values = values _keys = keys } private func contains(_ key: URLResourceKey) -> Bool { return _keys.contains(key) } private func _get<T>(_ key : URLResourceKey) -> T? { return _values[key] as? T } private func _get(_ key : URLResourceKey) -> Bool? { return (_values[key] as? NSNumber)?.boolValue } private func _get(_ key: URLResourceKey) -> Int? { return (_values[key] as? NSNumber)?.intValue } private mutating func _set(_ key : URLResourceKey, newValue : Any?) { _keys.insert(key) _values[key] = newValue } private mutating func _set(_ key : URLResourceKey, newValue : String?) { _keys.insert(key) _values[key] = newValue as NSString? } private mutating func _set(_ key : URLResourceKey, newValue : [String]?) { _keys.insert(key) _values[key] = newValue as NSObject? } private mutating func _set(_ key : URLResourceKey, newValue : Date?) { _keys.insert(key) _values[key] = newValue as NSDate? } private mutating func _set(_ key : URLResourceKey, newValue : URL?) { _keys.insert(key) _values[key] = newValue as NSURL? } private mutating func _set(_ key : URLResourceKey, newValue : Bool?) { _keys.insert(key) if let value = newValue { _values[key] = NSNumber(value: value) } else { _values[key] = nil } } private mutating func _set(_ key : URLResourceKey, newValue : Int?) { _keys.insert(key) if let value = newValue { _values[key] = NSNumber(value: value) } else { _values[key] = nil } } /// A loosely-typed dictionary containing all keys and values. /// /// If you have set temporary keys or non-standard keys, you can find them in here. public var allValues : [URLResourceKey : Any] { return _values } /// The resource name provided by the file system. public var name: String? { get { return _get(.nameKey) } set { _set(.nameKey, newValue: newValue) } } /// Localized or extension-hidden name as displayed to users. public var localizedName: String? { return _get(.localizedNameKey) } /// True for regular files. public var isRegularFile: Bool? { return _get(.isRegularFileKey) } /// True for directories. public var isDirectory: Bool? { return _get(.isDirectoryKey) } /// True for symlinks. public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) } /// True for the root directory of a volume. public var isVolume: Bool? { return _get(.isVolumeKey) } /// True for packaged directories. /// /// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect. public var isPackage: Bool? { get { return _get(.isPackageKey) } set { _set(.isPackageKey, newValue: newValue) } } /// True if resource is an application. @available(OSX 10.11, iOS 9.0, *) public var isApplication: Bool? { return _get(.isApplicationKey) } #if os(OSX) /// True if the resource is scriptable. Only applies to applications. @available(OSX 10.11, *) public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) } #endif /// True for system-immutable resources. public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) } /// True for user-immutable resources public var isUserImmutable: Bool? { get { return _get(.isUserImmutableKey) } set { _set(.isUserImmutableKey, newValue: newValue) } } /// True for resources normally not displayed to users. /// /// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property. public var isHidden: Bool? { get { return _get(.isHiddenKey) } set { _set(.isHiddenKey, newValue: newValue) } } /// True for resources whose filename extension is removed from the localized name property. public var hasHiddenExtension: Bool? { get { return _get(.hasHiddenExtensionKey) } set { _set(.hasHiddenExtensionKey, newValue: newValue) } } /// The date the resource was created. public var creationDate: Date? { get { return _get(.creationDateKey) } set { _set(.creationDateKey, newValue: newValue) } } /// The date the resource was last accessed. public var contentAccessDate: Date? { get { return _get(.contentAccessDateKey) } set { _set(.contentAccessDateKey, newValue: newValue) } } /// The time the resource content was last modified. public var contentModificationDate: Date? { get { return _get(.contentModificationDateKey) } set { _set(.contentModificationDateKey, newValue: newValue) } } /// The time the resource's attributes were last modified. public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) } /// Number of hard links to the resource. public var linkCount: Int? { return _get(.linkCountKey) } /// The resource's parent directory, if any. public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) } /// URL of the volume on which the resource is stored. public var volume: URL? { return _get(.volumeURLKey) } /// Uniform type identifier (UTI) for the resource. public var typeIdentifier: String? { return _get(.typeIdentifierKey) } /// User-visible type or "kind" description. public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) } /// The label number assigned to the resource. public var labelNumber: Int? { get { return _get(.labelNumberKey) } set { _set(.labelNumberKey, newValue: newValue) } } /// The user-visible label text. public var localizedLabel: String? { get { return _get(.localizedLabelKey) } } /// An identifier which can be used to compare two file system objects for equality using `isEqual`. /// /// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts. public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) } /// An identifier that can be used to identify the volume the file system object is on. /// /// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts. public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) } /// The optimal block size when reading or writing this file's data, or nil if not available. public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) } /// True if this process (as determined by EUID) can read the resource. public var isReadable: Bool? { return _get(.isReadableKey) } /// True if this process (as determined by EUID) can write to the resource. public var isWritable: Bool? { return _get(.isWritableKey) } /// True if this process (as determined by EUID) can execute a file resource or search a directory resource. public var isExecutable: Bool? { return _get(.isExecutableKey) } /// The file system object's security information encapsulated in a FileSecurity object. public var fileSecurity: NSFileSecurity? { get { return _get(.fileSecurityKey) } set { _set(.fileSecurityKey, newValue: newValue) } } /// True if resource should be excluded from backups, false otherwise. /// /// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents. public var isExcludedFromBackup: Bool? { get { return _get(.isExcludedFromBackupKey) } set { _set(.isExcludedFromBackupKey, newValue: newValue) } } #if os(OSX) /// The array of Tag names. public var tagNames: [String]? { return _get(.tagNamesKey) } #endif /// The URL's path as a file system path. public var path: String? { return _get(.pathKey) } /// The URL's path as a canonical absolute file system path. @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public var canonicalPath: String? { return _get(.canonicalPathKey) } /// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory. public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) } /// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified. /// /// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes. @available(OSX 10.10, iOS 8.0, *) public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) } /// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume. /// /// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes. @available(OSX 10.10, iOS 8.0, *) public var documentIdentifier: Int? { return _get(.documentIdentifierKey) } /// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes. @available(OSX 10.10, iOS 8.0, *) public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) } #if os(OSX) /// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property. @available(OSX 10.10, *) public var quarantineProperties: [String : Any]? { get { let value = _values[.quarantinePropertiesKey] // If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull if value is NSNull { return nil } else { return value as? [String : Any] } } set { // Use NSNull for nil, a special case for deleting quarantine // properties _set(.quarantinePropertiesKey, newValue: newValue ?? NSNull()) } } #endif /// Returns the file system object type. public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) } /// The user-visible volume format. public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) } /// Total volume capacity in bytes. public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) } /// Total free space in bytes. public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) } /// Total number of resources on the volume. public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) } /// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs. public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) } /// true if the volume format supports symbolic links. public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) } /// true if the volume format supports hard links. public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) } /// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal. public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) } /// true if the volume is currently using a journal for speedy recovery after an unplanned restart. public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) } /// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length. public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) } /// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media. public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) } /// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters. public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) } /// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case). public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) } /// true if the volume supports reliable storage of times for the root directory. public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) } /// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`). public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) } /// true if the volume can be renamed. public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) } /// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call. public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) } /// true if the volume implements extended security (ACLs). public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) } /// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume). public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) } /// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined. public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) } /// true if the volume's media is ejectable from the drive mechanism under software control. public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) } /// true if the volume's media is removable from the drive mechanism. public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) } /// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available. public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) } /// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey. public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) } /// true if the volume is stored on a local device. public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) } /// true if the volume is read-only. public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) } /// The volume's creation date, or nil if this cannot be determined. public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) } /// The `URL` needed to remount a network volume, or nil if not available. public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) } /// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume. public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) } /// The name of the volume public var volumeName : String? { get { return _get(.volumeNameKey) } set { _set(.volumeNameKey, newValue: newValue) } } /// The user-presentable name of the volume public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) } /// true if the volume is encrypted. @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) } /// true if the volume is the root filesystem. @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) } /// true if the volume supports transparent decompression of compressed files using decmpfs. @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) } /// true if this item is synced to the cloud, false if it is only a local file. public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) } /// true if this item has conflicts outstanding. public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) } /// true if data is being downloaded for this item. public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) } /// true if there is data present in the cloud for this item. public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) } /// true if data is being uploaded for this item. public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) } /// returns the download status of this item. public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) } /// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) } /// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) } /// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`. @available(OSX 10.10, iOS 8.0, *) public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) } /// returns the name of this item's container as displayed to users. @available(OSX 10.10, iOS 8.0, *) public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) } #if !os(OSX) /// The protection level for this file @available(iOS 9.0, *) public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) } #endif /// Total file size in bytes /// /// - note: Only applicable to regular files. public var fileSize : Int? { return _get(.fileSizeKey) } /// Total size allocated on disk for the file in bytes (number of blocks times block size) /// /// - note: Only applicable to regular files. public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) } /// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available. /// /// - note: Only applicable to regular files. public var totalFileSize : Int? { return _get(.totalFileSizeKey) } /// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed. /// /// - note: Only applicable to regular files. public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) } /// true if the resource is a Finder alias file or a symlink, false otherwise /// /// - note: Only applicable to regular files. public var isAliasFile : Bool? { return _get(.isAliasFileKey) } } /** A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data. You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide. URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`. */ public struct URL : ReferenceConvertible, Equatable { public typealias ReferenceType = NSURL fileprivate var _url : NSURL public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions /// Initialize with string. /// /// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string). public init?(string: String) { guard !string.isEmpty else { return nil } if let inner = NSURL(string: string) { _url = URL._converted(from: inner) } else { return nil } } /// Initialize with string, relative to another URL. /// /// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string). public init?(string: String, relativeTo url: URL?) { guard !string.isEmpty else { return nil } if let inner = NSURL(string: string, relativeTo: url) { _url = URL._converted(from: inner) } else { return nil } } /// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL. /// /// If an empty string is used for the path, then the path is assumed to be ".". /// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already. @available(OSX 10.11, iOS 9.0, *) public init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) { _url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base)) } /// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL. /// /// If an empty string is used for the path, then the path is assumed to be ".". @available(OSX 10.11, iOS 9.0, *) public init(fileURLWithPath path: String, relativeTo base: URL?) { _url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base)) } /// Initializes a newly created file URL referencing the local file or directory at path. /// /// If an empty string is used for the path, then the path is assumed to be ".". /// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already. public init(fileURLWithPath path: String, isDirectory: Bool) { _url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory)) } /// Initializes a newly created file URL referencing the local file or directory at path. /// /// If an empty string is used for the path, then the path is assumed to be ".". public init(fileURLWithPath path: String) { _url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path)) } /// Initializes a newly created URL using the contents of the given data, relative to a base URL. /// /// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil. @available(OSX 10.11, iOS 9.0, *) public init?(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) { guard dataRepresentation.count > 0 else { return nil } if isAbsolute { _url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url)) } else { _url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url)) } } /// Initializes a URL that refers to a location specified by resolving bookmark data. public init?(resolvingBookmarkData data: Data, options: BookmarkResolutionOptions = [], relativeTo url: URL? = nil, bookmarkDataIsStale: inout Bool) throws { var stale : ObjCBool = false _url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale)) bookmarkDataIsStale = stale.boolValue } /// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method. @available(OSX 10.10, iOS 8.0, *) public init(resolvingAliasFileAt url: URL, options: BookmarkResolutionOptions = []) throws { self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options)) } /// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding. public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: URL?) { _url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL)) } public var hashValue: Int { return _url.hash } // MARK: - /// Returns the data representation of the URL's relativeString. /// /// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding. @available(OSX 10.11, iOS 9.0, *) public var dataRepresentation: Data { return _url.dataRepresentation } // MARK: - // Future implementation note: // NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult. // Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API. /// Returns the absolute string for the URL. public var absoluteString: String { if let string = _url.absoluteString { return string } else { // This should never fail for non-file reference URLs return "" } } /// The relative portion of a URL. /// /// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`. public var relativeString: String { return _url.relativeString } /// Returns the base URL. /// /// If the URL is itself absolute, then this value is nil. public var baseURL: URL? { return _url.baseURL } /// Returns the absolute URL. /// /// If the URL is itself absolute, this will return self. public var absoluteURL: URL { if let url = _url.absoluteURL { return url } else { // This should never fail for non-file reference URLs return self } } // MARK: - /// Returns the scheme of the URL. public var scheme: String? { return _url.scheme } /// Returns true if the scheme is `file:`. public var isFileURL: Bool { return _url.isFileURL } // This thing was never really part of the URL specs @available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead") public var resourceSpecifier: String { fatalError() } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil. /// /// - note: This function will resolve against the base `URL`. public var host: String? { return _url.host } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil. /// /// - note: This function will resolve against the base `URL`. public var port: Int? { return _url.port?.intValue } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil. /// /// - note: This function will resolve against the base `URL`. public var user: String? { return _url.user } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil. /// /// - note: This function will resolve against the base `URL`. public var password: String? { return _url.password } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string. /// /// If the URL contains a parameter string, it is appended to the path with a `;`. /// - note: This function will resolve against the base `URL`. /// - returns: The path, or an empty string if the URL has an empty path. public var path: String { if let parameterString = _url.parameterString { if let path = _url.path { return path + ";" + parameterString } else { return ";" + parameterString } } else if let path = _url.path { return path } else { return "" } } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil. /// /// This is the same as path if baseURL is nil. /// If the URL contains a parameter string, it is appended to the path with a `;`. /// /// - note: This function will resolve against the base `URL`. /// - returns: The relative path, or an empty string if the URL has an empty path. public var relativePath: String { if let parameterString = _url.parameterString { if let path = _url.relativePath { return path + ";" + parameterString } else { return ";" + parameterString } } else if let path = _url.relativePath { return path } else { return "" } } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil. /// /// - note: This function will resolve against the base `URL`. public var fragment: String? { return _url.fragment } @available(*, unavailable, message: "use the 'path' property") public var parameterString: String? { fatalError() } /// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil. /// /// - note: This function will resolve against the base `URL`. public var query: String? { return _url.query } /// Returns true if the URL path represents a directory. @available(OSX 10.11, iOS 9.0, *) public var hasDirectoryPath: Bool { return _url.hasDirectoryPath } /// Passes the URL's path in file system representation to `block`. /// /// File system representation is a null-terminated C string with canonical UTF-8 encoding. /// - note: The pointer is not valid outside the context of the block. @available(OSX 10.9, iOS 7.0, *) public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType { return try block(_url.fileSystemRepresentation) } // MARK: - // MARK: Path manipulation /// Returns the path components of the URL, or an empty array if the path is an empty string. public var pathComponents: [String] { // In accordance with our above change to never return a nil path, here we return an empty array. return _url.pathComponents ?? [] } /// Returns the last path component of the URL, or an empty string if the path is an empty string. public var lastPathComponent: String { return _url.lastPathComponent ?? "" } /// Returns the path extension of the URL, or an empty string if the path is an empty string. public var pathExtension: String { return _url.pathExtension ?? "" } /// Returns a URL constructed by appending the given path component to self. /// /// - parameter pathComponent: The path component to add. /// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path. public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL { if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) { return result } else { // Now we need to do something more expensive if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) { c.path = (c.path as NSString).appendingPathComponent(pathComponent) if let result = c.url { return result } else { // Couldn't get url from components // Ultimate fallback: return self } } else { return self } } } /// Returns a URL constructed by appending the given path component to self. /// /// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`. /// - parameter pathComponent: The path component to add. public func appendingPathComponent(_ pathComponent: String) -> URL { if let result = _url.appendingPathComponent(pathComponent) { return result } else { // Now we need to do something more expensive if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) { c.path = (c.path as NSString).appendingPathComponent(pathComponent) if let result = c.url { return result } else { // Couldn't get url from components // Ultimate fallback: return self } } else { // Ultimate fallback: return self } } } /// Returns a URL constructed by removing the last path component of self. /// /// This function may either remove a path component or append `/..`. /// /// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged. public func deletingLastPathComponent() -> URL { // This is a slight behavior change from NSURL, but better than returning "http://www.example.com../". if path.isEmpty { return self } if let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) { return result } else { return self } } /// Returns a URL constructed by appending the given path extension to self. /// /// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged. /// /// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged. /// - parameter pathExtension: The extension to append. public func appendingPathExtension(_ pathExtension: String) -> URL { if path.isEmpty { return self } if let result = _url.appendingPathExtension(pathExtension) { return result } else { return self } } /// Returns a URL constructed by removing any path extension. /// /// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged. public func deletingPathExtension() -> URL { if path.isEmpty { return self } if let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) { return result } else { return self } } /// Appends a path component to the URL. /// /// - parameter pathComponent: The path component to add. /// - parameter isDirectory: Use `true` if the resulting path is a directory. public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) { self = appendingPathComponent(pathComponent, isDirectory: isDirectory) } /// Appends a path component to the URL. /// /// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`. /// - parameter pathComponent: The path component to add. public mutating func appendPathComponent(_ pathComponent: String) { self = appendingPathComponent(pathComponent) } /// Appends the given path extension to self. /// /// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing. /// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged. /// - parameter pathExtension: The extension to append. public mutating func appendPathExtension(_ pathExtension: String) { self = appendingPathExtension(pathExtension) } /// Returns a URL constructed by removing the last path component of self. /// /// This function may either remove a path component or append `/..`. /// /// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing. public mutating func deleteLastPathComponent() { self = deletingLastPathComponent() } /// Returns a URL constructed by removing any path extension. /// /// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing. public mutating func deletePathExtension() { self = deletingPathExtension() } /// Returns a `URL` with any instances of ".." or "." removed from its path. public var standardized : URL { // The NSURL API can only return nil in case of file reference URL, which we should not be if let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) { return result } else { return self } } /// Standardizes the path of a file URL. /// /// If the `isFileURL` is false, this method does nothing. public mutating func standardize() { self = self.standardized } /// Standardizes the path of a file URL. /// /// If the `isFileURL` is false, this method returns `self`. public var standardizedFileURL : URL { // NSURL should not return nil here unless this is a file reference URL, which should be impossible if let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) { return result } else { return self } } /// Resolves any symlinks in the path of a file URL. /// /// If the `isFileURL` is false, this method returns `self`. public func resolvingSymlinksInPath() -> URL { // NSURL should not return nil here unless this is a file reference URL, which should be impossible if let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) { return result } else { return self } } /// Resolves any symlinks in the path of a file URL. /// /// If the `isFileURL` is false, this method does nothing. public mutating func resolveSymlinksInPath() { self = self.resolvingSymlinksInPath() } // MARK: - Reachability /// Returns whether the URL's resource exists and is reachable. /// /// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned. public func checkResourceIsReachable() throws -> Bool { var error : NSError? let result = _url.checkResourceIsReachableAndReturnError(&error) if let e = error { throw e } else { return result } } /// Returns whether the promised item URL's resource exists and is reachable. /// /// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned. @available(OSX 10.10, iOS 8.0, *) public func checkPromisedItemIsReachable() throws -> Bool { var error : NSError? let result = _url.checkPromisedItemIsReachableAndReturnError(&error) if let e = error { throw e } else { return result } } // MARK: - Resource Values /// Sets the resource value identified by a given resource key. /// /// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources. /// /// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write. public mutating func setResourceValues(_ values: URLResourceValues) throws { try _url.setResourceValues(values._values) } /// Return a collection of resource values identified by the given resource keys. /// /// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources. /// /// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values. /// /// Only the values for the keys specified in `keys` will be populated. public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues { return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys))) } /// Sets a temporary resource value on the URL object. /// /// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property. /// /// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources. public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) { _url.setTemporaryResourceValue(value, forKey: key) } /// Removes all cached resource values and all temporary resource values from the URL object. /// /// This method is currently applicable only to URLs for file system resources. public mutating func removeAllCachedResourceValues() { _url.removeAllCachedResourceValues() } /// Removes the cached resource value identified by a given resource value key from the URL object. /// /// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources. public mutating func removeCachedResourceValue(forKey key: URLResourceKey) { _url.removeCachedResourceValue(forKey: key) } /// Get resource values from URLs of 'promised' items. /// /// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently: /// NSMetadataQueryUbiquitousDataScope /// NSMetadataQueryUbiquitousDocumentsScope /// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof /// /// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true: /// You are using a URL that you know came directly from one of the above APIs /// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly /// /// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil. @available(OSX 10.10, iOS 8.0, *) public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues { return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys))) } @available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead") public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws { fatalError() } @available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead") public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws { fatalError() } @available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead") public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws { fatalError() } // MARK: - Bookmarks and Alias Files /// Returns bookmark data for the URL, created with specified options and resource values. public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data { let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url) return result as Data } /// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data. public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? { return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) } } /// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory. public static func writeBookmarkData(_ data : Data, to url: URL) throws { // Options are unused try NSURL.writeBookmarkData(data, to: url, options: 0) } /// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file. public static func bookmarkData(withContentsOf url: URL) throws -> Data { let result = try NSURL.bookmarkData(withContentsOf: url) return result as Data } /// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted). @available(OSX 10.7, iOS 8.0, *) public func startAccessingSecurityScopedResource() -> Bool { return _url.startAccessingSecurityScopedResource() } /// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource. @available(OSX 10.7, iOS 8.0, *) public func stopAccessingSecurityScopedResource() { _url.stopAccessingSecurityScopedResource() } // MARK: - Bridging Support /// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions. private static func _converted(from url: NSURL) -> NSURL { // Future readers: file reference URL here is not the same as playgrounds "file reference" if url.isFileReferenceURL() { // Convert to a file path URL, or use an invalid scheme return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL } else { return url } } fileprivate init(reference: NSURL) { _url = URL._converted(from: reference).copy() as! NSURL } private var reference : NSURL { return _url } public static func ==(lhs: URL, rhs: URL) -> Bool { return lhs.reference.isEqual(rhs.reference) } } extension URL : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSURL { return _url } public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) { if !_conditionallyBridgeFromObjectiveC(source, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool { result = URL(reference: source) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL { var result: URL? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension URL : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return _url.description } public var debugDescription: String { return _url.debugDescription } } extension NSURL : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as URL) } } extension URL : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .url(absoluteString) } } //===----------------------------------------------------------------------===// // File references, for playgrounds. //===----------------------------------------------------------------------===// extension URL : _ExpressibleByFileReferenceLiteral { public init(fileReferenceLiteralResourceName name: String) { self = Bundle.main.url(forResource: name, withExtension: nil)! } } public typealias _FileReferenceLiteralType = URL
51.753794
765
0.685549
26824baa0c0fda0c7daa70eedb17aec1be0a6b6c
292
public class ExposureAdjustment: BasicOperation { public var exposure: Float = 0.0 { didSet { uniformSettings["exposure"] = exposure } } public init() { super.init(fragmentShader: ExposureFragmentShader, numberOfInputs: 1) ({ exposure = 0.0 })() } }
29.2
90
0.630137
7a440e39623b43bae56a2e85d4a3f0cb46c1ed9b
1,464
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Foundation import RxSwift class OpenQuicklyReducer: ReducerType { typealias StateType = AppState typealias ActionType = OpenQuicklyWindow.Action let mainWindow = MainWindowReducer() func typedReduce(_ pair: ReduceTuple) -> ReduceTuple { var appState = pair.state switch pair.action { case let .setUsesVcsIgnores(usesVcsIgnores): guard let uuid = appState.currentMainWindowUuid else { return pair } appState.mainWindows[uuid]?.usesVcsIgnores = usesVcsIgnores case let .open(url): guard let uuid = appState.currentMainWindowUuid else { return pair } appState.mainWindows[uuid]?.urlsToOpen[url] = .default appState.openQuickly.open = false case .close: appState.openQuickly.open = false break } return (appState, pair.action, true) } class MainWindowReducer: ReducerType { typealias StateType = AppState typealias ActionType = UuidAction<MainWindow.Action> func typedReduce(_ pair: ReduceTuple) -> ReduceTuple { switch pair.action.payload { case .openQuickly: var appState = pair.state guard let uuid = appState.currentMainWindowUuid, appState.mainWindows[uuid]?.cwd != nil else { return pair } appState.openQuickly.open = true return (appState, pair.action, true) default: return pair } } } }
22.875
74
0.676913
ffc63af9c48ffb31436102c7fc32727109c8a29b
4,998
// // TrendingViewController.swift // SWHub // // Created by 杨建祥 on 2020/11/28. // import UIKit import Parchment import SnapKit import SideMenu class TrendingViewController: ScrollViewController, ReactorKit.View { lazy var paging: NavigationBarPagingViewController = { let paging = NavigationBarPagingViewController() paging.menuBackgroundColor = .clear paging.menuHorizontalAlignment = .center paging.borderOptions = .hidden paging.menuItemSize = .selfSizing(estimatedWidth: 100, height: UINavigationBar.height) return paging }() init(_ navigator: NavigatorType, _ reactor: TrendingViewReactor) { defer { self.reactor = reactor } super.init(navigator, reactor) self.tabBarItem.title = reactor.currentState.title } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.addChild(self.paging) self.view.addSubview(self.paging.view) let tabBarHeight = self.tabBarController?.tabBar.height ?? 0 self.paging.view.snp.makeConstraints { make in make.leading.equalToSuperview() make.top.equalToSuperview().offset(self.contentTop) make.trailing.equalToSuperview() make.bottom.equalToSuperview().offset(-tabBarHeight) } self.paging.didMove(toParent: self) self.paging.dataSource = self self.paging.collectionView.size = CGSize(width: self.view.width, height: UINavigationBar.height) self.navigationBar.titleView = self.paging.collectionView // v1.0.0版本屏蔽该功能,完善功能后下个版本打开 // self.navigationBar.addButtonToLeft(image: R.image.nav_menu()).rx.tap // .subscribeNext(weak: self, type(of: self).tapMenu) // .disposed(by: self.disposeBag) self.navigationBar.addButtonToRight(image: R.image.nav_search()).rx.tap .subscribeNext(weak: self, type(of: self).tapSearch) .disposed(by: self.disposeBag) themeService.rx .bind({ $0.brightColor }, to: self.paging.view.rx.backgroundColor) .bind({ $0.primaryColor }, to: [self.paging.rx.indicatorColor, self.paging.rx.selectedTextColor]) .bind({ $0.titleColor }, to: self.paging.rx.textColor) .disposed(by: self.rx.disposeBag) } func bind(reactor: TrendingViewReactor) { super.bind(reactor: reactor) self.toAction(reactor: reactor) self.fromState(reactor: reactor) } func tapSearch(event: ControlEvent<Void>.Element) { self.navigator.present( Router.urlString(host: .search).url! .appendingPathComponent(Router.Path.history.rawValue), wrap: NavigationController.self, animated: false ) } func tapMenu(event: ControlEvent<Void>.Element) { let url = Router.urlString(host: .popup).url! .appendingPathComponent(Router.Path.menu.rawValue) (self.navigator as? Navigator)?.rx.open(url) .subscribeNext(weak: self, type(of: self).menuResult) .disposed(by: self.disposeBag) } func menuResult(event: Event<Any>.Element) { } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func handle(_ languages: [Language]) { Language.storeArray(languages) } } extension TrendingViewController: PagingViewControllerDataSource { func numberOfViewControllers(in pagingViewController: PagingViewController) -> Int { return self.reactor!.currentState.pages.count } func pagingViewController(_: PagingViewController, pagingItemAt index: Int) -> PagingItem { return PagingIndexItem(index: index, title: self.reactor!.currentState.pages[index].title) } func pagingViewController(_: PagingViewController, viewControllerAt index: Int) -> UIViewController { switch self.reactor!.currentState.pages[index] { case .repos: return self.navigator.viewController( for: Router.urlString(host: .repos).url! .appendingPathComponent(Router.Path.trending.rawValue) )! case .users: return self.navigator.viewController( for: Router.urlString(host: .users).url! .appendingPathComponent(Router.Path.trending.rawValue) )! } } } class NavigationBarPagingView: PagingView { override func setupConstraints() { pageView.snp.makeConstraints { $0.edges.equalToSuperview() } } } class NavigationBarPagingViewController: PagingViewController { override func loadView() { view = NavigationBarPagingView( options: options, collectionView: collectionView, pageView: pageViewController.view ) } }
33.099338
109
0.647459
c15212d340a28b8f2d35726e1f57ca6247088e23
1,189
// // Updater.swift // MimeLibGenerator // // Created by Ondrej Rafaj on 14/12/2016. // Copyright © 2016 manGoweb UK Ltd. All rights reserved. // import Foundation final class Updater { static func write(data: String, toFile file: URL) { print("Looking for \(file.path)") guard FileManager.default.fileExists(atPath: file.path) else { print("File not found") return } var fileContent: String = try! String.init(contentsOfFile: file.path, encoding: String.Encoding.utf8) if let dotRange = fileContent.range(of: "!") { fileContent.removeSubrange(dotRange.lowerBound..<fileContent.endIndex) } else { fileContent = "// Data has been extracted from an apache.org svn repository located on http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types/n/n" fileContent += "import Foundation\n\n\n" } fileContent += "!\n\n" fileContent += data try! fileContent.write(to: file, atomically: true, encoding: String.Encoding.utf8) print("File \(file.path) has been generated!") } }
31.289474
175
0.61312
fed5e960b807f4317f6528f064df9dc3ab1164d0
3,595
// // MessageSettingsViewController.swift // Bark // // Created by huangfeng on 2020/5/28. // Copyright © 2020 Fin. All rights reserved. // import UIKit import Material import RxDataSources class MessageSettingsViewController: BaseViewController { let tableView: UITableView = { let tableView = UITableView() tableView.separatorStyle = .none tableView.backgroundColor = Color.grey.lighten5 tableView.register(LabelCell.self, forCellReuseIdentifier: "\(LabelCell.self)") tableView.register(iCloudStatusCell.self, forCellReuseIdentifier: "\(iCloudStatusCell.self)") tableView.register(ArchiveSettingCell.self, forCellReuseIdentifier: "\(ArchiveSettingCell.self)") tableView.register(DetailTextCell.self, forCellReuseIdentifier: "\(DetailTextCell.self)") tableView.register(SpacerCell.self, forCellReuseIdentifier: "\(SpacerCell.self)") return tableView }() override func makeUI() { self.title = NSLocalizedString("settings") self.view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } override func bindViewModel() { guard let viewModel = self.viewModel as? MessageSettingsViewModel else { return } let output = viewModel.transform( input: MessageSettingsViewModel.Input( itemSelected: self.tableView.rx.modelSelected(MessageSettingItem.self).asDriver() ) ) let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, MessageSettingItem>> { (source, tableView, indexPath, item) -> UITableViewCell in switch item { case .label(let text): if let cell = tableView.dequeueReusableCell(withIdentifier: "\(LabelCell.self)") as? LabelCell { cell.textLabel?.text = text return cell } case .iCloudStatus: if let cell = tableView.dequeueReusableCell(withIdentifier: "\(iCloudStatusCell.self)") { return cell } case .archiveSetting(let viewModel): if let cell = tableView.dequeueReusableCell(withIdentifier: "\(ArchiveSettingCell.self)") as? ArchiveSettingCell { cell.bindViewModel(model: viewModel) return cell } case let .detail(title,text,textColor,_): if let cell = tableView.dequeueReusableCell(withIdentifier: "\(DetailTextCell.self)") as? DetailTextCell { cell.textLabel?.text = title cell.detailTextLabel?.text = text cell.detailTextLabel?.textColor = textColor return cell } case let .spacer(height, color): if let cell = tableView.dequeueReusableCell(withIdentifier: "\(SpacerCell.self)") as? SpacerCell { cell.height = height cell.backgroundColor = color return cell } } return UITableViewCell() } output.settings .drive(tableView.rx.items(dataSource: dataSource)) .disposed(by: rx.disposeBag) output.openUrl.drive {[weak self] url in self?.navigationController?.present(BarkSFSafariViewController(url: url), animated: true, completion: nil) }.disposed(by: rx.disposeBag) } }
40.852273
164
0.605563
1e93572ca314a30b44753ad30becae6da58ec9d0
434
// // SNotification.swift // Core // // Created by Gianluca Rago on 8/4/17. // Copyright © 2017 Gianluca Rago. All rights reserved. // class SNotification { public private(set) var id:String public private(set) var title:String public private(set) var message:String init(id:String, title:String, message:String) { self.id = id self.title = title self.message = message } }
19.727273
56
0.631336
7951aaa8c0c7ca2055682c32323d0593d001f890
1,825
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import EchoModel import GRPC import NIO /// An `Echo_EchoProvider` which always returns failed future for each RPC. class FailingEchoProvider: Echo_EchoProvider { let interceptors: Echo_EchoServerInterceptorFactoryProtocol? init(interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil) { self.interceptors = interceptors } func get( request: Echo_EchoRequest, context: StatusOnlyCallContext ) -> EventLoopFuture<Echo_EchoResponse> { return context.eventLoop.makeFailedFuture(GRPCStatus.processingError) } func expand( request: Echo_EchoRequest, context: StreamingResponseCallContext<Echo_EchoResponse> ) -> EventLoopFuture<GRPCStatus> { return context.eventLoop.makeFailedFuture(GRPCStatus.processingError) } func collect( context: UnaryResponseCallContext<Echo_EchoResponse> ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> { return context.eventLoop.makeFailedFuture(GRPCStatus.processingError) } func update( context: StreamingResponseCallContext<Echo_EchoResponse> ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> { return context.eventLoop.makeFailedFuture(GRPCStatus.processingError) } }
33.796296
75
0.767123
561e5d95d63ed004c7ea531e6456d7da4278513c
2,292
// // SceneDelegate.swift // AllocationsDemo // // Created by rayor on 2022/1/27. // 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.245283
147
0.713351
5b3b0a492d38d3d336d7248d7ed924a88c8e2576
1,734
// // TQQueue.swift // AsynchTaskQueue // // Created by joca on 6/29/19. // Copyright © 2019 joca. All rights reserved. // import Foundation import CouchbaseLiteSwift public struct TQTaskDependancyMap { let type: AnyClass? let dependancyReferenceList: [String]? public init(_ type: AnyClass?, _ dependancyReferenceList: [String]?) { self.type = type self.dependancyReferenceList = dependancyReferenceList } } public final class TQQueue: TQMonitor { public let name: String public let threadNumber: Int private var threads = [Thread]() public func addTask(_ task: TQTask, taskDependancyMap: [TQTaskDependancyMap]?) -> Bool { task.queueName = name return TQQueueManager.shared.addTask(task, taskDependancyMap: taskDependancyMap) } internal func getNextReadyTask() -> TQTask? { var task: TQTask? synchronized { task = TQQueueManager.shared.getNextReadyTask(for: name) } return task } internal func taskFailed(_ task: TQTask, error: Error) -> Bool { return TQQueueManager.shared.taskFailed(task) } internal func taskSucceeded(_ task: TQTask) { TQQueueManager.shared.taskSucceeded(task) } public func startThreads() { synchronized { threads.removeAll(where: { !$0.isExecuting }) let numberOfThreadsToStart = threadNumber - threads.count for _ in 1...numberOfThreadsToStart { let thread = TQThread(queue: self) threads.append(TQThread(queue: self)) thread.start() } } } public func stopThreads() { synchronized { for thread in threads { if thread.isExecuting { thread.cancel() } } threads = [] } } internal init(name: String, threadNumber: Int) { self.name = name self.threadNumber = threadNumber super.init() } }
20.642857
89
0.709919
f4cf8ecf95b295aee803f8cad8fc66abc790a27f
2,827
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import XCTest import SWCompression class DeflateCompressionTests: XCTestCase { func answerTest(_ testName: String) throws { let answerData = try Constants.data(forAnswer: testName) let compressedData = Deflate.compress(data: answerData) let redecompressedData = try Deflate.decompress(data: compressedData) XCTAssertEqual(redecompressedData, answerData) if answerData.count > 0 { // Compression ratio is always bad for empty file. let compressionRatio = Double(answerData.count) / Double(compressedData.count) print(String(format: "Deflate.\(testName).compressionRatio = %.3f", compressionRatio)) } } func stringTest(_ string: String) throws { let answerData = Data(string.utf8) let compressedData = Deflate.compress(data: answerData) let redecompressedData = try Deflate.decompress(data: compressedData) XCTAssertEqual(redecompressedData, answerData) } func testDeflateCompressStrings() throws { try stringTest("ban") try stringTest("banana") try stringTest("abaaba") try stringTest("abracadabra") try stringTest("cabbage") try stringTest("baabaabac") try stringTest("AAAAAAABBBBCCCD") try stringTest("AAAAAAA") try stringTest("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890") } func testDeflate1() throws { try self.answerTest("test1") } func testDeflate2() throws { try self.answerTest("test2") } func testDeflate3() throws { try self.answerTest("test3") } func testDeflate4() throws { try self.answerTest("test4") } func testDeflate5() throws { try self.answerTest("test5") } func testDeflate6() throws { try self.answerTest("test6") } func testDeflate7() throws { try self.answerTest("test7") } func testDeflate8() throws { try self.answerTest("test8") } func testDeflate9() throws { try self.answerTest("test9") } func testTrickySequence() throws { // This test helped us find an issue with implementation (match index was wrongly used as cyclical index). // This test may become useless in the future if the encoder starts preferring creation of an uncompressed block // for this input due to changes to the compression logic. let answerData = Data([0x2E, 0x20, 0x2E, 0x20, 0x2E, 0x20, 0x20]) let compressedData = Deflate.compress(data: answerData) let redecompressedData = try Deflate.decompress(data: compressedData) XCTAssertEqual(redecompressedData, answerData) } }
32.125
120
0.668553
d582253abffc2ff66565e3bdafb7c271035d4b1f
2,574
// // Context.swift // // Created by Christopher Helf on 03.11.16. // Copyright © 2016 Christopher Helf. All rights reserved. // import Foundation import Metal import MetalKit class Context { var kWarpSize : UInt32 = 32 var kLog2WarpSize : UInt32 = 5 var numThreadsAnchorsParallel : UInt32 = 64 var log2NumThreadsAnchorsParallel : UInt32 = 6 var functionConstantValues = MTLFunctionConstantValues() var minNeighbors : Int32 = 1 var eps : Float32 = 0.4 static let sharedInstance = Context() private var _device : MTLDevice private var _library : MTLLibrary private var _commandQueue : MTLCommandQueue private var _context : CIContext init() { functionConstantValues.setConstantValue(&kWarpSize, type: MTLDataType.uint, at: 0) functionConstantValues.setConstantValue(&kLog2WarpSize, type: MTLDataType.uint, at: 1) functionConstantValues.setConstantValue(&numThreadsAnchorsParallel, type: MTLDataType.uint, at: 2) functionConstantValues.setConstantValue(&log2NumThreadsAnchorsParallel, type: MTLDataType.uint, at: 3) functionConstantValues.setConstantValue(&eps, type: MTLDataType.float, at: 4) functionConstantValues.setConstantValue(&minNeighbors, type: MTLDataType.int, at: 5) _device = MTLCreateSystemDefaultDevice()!; _library = _device.newDefaultLibrary()!; _commandQueue = _device.makeCommandQueue() _context = CIContext(mtlDevice: _device); } class func device() -> MTLDevice { return Context.sharedInstance._device } class func library() -> MTLLibrary { return Context.sharedInstance._library } class func commandQueue() -> MTLCommandQueue { return Context.sharedInstance._commandQueue } class func context() -> CIContext { return Context.sharedInstance._context } class func makeFunction(name: String, withConstants: Bool = true) -> MTLFunction { if withConstants { return try! Context.library().makeFunction(name: name, constantValues: Context.sharedInstance.functionConstantValues) } else { return Context.library().makeFunction(name: name)! } } class func makeComputePipeline(name: String, withConstants: Bool = true) -> MTLComputePipelineState { let function = Context.makeFunction(name: name, withConstants: withConstants) return try! Context.device().makeComputePipelineState(function: function) } }
34.32
129
0.688034
76f67c135423ad1a6cbf3442bd6bd014a119f9f3
2,164
// // AppDelegate.swift // HttpCR // // Created by carum98 on 06/18/2021. // Copyright (c) 2021 carum98. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.042553
285
0.753697
e9d3eded222512431f56849b624482054bfbe47a
1,980
/* UICollectionViewCell.swift Created by William Falcon on 3/25/15. The MIT License (MIT) Copyright (c) 2015 William Falcon [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public extension UICollectionViewCell { //MARK: - Computed Properties /// Returns the class name of this cell as the identifier. override var _cellIdentifier : String { let identifier = NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last! return identifier } /// Returns the class name of this cell as the identifier. override class func _identifier() -> String { return _className() } //MARK: - Methods /// Registers this cell to the passed in collectionView class func _registerToCollectionView(cv: UICollectionView) { let name = _className() let nib = UINib(nibName: name, bundle: NSBundle.mainBundle()) cv.registerNib(nib, forCellWithReuseIdentifier: name) } }
31.935484
100
0.750505
e439fbd21ebf405d3a71f88833e3661fcef3aa35
2,337
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c<b:c func d<b: SequenceType, e where Optional<e> == b.Generator.Element>(c : b) -> e? { for (mx : e?) in c { } } protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } struct c<e> { let d: i h } func f(h: b) -> <e>(()-> e func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { class func f() } class d: c{ class func f {} struct d<c : f,f where g.i == c.i> func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2 class func g() { } } (h() as p).dynamicType.g() protocol p { } protocol h : p { } protocol g : p { } protocol n { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { } q(h()) func r(g: m) -> <s>(() -> s) -> n import Foundation class Foo<T>: NSObject { var foo: T init(foo: T) { B>(t: T) { t.c() } x x) { } class a { var _ = i() { } } a=1 as a=1 class c { func b((Any, c))(a: (Any, AnyObject)) { b(a) } } func i(f: g) -> <j>(() -> j) -> g { func g k, l { typealias l = m<k<m>, f> } func i(c: () -> ()) { } class a { var _ = i() { } } protocol A { func c() -> String } class B { func d() -> String { return "" } } class C: B, A { override func d() -> String { return "" } func c() -> String { return "" } } func e<T where T: A, T: B>(t: T) { t.c() } } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } func h<j>() -> (j, j -> j) -> j { var f: ({ (c: e, f: e -> e) -> return f(c) }(k, i) let o: e = { c, g return f(c) }(l) -> m) -> p>, e> } class n<j : n> b prot q g: n } func p<n>() -> [q<n>] { o : g.l) { } } class p { typealias g = g class a { typealias b = b } import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } }
15.375
87
0.443303
4a28dba0a923b488ec20c5eb30bb142c7d55204c
577
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache 2.0 */ import Foundation struct CallCodingPath: Equatable { let moduleName: String let callName: String } extension CallCodingPath { static var transfer: CallCodingPath { CallCodingPath(moduleName: "Assets", callName: "transfer") } static var transferKeepAlive: CallCodingPath { CallCodingPath(moduleName: "Assets", callName: "transfer_keep_alive") } var isTransfer: Bool { [.transfer, .transferKeepAlive].contains(self) } }
22.192308
77
0.694974
ebfc08f8fb2def8b2c560ab24962e0622d78fde9
2,580
// // Copyright (c) Vatsal Manot // import SwiftUI #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) extension Alert { public init( title: String, message: String? = nil, dismissButtonTitle: String? = nil ) { self.init( title: Text(title), message: message.map({ Text($0) }), dismissButton: dismissButtonTitle.map({ .cancel(Text($0)) }) ) } } extension Alert { @available(macCatalystApplicationExtension, unavailable) @available(iOSApplicationExtension, unavailable) @available(tvOSApplicationExtension, unavailable) public func present() { _ = _AlertWindow(alert: self) } } @available(macCatalystApplicationExtension, unavailable) @available(iOSApplicationExtension, unavailable) @available(tvOSApplicationExtension, unavailable) private class _AlertWindow: UIWindow { struct HostingView: View { @State var isPresenting: Bool = true let alert: Alert var body: some View { ZeroSizeView() .alert(isPresented: $isPresenting, content: { alert }) } } class HostingController: UIHostingController<HostingView> { var window: _AlertWindow? init(window: _AlertWindow) { self.window = window super.init(rootView: .init(alert: window.alert)) view.backgroundColor = .clear } @objc required dynamic init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { super.dismiss(animated: flag) { DispatchQueue.main.async { self.window = nil } } } } let alert: Alert init(alert: Alert) { self.alert = alert if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }), let scene = window.windowScene { super.init(windowScene: scene) windowLevel = .init(rawValue: window.windowLevel.rawValue + 1) } else { assertionFailure() super.init(frame: .zero) } rootViewController = HostingController(window: self) makeKeyAndVisible() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } #endif
26.597938
119
0.568217
bbd696bd2920574533ae13e6c03c3cd0200236ac
1,095
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "TCABooks", platforms: [ .macOS(.v10_15), .iOS(.v13) ], products: [ .library( name: "TCABooks", targets: ["TCABooks"] ), ], dependencies: [ .package( url: "https://github.com/pointfreeco/swift-composable-architecture", from: "0.9.0" ), .package(path: "../BooksCore") ], targets: [ .target( name: "TCABooks", dependencies: [ .product( name: "ComposableArchitecture", package: "swift-composable-architecture" ), .product( name: "BooksCore", package: "BooksCore" ) ] ), .testTarget( name: "TCABooksTests", dependencies: ["TCABooks"] ) ] )
24.333333
96
0.4621
750975ed316ca4802a2e429ee39dfc0bc8fdf985
22,704
// // DSIVPMultiSeriesChannelViewController.swift // DotstudioSampleApp-iOS // // Created by Anwer on 5/17/18. // Copyright © 2018 Dotstudioz. All rights reserved. // import UIKit import DotstudioPRO ////TODO We will remove this once we get the real apis //extension SPLTVideo { // class func getDummyVideo() -> SPLTVideo { // let video = SPLTVideo() // video.strTitle = "Video Title" // video.strSeriesTitle = "Series Title" // video.strVideoInfo = "Info" // video.strDescription = "We have a subclass for our cell, now let's create the view controller class. Inside the viewDidLoad method you have to set the estimatedItemSize property on the collection view. There if you give wrong size, the autorotation won't work as expected." // video.thumb = "http://via.placeholder.com/320x180" // video.progressPoint = 70 // video.iDuration = 400 // return video // } //} public protocol DSIVPMultiSeriesChannelViewControllerDelegate { func didClickCloseButton(_ dsIVPMultiSeriesChannelViewController: DSIVPMultiSeriesChannelViewController) } open class DSIVPMultiSeriesChannelViewController: SPLTIVPMultiSeriesChannelViewController { var delegate: DSIVPMultiSeriesChannelViewControllerDelegate? @IBOutlet weak open override var collectionView: UICollectionView? { get { return super.collectionView } set { super.collectionView = newValue } } var isCurrentVideoExpanded:Bool = false @IBOutlet weak open var viewDotstudioIMAPlayer: UIView! var dspPlayerViewController: DSPPlayerViewController? var offscreenCells: [String: Any] = [:] override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let dspPlayerViewController = DSPPlayerViewController.getViewController(theme: nil)as? DSPPlayerViewController{ dspPlayerViewController.delegate = self self.dspPlayerViewController = dspPlayerViewController self.splt_configureChildViewController(childController: dspPlayerViewController, onView: self.viewDotstudioIMAPlayer) } self.collectionView?.register(UINib(nibName: "DSIVPCurrentVideoDetailTableViewCell", bundle: nil), forCellWithReuseIdentifier: "DSIVPCurrentVideoDetailTableViewCell") self.collectionView?.register(UINib(nibName: "DSIVPVideoDetailTableViewCell", bundle: nil), forCellWithReuseIdentifier: "DSIVPVideoDetailTableViewCell") self.collectionView?.register(UINib(nibName: "DSIVPRecommendedVideoDetailTableViewCell", bundle: nil), forCellWithReuseIdentifier: "DSIVPRecommendedVideoDetailTableViewCell") self.collectionView?.register(UINib(nibName: "DSIVPVideosSectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "DSIVPVideosSectionHeaderView") // self.resetCollectionViewSize() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // self.resetCollectionViewSize() } open override func requestChannel() { super.requestChannel() } open override func reloadAllData() { super.reloadAllData() } // func resetCollectionViewSize() { // if let collectionView = self.collectionView { // if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { // flowLayout.minimumLineSpacing = CGFloat(0) // flowLayout.minimumInteritemSpacing = CGFloat(0) // flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) // flowLayout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: 30) // flowLayout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: 30) // //// if #available(iOS 10.0, *) { //// flowLayout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize //CGSize(width: collectionView.frame.size.width, height: 120.0) //UICollectionViewFlowLayoutAutomaticSize //// } else { //// // Fallback on earlier versions //// flowLayout.estimatedItemSize = CGSize(width: collectionView.frame.size.width, height: 120.0) //// } // } // } // } //MARK: - Set Video methods. open override func setCurrentVideo(curVideo: SPLTVideo) { super.setCurrentVideo(curVideo: curVideo) self.dspPlayerViewController?.setCurrentVideo(curVideo: curVideo) } //MARK: - UICollectionViewDataSource methods override open func numberOfSections(in collectionView: UICollectionView) -> Int { let iSections = super.numberOfSections(in: collectionView) // return 1 if iSections > 2 { return 2 } return iSections //3 //TODO We will remove this once we get the real apis } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { if section == 1 { if let spltMultiLevelChannel = self.channel as? SPLTMultiLevelChannel { return CGSize(width: collectionView.bounds.size.width, height: 100.0) } else if let playlistChannel = self.channel as? SPLTPlaylistChannel { return CGSize(width: collectionView.bounds.size.width, height: 50.0) // if playlistChannel.playlistVideos.count > 0 { // return CGSize(width: collectionView.bounds.size.width, height: 100.0) // } } } return CGSize(width: 0.0, height: 0.0) } open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if indexPath.section == 1 { switch kind { case UICollectionElementKindSectionHeader: if let dsIVPVideosSectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "DSIVPVideosSectionHeaderView", for: indexPath) as? DSIVPVideosSectionHeaderView { dsIVPVideosSectionHeaderView.setCellData(self.channel) return dsIVPVideosSectionHeaderView } default: fatalError("This should never happen!!") } } let uiCollectionReusableView = UICollectionReusableView(frame: CGRect.zero) return uiCollectionReusableView } override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let iItems = super.collectionView(collectionView, numberOfItemsInSection: section) return iItems } // MARK: - size calculation open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch indexPath.section { case 0: return self.getCurrentVideoDetailsCellSizeAt(indexPath) case 1: return self.getVideoDetailsCellSizeAt(indexPath) case 2: return self.getRecommendedVideoDetailsCellSizeAt(indexPath) default: return CGSize(width: 375.0, height: 100.0) } // return CGSize(width: UIScreen.main.bounds.width, height: 100) // let requiredWidth = collectionView.bounds.size.width // let targetSize = CGSize(width: requiredWidth, height: 0) // let cv = self.collectionView(collectionView, cellForItemAt: indexPath) // // cv.setNeedsLayout() // let adequateSize = cv.systemLayoutSizeFitting(targetSize) // return adequateSize // } open func getVideoAtIndexPath(_ indexPath: IndexPath) -> SPLTVideo? { if let spltMultiLevelChannel = self.channel as? SPLTMultiLevelChannel { if !self.isMoreEpisodesListHidden { if let curChildChannel = spltMultiLevelChannel.childChannels[self.iCurPlayingVideoSeasonIndex] as? SPLTVideoChannel { if let video = curChildChannel.video { return video } } } } if let spltPlaylistChannel = self.channel as? SPLTPlaylistChannel { if indexPath.row < spltPlaylistChannel.playlistVideos.count { let video = spltPlaylistChannel.playlistVideos[indexPath.row] return video } } if let spltVideoChannel = self.channel as? SPLTVideoChannel { if let video = spltVideoChannel.video { return video } } return nil } open func getCurrentVideoDetailsCellSizeAt(_ indexPath: IndexPath) -> CGSize { // var dsIVPCurrentVideoDetailCollectionViewCell_: DSIVPCurrentVideoDetailCollectionViewCell? // if let dsIVPCurrentVideoDetailCollectionViewCell = self.offscreenCells["DSIVPCurrentVideoDetailCollectionViewCell"] as? DSIVPCurrentVideoDetailCollectionViewCell { // dsIVPCurrentVideoDetailCollectionViewCell_ = dsIVPCurrentVideoDetailCollectionViewCell // } else if let dsIVPCurrentVideoDetailCollectionViewCell = Bundle.main.loadNibNamed("DSIVPCurrentVideoDetailCollectionViewCell", owner: self, options: nil)?[0] as? DSIVPCurrentVideoDetailCollectionViewCell { // dsIVPCurrentVideoDetailCollectionViewCell_ = dsIVPCurrentVideoDetailCollectionViewCell // self.offscreenCells["DSIVPCurrentVideoDetailCollectionViewCell"] = dsIVPCurrentVideoDetailCollectionViewCell // } let requiredWidth = self.view.frame.size.width // let targetSize = CGSize(width: requiredWidth, height: 0) // if let dsIVPCurrentVideoDetailCollectionViewCell = dsIVPCurrentVideoDetailCollectionViewCell_ { // dsIVPCurrentVideoDetailCollectionViewCell.frame.size.width = requiredWidth // dsIVPCurrentVideoDetailCollectionViewCell.constraintCellWidth?.constant = requiredWidth // if let curVideo = self.curVideo { // dsIVPCurrentVideoDetailCollectionViewCell.setCellData(curVideo,isExpanded: self.isCurrentVideoExpanded) // dsIVPCurrentVideoDetailCollectionViewCell.setNeedsLayout() // dsIVPCurrentVideoDetailCollectionViewCell.layoutIfNeeded() // let adequateSize = dsIVPCurrentVideoDetailCollectionViewCell.systemLayoutSizeFitting(UILayoutFittingCompressedSize) // return adequateSize // } // } if let video = self.getVideoAtIndexPath(indexPath) { var fontFuturaDescription = UIFont(name: "Arial", size: 14.0)! // var iImageHeight: CGFloat = 64.0 var topOffset: CGFloat = 100.0 var extraOffset: CGFloat = 20.0 var labelDescriptionWidth = self.view.frame.size.width - 50 if UIDevice.current.userInterfaceIdiom == .pad { fontFuturaDescription = UIFont(name: "Arial", size: 21.0)! topOffset = 150.0 extraOffset = 40.0 labelDescriptionWidth = self.view.frame.size.width - 100 } let attributes = [NSAttributedString.Key.font: fontFuturaDescription] // 15.0 for iPHone , 30.0 for iPad gap 5px top of image, bottom of image, bottom of description // 20 offset if self.isCurrentVideoExpanded { var adequateSize = CGSize(width: requiredWidth, height: topOffset + 30.0 + extraOffset) if let strDescription = video.strDescription { let labelDescriptionMaxSize = CGSize(width: labelDescriptionWidth, height: 1000) let estimatedFrame = NSString(string: strDescription).boundingRect(with: labelDescriptionMaxSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) if self.isCurrentVideoExpanded { //video.isExpandedUI { adequateSize = CGSize(width: requiredWidth, height: estimatedFrame.height + topOffset + 20 ) //+ extraOffset) // 50 extra offset } } return adequateSize } else { let adequateSize = CGSize(width: requiredWidth, height: topOffset + 15.0 + extraOffset) return adequateSize } // return adequateSize } return CGSize(width: 375.0, height: 100.0) } func getVideoDetailsCellSizeAt(_ indexPath: IndexPath) -> CGSize { let requiredWidth = self.view.frame.size.width // if let spltPlaylistChannel = self.channel as? SPLTPlaylistChannel { // if indexPath.row < spltPlaylistChannel.playlistVideos.count { // let video = spltPlaylistChannel.playlistVideos[indexPath.row] if let video = self.getVideoAtIndexPath(indexPath) { var fontFuturaDescription = UIFont(name: "HelveticaNeue", size: 12.0)! var iImageHeight: CGFloat = 64.0 var extraOffset: CGFloat = 10.0 var labelDescriptionWidth = self.view.frame.size.width - 150 if UIDevice.current.userInterfaceIdiom == .pad { fontFuturaDescription = UIFont(name: "HelveticaNeue", size: 18.0)! iImageHeight = 128.0 extraOffset = 20.0 labelDescriptionWidth = self.view.frame.size.width - 200 } let attributes = [NSAttributedString.Key.font: fontFuturaDescription] // 15.0 for iPHone , 30.0 for iPad gap 5px top of image, bottom of image, bottom of description // 20 offset var adequateSize = CGSize(width: requiredWidth, height: iImageHeight + 15.0 + extraOffset) if let strDescription = video.strDescription { let labelDescriptionMaxSize = CGSize(width: labelDescriptionWidth, height: 1000) let estimatedFrame = NSString(string: strDescription).boundingRect(with: labelDescriptionMaxSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) if video.isExpandedUI { adequateSize = CGSize(width: requiredWidth, height: estimatedFrame.height + iImageHeight + extraOffset)//+ 30.0 + extraOffset) // 50 extra offset } } return adequateSize } // } // } return CGSize(width: 375.0, height: 100.0) } func getRecommendedVideoDetailsCellSizeAt(_ indexPath: IndexPath) -> CGSize { let collectionViewNumberOfColumns = 2 let collectionViewItemSpacing = 10.0 var collectionViewItemWidth = self.view.frame.width - (CGFloat(collectionViewNumberOfColumns + 1) * CGFloat(collectionViewItemSpacing)) collectionViewItemWidth = collectionViewItemWidth / CGFloat(collectionViewNumberOfColumns) collectionViewItemWidth = floor(collectionViewItemWidth) var collectionViewItemHeight = collectionViewItemWidth * 9 / 16 collectionViewItemHeight = ceil(collectionViewItemHeight) let size = CGSize(width: collectionViewItemWidth, height: collectionViewItemHeight) return size } //TODO We will remove this once we get the real apis override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch indexPath.section { case 0: return self.getCurrentVideoDetailsCell(collectionView, cellForItemAt: indexPath) case 1: return self.getVideoDetailsCell(collectionView, cellForItemAt: indexPath) case 2: return self.getRecommendedVideoDetailsCell(collectionView, cellForItemAt: indexPath) default: return UICollectionViewCell() } } open func getCurrentVideoDetailsCell(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let dsIVPCurrentVideoDetailCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DSIVPCurrentVideoDetailCollectionViewCell", for: indexPath) as? DSIVPCurrentVideoDetailCollectionViewCell { dsIVPCurrentVideoDetailCollectionViewCell.delegate = self if let curVideo = self.curVideo { dsIVPCurrentVideoDetailCollectionViewCell.setCellData(curVideo,isExpanded: self.isCurrentVideoExpanded) } return dsIVPCurrentVideoDetailCollectionViewCell } return UICollectionViewCell() } func getVideoDetailsCell(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let dsIVPVideoDetailCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DSIVPVideoDetailCollectionViewCell", for: indexPath) as? DSIVPVideoDetailCollectionViewCell { dsIVPVideoDetailCollectionViewCell.delegate = self if let spltMultiLevelChannel = self.channel as? SPLTMultiLevelChannel { if !self.isMoreEpisodesListHidden { if let curChildChannel = spltMultiLevelChannel.childChannels[self.iCurPlayingVideoSeasonIndex] as? SPLTVideoChannel { if let video = curChildChannel.video { dsIVPVideoDetailCollectionViewCell.setCellData(video, isCurVideoPlaying: true) return dsIVPVideoDetailCollectionViewCell } } } } if let spltPlaylistChannel = self.channel as? SPLTPlaylistChannel { if indexPath.row < spltPlaylistChannel.playlistVideos.count { let video = spltPlaylistChannel.playlistVideos[indexPath.row] if self.iCurVideoIndex == indexPath.row { dsIVPVideoDetailCollectionViewCell.setCellData(video, isCurVideoPlaying: true) } else { dsIVPVideoDetailCollectionViewCell.setCellData(video, isCurVideoPlaying: false) } // dsIVPVideoDetailCollectionViewCell.setCellData(video) } } return dsIVPVideoDetailCollectionViewCell } return UICollectionViewCell() } func getRecommendedVideoDetailsCell(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let dsIVPRecommendedVideoDetailCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DSIVPRecommendedVideoDetailCollectionViewCell", for: indexPath) as? DSIVPRecommendedVideoDetailCollectionViewCell { dsIVPRecommendedVideoDetailCollectionViewCell.imageKey = "poster" if indexPath.row < self.recommendationChannels.count { let channel = self.recommendationChannels[indexPath.row] let size = self.getRecommendedVideoDetailsCellSizeAt(indexPath) dsIVPRecommendedVideoDetailCollectionViewCell.setCellChannelData(channel, collectionViewImageSize: size) } return dsIVPRecommendedVideoDetailCollectionViewCell } return UICollectionViewCell() } override open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.section == 0 { self.isCurrentVideoExpanded = !self.isCurrentVideoExpanded self.reloadAllUI() } } } //MARK: - DSIVPVideoDetailTableViewCellDelegate methods extension DSIVPMultiSeriesChannelViewController: DSIVPVideoDetailCollectionViewCellDelegate { public func didClickExpandButton(_ dsIVPVideoDetailTableViewCell: DSIVPVideoDetailCollectionViewCell) { if let indexPath = self.collectionView?.indexPath(for: dsIVPVideoDetailTableViewCell) { if indexPath.section == 1 { if let spltPlaylistChannel = self.channel as? SPLTPlaylistChannel { if indexPath.row < spltPlaylistChannel.playlistVideos.count { let video = spltPlaylistChannel.playlistVideos[indexPath.row] video.isExpandedUI = !video.isExpandedUI //dsIVPVideoDetailsCell.updateUI() self.reloadAllUI() } } } } } } //MARK: - DotstudioIMAPlayerViewControllerDelegate methods extension DSIVPMultiSeriesChannelViewController: DSPPlayerViewControllerDelegate, DSIVPCurrentVideoDetailCollectionViewCellDelegate { public func didClickShareButton(_ dsIVPCurrentVideoDetailCollectionViewCell: DSIVPCurrentVideoDetailCollectionViewCell, sender: UIButton) { } public func didClickCastButton(_ dsIVPCurrentVideoDetailCollectionViewCell: DSIVPCurrentVideoDetailCollectionViewCell, sender: UIButton) { } public func didClickCloseButton(_ dspPlayerViewController: DSPPlayerViewController) { self.delegate?.didClickCloseButton(self) } public func didClickCastButton(_ dspPlayerViewController: DSPPlayerViewController) { } public func didClickShareButton(_ dspPlayerViewController: DSPPlayerViewController) { } public func didClickShareButtonWithSender(_ dspPlayerViewController: DSPPlayerViewController, sender: UIButton) { } public func didFinishPlayingVideo(_ dspPlayerViewController: DSPPlayerViewController) { } public func didClickViewSchedule(curVideo: SPLTVideo) { } public func didClickCloseButton(sender: Any) { self.delegate?.didClickCloseButton(self) } public func didClickCastButton(sender: Any) { } public func didClickShareButton(sender: Any) { } }
50.90583
283
0.659663
09c2e3eba896236347bea6a4ca552dc6e329a831
741
// // XibID.swift // xibdump // // Created by Sergey Atroschenko on 3/25/19. // Copyright © 2019. All rights reserved. // import Cocoa class XibID: NSObject { private static let charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" static func generate() -> String { return "\(self.randomString(length: 3))-\(self.randomString(length: 2))-\(self.randomString(length: 3))" } private static func randomString(length: Int) -> String { let charactersArray = XibID.charSet.map { String($0) } var string: String = "" for _ in (1...length) { string.append(charactersArray[Int(arc4random()) % charactersArray.count]) } return string } }
24.7
112
0.643725
9c59ce36ab4c4feef14f27dc21112f347b8b0b61
1,161
import Cocoa @objc protocol SidebarBottomDelegate: AnyObject { func updateFilter(string: String?) func newBranch() func newRemote() func newTag() } final class SidebarBottomController: NSViewController { @IBOutlet weak var addButton: NSPopUpButton! @IBOutlet weak var settingsButton: NSPopUpButton! @IBOutlet weak var searchField: NSSearchField! @IBOutlet weak var delegate: SidebarBottomDelegate? func updateSearh() { delegate?.updateFilter(string: searchField.stringValue.nilIfEmpty) } } extension SidebarBottomController: NSSearchFieldDelegate { func searchFieldDidStartSearching(_ sender: NSSearchField) { updateSearh() } func searchFieldDidEndSearching(_ sender: NSSearchField) { updateSearh() } func controlTextDidChange(_ obj: Notification) { updateSearh() } } extension SidebarBottomController { @IBAction func newBranch(_ sender: Any) { delegate?.newBranch() } @IBAction func newRemote(_ sender: Any) { delegate?.newRemote() } @IBAction func newTag(_ sender: Any) { delegate?.newTag() } @IBAction func toggleHideOld(_ sender: Any) { } }
18.140625
70
0.718346
fccf1d2d11cdf5da55f76c80a82db94707771da6
744
public final class ListInteractor<DataModel, Cell: ConfigurableCell> { var store: () async throws -> [DataModel] var presenter: ListPresenter<[DataModel], ListViewController<Cell>>? var isLoading = false init(store: @escaping () async throws -> [DataModel]) { self.store = store } func loadResource() { guard !isLoading else { return } presenter?.load() isLoading = true Task.init { do { let resource = try await store() presenter?.didLoad(with: resource) isLoading = false } catch { presenter?.didLoad(with: error) isLoading = false } } } }
21.882353
72
0.533602
016ae007b144a8ee089a497725be5f7b1c8f48f0
1,070
// // AppCongfigure.swift // SwiftBilibili // // Created by 罗文 on 2018/1/22. // Copyright © 2018年 罗文. All rights reserved. // import UIKit let kScreenWidth = UIScreen.main.bounds.width let kScreenHeight = UIScreen.main.bounds.height let kScreenRatio = kScreenHeight/736.f //以8ps为标准 let kToastBottomMaxSpace = 560.f * kScreenRatio let kToastBottomCenterSpace = 420.f * kScreenRatio let kBannerHeight = 120.f let kNormalItemHeight = 180.f let kAdItemHeight = 170.f let kLiveItemHeight = 150.f let kShadowImageHeight = 50.f let kTipCellHeight = 30.f let kCornerRadius = 6.f let kCollectionItemPadding = 15.f let kDislikeViewMaxWidth = 330.f let kDislikeViewMinWidth = 180.f let kDislikeCellHeight = 60.f let kDislikeFooterHeight = 150.f let kLivePartitionRefreshRotationTime: Double = 0.5 let kTimeoutIntervalForRequest: TimeInterval = 10 let kRecommendRecallDislikeMinute = 2 let isIphoneX = kScreenWidth == 375.f && kScreenHeight == 812.f let bannerModuleId = 1 let regionModuleId = 2 let rcmdModuleId = 3 let hourRankModuleId = 4 let attentionModuleId = 13
24.318182
63
0.778505
4a7b2a7825db7c3bf7c6b4e1345e0da2edb61893
819
// // ProfileViewModel.swift // FireChat // // Created by Oscar Rodriguez Garrucho on 26/11/20. // Copyright © 2020 Little Monster. All rights reserved. // import Firebase enum ProfileCellViewModel: Int, CaseIterable { case accountInfo case settings var description: String { switch self { case .accountInfo: return "Account Info" case .settings: return "Settings" } } var iconImageName: String { switch self { case .accountInfo: return "person.circle" case .settings: return "gear" } } } struct ProfileViewModel { func fetchUser(completion: @escaping(User) -> Void) { guard let uid = Auth.auth().currentUser?.uid else { return } Service.shared.fetchUser(withUid: uid, completion: completion) } }
22.135135
70
0.637363
210c943d9106bd6c858dbc56c87af503fd7ce2d8
3,252
// // AppDelegate.swift // // Copyright (c) 2015 David Robles // // 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 import UPnAtom @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. UPnAtom.sharedInstance.stopSSDPDiscovery() } }
50.8125
285
0.75738
6adcfa524651bc28255d4bd061a8242f2a4ae447
1,358
// swift-tools-version:5.2 // // Package.swift // WiredSwift // // Created by Rafael Warnault on 17/04/2020. // Copyright © 2020 Read-Write. All rights reserved. // import PackageDescription let package = Package( name: "WiredSwift", platforms: [ // Add support for all platforms starting from a specific version. .macOS(.v10_13), .iOS(.v12) ], products: [ .library( name: "WiredSwift", targets: ["WiredSwift"]) ], dependencies: [ .package(name: "AEXML", url: "https://github.com/tadija/AEXML.git", from: "4.5.0"), .package(name: "CryptoSwift", url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.3.0"), .package(name: "CryptorRSA", url: "https://github.com/IBM-Swift/BlueRSA", from: "1.0.35"), .package(name: "CZlib", url: "https://github.com/IBM-Swift/CZlib.git", from: "0.1.2"), .package(name: "Gzip", url: "https://github.com/1024jp/GzipSwift", from: "5.1.1"), .package(name: "SocketSwift", url: "https://github.com/BiAtoms/Socket.swift.git", from: "2.4.0"), ], targets: [ .target(name: "WiredSwift", dependencies: [ "AEXML", "CryptoSwift", "CryptorRSA", "CZlib", "Gzip", "SocketSwift" ]) ] )
30.863636
110
0.555965
9c84188a0b5e459d7f27a08ce59d4ffcb59c0b16
7,044
// // YPProjectInverstmentViewController.swift // PropertyExchange // // Created by itachi on 16/9/29. // Copyright © 2016年 com.itachi. All rights reserved. // import UIKit import SwiftyJSON extension YPProjectInverstmentViewController:YPNetworkManagerDelegate { @available(iOS 2.0, *) public func networkManager(_ manager: YPNetworkManager!, successResponseObject responseObject: NSObject!) { guard let _responseObject = responseObject else {return} guard let code = JSON.init(_responseObject).dictionary?["Code"] , code == 0 else{return} guard let data = JSON.init(_responseObject).dictionary?["Data"] else{return} self.models = YPProjectInverstmentCellModel.models(json: data) } func requestUrl() -> String! { return "project_inverstment_list" } func parameters() -> [String : Any]! { return ["user":"" as AnyObject] } func networkManager(_ manager: YPNetworkManager!, failureResponseError error: Error!) { } } extension YPProjectInverstmentViewController:UITableViewDataSource,UITableViewDelegate { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.models?.count ?? 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let commentCell = YPProjectInverstmentTableViewCell.cell(withTableView: tableView, forReuseIdentifier: YPProjectInverstmentViewController.className()) as! YPProjectInverstmentTableViewCell commentCell.selectionStyle = .none return commentCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailController = YPProjectDetailViewController() detailController.model = self.models?[indexPath.row] self.navigationController?.pushViewController(detailController, animated: true) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let commentCell:YPProjectInverstmentTableViewCell = cell as! YPProjectInverstmentTableViewCell commentCell.model = self.models![indexPath.row] } } class YPProjectInverstmentViewController: UIViewController { private lazy var segementControl:YPOrderSegementControl = { var segementItems = [(title:String,status:YPOrderSegementItemOrderStatus)]() segementItems.append((title:"综合",status:.none)) segementItems.append((title:"利率",status:.ascending)) segementItems.append((title:"期限",status:.ascending)) segementItems.append((title:"金额",status:.ascending)) segementItems.append((title:"进度",status:.ascending)) let _segementControl = YPOrderSegementControl() _segementControl.backgroundColor = UIColor.colorWithHex(hex: 0xF5F5F5) _segementControl.selectedBackgroundColor = UIColor.colorWithHex(hex: 0xF5F5F5) _segementControl.titleColor = UIColor.colorWithHex(hex: 0x999999) _segementControl.selectedTitleColor = UIColor.black _segementControl.items = segementItems _segementControl.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 44) _segementControl.selectedIndex = 0 return _segementControl }() private lazy var filterView:YPFilterView = { let _filterView = YPFilterView(frame: UIScreen.main.bounds) return _filterView }() private let networkManager:YPNetworkManager = YPNetworkManager.default()! private lazy var tableView: UITableView = { var tableView = UITableView(frame: CGRect(x: 0, y: 44, width: ScreenWidth, height: ScreenHeight - 64 - 44)) tableView.register(YPProjectInverstmentTableViewCell.self, forCellReuseIdentifier: YPProjectInverstmentViewController.className()) tableView.rowHeight = 120 tableView.allowsSelection = true tableView.separatorStyle = .singleLine tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = UIColor.colorWithHex(hex: 0xF3F3F3) tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 0.01)) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 0.01)) tableView.showsVerticalScrollIndicator = false return tableView }() fileprivate var models:[YPProjectInverstmentCellModel]?{ didSet{ guard let _models = self.models , _models.count > 0 else{return} self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.setNavigationBar() self.view.addSubview(self.segementControl) self.view.addSubview(self.tableView) //self.view.addSubview(self.filterView) let appDelegate = UIApplication.shared.delegate as? AppDelegate appDelegate?.window.addSubview(self.filterView) appDelegate?.window.sendSubview(toBack: self.filterView) self.networkManager.delegate = self self.networkManager.sendRequest() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setNavigationBarStyle() } private func setNavigationBarStyle(){ self.navigationController?.navigationBar.setBackgroundImage(UIImage(color:UIColor.white), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage(color: UIColor.colorWithHex(hex: 0xDCDCDC)) self.navigationController?.navigationBar.backgroundColor = UIColor.white } private func setNavigationBar(){ self.setNavigationBarStyle() self.view.backgroundColor = UIColor.colorWithHex(hex: 0xFFFFFF) self.title = "项目投资" let backButton = UIButton(type: .custom) backButton.addTarget(self, action:#selector(self.backButtonTouched(sender:)), for: .touchUpInside) backButton.setImage(UIImage(named: "后退"), for: .normal) backButton.sizeToFit() let leftBarButton = UIBarButtonItem(customView: backButton) self.navigationItem.leftBarButtonItem = leftBarButton let filterButton = UIButton(type: .custom) filterButton.addTarget(self, action: #selector(self.filterButtonTouched(sender:)), for: .touchUpInside) filterButton.setImage(UIImage(named: "筛选"), for: .normal) filterButton.sizeToFit() let rightSearchBarButton = UIBarButtonItem(customView: filterButton) self.navigationItem.rightBarButtonItem = rightSearchBarButton } @objc private func backButtonTouched(sender:UIButton){ self.navigationController?.popViewController(animated: true) } @objc private func filterButtonTouched(sender:UIButton){ self.filterView.toggleDisplay() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
37.269841
192
0.746309
9ca80d89b92ab88138fdc459e7b17c1173022990
1,658
// // KeyValueStoreTest.swift // UnitTests // // Created by Thomas Visser on 04/09/2019. // Copyright © 2019 Thomas Visser. All rights reserved. // import Foundation import XCTest @testable import Construct import GRDB class KeyValueStoreTest: XCTestCase { var sut: KeyValueStore! override func setUp() { super.setUp() let database = try! Database(path: nil, importDefaultContent: false) self.sut = database.keyValueStore } func testPutAndGet() { try! sut.put(1, at: "1") XCTAssertEqual(try! sut.get("1"), 1) } func testFTS() { try! sut.put(1, at: "1", fts: FTSDocument(title: "Alpha", subtitle: nil, body: nil)) try! sut.put(2, at: "2", fts: FTSDocument(title: "Beta", subtitle: nil, body: nil)) XCTAssertEqual(try! sut.match("al*"), [1]) } func testOverwrite() { try! sut.put(1, at: "1") try! sut.put(11, at: "1") XCTAssertEqual(try! sut.get("1"), 11) } func testOverwriteWithFTS() { try! sut.put(1, at: "1", fts: FTSDocument(title: "Alpha", subtitle: nil, body: nil)) try! sut.put(11, at: "1", fts: FTSDocument(title: "Omega", subtitle: nil, body: nil)) XCTAssertEqual(try! sut.match("Omega"), [11]) } func testUpdateOfNonLastRowFTS() { try! sut.put(1, at: "1", fts: FTSDocument(title: "Alpha", subtitle: nil, body: nil)) try! sut.put(2, at: "2", fts: FTSDocument(title: "Beta", subtitle: nil, body: nil)) try! sut.put(10, at: "1", fts: FTSDocument(title: "Gamma", subtitle: nil, body: nil)) XCTAssertEqual(try! sut.match("Gamma"), [10]) } }
28.586207
93
0.597708
e842a7de47e8b5130a1fcdb640be416f95a47d86
1,461
// // AppReducer.swift // Foursquare Clone // // Created by Fabio Hiroki on 15/11/17. // Copyright © 2017 Fabio Hiroki. All rights reserved. // import Foundation import ReSwift import RxSwift import Moya import Moya_ModelMapper import CoreLocation struct AppReducer { fileprivate let nearbyPlacesService: NearbyPlacesService fileprivate let disposeBag = DisposeBag() init(_ nearbyPlacesService: NearbyPlacesService) { self.nearbyPlacesService = nearbyPlacesService } func reduce(action: Action, state: FetchedPlacesState?) -> FetchedPlacesState { switch action { case _ as FetchPlacesAction: _ = nearbyPlacesService.fetchNearbyPlaces() .subscribe({ (event) in switch event { case .next(let places): store.dispatch(SetPlacesAction(places: places)) case .error(let error): store.dispatch(SetErrorAction(error: error)) case .completed: break } }).disposed(by: disposeBag) case let action as SetPlacesAction: return FetchedPlacesState(places: Result.finished(action.places)) case _ as SetErrorAction: return FetchedPlacesState(places: Result.failed) default: break } return FetchedPlacesState(places: .loading) } }
29.22
83
0.607803
db65bf3913a99b2f7688e67a20dcaf34d17ed742
2,200
// // AppDelegate.swift // SKJProgressHUD // // Created by [email protected] on 11/17/2018. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.808511
285
0.755
08ddd34d74c75e933cc64193b53e83faee733ccc
25,485
// // SeatMapSceneView.swift // Shinkansen 3D Seat Booking Prototype // // Created by Virakri Jinangkul on 6/6/19. // Copyright © 2019 Virakri Jinangkul. All rights reserved. // import UIKit import SceneKit protocol SeatMapSceneViewDelegate: AnyObject { func sceneViewDidPanFurtherUpperBoundLimit(by offset: CGPoint) func sceneView(sceneView: SeatMapSceneView, didSelected reservableEntity: ReservableEntity) } extension SeatMapSceneViewDelegate { func sceneViewDidPanFurtherUpperBoundLimit(by offset: CGPoint) { } func sceneView(sceneView: SeatMapSceneView, didSelected reservableEntity: ReservableEntity) {} } class SeatMapSceneView: SCNView { private let lightFeedbackGenerator = UIImpactFeedbackGenerator(style: .light) weak var seatMapDelegate: SeatMapSceneViewDelegate? private var bottomOffset: CGFloat = 0 /// The main node that contains all content which is repositioned according to the vertical pan gesture. private var contentNode: SCNNode! = SCNNode() private var stationDirectionTextNode: SCNNode! = SCNNode() private var cameraNode: CameraNode! = CameraNode() private var hitTestPositionWhenTouchBegan: SCNVector3? private var contentNodePositionWhenTouchBegan: SCNVector3? private var loadingActivityIndicatorView: UIView! = UIView() private var centerScreenZ: Float = 0 private enum SeatNavigationState: String { case top case bottom case hide } private var seatNavigationState: SeatNavigationState = .hide { didSet { if seatNavigationState != oldValue { DispatchQueue.main.async { [weak self] in switch self?.seatNavigationState ?? .hide { case .top: self?.addHeadsUpBadgeControl(withMessage: "↑ Your \(self?.selectedSeatNode?.reservableEntity?.name ?? "selected") seat is up there.", bitMask: 1 << 1) case .bottom: self?.addHeadsUpBadgeControl(withMessage: "↓ Your \(self?.selectedSeatNode?.reservableEntity?.name ?? "selected") seat is down there.", bitMask: 1 << 1) case .hide: self?.removeHeadsUpBadgeControl(animated: true, bitMask: 1 << 1) } } } } } private var currectContentNodePosition: SCNVector3? { didSet { setCurrectContentNodePosition( currectContentNodePosition: currectContentNodePosition, oldValue: oldValue ) if centerScreenZ == 0 { centerScreenZ = positionOfFloorHitTest(.init(x: 0, y: frame.midY))?.z ?? 0 } if let selected = selectedSeatNode, let current = currectContentNodePosition?.z, centerScreenZ != 0 { if selected.position.z > centerScreenZ - current + 3 { seatNavigationState = .bottom } else if selected.position.z < centerScreenZ - current - 4 { seatNavigationState = .top }else{ seatNavigationState = .hide } }else{ seatNavigationState = .hide } } } private var highlightedSeatNodes = Set<SeatNode>() { didSet { oldValue.subtracting(highlightedSeatNodes).forEach { $0.isHighlighted = false } highlightedSeatNodes.subtracting(oldValue).forEach { $0.isHighlighted = true } } } private weak var selectedSeatNode: SeatNode? { didSet { oldValue?.isSelected = false selectedSeatNode?.isSelected = true if let reservableEntity = selectedSeatNode?.reservableEntity { seatMapDelegate?.sceneView(sceneView: self, didSelected: reservableEntity) // Make sure that the seat isn't the same one before showing the message if oldValue != selectedSeatNode { let message = "Seat \(reservableEntity.name) in \(reservableEntity.carNumber.lowercased()) has been selected." addHeadsUpBadgeControl(withMessage: message, delayUntilRemoved: 4, bitMask: 1 << 0) } // Activate Impact lightFeedbackGenerator.impactOccurred() } if let selectedSeat = selectedSeatNode { animateContentNodeToZPosition(of: selectedSeat.position.z) } } } var perspectiveVelocity: Float? var contentZPositionLimit: ClosedRange<Float> = 0...1 // MARK: Initialzer & Setup init() { super.init(frame: .zero, options: nil) setupView() setupScene() setupInteraction() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// View setup private func setupView() { backgroundColor = .clear /// Set Antialiasing Mode depending on the density of the pixels, so if the screen is 3X, the view will use `multisampling2X` otherwise it will use `multisampling4X` antialiasingMode = UIScreen.main.scale > 2 ? .multisampling2X : .multisampling4X /// Setup Loading Activity Indicator loadingActivityIndicatorView.backgroundColor = currentColorTheme.componentColor.cardBackground let indicatorView = UIActivityIndicatorView(style: .whiteLarge) indicatorView.color = currentColorTheme.componentColor.secondaryText indicatorView.startAnimating() loadingActivityIndicatorView .addSubview(indicatorView, withConstaintEquals: .centerSafeArea, insetsConstant: .init(bottom: 24)) addSubview(loadingActivityIndicatorView, withConstaintEquals: .edges) preservesSuperviewLayoutMargins = true } override func didMoveToSuperview() { super.didMoveToSuperview() /// Add visual effect superview?.addMotionEffect(TiltNodeMotionEffect(node: cameraNode)) } // MARK: Scene setup private func setupScene() { let hitTestFloorNode = HitTestFloorNode() let scene = SCNScene() scene.background.contents = currentColorTheme.componentColor.cardBackground currectContentNodePosition = contentNode.position scene.rootNode.addChildNode(hitTestFloorNode) scene.rootNode.addChildNode(contentNode) scene.rootNode.addChildNode(cameraNode) self.scene = scene } private func placeStaticNodes(using transformedModelEntities: [TransformedModelEntity], isEnabled: Bool = true) { let staticNode = SCNNode() // Place static nodes transformedModelEntities.compactMap({ if let node: StaticNode = NodeFactory.shared?.create(name: $0.modelEntity) { node.transformedModelEntity = $0 node.isEnabled = isEnabled return node } return nil }).forEach { staticNode.addChildNode($0) } DispatchQueue.main.async { [weak self] in self?.contentNode?.addChildNode(staticNode) } } private func playInitialAnimation() { DispatchQueue.main.async { [weak self] in guard let contentZPositionLimit = self?.contentZPositionLimit else { return } /// Play initial Animation self?.currectContentNodePosition?.z = contentZPositionLimit.lowerBound let duration: TimeInterval = TimeInterval(abs(contentZPositionLimit.upperBound) - abs(contentZPositionLimit.lowerBound)) / 100 + 0.5 SceneKitAnimator .animateWithDuration(duration: duration, timingFunction: .explodingEaseOut, animations: { self?.currectContentNodePosition?.z = (contentZPositionLimit.lowerBound * 2 + contentZPositionLimit.upperBound) / 3 }) } } deinit { // Try to inturrupt and remove model load operation workItems.forEach { $0.cancel() } workItems.removeAll() } var workItems: [DispatchWorkItem] = [] private let currentEntityQueue = DispatchQueue(label: "Current Entity Placing Queue", qos: .utility) private let otherEntityQueue = DispatchQueue(label: "Placing Object Queue", qos: .background) /// Place seat to content node (expensive process) /// - Parameter factory: NodeFactory object /// - Parameter seatClassEntity: Seat class data /// - Parameter isCurrentEntity: To consider priority to load private func placeSeatClassNodes(seatClassEntity: SeatClassEntity, isCurrentEntity: Bool) { var workItem: DispatchWorkItem! weak var seatClassEntity = seatClassEntity workItem = DispatchWorkItem { [weak self] in guard !workItem.isCancelled else { return } // Generate all interactible nodes with transform values let containerNode = SCNNode() containerNode.name = seatClassEntity?.name let nodes: [SeatNode] = seatClassEntity?.reservableEntities.compactMap({ guard !workItem.isCancelled else { return nil } if let node: SeatNode = NodeFactory.shared?.create(name: $0.transformedModelEntity.modelEntity) { node.reservableEntity = $0 // Assign Enabled state of interactible nodes node.isEnabled = $0.isAvailable && isCurrentEntity return node } /// Show Error node let node = PlaceholderSeatNode() node.reservableEntity = $0 return node }) ?? [] nodes.forEach { node in if !workItem.isCancelled { containerNode.addChildNode(node) } } // Try to inturrupt when process did cancelled guard !workItem.isCancelled else { return } self?.placeStaticNodes(using: seatClassEntity?.transformedModelEntities ?? [], isEnabled: isCurrentEntity) DispatchQueue.main.async { // Add bunch of nodes to contentNode self?.contentNode?.addChildNode(containerNode) // When current entity is loaded, will remove indicator view if isCurrentEntity { self?.playInitialAnimation() self?.loadingActivityIndicatorView?.removeFromSuperview() self?.alpha = 0 let duration: TimeInterval = TimeInterval(abs(self?.contentZPositionLimit.upperBound ?? 0) - abs(self?.contentZPositionLimit.lowerBound ?? 0)) / 100 + 0.5 UIView.animate(withDuration: duration, animations: { self?.alpha = 1 }) } } } (isCurrentEntity ? currentEntityQueue : otherEntityQueue).async(execute: workItem) workItems.append(workItem) } public func setupContent(seatMap: SeatMap, currentEntity: SeatClassEntity, fromStation: String?, toStation: String?) { setupGlobalStaticContent(seatMap: seatMap) var seatClassEntities = seatMap.seatClassEntities // Reorder to have current seatClassEnity to be first memeber of the array if let index = seatClassEntities.firstIndex(where: { $0 === currentEntity }) { seatClassEntities.remove(at: index) seatClassEntities.insert(currentEntity, at: 0) } seatClassEntities.forEach { let isCurrentEntity = $0 === currentEntity if isCurrentEntity { // Set Seat Range contentZPositionLimit = $0 .viewableRange .lowerBound.z...$0 .viewableRange .upperBound.z // Set origin of the content to be center between lowerBound and upperbound currectContentNodePosition?.z = ($0.viewableRange.lowerBound.z + $0.viewableRange.upperBound.z) / 2 } setupSeatClassContent(seatClassEntity: $0, isCurrentEntity: isCurrentEntity) } seatMap.transformedTextModelEntities.forEach { contentNode.addChildNode($0) } setupStationDirectionLabelNode(withFromStation: fromStation, toStation: toStation) } private func setupStationDirectionLabelNode(withFromStation fromStation: String?, toStation: String?) { let stationDirectionText = "\(toStation != nil ? "← \(toStation ?? "")" : "")\(fromStation != nil ? " \(fromStation ?? "") →" : "")" stationDirectionTextNode = TextNode(text: stationDirectionText, font: .systemFont(ofSize: 0.5, weight: .light), textAlignment: .right, color: currentColorTheme.componentColor.secondaryText) stationDirectionTextNode.position = SCNVector3(-3.15, 1.2, -13) stationDirectionTextNode.eulerAngles.y = .pi / 2 self.scene?.rootNode.addChildNode(stationDirectionTextNode) } private func setupGlobalStaticContent(seatMap: SeatMap) { if let factory = NodeFactory.shared { let onComplete: () -> Void = { [weak self] in self?.placeStaticNodes(using: seatMap.transformedModelEntities) } if factory.isLoaded { DispatchQueue.global(qos: .background).async(execute: onComplete) }else{ factory.onComplete(callback: onComplete) } }else{ fatalError("NodeFactory is not defined before used") } } private func setupSeatClassContent(seatClassEntity: SeatClassEntity, isCurrentEntity: Bool = true) { if let factory = NodeFactory.shared { let onComplete: () -> Void = { [weak self] in self?.placeSeatClassNodes(seatClassEntity: seatClassEntity, isCurrentEntity: isCurrentEntity) } if factory.isLoaded { DispatchQueue.global(qos: .background).async(execute: onComplete) }else{ factory.onComplete(callback: onComplete) } }else{ fatalError("NodeFactory is not defined before used") } } private func setupInteraction() { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureDidPan)) panGesture.maximumNumberOfTouches = 1 addGestureRecognizer(panGesture) } // MARK: State Change / Update private func setCurrectContentNodePosition(currectContentNodePosition: SCNVector3?, oldValue: SCNVector3?) { contentNode.position = currectContentNodePosition ?? contentNode.position guard let currectContentNodePosition = currectContentNodePosition, let oldValue = oldValue else { return } perspectiveVelocity = (currectContentNodePosition.z - oldValue.z) / (1 / 60) // Conform to the delegate let upperBoundLimitOffsetY: CGFloat = CGFloat(contentZPositionLimit.upperBound - currectContentNodePosition.z) seatMapDelegate? .sceneViewDidPanFurtherUpperBoundLimit(by: CGPoint(x: 0, y: upperBoundLimitOffsetY / 0.04)) } // MARK: Gestures override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) contentNode.removeAction(forKey: "panDrift") for node in filterReservationNodeFrom(touches) { highlightedSeatNodes.insert(node) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) if highlightedSeatNodes.count > 0 { highlightedSeatNodes.removeAll() } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) touches.compactMap ({ touch in highlightedSeatNodes.first { $0.touch == touch } }).forEach { node in selectedSeatNode = node highlightedSeatNodes.remove(node) } } @objc private func panGestureDidPan(_ sender: UIPanGestureRecognizer) { let location = sender.location(in: self) switch sender.state { case .began: hitTestPositionWhenTouchBegan = positionOfFloorHitTest(location) contentNodePositionWhenTouchBegan = contentNode.position case .changed: let hitTestPositionWhereCurrentTouch = positionOfFloorHitTest(location) if let hitTestPositionWhereTouchBegan = hitTestPositionWhenTouchBegan, let hitTestPositionWhereCurrentTouch = hitTestPositionWhereCurrentTouch, let contentNodePositionWhereTouchBegan = contentNodePositionWhenTouchBegan { let zPosition = zPositionClamp(hitTestPositionWhereCurrentTouch.z - hitTestPositionWhereTouchBegan.z + contentNodePositionWhereTouchBegan.z) self.currectContentNodePosition?.z = zPosition } case .ended: var currentTime: CGFloat = 0 var currentVelocity = CGPoint(x: 0, y: CGFloat(perspectiveVelocity ?? 0)) let driftAction = SCNAction .customAction(duration: DecayFunction .timeToHalt(velocity: currentVelocity), action: { [weak self] (node, elapsedTime) in guard let self = self else { return } let newStep = DecayFunction .step(timeElapsed: CFTimeInterval(elapsedTime - currentTime), velocity: currentVelocity) let yDisplacment = newStep.displacement.y let newZPosition = self.contentNode.position.z + Float(yDisplacment) self.currectContentNodePosition?.z = (newZPosition + self.zPositionClamp(newZPosition)) / 2 self.currectContentNodePosition = self.contentNode.position currentVelocity = newStep.velocity currentTime = elapsedTime }) contentNode.runAction(driftAction, forKey: "panDrift", completionHandler:{ [weak self] in guard let currentZ = self?.currectContentNodePosition?.z, let contentZPositionLimit = self?.contentZPositionLimit else { return } // reset the position of the content if it goes beyond the position limit after the panDrift animation self?.currectContentNodePosition?.z = max(min(currentZ, contentZPositionLimit.upperBound), contentZPositionLimit.lowerBound) }) default: break } } @objc private func headsUpbadgeControlDidTouch(_ sender: HeadsUpBadgeControl) { if let selectedSeat = selectedSeatNode { animateContentNodeToZPosition(of: selectedSeat.position.z) } } // MARK: Utility & Helper /// Recursive find parent node that be `ReservableNode` class /// - Parameter node: Target node to find func findParent(of node: SCNNode?) -> SeatNode? { guard let node = node else { return nil } if let node = node as? SeatNode { return node } return findParent(of: node.parent) } /// Get nodes from touches position /// - Parameter touches: Set of touch to determine private func filterReservationNodeFrom(_ touches: Set<UITouch>) -> [SeatNode] { return touches.compactMap { touch in let firstHitTestResult = hitTest(touch.location(in: self), options: [.categoryBitMask: SeatNode.defaultBitMask]).first if let node = firstHitTestResult?.node, let parent = findParent(of: node), parent.isEnabled { parent.touch = touch return parent } return nil } } private func zPositionClamp(_ value: Float) -> Float { let trimmedMaxValue = value > contentZPositionLimit.upperBound ? contentZPositionLimit.upperBound * (1 + log10(value/contentZPositionLimit.upperBound)) : value return value < contentZPositionLimit.lowerBound ? contentZPositionLimit.lowerBound * (1 + log10( trimmedMaxValue / contentZPositionLimit.lowerBound )) : trimmedMaxValue } private func positionOfFloorHitTest(_ point: CGPoint) -> SCNVector3? { let hitTests = hitTest(point, options: [.categoryBitMask : 1 << 1]) return hitTests.first?.worldCoordinates } private func animateContentNodeToZPosition(of zPosition: Float) { contentNode.removeAction(forKey: "panDrift") let center = positionOfFloorHitTest(.init(x: 0, y: frame.midY))?.z ?? 0 SceneKitAnimator.animateWithDuration( duration: 0.35 * 2, timingFunction: .easeOut, animations: { currectContentNodePosition?.z = -zPosition + center }) } } extension SeatMapSceneView { func addHeadsUpBadgeControl(withMessage message: String, animated: Bool = true, delayUntilRemoved: TimeInterval = 0, bitMask: Int = 1 << 0, completion: ((Bool)->())? = nil) { /// Remove all badgeControls first removeHeadsUpBadgeControl(animated: false) /// Setup headsUpBadgeControl let headsUpBadgeControl = HeadsUpBadgeControl() headsUpBadgeControl.tag = bitMask addSubview(headsUpBadgeControl, withConstaintEquals: [.topMargin, .centerHorizontal]) headsUpBadgeControl .addTarget(self, action: #selector(headsUpbadgeControlDidTouch(_:)), for: .touchUpInside) headsUpBadgeControl .setupContent(message: message, animated: animated, delay: 0, completion: { finished in if let completion = completion { completion(finished) } if delayUntilRemoved > 0 { headsUpBadgeControl.dismiss(animated: animated, delay: delayUntilRemoved, removeWhenComplete: true) } }) } func removeHeadsUpBadgeControl(animated: Bool = true, bitMask: Int? = nil, completion: ((Bool)->())? = nil) { subviews.forEach { guard let headsUpBadgeControl = $0 as? HeadsUpBadgeControl else { return } let removeHeadsUpBadgeAction = { headsUpBadgeControl.dismiss(animated: animated, removeWhenComplete: true) } if bitMask != nil { if $0.tag == bitMask { removeHeadsUpBadgeAction() } } else { removeHeadsUpBadgeAction() } } } }
42.054455
177
0.562684
ccff1c1d476599e961e1a53451b5803cc5668109
255
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let f = e.h> () { class a { enum A { protocol A { deinit { class case c, let a { prot
18.214286
87
0.709804
e9c3bba25e6f68115499933d9bd766a029123dc3
2,964
// // GlucoseAlarm.swift // LibreKit // // Created by Julian Groen on 18/05/2020. // Copyright © 2020 Julian Groen. All rights reserved. // import Foundation import HealthKit public enum AlarmResult: Int, CaseIterable { case none = 0 case low case high func isAlarming() -> Bool { return rawValue != AlarmResult.none.rawValue } } enum AlarmValidationStatus { case success case error(String) } class GlucoseAlarm: Codable, CustomStringConvertible { var enabled: Bool? var threshold: GlucoseThreshold? public func validateGlucose(_ glucose: Double) -> AlarmResult { if enabled == true, let threshold = threshold { if let low = threshold.low, glucose <= low { return .low } if let high = threshold.high, glucose >= high { return .high } } return .none } public func validateAlarm() -> AlarmValidationStatus { if let error = validateThreshold() { return error } return .success } private func validateThreshold() -> AlarmValidationStatus? { guard let threshold = self.threshold, let low = threshold.low, let high = threshold.high else { return .error("Threshold values not set or some are missing.") } if low == high { return .error("Invalid thresholds given, given values are identical.") } if low > high { return .error("Invalid thresholds given, low threshold is set above high threshold.") } if high < low { return .error("Invalid thresholds given, high threshold is set above low threshold.") } return nil } var description: String { return "GlucoseAlarm={enabled: \(enabled), threshold: \(threshold)}" } } class GlucoseThreshold: Codable, CustomStringConvertible { var low: Double? var high: Double? public func setLowTreshold(forUnit unit: HKUnit, threshold: Double) { self.low = (unit == HKUnit.millimolesPerLiter ? threshold * 18 : threshold) } public func setHighTreshold(forUnit unit: HKUnit, threshold: Double) { self.high = (unit == HKUnit.millimolesPerLiter ? threshold * 18 : threshold) } public func getLowTreshold(forUnit unit: HKUnit) -> Double? { guard let treshold = low else { return nil } return (unit == HKUnit.millimolesPerLiter ? (treshold / 18).roundTo(places: 1) : treshold) } public func getHighTreshold(forUnit unit: HKUnit) -> Double? { guard let treshold = high else { return nil } return (unit == HKUnit.millimolesPerLiter ? (treshold / 18).roundTo(places: 1) : treshold) } var description: String { return "GlucoseThreshold={low: \(low), high: \(high)}" } }
27.700935
103
0.596491
16e69e560bdf008795ba2128e93bc7f750cb8e8d
707
// // ClassModel.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif /** Model for testing model with \&quot;_class\&quot; property */ public struct ClassModel: Codable, Hashable { public var _class: String? public init(_class: String? = nil) { self._class = _class } public enum CodingKeys: String, CodingKey, CaseIterable { case _class } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } }
20.794118
67
0.683168
f558fd5fa85e7c1e4d93cd29ff7b6f3ee10bf7d3
1,044
// // SingleArticleFetcher.swift // Account // // Created by Maurice Parker on 11/29/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import Foundation import Articles import ArticlesDatabase public struct SingleArticleFetcher: ArticleFetcher { private let account: Account private let articleID: String public init(account: Account, articleID: String) { self.account = account self.articleID = articleID } public func fetchArticles() throws -> Set<Article> { return try account.fetchArticles(.articleIDs(Set([articleID]))) } public func fetchArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { return account.fetchArticlesAsync(.articleIDs(Set([articleID])), completion) } public func fetchUnreadArticles() throws -> Set<Article> { return try account.fetchArticles(.articleIDs(Set([articleID]))) } public func fetchUnreadArticlesAsync(_ completion: @escaping ArticleSetResultBlock) { return account.fetchArticlesAsync(.articleIDs(Set([articleID])), completion) } }
26.1
86
0.757663
38939b8756d902ab5c8d4727465422de4c00e32c
8,486
// // LiveLogViewControllerTests.swift // QLogTests // // Created by Christian Oberdörfer on 22.03.18. // Copyright © 2018 Quantum. All rights reserved. // @testable import QLog import Cuckoo import XCTest class LiveLogViewControllerMock: LiveLogViewController { var scrolled = false override func scroll() { self.scrolled = true } } class LiveLogViewControllerTests: XCTestCase { func testInit() { // 2. Action let liveLogViewController = LiveLogViewController() // 3. Assert XCTAssertEqual(liveLogViewController.navigationItem.leftBarButtonItem?.target as? LiveLogViewController, liveLogViewController) XCTAssertEqual(liveLogViewController.navigationItem.leftBarButtonItem?.action, #selector(LiveLogViewController.back)) XCTAssertEqual(liveLogViewController.navigationItem.rightBarButtonItem?.target as? LiveLogViewController, liveLogViewController) XCTAssertEqual(liveLogViewController.navigationItem.rightBarButtonItem?.action, #selector(LiveLogViewController.action)) XCTAssertTrue(liveLogViewController.extendedLayoutIncludesOpaqueBars) } func testInitWithCoder() { // 1. Arrange let archiver = NSKeyedArchiver(forWritingWith: NSMutableData()) // 2. Action let liveLogViewController = LiveLogViewController(coder: archiver) // 3. Assert XCTAssertNil(liveLogViewController) } func testLog() { // 1. Arrange let logEntry = LogEntry(date: Date(), file: "", function: "", line: 0, logLevel: .error, text: "Text") let attributedMetaText = NSMutableAttributedString(string: "\n\(logEntry.metaText)", attributes: [NSAttributedString.Key.foregroundColor: QLog.colorText, NSAttributedString.Key.font: QLog.font]) let attributedText = NSMutableAttributedString(string: "\(logEntry.text)", attributes: [NSAttributedString.Key.foregroundColor: logEntry.logLevel.color, NSAttributedString.Key.font: QLog.font]) let attributedTesttext = attributedMetaText attributedTesttext.append(attributedText) let liveLogViewController = LiveLogViewControllerMock() // 2. Action liveLogViewController.log(logEntry) // 3. Assert XCTAssertEqual(liveLogViewController.textView.attributedText, attributedTesttext) XCTAssertTrue(liveLogViewController.scrolled) } func testLogTwice() { // 1. Arrange let logEntry = LogEntry(date: Date(), file: "", function: "", line: 0, logLevel: .error, text: "Text") let logEntry2 = LogEntry(date: Date(), file: "", function: "", line: 0, logLevel: .error, text: "Text 2") let attributedMetaText = NSMutableAttributedString(string: "\n\(logEntry.metaText)", attributes: [NSAttributedString.Key.foregroundColor: QLog.colorText, NSAttributedString.Key.font: QLog.font]) let attributedMetaText2 = NSMutableAttributedString(string: "\n\(logEntry2.metaText)", attributes: [NSAttributedString.Key.foregroundColor: QLog.colorText, NSAttributedString.Key.font: QLog.font]) let attributedText = NSMutableAttributedString(string: "\(logEntry.text)", attributes: [NSAttributedString.Key.foregroundColor: logEntry.logLevel.color, NSAttributedString.Key.font: QLog.font]) let attributedText2 = NSMutableAttributedString(string: "\(logEntry2.text)", attributes: [NSAttributedString.Key.foregroundColor: logEntry.logLevel.color, NSAttributedString.Key.font: QLog.font]) let attributedTestText = attributedMetaText attributedTestText.append(attributedText) attributedTestText.append(attributedMetaText2) attributedTestText.append(attributedText2) let liveLogViewController = LiveLogViewControllerMock() // 2. Action liveLogViewController.log(logEntry) liveLogViewController.log(logEntry2) // 3. Assert XCTAssertEqual(liveLogViewController.textView.attributedText, attributedTestText) XCTAssertTrue(liveLogViewController.scrolled) } func testShowLog() { // 1. Arrange let liveLogViewController = LiveLogViewController() let logUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("log.test") FileManager.default.createFile(atPath: logUrl.path, contents: nil, attributes: nil) let logFileHandle = FileHandle(forWritingAtPath: logUrl.path) logFileHandle?.write("test".data(using: .utf8)!) // 2. Action liveLogViewController.showLog(logUrl) // 3. Assert XCTAssertEqual(liveLogViewController.textView.text, "test") // 4. Annihilate try? FileManager.default.removeItem(at: logUrl) } func testShowLogWrongLogUrl() { // 1. Arrange let liveLogViewController = LiveLogViewController() let logUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("log.test") // 2. Action liveLogViewController.showLog(logUrl) // 3. Assert XCTAssertEqual(liveLogViewController.textView.text, "") } func testScroll() { // 1. Arrange let liveLogViewController = LiveLogViewController() liveLogViewController.textView.bounds = CGRect(x: 0, y: 0, width: 0, height: 100) liveLogViewController.view.bounds = CGRect(x: 0, y: 0, width: 0, height: 50) // 2. Action liveLogViewController.scroll() // 3. Assert liveLogViewController.scrollView.contentOffset = CGPoint(x: 0, y: 50) } func testScrollNoChange() { // 1. Arrange let liveLogViewController = LiveLogViewController() // 2. Action liveLogViewController.scroll() // 3. Assert liveLogViewController.scrollView.contentOffset = CGPoint(x: 0, y: 0) } // MARK: - Navigation func testLogLevelSegmentedControlValueChanged() { // 1. Arrange let liveLogViewController = LiveLogViewController() let logLevel = LogLevel.error liveLogViewController.logLevelSegmentedControl.selectedSegmentIndex = logLevel.rawValue let object = NSObject() // 2. Action liveLogViewController.logLevelSegmentedControlValueChanged(object) // 3. Assert XCTAssertEqual(UiLogger.shared.logLevel.rawValue, logLevel.rawValue) } func testLogLevelSegmentedControlValueChangedInvalidIndex() { // 1. Arrange let liveLogViewController = LiveLogViewController() let logLevel = LogLevel.warning UiLogger.shared.logLevel = logLevel let logLevelSegmentedControl = UISegmentedControl(items: ["0", "1", "2", "3", "4", "5", "6"]) logLevelSegmentedControl.selectedSegmentIndex = 7 liveLogViewController.logLevelSegmentedControl = logLevelSegmentedControl let object = NSObject() // 2. Action liveLogViewController.logLevelSegmentedControlValueChanged(object) // 3. Assert XCTAssertEqual(UiLogger.shared.logLevel.rawValue, logLevel.rawValue) } func testBack() { // 1. Arrange let liveLogViewControllerDelegate = MockLiveLogViewControllerDelegate() stub(liveLogViewControllerDelegate) { liveLogViewControllerDelegate in when(liveLogViewControllerDelegate).back().thenDoNothing() } let liveLogViewController = LiveLogViewController() liveLogViewController.delegate = liveLogViewControllerDelegate // 2. Action liveLogViewController.back() // 3. Assert verify(liveLogViewControllerDelegate).back() verifyNoMoreInteractions(liveLogViewControllerDelegate) } func testAction() { // 1. Arrange let liveLogViewControllerDelegate = MockLiveLogViewControllerDelegate() stub(liveLogViewControllerDelegate) { liveLogViewControllerDelegate in when(liveLogViewControllerDelegate).action(sender: any()).thenDoNothing() } let liveLogViewController = LiveLogViewController() liveLogViewController.delegate = liveLogViewControllerDelegate let barButtonItem = UIBarButtonItem() // 2. Action liveLogViewController.action(barButtonItem) // 3. Assert verify(liveLogViewControllerDelegate).action(sender: equal(to: barButtonItem)) verifyNoMoreInteractions(liveLogViewControllerDelegate) } }
40.798077
204
0.703512
f8bc5b1ac6b1c761d5631a8d7e74af520564faa8
1,434
// // LaunchAdSkipButton.swift // SwiftBilibili // // Created by luowen on 2020/9/28. // Copyright © 2020 luowen. All rights reserved. // import UIKit public class LaunchAdSkipButton: UIButton { private let config: LaunchAdConfig init(config: LaunchAdConfig = LaunchAdConfig()) { self.config = config super.init(frame: config.skipButtonframe) backgroundColor = config.backgroundColor updateRemainTime(config.duration) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 倒计时更新 func updateRemainTime(_ remainTime: Int) { let time = "\(remainTime)" switch config.skipBtnType { case .none: isHidden = true case .textLeftTimerRight: let titleAtt = NSMutableAttributedString(string: "\(config.text) \(time)") titleAtt.addAttributes([.foregroundColor: config.textColor, .font: config.textFont], range: NSRange(location: 0, length: config.text.count)) titleAtt.addAttributes([.foregroundColor: config.timeColor, .font: config.timeFont], range: NSRange(location: config.text.count+1, length: time.count)) setAttributedTitle(titleAtt, for: .normal) layer.borderColor = config.borderColor.cgColor layer.borderWidth = config.borderWidth layer.cornerRadius = config.cornerRadius } } }
30.510638
163
0.658298
9c524a515a536ccfa10c84ad46fcbed0858c19f1
1,909
// // ResortRating.swift // EpicvsIkon // // Created by Jason Sanchez on 9/17/18. // Copyright © 2018 Jason Sanchez. All rights reserved. // import UIKit class ResortRating: UIView { var rating = 0 { didSet { //Trigger a layout update setNeedsLayout() } } var ratingButtons = [UIButton]() var spacing = 5 var stars = 5 // MARK: Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let filledStarImage = UIImage(named: "yellowstar") let emptyStarImage = UIImage(named: "blackstar") for _ in 0..<stars { let button = UIButton() button.setImage(emptyStarImage, for: UIControlState.normal) button.setImage(filledStarImage, for: UIControlState.selected) button.adjustsImageWhenHighlighted = false ratingButtons += [button] addSubview(button) } } override func layoutSubviews() { // Set the button's width and height to a square the size of the frame's height let buttonSize = Int(frame.size.height) var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize) var x = 0 // Offset each button's origin by the length of button plus spacing for button in ratingButtons { buttonFrame.origin.x = CGFloat(x * (buttonSize + spacing)) button.frame = buttonFrame x += 1 } updateButtonSelectionStates() } func updateButtonSelectionStates() { var x = 0 for button in ratingButtons { // if the index of a button is less than the rating, that button should be selected button.isSelected = x < rating x += 1 } } }
27.271429
95
0.565217
de282ec9a4adcb88b7b8afc82e13cdb6a87a3431
5,930
// // AsyncSequence+SwitchToLatest.swift // // // Created by Thibault Wittemberg on 04/01/2022. // import Foundation public extension AsyncSequence where Element: AsyncSequence { /// Republishes elements sent by the most recently received async sequence. /// /// ``` /// let sourceSequence = AsyncSequences.From([1, 2, 3]) /// let mappedSequence = sourceSequence.map { element in ["a\(element)", "b\(element)"].asyncElements } /// let switchedSequence = mappedSequence.switchToLatest() /// /// for try await element in switchedSequence { /// print(element) /// } /// /// // will print: /// a3, b3 /// ``` /// - parameter upstreamPriority: can be used to change the priority of the task that supports the iteration /// over the upstream sequence (nil by default) /// /// - Returns: The async sequence that republishes elements sent by the most recently received async sequence. func switchToLatest(upstreamPriority: TaskPriority? = nil) -> AsyncSwitchToLatestSequence<Self> { AsyncSwitchToLatestSequence<Self>(self, upstreamPriority: upstreamPriority) } } public struct AsyncSwitchToLatestSequence<UpstreamAsyncSequence: AsyncSequence>: AsyncSequence where UpstreamAsyncSequence.Element: AsyncSequence { public typealias Element = UpstreamAsyncSequence.Element.Element public typealias AsyncIterator = Iterator let upstreamAsyncSequence: UpstreamAsyncSequence let upstreamPriority: TaskPriority? public init( _ upstreamAsyncSequence: UpstreamAsyncSequence, upstreamPriority: TaskPriority? ) { self.upstreamAsyncSequence = upstreamAsyncSequence self.upstreamPriority = upstreamPriority } public func makeAsyncIterator() -> AsyncIterator { Iterator( upstreamIterator: self.upstreamAsyncSequence.makeAsyncIterator(), upstreamPriority: self.upstreamPriority ) } final class UpstreamIteratorManager { var upstreamIterator: UpstreamAsyncSequence.AsyncIterator var childIterators = [AsyncIteratorByRef<UpstreamAsyncSequence.Element.AsyncIterator>]() var hasStarted = false var currentTask: Task<Element?, Error>? let upstreamPriority: TaskPriority? let serialQueue = DispatchQueue(label: UUID().uuidString) init( upstreamIterator: UpstreamAsyncSequence.AsyncIterator, upstreamPriority: TaskPriority? ) { self.upstreamIterator = upstreamIterator self.upstreamPriority = upstreamPriority } func setCurrentTask(task: Task<Element?, Error>) { self.currentTask = task } /// iterates over the upstream sequence and maintain the current async iterator while cancelling the current .next() task for each new element func startUpstreamIterator() async throws { guard !self.hasStarted else { return } self.hasStarted = true if let firstChildSequence = try await self.upstreamIterator.next() { self.serialQueue.async { [weak self] in self?.childIterators.append(AsyncIteratorByRef(iterator: firstChildSequence.makeAsyncIterator())) } } Task(priority: self.upstreamPriority) { [weak self] in while let nextChildSequence = try await self?.upstreamIterator.next() { self?.serialQueue.async { [weak self] in self?.childIterators.removeFirst() self?.childIterators.append(AsyncIteratorByRef(iterator: nextChildSequence.makeAsyncIterator())) self?.currentTask?.cancel() } } } } func nextOnCurrentChildIterator() async throws -> Element? { let childIterator = self.serialQueue.sync { [weak self] in self?.childIterators.last } return try await childIterator?.next() } } public struct Iterator: AsyncIteratorProtocol { let upstreamIteratorManager: UpstreamIteratorManager init( upstreamIterator: UpstreamAsyncSequence.AsyncIterator, upstreamPriority: TaskPriority? ) { self.upstreamIteratorManager = UpstreamIteratorManager( upstreamIterator: upstreamIterator, upstreamPriority: upstreamPriority ) } public mutating func next() async throws -> Element? { guard !Task.isCancelled else { return nil } var noValueHasBeenEmitted = true var emittedElement: Element? var currentTask: Task<Element?, Error> // starting the root iterator to be able to iterate in the first child iterator try await self.upstreamIteratorManager.startUpstreamIterator() let localUpstreamIteratorManager = self.upstreamIteratorManager // if a task is cancelled while waiting with the next element (a new element arrived in the root iterator) // we create a new task and wait for the elements from the new child iterator while noValueHasBeenEmitted { currentTask = Task { do { return try await localUpstreamIteratorManager.nextOnCurrentChildIterator() } catch is CancellationError { return nil } catch { throw error } } localUpstreamIteratorManager.setCurrentTask(task: currentTask) emittedElement = try await currentTask.value noValueHasBeenEmitted = (emittedElement == nil && currentTask.isCancelled) } return emittedElement } } }
39.013158
150
0.632209
eb7ad9b25b55b6127abb627fcb596c972e5cce62
872
// // CZProfileViewController.swift // weiboSwift // // Created by 王灿辉 on 15/10/26. // Copyright © 2015年 王灿辉. All rights reserved. // import UIKit import SDWebImage class CZProfileViewController: CZBaseViewController { override func viewDidLoad() { super.viewDidLoad() // 获取SDWebImage缓存图片的大小 let size = Double(SDImageCache.sharedImageCache().getSize()) / 1000.0 / 1000.0 let newSize = String(format: "%.2f", arguments: [size]) navigationItem.title = "缓存大小:\(newSize) M" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "清理缓存", style: UIBarButtonItemStyle.Plain, target: self, action: "clear") } func clear() { SDImageCache.sharedImageCache().clearDiskOnCompletion { () -> Void in // print("清除缓存完成") // 刷新显示 self.viewDidLoad() } } }
26.424242
140
0.633028
91efe3001078ae4ddb1633142e6e3494c602f942
7,523
// // NotificationService.swift // APNSAttachmentService // // Created by Robbie Trencheny on 9/8/16. // Copyright © 2016 Robbie Trencheny. All rights reserved. // import UserNotifications import MobileCoreServices import Shared import Alamofire import PromiseKit final class NotificationService: UNNotificationServiceExtension { private var contentHandler: ((UNNotificationContent) -> Void)? private var bestAttemptContent: UNMutableNotificationContent? // swiftlint:disable cyclomatic_complexity function_body_length override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { Current.Log.verbose("APNSAttachmentService started!") Current.Log.verbose("Received userInfo \(request.content.userInfo)") // FIXME: Memory leak caused by ClientEvent/Realm. /* let event = ClientEvent(text: request.content.clientEventTitle, type: .notification, payload: request.content.userInfo as? [String: Any]) Current.clientEventStore.addEvent(event) */ Current.Log.debug("Added client event") self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) Current.Log.debug("Set bestAttemptContent") func failEarly(_ reason: String) { Current.Log.error("Failing early because \(reason)!") contentHandler(request.content) } guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else { return failEarly("Unable to get mutable copy of notification content") } guard var incomingAttachment = content.userInfo["attachment"] as? [String: Any] else { return failEarly("Attachment dictionary not in payload") } var needsAuth = false if content.categoryIdentifier.hasPrefix("camera") && incomingAttachment["url"] == nil { Current.Log.debug("Camera cat prefix") guard let entityId = content.userInfo["entity_id"] as? String else { return failEarly("Category identifier was prefixed camera but no entity_id was set") } incomingAttachment["url"] = "/api/camera_proxy/\(entityId)" if incomingAttachment["content-type"] == nil { incomingAttachment["content-type"] = "jpeg" } needsAuth = true Current.Log.debug("Camera so requiring auth") } else { Current.Log.debug("Not a camera notification") // Check if we still have an empty dictionary if incomingAttachment.isEmpty { // Attachment wasn't there/not a string:any, and this isn't a camera category, so we should fail return failEarly("Content dictionary was not empty") } } guard let attachmentString = incomingAttachment["url"] as? String else { return failEarly("url string did not exist in dictionary") } if attachmentString.hasPrefix("/") { // URL is something like /api or /www so lets prepend base URL Current.Log.debug("Appears to be local URL, requiring auth") needsAuth = true } guard let attachmentURL = URL(string: attachmentString) else { return failEarly("Could not convert string to URL") } var attachmentOptions: [String: Any] = [:] if let attachmentContentType = incomingAttachment["content-type"] as? String { attachmentOptions[UNNotificationAttachmentOptionsTypeHintKey] = self.contentTypeForString(attachmentContentType) } if let attachmentHideThumbnail = incomingAttachment["hide-thumbnail"] as? Bool { attachmentOptions[UNNotificationAttachmentOptionsThumbnailHiddenKey] = attachmentHideThumbnail } Current.Log.debug("Set attachment options to \(attachmentOptions)s") Current.Log.verbose("Going to get URL at \(attachmentURL)") firstly { return HomeAssistantAPI.authenticatedAPIPromise }.then { api in return api.DownloadDataAt(url: attachmentURL, needsAuth: needsAuth) }.done { fileURL in do { let attachment = try UNNotificationAttachment(identifier: attachmentURL.lastPathComponent, url: fileURL, options: attachmentOptions) content.attachments.append(attachment) } catch let error { return failEarly("Unable to build UNNotificationAttachment: \(error)") } Current.Log.debug("Successfully created and appended attachment \(content.attachments)") // Attempt to fill in the summary argument with the thread or category ID if it doesn't exist in payload. if #available(iOS 12.0, *) { if content.summaryArgument == "" { if content.threadIdentifier != "" { content.summaryArgument = content.threadIdentifier } else if content.categoryIdentifier != "" { content.summaryArgument = content.categoryIdentifier } } } Current.Log.debug("About to return") guard let copiedContent = content.copy() as? UNNotificationContent else { return failEarly("Unable to copy contents") } Current.Log.debug("Returning \(copiedContent)") contentHandler(copiedContent) }.catch { error in var reason = "Error when getting attachment data! \(error)" if let error = error as? AFError { reason = "Alamofire error while getting attachment data: \(error)" } return failEarly(reason) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, // otherwise the original push payload will be used. Current.Log.warning("serviceExtensionTimeWillExpire") if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } private func contentTypeForString(_ contentTypeString: String) -> CFString { let contentType: CFString switch contentTypeString.lowercased() { case "aiff": contentType = kUTTypeAudioInterchangeFileFormat case "avi": contentType = kUTTypeAVIMovie case "gif": contentType = kUTTypeGIF case "jpeg", "jpg": contentType = kUTTypeJPEG case "mp3": contentType = kUTTypeMP3 case "mpeg": contentType = kUTTypeMPEG case "mpeg2": contentType = kUTTypeMPEG2Video case "mpeg4": contentType = kUTTypeMPEG4 case "mpeg4audio": contentType = kUTTypeMPEG4Audio case "png": contentType = kUTTypePNG case "waveformaudio": contentType = kUTTypeWaveformAudio default: contentType = contentTypeString as CFString } return contentType } }
40.015957
120
0.623422
0170cc9b87170b377150df847ccb67c73c8f7800
2,713
// // SceneDelegate.swift // Instafilter // // Created by Prathamesh Kowarkar on 05/11/20. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not 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. } }
42.390625
147
0.706229
abed65aacb9eda00100291b4a371aac26f52a4a7
2,390
// // GZIP.swift // Sileo // // Created by Amy on 02/06/2021. // Copyright © 2021 Sileo Team. All rights reserved. // import Foundation final class GZIP { class func decompress(path: String) -> (String?, Data?) { guard let fin = fopen(path, "rb") else { return (GZIPError.fileLoad.rawValue, nil) } defer { fclose(fin) } let inBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(16384)) let outBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(16384)) defer { inBuf.deallocate() outBuf.deallocate() } var have: UInt32 var stream = z_stream() defer { inflateEnd(&stream) } var status: Int32 = inflateInit2_(&stream, MAX_WBITS + 32, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) if status != Z_OK { return (GZIPError.inflate.rawValue, nil) } let data = NSMutableData() repeat { stream.avail_in = uInt(fread(inBuf, 1, 16384, fin)) if ferror(fin) != 0 { return (GZIPError.fileRead.rawValue, nil) } if stream.avail_in == 0 { break } stream.next_in = inBuf repeat { stream.avail_out = 16384 stream.next_out = outBuf status = inflate(&stream, Z_NO_FLUSH) switch status { case Z_NEED_DICT: return ("Z_NEED_DICT", nil) case Z_DATA_ERROR: return ("Z_DATA_ERROR", nil) case Z_MEM_ERROR: return ("Z_MEM_ERROR", nil) case Z_STREAM_ERROR: return ("Z_STREAM_ERROR", nil) default: break } have = 16384 - stream.avail_out data.append(Data(bytes: outBuf, count: Int(have))) } while stream.avail_out == 0 } while status != Z_STREAM_END if status != Z_STREAM_END { return (GZIPError.unknown.rawValue, nil) } return (nil, data as Data) } } enum GZIPError: String { case fileLoad = "Failed to load file" case inflate = "Error starting inflate" case fileRead = "Failed to Read File" case unknown = "Unknown Error" }
31.038961
116
0.523849