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
e52593c9ae070fcb5de862fe49d0c7d8ddcc0b19
5,480
import XCTest @testable import Jetworking final class URLFactoryTests: XCTestCase { struct SampleResponse: Codable {} let baseURl: URL = URL(string: "https://www.jamitlabs.com")! let sampleEndpoint: Endpoint<SampleResponse> = .init(pathComponent: "sample") func testURLParameterEncoding() throws { let url = try URLFactory.makeURL( from: sampleEndpoint.addQueryParameter( key: "someKey", value: "someValue" ), withBaseURL: baseURl ) XCTAssertEqual(url.absoluteString, "https://www.jamitlabs.com/sample?someKey=someValue") } func testURLMultipleParametersEncoding() throws { let url = try URLFactory.makeURL( from: sampleEndpoint.addQueryParameters( [ "firstKey" : "firstValue", "secondKey" : "secondValue", "thirdKey" : "thirdValue" ] ), withBaseURL: baseURl ) guard let components = url.absoluteString.split(separator: "?") .dropFirst() .first? .split(separator: "&") else { return XCTFail("Invalid Components!") } XCTAssertEqual(components.count, 3) XCTAssertTrue(components.contains("firstKey=firstValue")) XCTAssertTrue(components.contains("secondKey=secondValue")) XCTAssertTrue(components.contains("thirdKey=thirdValue")) } func testSpecialCharacterEncoding() throws { let url = try URLFactory.makeURL( from: sampleEndpoint.addQueryParameter( key: "someSpecialChars", value: "␣\"#%&<=>[\\]{|}" ), withBaseURL: baseURl ) XCTAssertEqual(url.absoluteString, "https://www.jamitlabs.com/sample?someSpecialChars=%E2%90%A3%22%23%25%26%3C%3D%3E%5B%5C%5D%7B%7C%7D") } func testInvalidURLComponent() throws { let endpoint: Endpoint<SampleResponse> = .init(pathComponent: "сплин://ws.audioscrobbler.com/2.0/?method=artist.search&artist=сплин&api_key=bad5acca27008a09709ccb2c0258003b&format=json" ) do { let _ = try URLFactory.makeURL( from: endpoint, withBaseURL: baseURl ) } catch APIError.invalidURLComponents { // Expected! } catch { XCTFail("Unexpected error occured!") } } func testSingleAdditionalPathComponent() { let expectation: String = "https://www.jamitlabs.com/endpoint/additionalPathComponent" let endpoint: Endpoint<SampleResponse> = .init(pathComponent: "endpoint") do { let url = try URLFactory.makeURL(from: endpoint.addPathComponent("additionalPathComponent"), withBaseURL: baseURl) XCTAssertEqual(expectation, url.absoluteString) } catch { XCTFail() } } func testMultipleAdditionalPathComponents() { let expectation: String = "https://www.jamitlabs.com/endpoint/additionalPathComponent/anotherPathComponent" let endpoint: Endpoint<SampleResponse> = .init(pathComponent: "endpoint") do { let url = try URLFactory.makeURL(from: endpoint.addPathComponents(["additionalPathComponent", "anotherPathComponent"]), withBaseURL: baseURl) XCTAssertEqual(expectation, url.absoluteString) } catch { XCTFail() } } func testSingleAdditionalSlashInPathComponent() { let expectation: String = "https://www.jamitlabs.com/endpoint/additionalPathComponent" let endpoint: Endpoint<SampleResponse> = .init(pathComponent: "endpoint") do { let url = try URLFactory.makeURL(from: endpoint.addPathComponent("/additionalPathComponent"), withBaseURL: baseURl) XCTAssertEqual(expectation, url.absoluteString) } catch { XCTFail() } } func testMultipleAdditionalSlashInPathComponent() { let expectation: String = "https://www.jamitlabs.com/endpoint/additionalPathComponent/anotherPathComponent" let endpoint: Endpoint<SampleResponse> = .init(pathComponent: "endpoint") do { let url = try URLFactory.makeURL(from: endpoint.addPathComponents(["/additionalPathComponent", "/anotherPathComponent"]), withBaseURL: baseURl) XCTAssertEqual(expectation, url.absoluteString) } catch { XCTFail() } } func testEndpointPathComponentInitialiser() { let expectation: String = "https://www.jamitlabs.com/endpoint/additionalPathComponent" let endpoint: Endpoint<SampleResponse> = .init(pathComponent: "endpoint/additionalPathComponent") do { let url = try URLFactory.makeURL(from: endpoint, withBaseURL: baseURl) XCTAssertEqual(expectation, url.absoluteString) } catch { XCTFail() } } func testEndpointPathComponentsInitialiser() { let expectation: String = "https://www.jamitlabs.com/endpoint/additionalPathComponent" let endpoint: Endpoint<SampleResponse> = .init(pathComponents: ["endpoint", "additionalPathComponent"]) do { let url = try URLFactory.makeURL(from: endpoint, withBaseURL: baseURl) XCTAssertEqual(expectation, url.absoluteString) } catch { XCTFail() } } }
38.055556
193
0.624818
d601b6ddb02763b790aba3a287966bd5cabacbe9
1,082
// // WBSyncContext.swift // GoWWorldBosses // // Created by Austin Chen on 2016-11-29. // Copyright © 2016 Austin Chen. All rights reserved. // import Foundation import RealmSwift enum WBSyncPendingTaskPriority: Int { case low = 0, medium, high } class WBSyncPendingTask: NSObject { var taskPriority: WBSyncPendingTaskPriority = .low var taskAction: String = "" } class WBSyncContext: NSObject { // remote context var remoteSession: WBRemoteSession? // a list of to-do items var pendingTasks: [WBSyncPendingTask] = [] } // serializing HAPSyncContext extension WBSyncContext { convenience init (remoteSession: WBRemoteSession?) { self.init() self.remoteSession = remoteSession } convenience init?(coder decoder: NSCoder) { self.init() if let pt = decoder.decodeObject(forKey: "pendingTasks") as? [WBSyncPendingTask] { self.pendingTasks = pt } } func encodeWithCoder(_ coder: NSCoder) { coder.encode(self.pendingTasks, forKey: "pendingTasks") } }
23.021277
90
0.666359
4b040f4fed988d4895ca80e47aeb4aba22c2ce05
1,310
// // ViewController.swift // CustomPresentationsProject // // Created by Blake Macnair on 12/21/18. // Copyright © 2018 Macnair. All rights reserved. // import UIKit import CustomPresentations class ViewController: CardPresentingViewController { private lazy var button: UIButton = { let button = UIButton(type: .roundedRect) button.setTitle("Press me!", for: .normal) button.backgroundColor = UIColor.cyan button.translatesAutoresizingMaskIntoConstraints = false return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white view.addSubview(button) NSLayoutConstraint.activate([ button.heightAnchor.constraint(equalToConstant: 80), button.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8), button.centerXAnchor.constraint(equalTo: view.centerXAnchor), button.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) button.addTarget(self, action: #selector(displayModalView), for: .touchUpInside) } @objc func displayModalView() { presentCard(presentedViewController: ModalViewController(), animated: true, completion: nil) } }
28.478261
88
0.662595
ac31f6b2b1ab40182fe4e29f1a36f201ea65bce1
749
extension UITableViewController { private func scrollToFirstIndexPath() { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0) , atScrollPosition: .Top, animated: true) } } extension UICollectionViewController { private func scrollToFirstIndexPath() { collectionView?.scrollToItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0) , atScrollPosition: .Top, animated: true) } } extension WMFArticleListTableViewController { func scrollToTop(isScrollable: Bool) { guard isScrollable else { return } scrollToFirstIndexPath() } } extension WMFExploreViewController { func scrollToTop() { guard canScrollToTop else { return } scrollToFirstIndexPath() } }
27.740741
126
0.718291
56addc239ba9cbe2e990340f43a68ed03b03d1dd
1,578
// // SummaryView.swift // convey (iOS) // // Created by Galen Quinn on 11/2/21. // import SwiftUI struct SummaryView : View { @ObservedObject private var viewModel = ViewModelModule.passSummaryViewModel() var titleSection : some View { Text("Recordings") .font(.largeTitle) .fontWeight(.semibold) .foregroundColor(.black) .padding() } var recordList : some View { ScrollView() { VStack(spacing: 5) { if viewModel.recordList.isEmpty { Text("No Records") .font(.title) .foregroundColor(.gray) } else { ForEach(viewModel.recordList, id: \.RecordId) { rec in SummaryCardView(record: rec) } } } .listStyle(PlainListStyle()) } .frame(height: UIScreen.main.bounds.height - 250) } var body: some View { VStack { titleSection recordList Spacer() Spacer() } } }
20.493506
82
0.347275
fe02b39ed7f072539e98412fa85f567f220303c6
1,250
// // ConvenienceBarsExample.swift // Examples // // Created by ischuetz on 19/07/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class ConvenienceBarsExample: UIViewController { fileprivate var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let chartConfig = BarsChartConfig( chartSettings: ExamplesDefaults.chartSettingsWithPanZoom, valsAxisConfig: ChartAxisConfig(from: 0, to: 8, by: 2), xAxisLabelSettings: ExamplesDefaults.labelSettings, yAxisLabelSettings: ExamplesDefaults.labelSettings.defaultVertical() ) let chart = BarsChart( frame: ExamplesDefaults.chartFrame(view.bounds), chartConfig: chartConfig, xTitle: "X axis", yTitle: "Y axis", bars: [ ("A", 2), ("B", 4.5), ("C", 3), ("D", 5.4), ("E", 6.8), ("F", 0.5) ], color: UIColor.red, barWidth: Env.iPad ? 40 : 20 ) view.addSubview(chart.view) self.chart = chart } }
26.595745
80
0.5304
8f18c1264803f5f7a031ab3fc7efa939c2e383a6
1,168
// // DropDelegate.swift // Know Em? // // Created by Joe Maghzal on 9/7/21. // import SwiftUI #if targetEnvironment(macCatalyst) struct ImageDropDelegate: DropDelegate { @Binding var inputImage: Image? func validateDrop(info: DropInfo) -> Bool { return info.hasItemsConforming(to: ["public.file-url"]) } func dropEntered(info: DropInfo) { } func performDrop(info: DropInfo) -> Bool { NSSound(named: "Submarine")?.play() if let item = info.itemProviders(for: ["public.file-url"]).first { item.loadItem(forTypeIdentifier: "public.file-url", options: nil) { (urlData, error) in DispatchQueue.main.async { if let urlData = urlData as? Data { let url = NSURL(absoluteURLWithDataRepresentation: urlData, relativeTo: nil) as URL let nsImage = NSImage(byReferencing: url) print(url.absoluteString) inputImage = Image(nsImage: nsImage) } } } return true }else { return false } } } #endif
31.567568
107
0.558219
3376253a862e255da144d974a572ea5e5ba4852b
1,199
// // YPBottomPagerView.swift // YPImagePicker // // Created by Sacha DSO on 24/01/2018. // Copyright © 2016 Yummypets. All rights reserved. // import UIKit import Stevia final class YPBottomPagerView: UIView { var header = YPPagerMenu() var scrollView = UIScrollView() convenience init() { self.init(frame: .zero) backgroundColor = UIColor(red: 239/255, green: 238/255, blue: 237/255, alpha: 1) sv( scrollView, header ) layout( 0, |scrollView|, 0, |header| ~ 44 ) if #available(iOS 11.0, *) { header.Bottom == safeAreaLayoutGuide.Bottom } else { header.bottom(0) } header.heightConstraint?.constant = YPConfig.hidesBottomBar ? 0 : 44 clipsToBounds = false setupScrollView() } private func setupScrollView() { scrollView.clipsToBounds = false scrollView.isPagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false } }
23.057692
88
0.560467
8f9e807458c7e06bdaba6764de47fe82e9acd66f
1,852
// // WorkspaceCodeFileEditor.swift // CodeEdit // // Created by Pavel Kasila on 20.03.22. // import SwiftUI import CodeFile import WorkspaceClient import StatusBar struct WorkspaceCodeFileView: View { var windowController: NSWindowController @ObservedObject var workspace: WorkspaceDocument @ViewBuilder var codeView: some View { if let item = workspace.selectionState.openFileItems.first(where: { file in if file.id == workspace.selectionState.selectedId { print("Item loaded is: ", file.url) } return file.id == workspace.selectionState.selectedId }) { if let codeFile = workspace.selectionState.openedCodeFiles[item] { CodeFileView(codeFile: codeFile) .safeAreaInset(edge: .top, spacing: 0) { VStack(spacing: 0) { TabBar(windowController: windowController, workspace: workspace) TabBarDivider() BreadcrumbsView(item, workspace: workspace) } } .safeAreaInset(edge: .bottom) { if let url = workspace.fileURL { StatusBarView(workspaceURL: url) } } } else { Text("CodeEdit cannot open this file because its file type is not supported.") } } else { Text("Open file from sidebar") } } var body: some View { HSplitView { codeView .frame(maxWidth: .infinity, maxHeight: .infinity) InspectorSidebar(workspace: workspace, windowController: windowController) .frame(minWidth: 250, maxWidth: 250, maxHeight: .infinity) } } }
33.071429
94
0.550216
215d3ef84f53fe402b9c92eef56e89c074932eee
1,301
// // Project_01___StopWatchMeowUITests.swift // Project 01 - StopWatchMeowUITests // // Created by mac on 2017/1/20. // Copyright © 2017年 Meow.minithon.teama. All rights reserved. // import XCTest class Project_01___StopWatchMeowUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
35.162162
182
0.674097
e8b2e1990d62c5fb40d59651db28fbdb3d53a227
203
// // Constants.swift // MyFancyWeatherApp // // Created by Sanad Barjawi on 29/11/2020. // import Foundation struct UserDefaultNames { static let selectedCountry: String = "SelectedCountry" }
14.5
58
0.714286
b9f5a6201260ee8f7a520a2501d341c4865d496e
1,451
// // Blacklist.swift // Pulse // // Created by Luke Klinker on 1/10/18. // Copyright © 2018 Luke Klinker. All rights reserved. // import Alamofire struct Blacklist : ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { let id: Int64 let phoneNumber: String? let phrase: String? var description: String { return "Blacklist: { phone_number: \(String(describing: phoneNumber)), phrase: \(String(describing: phrase)) }" } init(id: Int64, phoneNumber: String?, phrase: String?) { self.id = id self.phoneNumber = phoneNumber self.phrase = phrase } init?(json: Any) { guard let json = json as? [String: Any], let id = json["device_id"] as? Int64 else { return nil } let phoneNumber = Blacklist.getOptionalString(representation: json, key: "phone_number") let phrase = Blacklist.getOptionalString(representation: json, key: "phrase") self.id = id self.phoneNumber = phoneNumber ?? "" self.phrase = phrase ?? "" } private static func getOptionalString(representation: [String: Any], key: String) -> String? { let value = representation[key] if !(value is NSNull) { return Account.encryptionUtils?.decrypt(data: (value as? String)!) ?? nil } else { return nil } } }
29.02
119
0.602343
e838f498f2ceaffbb5d3c50ca2c4457e88116b32
759
// // Todo.swift // SocialAppCleanSwift // // Created by Christian Slanzi on 04.12.20. // import SwiftyJSON struct Todo: JSONinitiable { var userId: String var id: String var title: String var completed: Bool init(json: JSON) { self.userId = json["userId"].string ?? (json["id"].int != nil ? String(json["id"].int!): "") self.id = json["id"].string ?? (json["id"].int != nil ? String(json["id"].int!): "") self.title = json["title"].string ?? "" self.completed = json["completed"].bool ?? false } init(userId: String, id: String, title: String, completed: Bool) { self.userId = userId self.id = id self.title = title self.completed = completed } }
25.3
100
0.56917
5dd87099594cd05224807cda4bd5bb8776e70f71
186
// // MainEntity.swift // MovieDB-VIPER // // Created by Conrado Mateu on 9/12/20. // import Foundation struct MainEntity: Codable { let page: Int let results: [MovieEntity] }
12.4
40
0.672043
2fa2c3ed1a84b56492e77192b19d5a2386da8b95
1,886
// // ViewController.swift // ByvStyledLocalizations // // Created by adrianByv on 05/08/2018. // Copyright (c) 2018 adrianByv. All rights reserved. // import UIKit import ByvLocalizations import ByvStylesIB class ViewController: UIViewController { @IBOutlet weak var searchBar: StyledUISearchBar! @IBOutlet weak var label: UILabel! @IBOutlet weak var languageName: UILabel! @IBOutlet weak var barButton: UIBarButtonItem! @IBOutlet weak var changeBtn: UIButton! @IBOutlet weak var textField: UITextField! @IBOutlet weak var segmented: UISegmentedControl! @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver( self, selector: #selector(self.reloadLabels), name: ByvLocalizator.notiName, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func change(_ sender: UIButton) { let av = UIAlertController(title: "Language".localize(comment: "Action sheet title"), message: "Select the language you want".localize(comment: "Action sheet description"), preferredStyle: .actionSheet) for language in ByvLocalizator.shared.availableLanguages { av.addAction(UIAlertAction(title: language.name(), style: .default, handler: { (action) in ByvLocalizator.shared.setLanguage(code: language.code) })) } av.addAction(UIAlertAction(title: "Cancel".localize(), style: .cancel, handler: nil)) self.present(av, animated: true, completion: nil) } @objc func reloadLabels() { languageName.text = ByvLocalizator.shared.currentLanguage.name() } }
32.517241
210
0.668081
2fffe51281b988455b063472034b113c58b29019
12,450
import XCTest import FigmaExportCore @testable import XcodeExport import CustomDump final class XcodeColorExporterTests: XCTestCase { // MARK: - Properties private let fileManager = FileManager.default private var colorsFile: URL! private var colorsAssetCatalog: URL! private let colorPair1 = AssetPair<Color>( light: Color(name: "colorPair1", red: 1, green: 1, blue: 1, alpha: 1), dark: Color(name: "colorPair1", red: 0, green: 0, blue: 0, alpha: 1)) private let colorPair2 = AssetPair<Color>( light: Color(name: "colorPair2", red: 119.0/255.0, green: 3.0/255.0, blue: 1.0, alpha: 0.5), dark: nil) private lazy var color3: Color = { var color = Color(name: "background/primary", red: 119.0/255.0, green: 3.0/255.0, blue: 1.0, alpha: 0.5) color.name = "backgroundPrimary" return color }() private lazy var colorPair3 = AssetPair<Color>( light: color3, dark: nil) private let colorWithKeyword = AssetPair<Color>( light: Color(name: "class", platform: .ios, red: 1, green: 1, blue: 1, alpha: 1), dark: nil ) // MARK: - Setup override func setUp() { super.setUp() colorsFile = fileManager.temporaryDirectory.appendingPathComponent("Colors.swift") colorsAssetCatalog = fileManager.temporaryDirectory.appendingPathComponent("Assets.xcassets/Colors") } // MARK: - Tests func testExport_without_assets() throws { let output = XcodeColorsOutput(assetsColorsURL: nil, assetsInMainBundle: true, colorSwiftURL: colorsFile) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 1) let content = result[0].data XCTAssertNotNil(content) try assertCodeEquals(content, """ \(header) import UIKit public extension UIColor { static var colorPair1: UIColor { UIColor { traitCollection -> UIColor in if traitCollection.userInterfaceStyle == .dark { return UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) } else { return UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) } } } static var colorPair2: UIColor { UIColor(red: 0.467, green: 0.012, blue: 1.000, alpha: 0.500) } } """) } func testExport_with_assets() throws { let output = XcodeColorsOutput(assetsColorsURL: colorsAssetCatalog, assetsInMainBundle: true, colorSwiftURL: colorsFile) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 4) XCTAssertTrue(result[0].destination.url.absoluteString.hasSuffix("Colors.swift")) XCTAssertTrue(result[1].destination.url.absoluteString.hasSuffix("Assets.xcassets/Colors/Contents.json")) XCTAssertTrue(result[2].destination.url.absoluteString.hasSuffix("colorPair1.colorset/Contents.json")) XCTAssertTrue(result[3].destination.url.absoluteString.hasSuffix("colorPair2.colorset/Contents.json")) let content = result[0].data XCTAssertNotNil(content) try assertCodeEquals(content, """ \(header) import UIKit public extension UIColor { static var colorPair1: UIColor { UIColor(named: #function)! } static var colorPair2: UIColor { UIColor(named: #function)! } } """) } func testExport_with_objc() throws { let output = XcodeColorsOutput( assetsColorsURL: colorsAssetCatalog, assetsInMainBundle: true, addObjcAttribute: true, colorSwiftURL: colorsFile ) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 4) XCTAssertTrue(result[0].destination.url.absoluteString.hasSuffix("Colors.swift")) XCTAssertTrue(result[1].destination.url.absoluteString.hasSuffix("Assets.xcassets/Colors/Contents.json")) XCTAssertTrue(result[2].destination.url.absoluteString.hasSuffix("colorPair1.colorset/Contents.json")) XCTAssertTrue(result[3].destination.url.absoluteString.hasSuffix("colorPair2.colorset/Contents.json")) let content = result[0].data XCTAssertNotNil(content) try assertCodeEquals(content, """ \(header) import UIKit public extension UIColor { @objc static var colorPair1: UIColor { UIColor(named: #function)! } @objc static var colorPair2: UIColor { UIColor(named: #function)! } } """) } func testExport_with_assets_in_separate_bundle() throws { let output = XcodeColorsOutput(assetsColorsURL: colorsAssetCatalog, assetsInMainBundle: false, colorSwiftURL: colorsFile) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 4) XCTAssertTrue(result[0].destination.url.absoluteString.hasSuffix("Colors.swift")) XCTAssertTrue(result[1].destination.url.absoluteString.hasSuffix("Assets.xcassets/Colors/Contents.json")) XCTAssertTrue(result[2].destination.url.absoluteString.hasSuffix("colorPair1.colorset/Contents.json")) XCTAssertTrue(result[3].destination.url.absoluteString.hasSuffix("colorPair2.colorset/Contents.json")) let content = result[0].data XCTAssertNotNil(content) try assertCodeEquals(content, """ \(header) import UIKit private class BundleProvider { static let bundle = Bundle(for: BundleProvider.self) } public extension UIColor { static var colorPair1: UIColor { UIColor(named: #function, in: BundleProvider.bundle, compatibleWith: nil)! } static var colorPair2: UIColor { UIColor(named: #function, in: BundleProvider.bundle, compatibleWith: nil)! } } """) } func testExport_with_assets_in_swift_package() throws { let output = XcodeColorsOutput(assetsColorsURL: colorsAssetCatalog, assetsInMainBundle: false, assetsInSwiftPackage: true, colorSwiftURL: colorsFile) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 4) XCTAssertTrue(result[0].destination.url.absoluteString.hasSuffix("Colors.swift")) XCTAssertTrue(result[1].destination.url.absoluteString.hasSuffix("Assets.xcassets/Colors/Contents.json")) XCTAssertTrue(result[2].destination.url.absoluteString.hasSuffix("colorPair1.colorset/Contents.json")) XCTAssertTrue(result[3].destination.url.absoluteString.hasSuffix("colorPair2.colorset/Contents.json")) let content = result[0].data XCTAssertNotNil(content) try assertCodeEquals(content, """ \(header) import UIKit private class BundleProvider { static let bundle = Bundle.module } public extension UIColor { static var colorPair1: UIColor { UIColor(named: #function, in: BundleProvider.bundle, compatibleWith: nil)! } static var colorPair2: UIColor { UIColor(named: #function, in: BundleProvider.bundle, compatibleWith: nil)! } } """) } func testExport_swiftui() throws { let output = XcodeColorsOutput(assetsColorsURL: colorsAssetCatalog, assetsInMainBundle: true, colorSwiftURL: nil, swiftuiColorSwiftURL: colorsFile) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 4) XCTAssertTrue(result[0].destination.url.absoluteString.hasSuffix("Colors.swift")) XCTAssertTrue(result[1].destination.url.absoluteString.hasSuffix("Assets.xcassets/Colors/Contents.json")) XCTAssertTrue(result[2].destination.url.absoluteString.hasSuffix("colorPair1.colorset/Contents.json")) XCTAssertTrue(result[3].destination.url.absoluteString.hasSuffix("colorPair2.colorset/Contents.json")) let content = result[0].data try assertCodeEquals(content, """ \(header) import SwiftUI public extension Color { static var colorPair1: Color { Color(#function) } static var colorPair2: Color { Color(#function) } } """) } func testExport_swiftui_and_assets_in_swift_package() throws { let output = XcodeColorsOutput( assetsColorsURL: colorsAssetCatalog, assetsInMainBundle: false, assetsInSwiftPackage: true, colorSwiftURL: nil, swiftuiColorSwiftURL: colorsFile ) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair1, colorPair2]) XCTAssertEqual(result.count, 4) XCTAssertTrue(result[0].destination.url.absoluteString.hasSuffix("Colors.swift")) XCTAssertTrue(result[1].destination.url.absoluteString.hasSuffix("Assets.xcassets/Colors/Contents.json")) XCTAssertTrue(result[2].destination.url.absoluteString.hasSuffix("colorPair1.colorset/Contents.json")) XCTAssertTrue(result[3].destination.url.absoluteString.hasSuffix("colorPair2.colorset/Contents.json")) let content = result[0].data try assertCodeEquals(content, """ \(header) import SwiftUI private class BundleProvider { static let bundle = Bundle.module } public extension Color { static var colorPair1: Color { Color(#function, in: BundleProvider.bundle) } static var colorPair2: Color { Color(#function, in: BundleProvider.bundle) } } """) } func testExport_withProvidesNamespace() throws { let output = XcodeColorsOutput( assetsColorsURL: colorsAssetCatalog, assetsInMainBundle: true, colorSwiftURL: colorsFile, groupUsingNamespace: true ) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorPair3]) XCTAssertEqual(result.count, 4) XCTAssertTrue(result[0].destination.url.absoluteString.hasSuffix("Colors.swift")) XCTAssertTrue(result[1].destination.url.absoluteString.hasSuffix("Assets.xcassets/Colors/Contents.json")) XCTAssertTrue(result[2].destination.url.absoluteString.hasSuffix("background/Contents.json")) XCTAssertTrue(result[3].destination.url.absoluteString.hasSuffix("primary.colorset/Contents.json")) let content = result[0].data XCTAssertNotNil(content) try assertCodeEquals(content, """ \(header) import UIKit public extension UIColor { static var backgroundPrimary: UIColor { UIColor(named: "background/primary")! } } """) } func testExportWhenNameIsSwiftKeyword() throws { let output = XcodeColorsOutput(assetsColorsURL: nil, assetsInMainBundle: true, colorSwiftURL: colorsFile) let exporter = XcodeColorExporter(output: output) let result = try exporter.export(colorPairs: [colorWithKeyword]) XCTAssertEqual(result.count, 1) let content = result[0].data XCTAssertNotNil(content) try assertCodeEquals(content, """ \(header) import UIKit public extension UIColor { static var `class`: UIColor { UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) } } """) } } fileprivate func assertCodeEquals(_ data: Data?, _ referenceCode: String) throws { let data = try XCTUnwrap(data) let generatedCode = String(data: data, encoding: .utf8) XCTAssertNoDifference(generatedCode, referenceCode) }
37.613293
157
0.653253
4a10b2562c0f2773adf482a29126cc7fbc804884
1,316
import SwiftUI extension View { func addGravityMoving() -> some View { self.modifier(GravityMovingModifier()) } } struct GravityMovingModifier: ViewModifier { private var timer = Timer.publish(every: 1, on: RunLoop.main, in: .default).autoconnect() @State private var value: CGSize = .zero private func randomOffset() -> CGSize { let items = Array(-20...20) let x = items.randomElement() ?? 0 let y = items.randomElement() ?? 0 return CGSize(width: CGFloat(x), height: CGFloat(y)) } func body(content: Content) -> some View { content .modifier(GravityMovingEffect(offset: value)) .onReceive(timer) { _ in withAnimation(Animation.easeInOut(duration: 2)) { self.value = self.randomOffset() } } } } struct GravityMovingEffect: GeometryEffect { var offset: CGSize var animatableData: CGSize.AnimatableData { get { CGSize.AnimatableData(offset.width, offset.height) } set { offset = CGSize(width: newValue.first, height: newValue.second) } } func effectValue(size: CGSize) -> ProjectionTransform { return ProjectionTransform(CGAffineTransform(translationX: offset.width, y: offset.height)) } }
30.604651
99
0.62462
f4100d30816c713782084c7d07a5c70e78ed11b2
27,552
// // PolicyCardType.swift // SmartAILibrary // // Created by Michael Rommel on 29.01.20. // Copyright © 2020 Michael Rommel. All rights reserved. // import Foundation public enum PolicyCardSlotType { case military case economic case diplomatic case wildcard public static var all: [PolicyCardSlotType] = [ .military, .economic, .diplomatic, .wildcard ] func name() -> String { switch self { case .military: return "Military" case .economic: return "Economic" case .diplomatic: return "Diplomatic" case .wildcard: return "Wildcard" } } } // https://civilization.fandom.com/wiki/Policy_Cards_(Civ6) // swiftlint:disable type_body_length public enum PolicyCardType: Int, Codable { case slot // ancient case survey case godKing case discipline case urbanPlanning case ilkum case agoge case caravansaries case maritimeIndustries case maneuver case strategos case conscription case corvee case landSurveyors case colonization case inspiration case revelation case limitanei // classical case insulae case charismaticLeader case diplomaticLeague case literaryTradition case raid case veterancy case equestrianOrders case bastions case limes case naturalPhilosophy case scripture case praetorium // medieval case navalInfrastructure case navigation case feudalContract case serfdom case meritocracy case retainers case sack case professionalArmy case retinues case tradeConfederation case merchantConfederation case aesthetics case medinaQuarter case craftsmen case townCharters case travelingMerchants case chivalry case gothicArchitecture case civilPrestige // industrial // case nativeConquest // information public static var all: [PolicyCardType] { return [ // ancient .survey, .godKing, .discipline, .urbanPlanning, .ilkum, .agoge, .caravansaries, .maritimeIndustries, .maneuver, .strategos, .conscription, .corvee, .landSurveyors, .colonization, .inspiration, .revelation, .limitanei, // classical .insulae, .charismaticLeader, .diplomaticLeague, .literaryTradition, .raid, .veterancy, .equestrianOrders, .bastions, .limes, .naturalPhilosophy, .scripture, .praetorium, // medieval .navalInfrastructure, .navigation, .feudalContract, .serfdom, .meritocracy, .retainers, .sack, .professionalArmy, .retinues, .tradeConfederation, .merchantConfederation, .aesthetics, .medinaQuarter, .craftsmen, .townCharters, .travelingMerchants, .chivalry, .gothicArchitecture, .civilPrestige // information ] } public func name() -> String { return self.data().name } public func bonus() -> String { return self.data().bonus } public func slot() -> PolicyCardSlotType { return self.data().slot } public func required() -> CivicType { return self.data().required } // swiftlint:disable function_body_length private func data() -> PolicyCardTypeData { switch self { case .slot: return PolicyCardTypeData( name: "-", bonus: "-", slot: .wildcard, required: .none, obsolete: nil, replace: nil, flavours: [] ) case .survey: // https://civilization.fandom.com/wiki/Survey_(Civ6) return PolicyCardTypeData( name: "Survey", bonus: "Doubles experience for recon units.", slot: .military, required: .codeOfLaws, obsolete: .exploration, replace: nil, flavours: [Flavor(type: .recon, value: 5)] ) case .godKing: // https://civilization.fandom.com/wiki/God_King_(Civ6) return PolicyCardTypeData( name: "God King", bonus: "+1 Faith and +1 Gold in the Capital.", slot: .economic, required: .codeOfLaws, obsolete: .theology, replace: nil, flavours: [ Flavor(type: .religion, value: 3), Flavor(type: .gold, value: 2) ] ) case .discipline: // https://civilization.fandom.com/wiki/Discipline_(Civ6) return PolicyCardTypeData( name: "Discipline", bonus: "+5 Combat Strength when fighting Barbarians.", slot: .military, required: .codeOfLaws, obsolete: .colonialism, replace: nil, flavours: [ Flavor(type: .defense, value: 4), Flavor(type: .growth, value: 1) ] ) case .urbanPlanning: return PolicyCardTypeData( name: "Urban Planning", bonus: "+1 Production in all cities.", slot: .economic, required: .codeOfLaws, obsolete: .gamesAndRecreation, replace: nil, flavours: [ Flavor(type: .growth, value: 2), Flavor(type: .production, value: 3) ] ) case .ilkum: // https://civilization.fandom.com/wiki/Ilkum_(Civ6) return PolicyCardTypeData( name: "Ilkum", bonus: "+30% Production toward Builders.", slot: .economic, required: .craftsmanship, obsolete: .gamesAndRecreation, replace: nil, flavours: [ Flavor(type: .growth, value: 2), Flavor(type: .tileImprovement, value: 3) ] ) case .agoge: // https://civilization.fandom.com/wiki/Agoge_(Civ6) return PolicyCardTypeData( name: "Agoge", bonus: "+50% Production toward Ancient and Classical era melee, ranged units and anti-cavalry units.", slot: .military, required: .craftsmanship, obsolete: .feudalism, replace: nil, flavours: [ Flavor(type: .offense, value: 3), Flavor(type: .defense, value: 2) ] ) case .caravansaries: // https://civilization.fandom.com/wiki/Caravansaries_(Civ6) return PolicyCardTypeData( name: "Caravansaries", bonus: "+2 Gold from all Trade Routes.", slot: .economic, required: .foreignTrade, obsolete: .mercantilism, replace: nil, flavours: [Flavor(type: .gold, value: 5)] ) case .maritimeIndustries: // https://civilization.fandom.com/wiki/Maritime_Industries_(Civ6) return PolicyCardTypeData( name: "Maritime Industries", bonus: "+100% Production toward Ancient and Classical era naval units.", slot: .military, required: .foreignTrade, obsolete: .colonialism, replace: nil, flavours: [ Flavor(type: .navalGrowth, value: 3), Flavor(type: .naval, value: 2) ] ) case .maneuver: // https://civilization.fandom.com/wiki/Maneuver_(Civ6) return PolicyCardTypeData( name: "Maneuver", bonus: "+50% Production toward Ancient and Classical era heavy and light cavalry units.", slot: .military, required: .militaryTradition, obsolete: .divineRight, replace: nil, flavours: [ Flavor(type: .mobile, value: 4), Flavor(type: .offense, value: 1) ] ) case .strategos: // https://civilization.fandom.com/wiki/Strategos_(Civ6) return PolicyCardTypeData( name: "Strategos", bonus: "+2 Great General points per turn.", slot: .wildcard, required: .militaryTradition, obsolete: .scorchedEarth, replace: nil, flavours: [Flavor(type: .greatPeople, value: 5)] ) case .conscription: // https://civilization.fandom.com/wiki/Conscription_(Civ6) return PolicyCardTypeData( name: "Conscription", bonus: "Unit maintenance reduced by 1 Gold per turn, per unit.", slot: .military, required: .stateWorkforce, obsolete: .mobilization, replace: nil, flavours: [ Flavor(type: .offense, value: 4), Flavor(type: .gold, value: 1) ] ) case .corvee: // https://civilization.fandom.com/wiki/Corv%C3%A9e_(Civ6) return PolicyCardTypeData( name: "Corvee", bonus: "+15% Production toward Ancient and Classical wonders.", slot: .economic, required: .stateWorkforce, obsolete: .divineRight, replace: nil, flavours: [Flavor(type: .wonder, value: 5)] ) case .landSurveyors: // https://civilization.fandom.com/wiki/Land_Surveyors_(Civ6) return PolicyCardTypeData( name: "Land Surveyors", bonus: "Reduces the cost of purchasing a tile by 20%.", slot: .economic, required: .earlyEmpire, obsolete: .scorchedEarth, replace: nil, flavours: [ Flavor(type: .growth, value: 3), Flavor(type: .tileImprovement, value: 2) ] ) case .colonization: // https://civilization.fandom.com/wiki/Colonization_(Civ6) return PolicyCardTypeData( name: "Colonization", bonus: "+50% Production toward Settlers.", slot: .economic, required: .earlyEmpire, obsolete: .scorchedEarth, replace: nil, flavours: [Flavor(type: .growth, value: 5)] ) case .inspiration: // https://civilization.fandom.com/wiki/Inspiration_(Civ6) return PolicyCardTypeData( name: "Inspiration", bonus: "+2 Great Scientist points per turn.", slot: .wildcard, required: .mysticism, obsolete: .nuclearProgram, replace: nil, flavours: [ Flavor(type: .science, value: 2), Flavor(type: .greatPeople, value: 3) ] ) case .revelation: // https://civilization.fandom.com/wiki/Revelation_(Civ6) return PolicyCardTypeData( name: "Revelation", bonus: "+2 Great Prophet points per turn.", slot: .wildcard, required: .mysticism, obsolete: .humanism, replace: nil, flavours: [ Flavor(type: .religion, value: 2), Flavor(type: .greatPeople, value: 3) ] ) case .limitanei: // https://civilization.fandom.com/wiki/Limitanei_(Civ6) return PolicyCardTypeData( name: "Limitanei", bonus: "+2 Loyalty per turn for cities with a garrisoned unit.", slot: .military, required: .earlyEmpire, obsolete: nil, replace: nil, flavours: [Flavor(type: .growth, value: 5)] ) // classical case .insulae: // https://civilization.fandom.com/wiki/Insulae_(Civ6) return PolicyCardTypeData( name: "Insulae", bonus: "+1 Housing in all cities with at least 2 specialty districts.", slot: .economic, required: .gamesAndRecreation, obsolete: .medievalFaires, replace: nil, flavours: [Flavor(type: .growth, value: 3), Flavor(type: .tileImprovement, value: 2)] ) case .charismaticLeader: // https://civilization.fandom.com/wiki/Charismatic_Leader_(Civ6) return PolicyCardTypeData( name: "Charismatic Leader", bonus: "+2 Influence Points per turn toward earning city-state Envoys.", // # slot: .diplomatic, required: .politicalPhilosophy, obsolete: .totalitarianism, replace: nil, flavours: [] ) case .diplomaticLeague: // https://civilization.fandom.com/wiki/Diplomatic_League_(Civ6) return PolicyCardTypeData( name: "Diplomatic League", bonus: "The first Envoy you send to each city-state counts as two Envoys.", // # slot: .diplomatic, required: .politicalPhilosophy, obsolete: nil, replace: nil, flavours: [] ) case .literaryTradition: // https://civilization.fandom.com/wiki/Literary_Tradition_(Civ6) return PolicyCardTypeData( name: "Literary Tradition", bonus: "+2 Great Writer points per turn.", slot: .wildcard, required: .dramaAndPoetry, obsolete: nil, replace: nil, flavours: [] ) case .raid: // https://civilization.fandom.com/wiki/Raid_(Civ6) return PolicyCardTypeData( name: "Raid", bonus: "Yields gained from pillaging and coastal raids are +50%.", // # slot: .military, required: .militaryTraining, obsolete: .scorchedEarth, replace: nil, flavours: [] ) case .veterancy: // https://civilization.fandom.com/wiki/Veterancy_(Civ6) return PolicyCardTypeData( name: "Veterancy", bonus: "+30% Production toward Encampment and Harbor districts and buildings for those districts.", // # slot: .military, required: .militaryTraining, obsolete: nil, replace: nil, flavours: [] ) case .equestrianOrders: // https://civilization.fandom.com/wiki/Equestrian_Orders_(Civ6) return PolicyCardTypeData( name: "Equestrian Orders", bonus: "All improved Horses and Iron resources yield 1 additional resource per turn.", // # slot: .military, required: .militaryTraining, obsolete: nil, replace: nil, flavours: [] ) case .bastions: // https://civilization.fandom.com/wiki/Bastions_(Civ6) return PolicyCardTypeData( name: "Bastions", bonus: "+6 City Defense Strength. +5 City Ranged Strength.", slot: .military, required: .defensiveTactics, obsolete: .civilEngineering, replace: nil, flavours: [] ) case .limes: // https://civilization.fandom.com/wiki/Limes_(Civ6) return PolicyCardTypeData( name: "Limes", bonus: "+100% Production toward defensive buildings.", // # slot: .military, required: .defensiveTactics, obsolete: .totalitarianism, replace: nil, flavours: [] ) case .naturalPhilosophy: // https://civilization.fandom.com/wiki/Natural_Philosophy_(Civ6) return PolicyCardTypeData( name: "Natural Philosophy", bonus: "+100% Campus district adjacency bonuses.", // # slot: .economic, required: .recordedHistory, obsolete: .classStruggle, replace: nil, flavours: [] ) case .scripture: // https://civilization.fandom.com/wiki/Scripture_(Civ6) return PolicyCardTypeData( name: "Scripture", bonus: "+100% Holy Site district adjacency bonuses.", // # slot: .economic, required: .theology, obsolete: nil, replace: .godKing, flavours: [] ) case .praetorium: // https://civilization.fandom.com/wiki/Praetorium_(Civ6) return PolicyCardTypeData( name: "Praetorium", bonus: "Governors provide +2 Loyalty per turn to their city.", slot: .diplomatic, required: .recordedHistory, obsolete: .socialMedia, replace: nil, flavours: [Flavor(type: .growth, value: 4)] ) // medieval case .navalInfrastructure: // https://civilization.fandom.com/wiki/Naval_Infrastructure_(Civ6) return PolicyCardTypeData( name: "Naval Infrastructure", bonus: "+100% Harbor district adjacency bonus.", // # slot: .economic, required: .navalTradition, obsolete: .suffrage, replace: nil, flavours: [] ) case .navigation: // https://civilization.fandom.com/wiki/Navigation_(Civ6) return PolicyCardTypeData( name: "Navigation", bonus: "+2 Great Admiral Great Admiral points per turn.", slot: .wildcard, required: .navalTradition, obsolete: nil, replace: nil, flavours: [] ) case .feudalContract: // https://civilization.fandom.com/wiki/Feudal_Contract_(Civ6) return PolicyCardTypeData( name: "Feudal Contract", bonus: "+50% Production toward Ancient, Classical, Medieval and Renaissance era melee, " + // # "ranged and anti-cavalry units.", slot: .military, required: .feudalism, obsolete: .nationalism, replace: .agoge, flavours: [] ) case .serfdom: // https://civilization.fandom.com/wiki/Serfdom_(Civ6) return PolicyCardTypeData( name: "Serfdom", bonus: "Newly trained Builders gain 2 extra build actions.", slot: .economic, required: .feudalism, obsolete: .civilEngineering, replace: PolicyCardType.ilkum, flavours: [] ) case .meritocracy: // https://civilization.fandom.com/wiki/Meritocracy_(Civ6) return PolicyCardTypeData( name: "Meritocracy", bonus: "Each city receives +1 Culture for each specialty District it constructs.", // # slot: .economic, required: .civilService, obsolete: nil, replace: nil, flavours: [] ) case .retainers: // https://civilization.fandom.com/wiki/Retainers_(Civ6) return PolicyCardTypeData( name: "Retainers", bonus: "+1 Amenity for cities with a garrisoned unit.", // # slot: .military, required: .civilService, obsolete: .massMedia, replace: nil, flavours: [] ) case .sack: // https://civilization.fandom.com/wiki/Sack_(Civ6) return PolicyCardTypeData( name: "Sack", bonus: "Yields gained from pillaging are doubled for pillaging Districts.", // # slot: .military, required: .mercenaries, obsolete: .scorchedEarth, replace: nil, flavours: [] ) case .professionalArmy: // https://civilization.fandom.com/wiki/Professional_Army_(Civ6) return PolicyCardTypeData( name: "Professional Army", bonus: "50% Gold discount on all unit upgrades.", slot: .military, required: .mercenaries, obsolete: .urbanization, replace: nil, flavours: [] ) case .retinues: // https://civilization.fandom.com/wiki/Retinues_(Civ6) return PolicyCardTypeData( name: "Retinues", bonus: "50% resource discount on all unit upgrades.", // # slot: .military, required: .mercenaries, obsolete: .urbanization, replace: nil, flavours: [] ) case .tradeConfederation: // https://civilization.fandom.com/wiki/Trade_Confederation_(Civ6) return PolicyCardTypeData( name: "Trade Confederation", bonus: "+1 Culture and +1 Science from international Trade Routes.", slot: .economic, required: .mercenaries, obsolete: .capitalism, replace: nil, flavours: [] ) case .merchantConfederation: // https://civilization.fandom.com/wiki/Merchant_Confederation_(Civ6) return PolicyCardTypeData( name: "Merchant Confederation", bonus: "+1 Gold from each of your Envoys at city-states.", // # slot: .diplomatic, required: .medievalFaires, obsolete: nil, replace: nil, flavours: [] ) case .aesthetics: // https://civilization.fandom.com/wiki/Aesthetics_(Civ6) return PolicyCardTypeData( name: "Aesthetics", bonus: "+100% Theater Square district adjacency bonuses.", // # slot: .economic, required: .medievalFaires, obsolete: .professionalSports, replace: nil, flavours: [] ) case .medinaQuarter: // https://civilization.fandom.com/wiki/Medina_Quarter_(Civ6) return PolicyCardTypeData( name: "Medina Quarter", bonus: "+2 Housing in all cities with at least 3 specialty Districts.", // # slot: .economic, required: .medievalFaires, obsolete: .suffrage, replace: .insulae, flavours: [] ) case .craftsmen: // https://civilization.fandom.com/wiki/Craftsmen_(Civ6) return PolicyCardTypeData( name: "Craftsmen", bonus: "+100% Industrial Zone adjacency bonuses.", // # slot: .military, required: .guilds, obsolete: .classStruggle, replace: nil, flavours: [] ) case .townCharters: // https://civilization.fandom.com/wiki/Town_Charters_(Civ6) return PolicyCardTypeData( name: "Town Charters", bonus: "+100% Commercial Hub adjacency bonuses.", // # slot: .economic, required: .guilds, obsolete: .suffrage, replace: nil, flavours: [] ) case .travelingMerchants: // https://civilization.fandom.com/wiki/Traveling_Merchants_(Civ6) return PolicyCardTypeData( name: "Traveling Merchants", bonus: "+2 Great Merchant points per turn.", slot: .wildcard, required: .guilds, obsolete: .capitalism, replace: nil, flavours: [] ) case .chivalry: // https://civilization.fandom.com/wiki/Chivalry_(Civ6) return PolicyCardTypeData( name: "Chivalry", bonus: "+50% Production toward Industrial era and earlier heavy and light cavalry units.", // # slot: .military, required: .divineRight, obsolete: .totalitarianism, replace: nil, flavours: [] ) case .gothicArchitecture: // https://civilization.fandom.com/wiki/Gothic_Architecture_(Civ6) return PolicyCardTypeData( name: "Gothic Architecture", bonus: "+15% Production toward Ancient, Classical, Medieval and Renaissance wonders.", // # slot: .economic, required: .divineRight, obsolete: .civilEngineering, replace: nil, flavours: [] ) case .civilPrestige: // https://civilization.fandom.com/wiki/Civil_Prestige_(Civ6) return PolicyCardTypeData( name: "Civil Prestige", bonus: "Established Governors with at least 2 Promotions provide +1 Amenity and +2 Housing.", slot: .economic, required: .civilService, obsolete: nil, replace: nil, flavours: [] ) /* ... */ } } private struct PolicyCardTypeData { let name: String let bonus: String let slot: PolicyCardSlotType let required: CivicType let obsolete: CivicType? let replace: PolicyCardType? let flavours: [Flavor] } public func obsoleteCivic() -> CivicType? { return self.data().obsolete } public func replacePolicyCard() -> PolicyCardType? { return self.data().replace } func flavorValue(for flavor: FlavorType) -> Int { if let flavorOfTech = self.flavours().first(where: { $0.type == flavor }) { return flavorOfTech.value } return 0 } func flavours() -> [Flavor] { return self.data().flavours } }
34.613065
123
0.504936
f587e400b20fbc925fa08eb330fe160dcc07d0c8
257
// // ViewController.swift // Demo // // Created by John on 2019/12/13. // Copyright © 2019 MessageUI. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
16.0625
52
0.661479
4895b037ea5ab19fdb28d507976f02855d712e7d
338
// // Updatable.swift // MercadoPagoSDK // // Created by AUGUSTO COLLERONE ALFONSO on 3/9/17. // Copyright © 2017 MercadoPago. All rights reserved. // import Foundation @objc internal protocol Updatable { func updateCard(token: PXCardInformationForm?, paymentMethod: PXPaymentMethod) func setCornerRadius(radius: CGFloat) }
22.533333
82
0.745562
e523c382936fa634f15135a90bd8f6e8c0875182
2,069
import Foundation #if canImport(QuartzCore) import QuartzCore #endif class DisplayLink { static var currentTime: TimeInterval { #if canImport(QuartzCore) return CACurrentMediaTime() #else return NSDate().timeIntervalSinceReferenceDate #endif } #if os(iOS) || os(tvOS) private lazy var link = CADisplayLink(target: self, selector: #selector(displayLinkFired)) #else private var timeInterval: TimeInterval private var timer: Timer? { didSet { oldValue?.invalidate() } } #endif func start() { #if os(iOS) || os(tvOS) self.link.add(to: .main, forMode: .default) #else #endif self.isPaused = false } public var isPaused: Bool = true { didSet { #if os(iOS) || os(tvOS) self.link.isPaused = self.isPaused #else if !self.isPaused { self.timer = Timer.scheduledTimer(timeInterval: self.timeInterval, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats: true) } else if self.timer == nil { self.timer = nil } #endif } } public func invalidate() { #if os(iOS) || os(tvOS) self.link.invalidate() #else self.timer = nil #endif } #if os(iOS) || os(tvOS) @objc private func displayLinkFired(_: CADisplayLink) { if #available(iOS 10.0, tvOS 10.0, *) { self.onFire(self.link.targetTimestamp) } else { self.onFire(self.link.timestamp) } } #else @objc private func timerFired() { self.onFire(DisplayLink.currentTime) } #endif public var preferredFramesPerSecond: Int public var onFire: (TimeInterval) -> Void public init(preferredFramesPerSecond: Int = 0, onFire: @escaping ((TimeInterval) -> Void)) { self.preferredFramesPerSecond = preferredFramesPerSecond self.onFire = onFire #if os(iOS) || os(tvOS) if #available(iOS 10.0, tvOS 10.0, macCatalyst 13.0, *) { self.link.preferredFramesPerSecond = preferredFramesPerSecond } #else self.timeInterval = preferredFramesPerSecond == 0 ? 1 / 60 : 1 / TimeInterval(preferredFramesPerSecond) #endif } deinit { invalidate() } }
22.247312
153
0.675205
bf39288b0f2d34162a1c3650a6be25061df44e02
1,317
// RUN: %empty-directory(%t) // RUN: %target-build-swift -c -force-single-frontend-invocation -parse-as-library -emit-module -emit-module-path %t/PrintTestTypes.swiftmodule -o %t/PrintTestTypes.o %S/Inputs/PrintTestTypes.swift // RUN: %target-build-swift %s -Xlinker %t/PrintTestTypes.o -I %t -L %t -o %t/main // RUN: %target-run %t/main // REQUIRES: executable_test import StdlibUnittest import PrintTestTypes let PrintTests = TestSuite("PrintArray") PrintTests.test("Printable") { expectPrinted("[]", [Int]()) expectPrinted("[1]", [ 1 ]) expectPrinted("[1, 2]", [ 1, 2 ]) expectPrinted("[1, 2, 3]", [ 1, 2, 3 ]) expectPrinted("[\"foo\", \"bar\", \"bas\"]", ["foo", "bar", "bas"]) expectDebugPrinted("[\"foo\", \"bar\", \"bas\"]", ["foo", "bar", "bas"]) expectPrinted("[►1◀︎, ►2◀︎, ►3◀︎]", [StructPrintable(1), StructPrintable(2), StructPrintable(3)]) expectPrinted("[<10 20 30 40>, <50 60 70 80>]", [LargeStructPrintable(10, 20, 30, 40), LargeStructPrintable(50, 60, 70, 80)]) expectPrinted("[►1◀︎]", [StructDebugPrintable(1)]) expectPrinted("[►1◀︎, ►2◀︎, ►3◀︎]", [ClassPrintable(1), ClassPrintable(2), ClassPrintable(3)]) expectPrinted("[►1◀︎, ►2◀︎, ►3◀︎]", [ClassPrintable(1), ClassPrintable(2), ClassPrintable(3)] as Array<AnyObject>) } runAllTests()
34.657895
197
0.629461
69adb67197e4eba33bd5d516cbb26d5dcb6ab848
1,207
// // Solution217.swift // leetcode // // Created by 景生善 on 2021/8/20. // Copyright © 2021 peter. All rights reserved. // import Foundation class Solution217 { func containsDuplicate(_ nums: [Int]) -> Bool { var dict = [Int:Int]() for i in 0 ..< nums.count { if dict[nums[i]] != nil { return true } else { dict[nums[i]] = nums[i]; } } return false } func isHappy(_ n: Int) -> Bool { var repeatList = [Int]() return check(n, &repeatList) } func check(_ n: Int, _ repeatList: inout [Int]) -> Bool { if n == 1 { return true } repeatList.append(n) let sepate = separt(n) var sum = 0 for i in sepate { sum += i*i } if repeatList.contains(sum) { return false } return check(sum, &repeatList) } func separt(_ n: Int) -> [Int] { var result = [Int]() var m = n repeat { result.append(m % 10) m = m / 10 } while (m > 0) return result } }
20.810345
61
0.439105
d5d9c26064adae952a0195fce56fd28327c3bed3
3,077
// // SelectionViewController.swift // Project30 // // Created by Hudzilla on 26/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // // The images used in this app are blurry copies of images used in my // Mythology app. As keen as I am to help you learn, I have my limits :) import UIKit class SelectionViewController: UITableViewController { var items = [String]() // this is the array that will store the filenames to load var viewControllers = [UIViewController]() // create a cache of the detail view controllers for faster loading var dirty = false override func viewDidLoad() { super.viewDidLoad() title = "Select-a-Greek" tableView.rowHeight = 250 tableView.separatorStyle = .None // load all the JPEGs into our array let fm = NSFileManager.defaultManager() let tempItems = fm.contentsOfDirectoryAtPath(NSBundle.mainBundle().resourcePath!, error: nil) as! [String] for item in tempItems { if item.pathExtension == "jpg" { items.append(item) } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if dirty { // we've been marked as needing a counter reload, so reload the whole table tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell") // find the image for this cell, and load its thumbnail let currentImage = items[indexPath.row] let imageRootName = currentImage.stringByDeletingPathExtension let path = NSBundle.mainBundle().pathForResource(imageRootName, ofType: "png")! cell.imageView!.image = UIImage(contentsOfFile: path) // give the images a nice shadow to make them look a bit more dramatic cell.imageView!.layer.shadowColor = UIColor.blackColor().CGColor cell.imageView!.layer.shadowOpacity = 1 cell.imageView!.layer.shadowRadius = 10 // each image stores how often it's been tapped let defaults = NSUserDefaults.standardUserDefaults() cell.textLabel!.text = "\(defaults.integerForKey(currentImage))" return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = ImageViewController() vc.image = items[indexPath.row] vc.owner = self // mark us as not needing a counter reload when we return dirty = false // add to our view controller cache and show viewControllers.append(vc) navigationController!.pushViewController(vc, animated: true) } }
31.080808
118
0.723107
76317688f35c4b64b84e12f827a5f528068413bd
7,210
// // DeckCreateCollectionView.swift // Presentation // // Created by nakandakari on 2020/08/30. // Copyright © 2020 nakandakari. All rights reserved. // import Domain import UIKit protocol DeckCreateListViewDelegate: AnyObject { func didUpdateSelectedCardList(selectedCardList: [CardModel]) } final class DeckCreateListView: UIView { let maxCardCountPerDeck = 8 let itemsPerRow: Int = 4 private var cardList: [CardModel] = [] private var selectedCardList: [CardModel] = [] @IBOutlet weak private var deckCardCollectionView: UICollectionView! { willSet { newValue.delegate = self newValue.dataSource = self newValue.delaysContentTouches = false newValue.register(DeckCreateListCell.nib, forCellWithReuseIdentifier: DeckCreateListCell.className) } } @IBOutlet weak private var indicator: UIActivityIndicatorView! override init(frame: CGRect) { super.init(frame: frame) self.initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } private func initialize() { self.loadXib() } private var willReloadIndexPathList: [IndexPath] = [] weak var delegate: DeckCreateListViewDelegate? } // MARK: - Setup extension DeckCreateListView { func setup(cardList: [CardModel], selectedCardList: [CardModel]) { self.cardList = cardList self.selectedCardList = selectedCardList self.deckCardCollectionView.reloadData() } } // MARK: - Clear/Remove SelectedCard extension DeckCreateListView { func clearSelectedCardList() { self.selectedCardList = [] self.deckCardCollectionView.reloadData() } func removeSelectedCard(_ selectedCard: CardModel) { guard let index = self.selectedCardList.firstIndex(where: { $0.id == selectedCard.id }) else { return } self.selectedCardList.remove(at: index) self.deckCardCollectionView.reloadData() } } // MARK: - UICollectionViewDataSource extension DeckCreateListView: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { let section = ceil(Double(cardList.count) / Double(self.itemsPerRow)) return Int(section) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.itemsPerRow } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DeckCreateListCell.className, for: indexPath) as! DeckCreateListCell let cardIndex = self.cardIndex(from: indexPath) if cardIndex < 0 { cell.isHidden = true return cell } let cardData = self.cardList[cardIndex] cell.setup(card: cardData, selectedNumber: self.selectedCardNumber(indexPath: indexPath)) cell.isHidden = false cell.delegate = self return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DeckCreateListCell.className, for: indexPath) as! DeckCreateListCell let cardIndex = self.cardIndex(from: indexPath) if cardIndex < 0 { return } // already selected, do deselct if let selectedIndex = self.selectedCardList.firstIndex(where: { $0.id == self.cardList[cardIndex].id }) { cell.deselect() self.selectedCardList.remove(at: selectedIndex) self.willReloadIndexPathList = self.indexPathList(from: self.selectedCardList) self.willReloadIndexPathList.append(indexPath) } else { if self.selectedCardList.count >= self.maxCardCountPerDeck { return } self.selectedCardList.append(self.cardList[cardIndex]) cell.select(selectedNumber: self.selectedCardList.count) self.willReloadIndexPathList = self.indexPathList(from: self.selectedCardList) } SoundManager.shared.playSoundEffect(.selectCell) self.delegate?.didUpdateSelectedCardList(selectedCardList: self.selectedCardList) } private func selectedCardNumber(indexPath: IndexPath) -> Int { let cardIndex = self.cardIndex(from: indexPath) if cardIndex < 0 { return 0 } if let index = self.selectedCardList.firstIndex(where: { $0.id == self.cardList[cardIndex].id }) { return index + 1 } return 0 } private func selectedIndexPathListToCardList(_ selectedIndexPathList: [IndexPath]) -> [CardModel] { return selectedIndexPathList.map { self.cardList[($0.section * self.itemsPerRow) + $0.row] } } private func cardIndex(from indexPath: IndexPath) -> Int { let cardIndex = indexPath.section * self.itemsPerRow + indexPath.row if self.cardList.count <= cardIndex { return -1 } return cardIndex } private func indexPath(from card: CardModel) -> IndexPath? { guard let cardIndex = self.cardList.firstIndex(where: { $0.id == card.id }) else { return nil } let section = Int(floor(Double(cardIndex) / Double(self.itemsPerRow))) let row = cardIndex % self.itemsPerRow return IndexPath(row: row, section: section) } private func indexPathList(from cards: [CardModel]) -> [IndexPath] { let indexPathList = cards.compactMap { self.indexPath(from: $0) } return indexPathList } } // MARK: - UICollectionViewDelegateFlowLayout extension DeckCreateListView: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return self.resizeWithRatio(defaultCellSize: DeckCreateListCell.CellSize) } private func resizeWithRatio(defaultCellSize: CGSize) -> CGSize { let sideMargin: CGFloat = 2 * 2 let cellSpacing: CGFloat = 2 * CGFloat(self.itemsPerRow - 1) let cellWidth: CGFloat = (self.deckCardCollectionView.bounds.width - sideMargin - cellSpacing) / CGFloat(self.itemsPerRow) let ratio: CGFloat = cellWidth / defaultCellSize.width let cellHeight: CGFloat = defaultCellSize.height * ratio return CGSize(width: cellWidth, height: cellHeight) } } // MARK: - HoverCollectionViewCellDelegate extension DeckCreateListView: HoverCollectionViewCellDelegate { func didFinishTapAnimation() { self.deckCardCollectionView.reloadItems(at: self.willReloadIndexPathList) self.willReloadIndexPathList = [] } } // MARK: - Indicator extension DeckCreateListView { func showLoading() { self.indicator.isHidden = false self.indicator.startAnimating() } func hideLoading() { self.indicator.isHidden = true self.indicator.stopAnimating() } }
33.225806
160
0.679334
0849506a42ccc21debbec440d3808341a4c60ac5
314
import Foundation import UIKit import CommonClient public class UI: Kotlinx_coroutines_core_nativeCoroutineDispatcher { override public func dispatch(context: KotlinCoroutineContext, block: Kotlinx_coroutines_core_nativeRunnable) { DispatchQueue.main.async { block.run() } } }
26.166667
115
0.748408
5db24eea14ea89b1dc700eac3e02e40d19c022a9
4,631
// // EventkManager.swift // inviti // // Created by Hannah.C on 20.05.21. // import Foundation import Firebase import FirebaseFirestoreSwift import JKCalendar class EventManager { static let shared = EventManager() lazy var db = Firestore.firestore() var userUID = UserDefaults.standard.string(forKey: UserDefaults.Keys.uid.rawValue) ?? "" func fetchEvents(completion: @escaping (Result<[Event], Error>) -> Void) { db.collection("events") .order(by: "date", descending: false) .getDocuments { querySnapshot, error in if let error = error { completion(.failure(error)) } else { var events = [Event]() for document in querySnapshot!.documents { do { if let event = try document.data(as: Event.self, decoder: Firestore.Decoder()) { events.append(event) } } catch { completion(.failure(error)) } } completion(.success(events)) } } } // User 下面的 subcollection func fetchSubEvents(completion: @escaping (Result<[Event], Error>) -> Void) { self.db.collection("users") .document(self.userUID) .collection("events") .order(by: "startTime", descending: false) .getDocuments { querySnapshot, error in if let error = error { completion(.failure(error)) } else { var events = [Event]() for document in querySnapshot!.documents { do { if let event = try document.data(as: Event.self, decoder: Firestore.Decoder()) { events.append(event) } } catch { completion(.failure(error)) } } completion(.success(events)) } } } func createEvent(event: inout Event, completion: @escaping (Result<String, Error>) -> Void) { let document = db.collection("users") .document(userUID) .collection("events") .document() event.id = document.documentID document.setData(event.toDict) { error in if let error = error { completion(.failure(error)) } else { completion(.success(document.documentID)) } } } func createParticipantsEvent(peopleID: [String], event: inout Event, completion: @escaping (Result<String, Error>) -> Void) { for personID in peopleID { let document = db.collection("users") .document(personID) .collection("events") .document() event.id = document.documentID document.setData(event.toDict) { error in if let error = error { completion(.failure(error)) } else { completion(.success(document.documentID)) } } } } func deleteEvent(eventID: String, completion: @escaping (Result<String, Error>) -> Void) { db.collection("users") .document(userUID) .collection("events") .document(eventID) .delete { error in if let error = error { completion(.failure(error)) } else { completion(.success(eventID)) print("\(eventID) has been deleted!") } } } }
29.877419
129
0.398186
46b96b5d1cade29f8887ffbde20f3e67c7e308ee
231
// 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 f<H { class c { { { } } typealias f = g { } let g = c( )
15.4
87
0.688312
d61766701505665083b56fb9b8951222eb01a1e5
2,680
// // MarginAdjustable+Animation.swift // SwiftMessages // // Created by Ali Fakih on 8/1/17. // Copyright © 2018 Fakiho. All rights reserved. // import UIKit public extension MarginAdjustable where Self: UIView { public func defaultMarginAdjustment(context: AnimationContext) -> UIEdgeInsets { return UIEdgeInsets(top: topAdjustment(context: context), left: 0, bottom: bottomAdjustment(context: context), right: 0) } private func topAdjustment(context: AnimationContext) -> CGFloat { var top: CGFloat = 0 if !context.safeZoneConflicts.isDisjoint(with: [.sensorNotch, .statusBar]) { #if SWIFTMESSAGES_APP_EXTENSIONS let application: UIApplication? = nil #else let application: UIApplication? = UIApplication.shared #endif if #available(iOS 11, *) { do { // To accommodate future safe areas, using a linear formula based on // two data points: // iPhone 8 - 20pt top safe area needs 0pt adjustment // iPhone X - 44pt top safe area needs -6pt adjustment top -= 6 * (safeAreaInsets.top - 20) / (44 - 20) } top += safeAreaTopOffset } else if let app = application, app.statusBarOrientation == .portrait || app.statusBarOrientation == .portraitUpsideDown { let frameInWindow = convert(bounds, to: window) if frameInWindow.minY == 0 { top += statusBarOffset } } } else if #available(iOS 11, *), !context.safeZoneConflicts.isDisjoint(with: .overStatusBar) { top -= safeAreaInsets.top } return top } private func bottomAdjustment(context: AnimationContext) -> CGFloat { var bottom: CGFloat = 0 if !context.safeZoneConflicts.isDisjoint(with: [.homeIndicator]) { if #available(iOS 11, *), safeAreaInsets.bottom > 0 { do { // This adjustment was added to fix a layout issue with iPhone X in // landscape mode. Using a linear formula based on two data points to help // future proof against future safe areas: // iPhone X portrait: 34pt bottom safe area needs 0pt adjustment // iPhone X landscape: 21pt bottom safe area needs 12pt adjustment bottom -= 12 * (safeAreaInsets.bottom - 34) / (34 - 21) } bottom += safeAreaBottomOffset } } return bottom } }
41.875
135
0.571642
9c488a117c6232bb80fa6b1a327249f1cb36c5ff
5,289
// // LookupUsersCloudKitOperation.swift // Resolve // // Created by David Mitchell // Copyright © 2021 The App Studio LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #if canImport(Contacts) import Foundation import CloudKit import CoreResolve import Contacts internal final class LookupUsersCloudKitOperation: CloudKitGroupOperation { private var cloudOperation: CKOperation? public let contacts: [CNContact] public private(set) var userInfos = Set<CloudUserInfo>() public required init(with workflowContext: CloudKitContext, contacts: [CNContact]) { self.contacts = contacts super.init(with: workflowContext) } public override func cancel() { cloudOperation?.cancel() super.cancel() } public override func finish(withError error: Error) { switch error { case let cloudKitError as CKError where cloudKitError.code == CKError.requestRateLimited: guard let retryAfterDuration = cloudKitError.errorUserInfo[CKErrorRetryAfterKey] as? TimeInterval else { workflowContext.logger.log(.error, "Unexpected error without a retryAfter value: %{public}@", cloudKitError.localizedDescription) super.finish(withError: cloudKitError) return } let retryAfter = Date(timeIntervalSinceNow: retryAfterDuration) super.finish(withError: CloudKitError.cloudBusy(retryAfter)) default: super.finish(withError: error) } } public override func main() { let emailAddresses: [String] = contacts.flatMap { contact in return contact.emailAddresses.map { String($0.value) } } let userRecordIDs: [CKRecord.ID] if let userRecordID = workflowContext.currentUserRecordID { userRecordIDs = [userRecordID] } else { userRecordIDs = [] } let operation = configuredOperation(emailAddresses: emailAddresses, userRecordIDs: userRecordIDs) operation.setOperationQuality(from: self) cloudOperation = operation workflowContext.cloudContainer.add(operation) } #if os(watchOS) || targetEnvironment(macCatalyst) private func configuredOperation(emailAddresses: [String], userRecordIDs: [CKRecord.ID]) -> CKOperation { let operation = CKDiscoverUserIdentitiesOperation(userIdentityLookupInfos: lookupInfos(emailAddresses: emailAddresses, userRecordIDs: userRecordIDs)) operation.userIdentityDiscoveredBlock = userIdentityResponseHandler operation.discoverUserIdentitiesCompletionBlock = userIdentitiesCompletedResponseHandler return operation } #elseif !os(tvOS) private func configuredOperation(emailAddresses: [String], userRecordIDs: [CKRecord.ID]) -> CKOperation { guard #available(iOS 10.0, macOS 10.12, watchOS 3.0, *) else { let operation = CKDiscoverUserInfosOperation(emailAddresses: emailAddresses, userRecordIDs: userRecordIDs) operation.discoverUserInfosCompletionBlock = discoveredUsersResponseHandler return operation } let operation = CKDiscoverUserIdentitiesOperation(userIdentityLookupInfos: lookupInfos(emailAddresses: emailAddresses, userRecordIDs: userRecordIDs)) operation.userIdentityDiscoveredBlock = userIdentityResponseHandler operation.discoverUserIdentitiesCompletionBlock = userIdentitiesCompletedResponseHandler return operation } @available(macOS, deprecated: 10.12) private func discoveredUsersResponseHandler(_ emailsToUserInfos: [String : CKDiscoveredUserInfo]?, _ userRecordIDsToUserInfos: [CKRecord.ID : CKDiscoveredUserInfo]?, _ operationError: Error?) { if let error = error { finish(withError: error) } else { if let emailsToUserInfos = emailsToUserInfos { let mappedUserInfos = emailsToUserInfos.compactMap { CloudUserInfo(discoveredUserInfo: $0.value) } self.userInfos.formUnion(mappedUserInfos) } if let userRecordIDsToUserInfos = userRecordIDsToUserInfos { let mappedUserInfos = userRecordIDsToUserInfos.compactMap { CloudUserInfo(discoveredUserInfo: $0.value) } self.userInfos.formUnion(mappedUserInfos) } finish() } } #endif @available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) private func lookupInfos(emailAddresses: [String], userRecordIDs: [CKRecord.ID]) -> [CKUserIdentity.LookupInfo] { return emailAddresses.map { emailAddress in return CKUserIdentity.LookupInfo(emailAddress: emailAddress) } + userRecordIDs.map { userRecordID in return CKUserIdentity.LookupInfo(userRecordID: userRecordID) } } @available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) private func userIdentityResponseHandler(_ userIdentity: CKUserIdentity, _ lookupInfo: CKUserIdentity.LookupInfo) { guard let userInfo = CloudUserInfo(userIdentity: userIdentity) else { return } userInfos.insert(userInfo) } private func userIdentitiesCompletedResponseHandler(_ error: Error?) { if let error = error { finish(withError: error) } else { finish() } } } #endif
36.729167
194
0.774438
1d83d6294f95c935682b378c23ee68051438b33f
651
// // TableRefresh+Rx.swift // ZhongHuiNong // // Created by Andylau on 2019/1/22. // Copyright © 2019 Andylau. All rights reserved. // import Foundation import RxSwift import RxCocoa //import KafkaRefresh // //extension Reactive where Base: KafkaRefreshControl { // // public var isAnimating: Binder<Bool> { // return Binder(self.base) { refreshControl, active in // // debugPrints("刷新是否结束---\(active)") // // if active { // refreshControl.beginRefreshing() // } else { // refreshControl.endRefreshing() // } // } // } //}
22.448276
62
0.554531
dbafd5285f23a33c5e2740a7b00a0ce1349d5c7f
799
// // ViewController.swift // Cocoapods-Example // // Created by Soeng Saravit on 12/3/18. // Copyright © 2018 Soeng Saravit. All rights reserved. // import UIKit import SVProgressHUD class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. SVProgressHUD.setBackgroundColor(UIColor.black) SVProgressHUD.setBorderColor(UIColor.white) SVProgressHUD.setForegroundColor(UIColor.white) SVProgressHUD.show() Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(shopSVProgressHUD), userInfo: nil, repeats: false) } @objc func shopSVProgressHUD() { SVProgressHUD.dismiss() } }
25.774194
130
0.68836
d68942624d7a529f5ea61acd8a091613e0378aea
767
import UIKit import XCTest import APAvatarImageView class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.566667
111
0.608866
2313bd76b2f0ff1dbe0aab7a5893efa40c5655b9
228
// // FunctionA.swift // MyStaticLib // // Created by Anurag Ajwani on 16/03/2020. // Copyright © 2020 Anurag Ajwani. All rights reserved. // import Foundation public func functionA() { print("hello from functionA") }
16.285714
56
0.684211
ef6f6bfffa403f34e68964601552e9a8c8634469
513
// // AuthCredentials.swift // UpperQuizz // // Created by Emanuel Flores Martínez on 15/09/21. // import Foundation struct LoginCredentials: Encodable { let correo: String let contrasena: String } struct RegisterCredentials: Encodable { let nombre: String? let apellidos: String? let correo: String let contrasena: String } enum AuthError: Error { case networkError(message: String) case userAlreadyCreated(message: String) case incorrectCredentials(message: String) }
19
51
0.719298
18dafd48ad90f318c2353b8c8912146b0fa007d4
2,671
// // Github.swift // Escape // // Created by Aly Ezz on 10/8/19. // import Foundation import SwiftCLI import SwiftShell import FileUtils import SynchronousNetworking class Instabug { enum InstabugError: Error { case markdownToHTMLFailed case publishfailed } static let token = ProcessInfo.processInfo.environment["DASHBOARD_TOKEN"]! /** Updates the changelog on the dashboard */ static func publishToDashboard(repoAt repository: RepositoryName, versionFrom versionPath: VersionFrom, forTargetOS targetOs: TargetOS, withVersionNumber versionNumber: String?) throws { let version: String = versionNumber ?? Helpers.getVersion(versionFrom: versionPath, omitPrefix: true) let changeLog = Helpers.getChangelog() // Releases as bullet points seperated by line breaks let markdownChangelog = changeLog.joined(separator: "\n") // Converting markdown to HTML for dashboard changelog guard let dashboardChangelogs = markdownChangelog.markdownToHTML else { throw InstabugError.markdownToHTMLFailed } let dashChangelog = String(dashboardChangelogs.filter { !"\n".contains($0) }) var dashboardChangelog = "" for char in dashChangelog { if (char == "\"") { dashboardChangelog += "\\" } dashboardChangelog += String(char) } // Getting today's date to be published on the dashboard let date = Date() let formatter = DateFormatter() formatter.dateFormat = "MMM dd yyyy" let today = formatter.string(from: date) let networking = SynchronousNetworking(baseUrl: URL(string: "https://api.instabug.com/api/internal/")!) let changeLogJson: [String : Any] = ["version": version, "release_date": today, "target_os": targetOs.rawValue, "sdk_changes": dashboardChangelog] as [String : Any] let parameters: [String : Any] = ["token": token, "change_log": changeLogJson, "sdk_remote_url": "\(Constants.githubBaseRepo)/\(repository.rawValue)", "sample_app_remote_url": "\(Constants.githubBaseRepo)/\(repository.rawValue)/tree/master"] let headers = ["Content-Type": "application/json"] let networkResponse = networking.postSynchronously(path: "change_logs", parameters: parameters, headers: headers) if (networkResponse.error != nil || !(networkResponse.response!.statusCode == 201 || networkResponse.response!.statusCode == 200)) { print(networkResponse) throw InstabugError.publishfailed } } }
40.469697
249
0.657432
e9c69f8b056726b8593e5c482090debe7fbb8457
6,900
// // OmetriaEvent.swift // Ometria // // Created by Cata on 7/22/20. // Copyright © 2020 Cata. All rights reserved. // import Foundation import UIKit enum OmetriaEventType: String, Codable, CaseIterable { // MARK: Product related event types case basketUpdated case basketViewed case checkoutStarted case orderCompleted case productListingViewed case productViewed case wishlistAddedTo case wishlistRemovedFrom // MARK: Application related event types case appInstalled case appLaunched case appBackgrounded case appForegrounded case homeScreenViewed case screenViewedAutomatic case screenViewedExplicit case profileIdentified case profileDeidentified // MARK: Notification related event types case pushTokenRefreshed case notificationReceived case notificationInteracted case permissionsUpdate // MARK: Other event types case deepLinkOpened case custom = "customEvent" case errorOccurred } class OmetriaEvent: CustomDebugStringConvertible, Codable { var eventId: String var appId = Bundle.main.bundleIdentifier ?? "unknown" var installationId = OmetriaDefaults.installationID ?? "unknown" var appVersion: String? var appBuildNumber: String? var sdkVersion: String var sdkVersionRN: String? var platform = UIDevice.current.systemName var osVersion = UIDevice.current.systemVersion var deviceManufacturer = "Apple" var deviceModel = UIDevice.current.model var timestampOccurred = Date() var isBeingFlushed = false var eventType: OmetriaEventType var data: [String: Any] = [:] enum CodingKeys: String, CodingKey { case eventId case appId case installationId case appVersion case appBuildNumber case sdkVersion case sdkVersionRN case platform case osVersion case deviceManufacturer case deviceModel case dtOccurred case eventType = "type" case data } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) eventId = try values.decode(String.self, forKey: .eventId) appId = try values.decode(String.self, forKey: .appId) installationId = try values.decode(String.self, forKey: .installationId) appVersion = try values.decode(String.self, forKey: .appVersion) appBuildNumber = try values.decode(String.self, forKey: .appBuildNumber) sdkVersion = try values.decode(String.self, forKey: .sdkVersion) sdkVersionRN = try values.decode(String.self, forKey: .sdkVersionRN) platform = try values.decode(String.self, forKey: .platform) osVersion = try values.decode(String.self, forKey: .osVersion) deviceManufacturer = try values.decode(String.self, forKey: .deviceManufacturer) deviceModel = try values.decode(String.self, forKey: .deviceModel) timestampOccurred = try values.decode(Date.self, forKey: .dtOccurred) eventType = try values.decode(OmetriaEventType.self, forKey: .eventType) if values.contains(.data), let jsonData = try? values.decode(Data.self, forKey: .data) { data = (try? JSONSerialization.jsonObject(with: jsonData) as? [String : Any]) ?? [String:Any]() } else { data = [String:Any]() } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if !data.isEmpty { let jsonData = try JSONSerialization.data(withJSONObject: data) try container.encode(jsonData, forKey: .data) } try container.encode(eventId, forKey: .eventId) try container.encode(appId, forKey: .appId) try container.encode(installationId, forKey: .installationId) try container.encode(appVersion, forKey: .appVersion) try container.encode(appBuildNumber, forKey: .appBuildNumber) try container.encode(sdkVersion, forKey: .sdkVersion) try container.encode(sdkVersionRN, forKey: .sdkVersionRN) try container.encode(platform, forKey: .platform) try container.encode(osVersion, forKey: .osVersion) try container.encode(deviceManufacturer, forKey: .deviceManufacturer) try container.encode(deviceModel, forKey: .deviceModel) try container.encode(timestampOccurred, forKey: .dtOccurred) try container.encode(eventType, forKey: .eventType) } init(eventType: OmetriaEventType, data: [String: Any]) { self.eventId = UUID().uuidString self.eventType = eventType self.data = data let infoDict = Bundle.main.infoDictionary if let infoDict = infoDict { appBuildNumber = infoDict["CFBundleVersion"] as? String appVersion = infoDict["CFBundleShortVersionString"] as? String } sdkVersion = Constants.sdkVersion sdkVersionRN = OmetriaDefaults.sdkVersionRN } // MARK: - CustomDebugStringConvertible var debugDescription: String { return "'\(eventType.rawValue)'\n" + " data: \(data)\n" } // MARK: - Dictionary var baseDictionary: [String: Any]? { let encoder = JSONEncoder.iso8601DateJSONEncoder guard let data = try? encoder.encode(self) else { return nil } let dictionary = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] return dictionary?.filter({ ![.data, .eventId, .eventType, .dtOccurred].contains(CodingKeys(rawValue:$0.key)) }) } var dictionary: [String: Any]? { let encoder = JSONEncoder.iso8601DateJSONEncoder guard let encodedObject = try? encoder.encode(self) else { return nil } var dictionary = try? JSONSerialization.jsonObject(with: encodedObject, options: .allowFragments) as? [String: Any] if data.count != 0 { dictionary?[CodingKeys.data.rawValue] = data } return dictionary?.filter({ [.data, .eventId, .eventType, .dtOccurred].contains(CodingKeys(rawValue:$0.key)) }) } // MARK: - Batching Hash var commonInfoHash: Int { var hasher = Hasher() hasher.combine(appId) hasher.combine(installationId) hasher.combine(appVersion) hasher.combine(appBuildNumber) hasher.combine(sdkVersion) hasher.combine(platform) hasher.combine(osVersion) hasher.combine(deviceManufacturer) hasher.combine(deviceModel) let hash = hasher.finalize() return hash } }
34.673367
123
0.650725
8772ae4f73b1c2143859404da23938d0a9f9d479
8,671
// // VersaPlayerView.swift // VersaPlayerView Demo // // Created by Jose Quintero on 10/11/18. // Copyright © 2018 Quasar. All rights reserved. // #if os(macOS) import Cocoa #else import UIKit #endif import CoreMedia import AVFoundation import AVKit #if os(macOS) public typealias View = NSView #else public typealias View = UIView #endif #if os(iOS) public typealias PIPProtocol = AVPictureInPictureControllerDelegate #else public protocol PIPProtocol {} #endif open class VersaPlayerView: View, PIPProtocol { deinit { player.replaceCurrentItem(with: nil) } /// VersaPlayer extension dictionary public var extensions: [String: VersaPlayerExtension] = [:] /// AVPlayer used in VersaPlayer implementation public var player: VersaPlayer! /// VersaPlayerControls instance being used to display controls public var controls: VersaPlayerControls? /// VersaPlayerRenderingView instance public var renderingView: VersaPlayerRenderingView! /// VersaPlayerPlaybackDelegate instance public weak var playbackDelegate: VersaPlayerPlaybackDelegate? /// VersaPlayerDecryptionDelegate instance to be used only when a VPlayer item with isEncrypted = true is passed public weak var decryptionDelegate: VersaPlayerDecryptionDelegate? /// VersaPlayer initial container private weak var nonFullscreenContainer: View! #if os(iOS) /// AVPictureInPictureController instance public var pipController: AVPictureInPictureController? #endif /// Whether player is prepared public var ready: Bool = false /// Whether it should autoplay when adding a VPlayerItem public var autoplay: Bool = true /// Whether Player is currently playing public var isPlaying: Bool = false /// Whether Player is seeking time public var isSeeking: Bool = false /// Whether Player is presented in Fullscreen public var isFullscreenModeEnabled: Bool = false /// Whether PIP Mode is enabled via pipController public var isPipModeEnabled: Bool = false #if os(macOS) open override var wantsLayer: Bool { get { return true } set { } } #endif /// Whether Player is Fast Forwarding public var isForwarding: Bool { return player.rate > 1 } /// Whether Player is Rewinding public var isRewinding: Bool { return player.rate < 0 } public override init(frame: CGRect) { super.init(frame: frame) prepare() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /// VersaPlayerControls instance to display controls in player, using VersaPlayerGestureRecieverView instance /// to handle gestures /// /// - Parameters: /// - controls: VersaPlayerControls instance used to display controls /// - gestureReciever: Optional gesture reciever view to be used to recieve gestures public func use(controls: VersaPlayerControls, with gestureReciever: VersaPlayerGestureRecieverView? = nil) { self.controls = controls let coordinator = VersaPlayerControlsCoordinator() coordinator.player = self coordinator.controls = controls coordinator.gestureReciever = gestureReciever controls.controlsCoordinator = coordinator #if os(macOS) addSubview(coordinator, positioned: NSWindow.OrderingMode.above, relativeTo: renderingView) #else addSubview(coordinator) #endif } /// Update controls to specified time /// /// - Parameters: /// - time: Time to be updated to public func updateControls(toTime time: CMTime) { controls?.timeDidChange(toTime: time) } /// Add a VersaPlayerExtension instance to the current player /// /// - Parameters: /// - ext: The instance of the extension. /// - name: The name of the extension. open func addExtension(extension ext: VersaPlayerExtension, with name: String) { ext.player = self ext.prepare() extensions[name] = ext } /// Retrieves the instance of the VersaPlayerExtension with the name given /// /// - Parameters: /// - name: The name of the extension. open func getExtension(with name: String) -> VersaPlayerExtension? { return extensions[name] } /// Prepares the player to play open func prepare() { ready = true player = VersaPlayer() player.usesExternalPlaybackWhileExternalScreenIsActive = true player.allowsExternalPlayback = true player.automaticallyWaitsToMinimizeStalling = true player.handler = self player.preparePlayerPlaybackDelegate() renderingView = VersaPlayerRenderingView(with: self) layout(view: renderingView, into: self) } /// Layout a view within another view stretching to edges /// /// - Parameters: /// - view: The view to layout. /// - into: The container view. open func layout(view: View, into: View? = nil) { guard let into = into else { return } into.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false view.topAnchor.constraint(equalTo: into.topAnchor).isActive = true view.leftAnchor.constraint(equalTo: into.leftAnchor).isActive = true view.rightAnchor.constraint(equalTo: into.rightAnchor).isActive = true view.bottomAnchor.constraint(equalTo: into.bottomAnchor).isActive = true } #if os(iOS) /// Enables or disables PIP when available (when device is supported) /// /// - Parameters: /// - enabled: Whether or not to enable open func setNativePip(enabled: Bool) { if pipController == nil && renderingView != nil { let controller = AVPictureInPictureController(playerLayer: renderingView!.playerLayer) controller?.delegate = self pipController = controller } if enabled { pipController?.startPictureInPicture() } else { pipController?.stopPictureInPicture() } } #endif /// Enables or disables fullscreen /// /// - Parameters: /// - enabled: Whether or not to enable open func setFullscreen(enabled: Bool) { if enabled == isFullscreenModeEnabled { return } if enabled { #if os(macOS) if let window = NSApplication.shared.keyWindow { nonFullscreenContainer = superview removeFromSuperview() layout(view: self, into: window.contentView) } #else if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) { nonFullscreenContainer = superview removeFromSuperview() layout(view: self, into: window) } #endif } else { removeFromSuperview() layout(view: self, into: nonFullscreenContainer) } isFullscreenModeEnabled = enabled } /// Sets the item to be played /// /// - Parameters: /// - item: The VPlayerItem instance to add to player. open func set(item: VersaPlayerItem?) { if !ready { prepare() } player.replaceCurrentItem(with: item) if autoplay && item?.error == nil { play() } } /// Play @IBAction open func play(sender: Any? = nil) { if playbackDelegate?.playbackShouldBegin(player: player) ?? true { player.play() controls?.playPauseButton?.set(active: true) isPlaying = true } } /// Pause @IBAction open func pause(sender: Any? = nil) { player.pause() controls?.playPauseButton?.set(active: false) isPlaying = false } /// Toggle Playback @IBAction open func togglePlayback(sender: Any? = nil) { if isPlaying { pause() } else { play() } } #if os(iOS) open func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { print("stopped") //hide fallback } open func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { print("started") //show fallback } open func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { isPipModeEnabled = false controls?.controlsCoordinator.isHidden = false } open func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { controls?.controlsCoordinator.isHidden = true isPipModeEnabled = true } public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, failedToStartPictureInPictureWithError error: Error) { print(error.localizedDescription) } public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) { } #endif }
28.2443
212
0.710183
4b1390aa6684f29fd1aee398b9b59d5f7766f178
459
// // ViewController.swift // DragSwitchViewDemo // // Created by Nirvana on 9/17/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.storyboard } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
17.653846
58
0.653595
3a600ad3af966da60ecdeeff401568de617e4813
871
// // DetailInteractor.swift // TestTask // // Created by Кирилл Володин on 10.11.2021. // import UIKit protocol DetailBusinessLogic { func viewDidLoad() func saveTapped() } protocol DetailModuleInput { } protocol DetailModuleOutput: AnyObject { } final class DetailInteractor { private weak var output: DetailModuleOutput? private let presenter: DetailPresentationLogic private let photo: Photo init(output: DetailModuleOutput, presenter: DetailPresentationLogic, photo: Photo) { self.output = output self.presenter = presenter self.photo = photo } } extension DetailInteractor: DetailBusinessLogic { func saveTapped() { presenter.presentSavingToGallery() } func viewDidLoad() { presenter.present(photo: photo) } } extension DetailInteractor: DetailModuleInput { }
18.934783
88
0.698048
dee7bedd6211eaf436a3bca309a94afcdc3261e2
746
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // BackupScheduleProtocol is description of a backup schedule. Describes how often should be the backup performed and // what should be the retention policy. public protocol BackupScheduleProtocol : Codable { var frequencyInterval: Int32 { get set } var frequencyUnit: FrequencyUnitEnum { get set } var keepAtLeastOneBackup: Bool { get set } var retentionPeriodInDays: Int32 { get set } var startTime: Date? { get set } var lastExecutionTime: Date? { get set } }
46.625
118
0.731903
1ad24f4c3e6ad92e84154b1d9124ac78b9e2bcab
5,720
// // DiomedeQuadStore.swift // Kineo // // Created by Gregory Todd Williams on 5/26/20. // import Foundation import SPARQLSyntax import DiomedeQuadStore extension DiomedeQuadStore: MutableQuadStoreProtocol {} extension DiomedeQuadStore: LazyMaterializingQuadStore {} extension DiomedeQuadStore: PlanningQuadStore { private func characteristicSetSatisfiableCardinality(_ algebra: Algebra, activeGraph: Term, dataset: DatasetProtocol, distinctStarSubject: Node? = nil) throws -> Int? { if case let .bgp(tps) = algebra, tps.allSatisfy({ (tp) in !tp.subject.isBound && !tp.object.isBound }) { let csDataset = try self.characteristicSets(for: activeGraph) let objectVariables = tps.compactMap { (tp) -> String? in if case .variable(let v, _) = tp.object { return v } else { return nil } } let objects = Set(objectVariables) // if these don't match, then there's at least one object variable that is used twice, meaning it's not a simple star guard objects.count == objectVariables.count else { return nil } if let v = distinctStarSubject { if !tps.allSatisfy({ (tp) in tp.subject == v }) { return nil } else { let acs = try csDataset.aggregatedCharacteristicSet(matching: tps, in: activeGraph, store: self) return acs.count } } else { if let card = try? csDataset.starCardinality(matching: tps, in: activeGraph, store: self) { return Int(card) } } } else if case let .triple(tp) = algebra, !tp.subject.isBound, !tp.object.isBound { return try characteristicSetSatisfiableCardinality(.bgp([tp]), activeGraph: activeGraph, dataset: dataset, distinctStarSubject: distinctStarSubject) } else if case let .namedGraph(child, .bound(g)) = algebra { guard dataset.namedGraphs.contains(g) else { return 0 } return try characteristicSetSatisfiableCardinality(child, activeGraph: g, dataset: dataset, distinctStarSubject: distinctStarSubject) } return nil } /// If `algebra` represents a COUNT(*) aggregation with no grouping, and the graph pattern being aggregated is a simple star /// (one subject variable, and all objects are non-shared variables), then compute the count statically using the database's /// Characteristic Sets, and return Table (static data) query plan. private func characteristicSetSatisfiableCountPlan(_ algebra: Algebra, activeGraph: Term, dataset: DatasetProtocol) throws -> QueryPlan? { // COUNT(*) with no GROUP BY over a triple pattern with unbound subject and object if case let .aggregate(child, [], aggs) = algebra { if aggs.count == 1, let a = aggs.first { let agg = a.aggregation switch agg { case .countAll: if let card = try characteristicSetSatisfiableCardinality(child, activeGraph: activeGraph, dataset: dataset) { let qp = TablePlan(columns: [.variable(a.variableName, binding: true)], rows: [[Term(integer: Int(card))]], metricsToken: QueryPlanEvaluationMetrics.silentToken) return qp } case .count(_, false): // COUNT(?v) can be answered by Characteristic Sets if let card = try characteristicSetSatisfiableCardinality(child, activeGraph: activeGraph, dataset: dataset) { let qp = TablePlan(columns: [.variable(a.variableName, binding: true)], rows: [[Term(integer: Int(card))]], metricsToken: QueryPlanEvaluationMetrics.silentToken) return qp } case let .count(.node(v), true): // COUNT(DISTINCT ?v) can be answered by Characteristic Sets only if ?v is the CS star subject if let card = try characteristicSetSatisfiableCardinality(child, activeGraph: activeGraph, dataset: dataset, distinctStarSubject: v) { let qp = TablePlan(columns: [.variable(a.variableName, binding: true)], rows: [[Term(integer: Int(card))]], metricsToken: QueryPlanEvaluationMetrics.silentToken) return qp } default: return nil } } } return nil } /// Returns a QueryPlan object for any algebra that can be efficiently executed by the QuadStore, nil for all others. public func plan(algebra: Algebra, activeGraph: Term, dataset: DatasetProtocol, metrics: QueryPlanEvaluationMetrics) throws -> QueryPlan? { if self.characteristicSetsAreAccurate { // Characteristic Sets are "accurate" is they were computed at or after the moment // when the last quad was inserted or deleted. if let qp = try self.characteristicSetSatisfiableCountPlan(algebra, activeGraph: activeGraph, dataset: dataset) { return qp } } switch algebra { // case .triple(let t): // return try plan(bgp: [t], activeGraph: activeGraph) // case .bgp(let triples): // return try plan(bgp: triples, activeGraph: activeGraph) default: return nil } } } extension DiomedeQuadStore: PrefixNameStoringQuadStore { public var prefixes: [String : Term] { do { return try self.prefixes() } catch { return [:] } } }
52.477064
185
0.611364
2069bc9a193098705c4d9c097fb1a755ccd3cd81
1,344
// // AppDelegate.swift // Prework // // Created by Warren Kim on 1/20/22. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.324324
179
0.744792
f90bed6a31b85ae6a7536189ccecbc92d8959f87
274
// // Event.swift // AERecordExample // // Created by Marko Tadic on 11/4/14. // Copyright (c) 2014 ae. All rights reserved. // import Foundation import CoreData class Event: NSManagedObject { @NSManaged var timeStamp: NSDate @NSManaged var selected: Bool }
15.222222
47
0.693431
dbd80f363221164287cde29d8df6cf09d7596ddf
4,321
// // NagBarTabController.swift // NagBar // // Created by Volen Davidov on 14.01.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Foundation import Cocoa protocol InterfaceAction { func performAction() } class DefaultButton : NSButton, InterfaceAction { required init?(coder: NSCoder) { super.init(coder: coder) guard let identifier = self.identifier else { NSLog("Button identifier not defined") return } if Settings().boolForKey(identifier.rawValue) { self.state = NSControl.StateValue.on } else { self.state = NSControl.StateValue.off } } override func mouseDown(with theEvent: NSEvent) { super.mouseDown(with: theEvent) self.performAction() } func performAction() { guard let identifier = self.identifier else { NSLog("Button identifier not defined") return } if(self.state == NSControl.StateValue.on) { Settings().setBool(true, forKey: identifier.rawValue) } else { Settings().setBool(false, forKey: identifier.rawValue) } } } class DefaultPopUpButton : NSPopUpButton { var popUpButtons: Dictionary <String, Dictionary<Int, String>> { return [ "flashStatusBarType": [1: "Shake", 2: "Flash", 3: "Bright Flash"], "statusInformationLength": [100: "100", 200: "200", 300: "300", 400: "400", 500: "500", 600: "600", 700: "700"], "sortColumn": [0: "None", 1: "Host", 2: "Service", 3: "Status", 4: "Last Check", 5: "Attempt", 6: "Duration"], "sortOrder": [1: "Ascending", 2: "Descending"] ] } required init?(coder: NSCoder) { super.init(coder: coder) guard let identifier = self.identifier else { NSLog("Button identifier not defined") return } guard let popUpButtonDict = self.popUpButtons[identifier.rawValue] else { NSLog("Button identifier " + identifier.rawValue + " not found in dictionary") return } for i in popUpButtonDict { if (Settings().integerForKey(identifier.rawValue) == i.0) { self.selectItem(withTitle: i.1) } } } override func mouseDown(with theEvent: NSEvent) { super.mouseDown(with: theEvent) self.performAction() } func performAction() { guard let identifier = self.identifier else { NSLog("Button identifier not defined") return } for (popUpButton, values) in self.popUpButtons { if identifier.rawValue != popUpButton { continue } for (id, text) in values { if self.titleOfSelectedItem == text { Settings().setInteger(id, forKey: popUpButton) } } } } } class DefaultColorWell : NSColorWell { required init?(coder: NSCoder) { super.init(coder: coder) guard let identifier = self.identifier else { NSLog("Color well identifier not defined") return } guard let colorWheelColors = Settings().stringForKey(identifier.rawValue) else { NSLog("Color well " + identifier.rawValue + " not found in dictionary") return } let colorArr = colorWheelColors.components(separatedBy: ",") let red = CGFloat(Double(colorArr[0])!) let green = CGFloat(Double(colorArr[1])!) let blue = CGFloat(Double(colorArr[2])!) let alpha = CGFloat(Double(colorArr[3])!) self.color = NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) } override func deactivate() { super.deactivate() let stringToSave = String(format: "%.3f", self.color.redComponent) + "," + String(format: "%.3f", self.color.greenComponent) + "," + String(format: "%.3f", self.color.blueComponent) + ",1.0" Settings().setString(stringToSave, forKey: self.identifier?.rawValue ?? "") } }
30.429577
124
0.554964
e2992d01a6f8bec419d2d19ebfe9c1586ad0ebb0
7,206
// // Util.swift // Trips // // Created by Lucas Kellar on 2019-10-04. // Copyright © 2019 Lucas Kellar. All rights reserved. // import Foundation import CoreData import SwiftUI import os let coreDataLogger = Logger(subsystem: "org.kellar.trips", category: "coredata") extension Date { var formatted_date: String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.locale = Locale(identifier: Locale.current.languageCode!) return dateFormatter.string(from: self) } } extension Color { // So basically, as far as I can tell, there's no way to create a Color from a string, and it's hard to store a Color in core data, and I plan to use only named colors, so this will allow me to store strings and convert to color. static func fromString(color: String) -> Color { switch color { case "black": return Color.black case "blue": return Color.blue case "clear": return Color.clear case "gray": return Color.gray case "green": return Color.green case "orange": return Color.orange case "pink": return Color.pink case "primary": return Color.primary case "purple": return Color.purple case "red": return Color.red case "secondary": return Color.secondary case "white": return Color.white case "yellow": return Color.yellow default: // Don't want to raise an error, so returning primary color seems like best option return Color.primary } } } func saveContext(_ context: NSManagedObjectContext) -> Void { do { if context.hasChanges { try context.save() } } catch { coreDataLogger.log("Failed Saving Context: \(error.localizedDescription)") } } func checkDateValidity(startDate: Date, endDate: Date, showStartDate: Bool, showEndDate: Bool) -> Bool { if showEndDate == true && showStartDate == true { if startDate > endDate { if startDate.formatted_date != endDate.formatted_date { return false } } } return true } func copyTemplateToTrip(template: Category, trip: Trip, context: NSManagedObjectContext) throws { guard template.isTemplate else { throw TripError.TemplateIsCategoryError("Provided \"template\" is NOT a template!") } let transitionCategory = Category(context: context) // completed and istemplate are by default set to false transitionCategory.name = template.name transitionCategory.index = try Category.generateCategoryIndex(trip: trip, context: context) for item in template.items { let itom = Item(context: context) itom.name = (item as! Item).name itom.index = (item as! Item).index transitionCategory.addToItems(itom) } trip.addToCategories(transitionCategory) } func increturn(_ num: inout Int) -> Int { // increment by one and return num += 1 return num } func fetchItems(_ category: Category, _ context: NSManagedObjectContext) -> [Item] { let request: NSFetchRequest<Item> = Item.fetchRequest() as! NSFetchRequest<Item> request.sortDescriptors = [NSSortDescriptor(key: "index", ascending: true)] request.predicate = NSPredicate(format: "%K == %@", #keyPath(Item.category), category) do { return try context.fetch(request) } catch { coreDataLogger.error("Failed to fetch items from Category \(category.objectID, privacy: .private(mask: .hash)): \(error.localizedDescription)") return [] } } func copyToOther(category: Category, trip: Trip, context: NSManagedObjectContext) { coreDataLogger.debug("Copying category \(category.objectID, privacy: .private(mask: .hash)) to Trip \(trip.objectID, privacy: .private(mask: .hash))") do { let newCategory = Category(context: context) newCategory.items = NSSet() newCategory.name = category.name newCategory.index = try Category.generateCategoryIndex(trip: trip, context: context) for item in category.items { let newItem = Item(context: context) newItem.completed = false newItem.completedCount = 0 newItem.name = (item as! Item).name newItem.index = try Item.generateItemIndex(category: newCategory, context: context) newCategory.addToItems(newItem) } trip.addToCategories(newCategory) saveContext(context) } catch { coreDataLogger.error("Error Copying Category \(category.objectID, privacy: .private(mask: .hash)) to Trip \(trip.objectID, privacy: .private(mask: .hash)): \(error.localizedDescription)") } } func sortTrips(_ trips: FetchedResults<Trip>) -> [Trip] { var newTrips = trips.filter {$0.startDate != nil} newTrips = newTrips.sorted(by: {$0.startDate! < $1.startDate!}) newTrips.append(contentsOf: trips.filter {$0.startDate == nil}) return newTrips } enum ItemCompletionStatus { case completed case partial case notcompleted } enum PrimarySelectionType { case trip case template case addTrip case addTemplate } enum SecondarySelectionType { case editTrip case editTemplate case editItem case addItem case addTemplate case addCategory } struct SelectionConfig: Equatable { var viewSelectionType: PrimarySelectionType var viewSelection: NSManagedObjectID? var secondaryViewSelectionType: SecondarySelectionType? var secondaryViewSelection: NSManagedObjectID? } extension PrimarySelectionType { func text() -> String { switch(self) { case .trip: return "trip" case .template: return "template" case .addTrip: return "addTrip" case .addTemplate: return "addTemplate" } } } func fetchEntityByExisting<T: NSManagedObject>(id: NSManagedObjectID?, entityType: T.Type, context: NSManagedObjectContext) -> T? { if let id = id { do { // We can force unwrap the selection, as there is a check in the parent to only use this view if selection is valid logger.info("Looking up existing entity by ID. ID is \(id, privacy: .private(mask: .hash))") let entity = try context.existingObject(with: id) as? T if let unwrappedEntity = entity { logger.info("Successfully found entity with ID: \(id, privacy: .private(mask: .hash))") return unwrappedEntity } logger.info("Couldn't found entity with ID for Given Type: \(id, privacy: .private(mask: .hash))") return nil } catch { logger.error("Looking up entity with ID: \(id, privacy: .private(mask: .hash)) failed. Error: \(error.localizedDescription, privacy: .public)") return nil } } else { return nil } }
31.605263
233
0.630031
ab3c633ad241ba2fccff6e8343a3f82692a7310a
1,155
// // FixedMatrixGate.swift // SwiftQuantumComputing // // Created by Enrique de la Torre on 11/11/2020. // Copyright © 2020 Enrique de la Torre. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation // MARK: - Main body struct FixedMatrixGate { // MARK: - Internal properties let matrix: Matrix let inputs: [Int] } // MARK: - Hashable methods extension FixedMatrixGate: Hashable {} // MARK: - SimplifiedGateConvertible methods extension FixedMatrixGate: SimplifiedGateConvertible { var simplified: SimplifiedGate { return .matrix(matrix: matrix, inputs: inputs) } }
26.25
75
0.722944
2928a0307589ab9014ca609940cf31920d58fb4e
515
// // RedditServiceProtocol.swift // RedditGallery // // Created by Andrea Cerra on 7/11/20. // Copyright © 2020 Andrea Cerra. All rights reserved. // import Foundation import RxSwift protocol RedditServiceProtocol { /// This function retrieves from the web /// the latest reddit top posts based on the keyword passed /// /// - Parameter keyword: reddit keyword /// - Returns: Parsed JSON as a TopPosts entity func retriveRedditTopPosts(keyword: String) -> Single<TopPosts> }
24.52381
67
0.693204
abd18768d935eb6a3c507598a71ec2fdcfac6d34
3,247
/** * (C) Copyright IBM Corp. 2019. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** Configuration for passage retrieval. */ public struct QueryLargePassages: Codable, Equatable { /** A passages query that returns the most relevant passages from the results. */ public var enabled: Bool? /** When `true`, passages will be returned whithin their respective result. */ public var perDocument: Bool? /** Maximum number of passages to return per result. */ public var maxPerDocument: Int? /** A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. */ public var fields: [String]? /** The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. The maximum is `100`. */ public var count: Int? /** The approximate number of characters that any one passage will have. */ public var characters: Int? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case enabled = "enabled" case perDocument = "per_document" case maxPerDocument = "max_per_document" case fields = "fields" case count = "count" case characters = "characters" } /** Initialize a `QueryLargePassages` with member variables. - parameter enabled: A passages query that returns the most relevant passages from the results. - parameter perDocument: When `true`, passages will be returned whithin their respective result. - parameter maxPerDocument: Maximum number of passages to return per result. - parameter fields: A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. - parameter count: The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. The maximum is `100`. - parameter characters: The approximate number of characters that any one passage will have. - returns: An initialized `QueryLargePassages`. */ public init( enabled: Bool? = nil, perDocument: Bool? = nil, maxPerDocument: Int? = nil, fields: [String]? = nil, count: Int? = nil, characters: Int? = nil ) { self.enabled = enabled self.perDocument = perDocument self.maxPerDocument = maxPerDocument self.fields = fields self.count = count self.characters = characters } }
33.132653
117
0.673237
796d2898a4423dbb2f8f6234f9f81b43d55c14af
2,181
// // AppDelegate.swift // DSLoadable // // Created by MaherKSantina on 10/18/2018. // Copyright (c) 2018 MaherKSantina. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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.404255
285
0.755158
d9330c46e1cc836c258e324e3d934b0a5a7cb7e5
1,013
import SwiftUI @usableFromInline struct SliderPreferences { @usableFromInline var height: CGFloat? = nil @usableFromInline var width: CGFloat? = nil @usableFromInline var thickness: CGFloat? = nil @usableFromInline var thumbSize: CGSize? = nil @usableFromInline var thumbColor: Color? = nil @usableFromInline var thumbBorderColor: Color? = nil @usableFromInline var thumbBorderWidth: CGFloat? = nil @usableFromInline var thumbShadowColor: Color? = nil @usableFromInline var thumbShadowRadius: CGFloat? = nil @usableFromInline var thumbShadowX: CGFloat? = nil @usableFromInline var thumbShadowY: CGFloat? = nil @usableFromInline var valueColor: Color? = nil @usableFromInline var trackColor: Color? = nil @usableFromInline var trackBorderColor: Color? = nil @usableFromInline var trackBorderWidth: CGFloat? = nil }
20.26
41
0.645607
f41d9b88ec237dbc6f8196796d10896cdc4ff311
435
// // PlatformName.swift // Snowplow // // Created by Olivier Collet on 2018-06-08. // Copyright © 2018 Unsplash. All rights reserved. // import Foundation enum PlatformName: String { case web case mobile = "mob" case computer = "pc" case server = "srv" case application = "app" case television = "tv" case console = "cnsl" case internetOfThing = "iot" }
20.714286
51
0.577011
b99c7d2d2c89fd6855533603838a7e3833ea82ff
6,575
/* * -------------------------------------------------------------------------------- * <copyright company="Aspose" file="DeleteCustomXmlPartOnlineRequest.swift"> * Copyright (c) 2021 Aspose.Words for Cloud * </copyright> * <summary> * 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. * </summary> * -------------------------------------------------------------------------------- */ import Foundation // Request model for deleteCustomXmlPartOnline operation. @available(macOS 10.12, iOS 10.3, watchOS 3.3, tvOS 12.0, *) public class DeleteCustomXmlPartOnlineRequest : WordsApiRequest { private let document : InputStream; private let customXmlPartIndex : Int; private let loadEncoding : String?; private let password : String?; private let destFileName : String?; private let revisionAuthor : String?; private let revisionDateTime : String?; private enum CodingKeys: String, CodingKey { case document; case customXmlPartIndex; case loadEncoding; case password; case destFileName; case revisionAuthor; case revisionDateTime; case invalidCodingKey; } // Initializes a new instance of the DeleteCustomXmlPartOnlineRequest class. public init(document : InputStream, customXmlPartIndex : Int, loadEncoding : String? = nil, password : String? = nil, destFileName : String? = nil, revisionAuthor : String? = nil, revisionDateTime : String? = nil) { self.document = document; self.customXmlPartIndex = customXmlPartIndex; self.loadEncoding = loadEncoding; self.password = password; self.destFileName = destFileName; self.revisionAuthor = revisionAuthor; self.revisionDateTime = revisionDateTime; } // The document. public func getDocument() -> InputStream { return self.document; } // The index of the custom xml part. This index is the number of the entry in the collection of custom xml parts, not the ID of the part. public func getCustomXmlPartIndex() -> Int { return self.customXmlPartIndex; } // Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML. public func getLoadEncoding() -> String? { return self.loadEncoding; } // Password for opening an encrypted document. public func getPassword() -> String? { return self.password; } // Result path of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document. public func getDestFileName() -> String? { return self.destFileName; } // Initials of the author to use for revisions.If you set this parameter and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions. public func getRevisionAuthor() -> String? { return self.revisionAuthor; } // The date and time to use for revisions. public func getRevisionDateTime() -> String? { return self.revisionDateTime; } // Creates the api request data public func createApiRequestData(apiInvoker : ApiInvoker, configuration : Configuration) throws -> WordsApiRequestData { var rawPath = "/words/online/delete/customXmlParts/{customXmlPartIndex}"; rawPath = rawPath.replacingOccurrences(of: "{customXmlPartIndex}", with: try ObjectSerializer.serializeToString(value: self.getCustomXmlPartIndex())); rawPath = rawPath.replacingOccurrences(of: "//", with: "/"); let urlPath = (try configuration.getApiRootUrl()).appendingPathComponent(rawPath); var urlBuilder = URLComponents(url: urlPath, resolvingAgainstBaseURL: false)!; var queryItems : [URLQueryItem] = []; if (self.getLoadEncoding() != nil) { queryItems.append(URLQueryItem(name: "loadEncoding", value: try ObjectSerializer.serializeToString(value: self.getLoadEncoding()!))); } if (self.getPassword() != nil) { queryItems.append(URLQueryItem(name: apiInvoker.isEncryptionAllowed() ? "encryptedPassword" : "password", value: try apiInvoker.encryptString(value: self.getPassword()!))); } if (self.getDestFileName() != nil) { queryItems.append(URLQueryItem(name: "destFileName", value: try ObjectSerializer.serializeToString(value: self.getDestFileName()!))); } if (self.getRevisionAuthor() != nil) { queryItems.append(URLQueryItem(name: "revisionAuthor", value: try ObjectSerializer.serializeToString(value: self.getRevisionAuthor()!))); } if (self.getRevisionDateTime() != nil) { queryItems.append(URLQueryItem(name: "revisionDateTime", value: try ObjectSerializer.serializeToString(value: self.getRevisionDateTime()!))); } if (queryItems.count > 0) { urlBuilder.queryItems = queryItems; } var formParams : [RequestFormParam] = []; formParams.append(RequestFormParam(name: "document", body: try ObjectSerializer.serializeFile(value: self.getDocument()), contentType: "application/octet-stream")); var result = WordsApiRequestData(url: urlBuilder.url!, method: "PUT"); result.setBody(formParams: formParams); return result; } // Deserialize response of this request public func deserializeResponse(data : Data) throws -> Any? { return data; } }
46.964286
235
0.679087
ff23ffcb90d1a841521ef4dec0b4ecf109a187d6
854
// // ViewController.swift // FlipLabel // // Created by Ryuta Kibe on 2016/01/21. // Copyright (c) 2016 blk. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label: FlipLabel! private weak var messageTimer: Timer? private var currentMessageIndex = -1 private var messages = ["Hello, world!", "This is demo.", "Use monospaced fonts."] override func viewDidLoad() { super.viewDidLoad() self.messageTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(switchMessage), userInfo: nil, repeats: true) } @objc private func switchMessage() { self.currentMessageIndex = (self.currentMessageIndex + 1) % self.messages.count self.label.playFlip(text: self.messages[self.currentMessageIndex]) } }
28.466667
147
0.677986
7a691b05f56a1225b9f1220bb0b55985477dc4ce
6,206
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit; class DialogCell: UITableViewCell { let avatarView = AvatarView(frameSize: 48, type: .Rounded) let titleView: UILabel = UILabel() let messageView: UILabel = UILabel() let dateView: UILabel = UILabel() let statusView: UIImageView = UIImageView() let separatorView = TableViewSeparator(color: MainAppTheme.list.separatorColor) let unreadView: UILabel = UILabel() let unreadViewBg: UIImageView = UIImageView() var bindedFile: jlong? = nil; var avatarCallback: CocoaDownloadCallback? = nil; init(reuseIdentifier:String) { super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier) backgroundColor = MainAppTheme.list.bgColor titleView.font = UIFont(name: "Roboto-Medium", size: 19); titleView.textColor = MainAppTheme.list.dialogTitle messageView.font = UIFont(name: "HelveticaNeue", size: 16); messageView.textColor = MainAppTheme.list.dialogText dateView.font = UIFont(name: "HelveticaNeue", size: 14); dateView.textColor = MainAppTheme.list.dialogDate dateView.textAlignment = NSTextAlignment.Right; statusView.contentMode = UIViewContentMode.Center; unreadView.font = UIFont(name: "HelveticaNeue", size: 14); unreadView.textColor = MainAppTheme.list.unreadText unreadView.textAlignment = .Center unreadViewBg.image = Imaging.imageWithColor(MainAppTheme.list.unreadBg, size: CGSizeMake(18, 18)) .roundImage(18).resizableImageWithCapInsets(UIEdgeInsetsMake(9, 9, 9, 9)) self.contentView.addSubview(avatarView) self.contentView.addSubview(titleView) self.contentView.addSubview(messageView) self.contentView.addSubview(dateView) self.contentView.addSubview(statusView) self.contentView.addSubview(separatorView) self.contentView.addSubview(unreadViewBg) self.contentView.addSubview(unreadView) var selectedView = UIView() selectedView.backgroundColor = MainAppTheme.list.bgSelectedColor selectedBackgroundView = selectedView } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bindDialog(dialog: AMDialog, isLast:Bool) { self.avatarView.bind(dialog.getDialogTitle(), id: dialog.getPeer().getPeerId(), avatar: dialog.getDialogAvatar()); self.titleView.text = dialog.getDialogTitle(); self.messageView.text = MSG.getFormatter().formatDialogText(dialog) if (dialog.getDate() > 0) { self.dateView.text = MSG.getFormatter().formatShortDate(dialog.getDate()); self.dateView.hidden = false; } else { self.dateView.hidden = true; } if (dialog.getUnreadCount() != 0) { self.unreadView.text = "\(dialog.getUnreadCount())" self.unreadView.hidden = false self.unreadViewBg.hidden = false } else { self.unreadView.hidden = true self.unreadViewBg.hidden = true } var messageState = UInt(dialog.getStatus().ordinal()); if (messageState == AMMessageState.PENDING.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSending self.statusView.image = Resources.iconClock; self.statusView.hidden = false; } else if (messageState == AMMessageState.READ.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogRead self.statusView.image = Resources.iconCheck2; self.statusView.hidden = false; } else if (messageState == AMMessageState.RECEIVED.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogReceived self.statusView.image = Resources.iconCheck2; self.statusView.hidden = false; } else if (messageState == AMMessageState.SENT.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSent self.statusView.image = Resources.iconCheck1; self.statusView.hidden = false; } else if (messageState == AMMessageState.ERROR.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogError self.statusView.image = Resources.iconError; self.statusView.hidden = false; } else { self.statusView.hidden = true; } self.separatorView.hidden = isLast; setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews(); // We expect height == 76; let width = self.contentView.frame.width; let leftPadding = CGFloat(76); let padding = CGFloat(14); avatarView.frame = CGRectMake(padding, padding, 48, 48); titleView.frame = CGRectMake(leftPadding, 18, width - leftPadding - /*paddingRight*/(padding + 50), 18); var messagePadding:CGFloat = 0; if (!self.statusView.hidden) { messagePadding = 22; statusView.frame = CGRectMake(leftPadding, 44, 20, 18); } var unreadPadding = CGFloat(0) if (!self.unreadView.hidden) { unreadView.frame = CGRectMake(0, 0, 1000, 1000) unreadView.sizeToFit() let unreadW = max(unreadView.frame.width + 8, 18) unreadView.frame = CGRectMake(width - padding - unreadW, 44, unreadW, 18) unreadViewBg.frame = unreadView.frame unreadPadding = unreadW } messageView.frame = CGRectMake(leftPadding+messagePadding, 44, width - leftPadding - /*paddingRight*/padding - messagePadding - unreadPadding, 18); dateView.frame = CGRectMake(width - /*width*/60 - /*paddingRight*/padding , 18, 60, 18); separatorView.frame = CGRectMake(leftPadding, 75.5, width, 0.5); } }
40.828947
155
0.631486
d92c2d58d6d0c67f9382232d54704a477f202a0f
5,608
import MapboxCoreMaps internal protocol MapboxObservableProtocol: AnyObject { func subscribe(_ observer: Observer, events: [String]) func unsubscribe(_ observer: Observer, events: [String]) func onNext(_ eventTypes: [MapEvents.EventKind], handler: @escaping (Event) -> Void) -> Cancelable func onEvery(_ eventTypes: [MapEvents.EventKind], handler: @escaping (Event) -> Void) -> Cancelable func performWithoutNotifying(_ block: () -> Void) } /// `MapboxObservable` wraps the event listener APIs of ``MapboxCoreMaps/MBMObservable``, /// re-exposing the subscribe/unsubscribe interfaces and adding onNext/onEvery block-based interfaces. /// This design reduces duplication between ``MapboxMap`` and ``Snapshotter``, which can both /// implement their public versions of this API via thin wrappers around this class. /// /// Regardless of whether a listener is added via ``MapboxObservable/subscribe(_:events:)``, /// ``MapboxObservalbe/onNext(_:handler:)``, or /// ``MapboxObservable/onEvery(_:handler:)``, `MapboxObservable` wraps the provided /// object or closure, keeps a strong reference to the wrapper, and passes the wrapper to /// `MapboxCoreMaps`. This will enable us to build filtering capabilities by selectively ignoring certain /// events regardless of which listener API was used. internal final class MapboxObservable: MapboxObservableProtocol { private let observable: ObservableProtocol private var observerWrappers = [ObjectIdentifier: ObserverWrapper]() internal init(observable: ObservableProtocol) { self.observable = observable } deinit { for observer in observerWrappers.values { observable.unsubscribe(for: observer) } } internal func subscribe(_ observer: Observer, events: [String]) { // maintain only one wrapper per observer. merge current and new events. var allEvents = Set(events) if let oldWrapper = observerWrappers[ObjectIdentifier(observer)] { guard Set(oldWrapper.events) != allEvents else { return } allEvents.formUnion(oldWrapper.events) observable.unsubscribe(for: oldWrapper) } let allEventsArray = Array(allEvents) let newWrapper = ObserverWrapper(wrapped: observer, events: allEventsArray) observerWrappers[ObjectIdentifier(observer)] = newWrapper observable.subscribe(for: newWrapper, events: allEventsArray) } internal func unsubscribe(_ observer: Observer, events: [String]) { guard let wrapper = observerWrappers.removeValue(forKey: ObjectIdentifier(observer)) else { return } let wrapperEvents = Set(wrapper.events) guard events.isEmpty || !wrapperEvents.isDisjoint(with: events) else { return } observable.unsubscribe(for: wrapper) if !events.isEmpty { let remainingEvents = wrapperEvents.subtracting(events) if !remainingEvents.isEmpty { subscribe(observer, events: Array(remainingEvents)) } } } internal func onNext(_ eventTypes: [MapEvents.EventKind], handler: @escaping (Event) -> Void) -> Cancelable { let cancelable = CompositeCancelable() let observer = BlockObserver { handler($0) cancelable.cancel() } subscribe(observer, events: eventTypes.map(\.rawValue)) // Capturing self and observer with weak refs in the closure passed to BlockCancelable // avoids a retain cycle. MapboxObservable holds a strong reference to observer, which has a // strong reference to cancelable, which has a strong reference to BlockCancelable, which only // has weak references back to MapboxObservable and observer. If MapboxObservable is deinited, // observer will be released. cancelable.add(BlockCancelable { [weak self, weak observer] in if let self = self, let observer = observer { self.unsubscribe(observer, events: []) } }) return cancelable } internal func onEvery(_ eventTypes: [MapEvents.EventKind], handler: @escaping (Event) -> Void) -> Cancelable { let observer = BlockObserver(block: handler) subscribe(observer, events: eventTypes.map(\.rawValue)) return BlockCancelable { [weak self, weak observer] in if let self = self, let observer = observer { self.unsubscribe(observer, events: []) } } } internal func performWithoutNotifying(_ block: () -> Void) { for wrapper in observerWrappers.values { wrapper.ignoringCount += 1 } block() for wrapper in observerWrappers.values { wrapper.ignoringCount -= 1 } } private final class ObserverWrapper: Observer { internal let wrapped: Observer internal let events: [String] internal var ignoringCount = 0 internal init(wrapped: Observer, events: [String]) { self.wrapped = wrapped self.events = events } internal func notify(for event: Event) { if ignoringCount == 0 { wrapped.notify(for: event) } } } private final class BlockObserver: Observer { private let block: (Event) -> Void internal init(block: @escaping (Event) -> Void) { self.block = block } internal func notify(for event: Event) { block(event) } } }
38.944444
114
0.650143
ccb6b3414a38184a9ca2cfe74bc0fa9a1e6b9bef
5,614
/* Copyright Airship and Contributors */ import UIKit #if canImport(AirshipCore) import AirshipCore import AirshipAutomation #elseif canImport(AirshipKit) import AirshipKit #endif /** * The AutomationCell represents a single IAA schedule in the table. */ class AutomationCell: UITableViewCell { @IBOutlet weak var messageType: UILabel! @IBOutlet weak var messageName: UILabel! @IBOutlet weak var messageID: UILabel! var schedule : UASchedule? func setCellTheme() { backgroundColor = ThemeManager.shared.currentTheme.Background messageName.textColor = ThemeManager.shared.currentTheme.PrimaryText messageID.textColor = ThemeManager.shared.currentTheme.SecondaryText messageType.textColor = ThemeManager.shared.currentTheme.WidgetTint } override func layoutSubviews() { super.layoutSubviews() setCellTheme() } } /** * The AutomationTableViewController displays a list of IAA schedules * for debugging use. */ class AutomationTableViewController: UITableViewController { var launchPathComponents : [String]? var launchCompletionHandler : (() -> Void)? private var schedules : Array<UASchedule>? func setTableViewTheme() { tableView.backgroundColor = ThemeManager.shared.currentTheme.Background; navigationController?.navigationBar.titleTextAttributes = [.foregroundColor:ThemeManager.shared.currentTheme.NavigationBarText] navigationController?.navigationBar.barTintColor = ThemeManager.shared.currentTheme.NavigationBarBackground; } override func viewDidLoad() { super.viewDidLoad() let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshInAppAutomation), for: UIControl.Event.valueChanged) self.refreshControl = refreshControl } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.backgroundColor = ThemeManager.shared.currentTheme.Background; setTableViewTheme() refreshInAppAutomation() } @objc private func refreshInAppAutomation() { InAppAutomation.shared.getSchedules({ (schedulesFromAutomation) in self.schedules = schedulesFromAutomation self.tableView.reloadData() self.refreshControl?.endRefreshing() }) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.schedules?.count ?? 0 } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView { headerView.textLabel?.textColor = ThemeManager.shared.currentTheme.WidgetTint } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AutomationCell", for: indexPath) as! AutomationCell // clear cell cell.schedule = nil cell.messageType.text = nil cell.messageName.text = nil cell.messageID.text = nil cell.backgroundColor = nil if let schedule = self.schedules?[indexPath.row] { cell.schedule = schedule if let inAppMessage = schedule as? InAppMessageSchedule { let message = inAppMessage.message switch (message.displayContent.displayType) { case .banner: cell.messageType.text = "B" case .fullScreen: cell.messageType.text = "F" case .modal: cell.messageType.text = "M" case .HTML: cell.messageType.text = "H" case .custom: cell.messageType.text = "C" @unknown default: break } cell.messageName.text = message.name } else if schedule is ActionSchedule { cell.messageType.text = "A" cell.messageName.text = "Action" } else if schedule is DeferredSchedule { cell.messageType.text = "D" cell.messageName.text = "Deferred" } cell.messageID.text = schedule.identifier if (schedule.isValid) { cell.backgroundColor = nil } else { cell.backgroundColor = UIColor.red } } return cell } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch(segue.identifier ?? "") { case AutomationDetailViewController.segueID: guard let automationDetailViewController = segue.destination as? AutomationDetailViewController else { fatalError("Unexpected destination: \(segue.destination)") } guard let selectedAutomationCell = sender as? AutomationCell else { fatalError("Unexpected sender: \(sender ?? "unknown sender")") } automationDetailViewController.schedule = selectedAutomationCell.schedule default: print("ERROR: Unexpected Segue Identifier; \(segue.identifier ?? "unknown identifier")") } } }
34.654321
135
0.640542
38575b1b4bbefbda04598819b99630901843c84f
1,190
// // MarkDownConverterConfigurationTests.swift // MarkyMark // // Created by Jim van Zummeren on 29/04/16. // Copyright © 2016 M2mobi. All rights reserved. // import XCTest @testable import markymark /* class MarkDownConverterConfigurationTests: XCTestCase { var sut:MarkDownConverterConfiguration<String>! override func setUp() { super.setUp() sut = MarkDownConverterConfiguration<String>() } func testLayoutBuilderForMarkDownItemTypeReturnsCorrectLayoutBuilder() { //Arrange let expectedLayoutBuilder = MockLayoutBuilder() //Act sut.addMapping(MockMarkDownItem.self, layoutBuilder: expectedLayoutBuilder) //Assert XCTAssert(sut.layoutBlockBuilderForMarkDownItemType(MockMarkDownItem.self) === expectedLayoutBuilder) } } private class MockMarkDownItem : MarkDownItem { } private class MockLayoutBlockBuilder : LayoutBlockBuilder<String> { override func relatedMarkDownItemType() -> MarkDownItem.Type { return MockMarkDownItem.self } //MARK: LayoutBuilder override func build(markDownItem:MarkDownItem) -> String { return markDownItem.lines.first! } }*/
24.791667
109
0.720168
1e15facd8bd7f035f07e38c4bbfd99cda8f5f216
880
// // HU17Tests.swift // HU17Tests // // Created by fangtaohou on 2021/9/7. // import XCTest @testable import HU17 class HU17Tests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.882353
111
0.657955
0abc411412bf82a69c507efca0b91c421b19d78c
1,055
// // EECellSwipeGestureRecognizerTests.swift // EECellSwipeGestureRecognizerTests // // Created by Enric Enrich on 23/06/16. // Copyright © 2016 Enric Enrich. All rights reserved. // import XCTest @testable import EECellSwipeGestureRecognizer class EECellSwipeGestureRecognizerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
28.513514
111
0.661611
69d57e069bb140e7c14c33174ec103553d555a76
1,243
// // ForgotPasswordViewController.swift // StoreAppProject // // Created by Home on 5/21/21. // import UIKit class ForgotPasswordViewController: UIViewController { @IBOutlet weak var username: UITextField! @IBOutlet weak var warningLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() } @IBAction func submit(_ sender: Any) { let data: Customer let alert: UIAlertController if DBHelper.found == 0 { warningLabel.text = "Username not found" username.text = "" return } else { warningLabel.text = "" data = DBHelper.inst.getCustomer(withEmailID: username.text!) // create the alert alert = UIAlertController(title: "Password Request", message: "Your password is \(data.password!)! Thank you for signing up with us.", preferredStyle: UIAlertController.Style.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) // show the alert self.present(alert, animated: true, completion: nil) username.text = "" } } }
29.595238
193
0.604183
879dc6b1e58946a5d8feadbdf978cf3ec0e76711
1,118
// // DisplayItem.swift // macOS Utilities // // Created by Keaton Burleson on 5/17/19. // Copyright © 2019 Keaton Burleson. All rights reserved. // import Foundation struct DisplayItem: ConcreteItemType { typealias ItemType = DisplayItem static var isNested: Bool = false var dataType: SPDataType = .display var graphicsCardModel: String var graphicsCardVRAM: String? var graphicsCardVRAMShared: String? private var _metalFamily: String? var isMetalCompatible: Bool { if let metalFamily = self._metalFamily { return metalFamily.contains("spdisplays_metalfeaturesetfamily") } return false } var description: String { return "\(graphicsCardModel): \(graphicsCardVRAM ?? graphicsCardVRAMShared ?? "No VRAM") Metal: \(self.isMetalCompatible ? "Yes" : "No")" } enum CodingKeys: String, CodingKey { case graphicsCardModel = "sppci_model" case graphicsCardVRAM = "spdisplays_vram" case graphicsCardVRAMShared = "spdisplays_vram_shared" case _metalFamily = "spdisplays_metal" } }
26.619048
145
0.682469
d9b8e9c48cf78da3526fefe05c77cd026b4fa5c9
418
// // UIControl+ATEventTriggerUICompatible.swift // iosApp // // Created by Steve Kim on 2021/03/15. // Copyright © 2021 orgName. All rights reserved. // import shared import UIKit extension UIControl: ATEventTriggerUICompatible { public func registerTrigger(invoke: @escaping () -> Void) { rx.controlEvent(.touchUpInside) .bind { invoke() } .disposed(by: disposeBag) } }
22
63
0.662679
e2307bd19c511dd51d9d5936605f8408c2e2245d
1,266
// // DeserializableSupportedTypeConvertibleTest.swift // DataMapper // // Created by Filip Dolnik on 27.12.16. // Copyright © 2016 Brightify. All rights reserved. // import Quick import Nimble import DataMapper class DeserializableSupportedTypeConvertibleTest: QuickSpec { override func spec() { describe("DeserializableSupportedTypeConvertible") { it("can be used in ObjectMapper without transformation") { let objectMapper = ObjectMapper() let value: DeserializableSupportedTypeConvertibleStub? = DeserializableSupportedTypeConvertibleStub() let type: SupportedType = .null let result: DeserializableSupportedTypeConvertibleStub? = objectMapper.deserialize(type) expect(String(describing: result)) == String(describing: value) } } } private struct DeserializableSupportedTypeConvertibleStub: DeserializableSupportedTypeConvertible { static let defaultDeserializableTransformation: AnyDeserializableTransformation<DeserializableSupportedTypeConvertibleStub> = AnyDeserializableTransformation(transformFrom: { _ in DeserializableSupportedTypeConvertibleStub() }) } }
37.235294
133
0.707741
8ac830a2689c3b5dd048707749f4041dd1d9acaa
362
// // InlineResponse2003.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct InlineResponse2003: Codable { public var total: Int? public var data: [VideoChannel]? public init(total: Int? = nil, data: [VideoChannel]? = nil) { self.total = total self.data = data } }
17.238095
65
0.651934
288c10bce6c54d3448c77f8f2f4af42e576e29bd
1,383
// Copyright (C) 2020 littlegnal // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import Flutter class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Make a button to call the showFlutter function when pressed. let button = UIButton(type:UIButton.ButtonType.custom) button.addTarget(self, action: #selector(showFlutter), for: .touchUpInside) button.setTitle("Show Flutter!", for: UIControl.State.normal) button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0) button.backgroundColor = UIColor.blue self.view.addSubview(button) } @objc func showFlutter() { let viewController = CustomAddonViewController(displayInitialRoute: "/first_page") viewController.modalPresentationStyle = .fullScreen present(viewController, animated: true, completion: nil) } }
36.394737
86
0.739696
fffe88969cb2b4f6b4115e3b797cc7ba44f3b0d1
526
// LeaseAction enumerates the values for lease action. public enum LeaseAction: String, Codable { // Acquire specifies the acquire state for lease action. case Acquire = "acquire" // Break specifies the break state for lease action. case Break = "break" // Change specifies the change state for lease action. case Change = "change" // Release specifies the release state for lease action. case Release = "release" // Renew specifies the renew state for lease action. case Renew = "renew" }
32.875
57
0.709125
1c10f661855f72eaa790e3cbeefefca23ef2971a
753
import XCTest import YLExtensionTools class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.965517
111
0.60425
71df3fedfc55d4eda042e214ae38fa1b3082ad11
1,983
// // ConstraintKeyboardContentManager.swift // SLEssentials // // Created by Vukasin on 2/22/19. // Copyright © 2019 SwiftyLabs. All rights reserved. // import UIKit public final class ConstraintKeyboardContentManager: KeyboardManageable { // MARK: - Properties public var bottomOffsetHeight: CGFloat? public var keyboardHides: () -> () = {} public var keyboardShows: () -> () = {} private var notificationCenter: NotificationCenter = .default private var constraintBottom: NSLayoutConstraint private var containerView: UIView // MARK: - Initialization public init(containerView: UIView, constraintBottom: NSLayoutConstraint) { self.constraintBottom = constraintBottom self.containerView = containerView } // MARK: - Public methods public func registerForKeyboardNotifications() { notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } public func unregisterForKeyboardNotifications() { notificationCenter.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } // MARK: - Actions @objc func keyboardWillShow(_ notification: Notification) { if let userInfo = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { UIView.animate(withDuration: 0.25, animations: {[weak self] in self?.constraintBottom.constant = userInfo.cgRectValue.height - (self?.bottomOffsetHeight ?? 0.0) }) keyboardShows() } } @objc func keyboardWillHide(_ notification: Notification) { keyboardHides() constraintBottom.constant = 0.0 UIView.animate(withDuration: 0.25, animations: {[weak self] in self?.containerView.layoutIfNeeded() }) } }
32.508197
142
0.76349
1ec1719080b5e37553d8bc288c64159e285eb8f0
26,540
// // TopActionDatabaseVC.swift // Geeklink // // Created by Lieshutong on 2018/3/22. // Copyright © 2018年 Geeklink. All rights reserved. // import UIKit enum TopActionType: Int { case macroAction case miniPiSubDeviceAction } class TopActionLiveDeviceVC: TopSuperVC, TopCodeViewDelegate, TopSpecialActionViewDelegate,TVSTBNumberViewDelegate, TopACCodeViewDelegate { private weak var viewAC: TopACCodeView? private weak var stbCodeView: TopSTBCodeView? private weak var tvCodeView: TopTVCodeView? private weak var iptvCodeView: TopIPTVCodeView? private weak var projectorCodeView: TopProjectorCodeView? private weak var fanCodeView: TopFANCodeView? private weak var voiceBoxCodeView: TopVoiceBoxCodeView? private weak var acFanCodeView: TopACFanCodeView? private weak var airCleanCodeView: TopAirCleanCodeView? private weak var customSpecialView: TopCustomSpecialView? private weak var specialActionView: TopSpecialActionView? var type: TopActionType = .macroAction private var ratio: CGFloat = 1 weak var tVSTBNumberView: TopTVSTBNumberView? var selectKeyType: GLKeyType = .CTLSWITCH var homeInfo = GLHomeInfo()//必须填 var keyList = [GLKeyInfo]() var deviceInfo = GLDeviceInfo()//必须填 var oldActionInfo = GLActionInfo()//修改时需要填, 添加时不需要填 var tempStateInfo = GLDbAcCtrlInfo(powerState: 0, mode: 0, temperature: 24, speed: 0, direction: 0) func ACRcCodeViewStateChange(stateInfo: GLRcStateInfo, keyType: GLDbAirKeyType, view: UIView) { var speed = stateInfo.acSpeed var power = stateInfo.acPowerState var dir = stateInfo.acDirection var mode = stateInfo.acMode var temp = stateInfo.acTemperature switch keyType { case .AIRMODE: mode += 1 if mode > 4 { mode = 0 } case .AIRSWITCH: power += 1 if power > 1 { power = 0 } case .AIRWINSPEED: speed += 1 if speed > 3 { speed = 0 } case .AIRWINDIR: dir += 1 if dir > 3 { dir = 0 } case .AIRTEMPPLUS: temp += 1 if temp > 30 { temp = 30 } case .AIRTEMPMINUS: temp -= 1 if temp < 16 { temp = 16 } case .count: break @unknown default: break } let rcStateInfo = GLRcStateInfo.init(hostDeviceId: stateInfo.hostDeviceId, online: stateInfo.online, ctrlId: stateInfo.ctrlId, fileId: stateInfo.fileId, carrier: stateInfo.carrier, acPowerState: power, acMode: mode, acTemperature: temp, acSpeed: speed, acDirection: dir, socketMD5: stateInfo.socketMD5) self.tempStateInfo = GLDbAcCtrlInfo(powerState: power, mode: mode, temperature: temp, speed: speed, direction: dir) viewAC?.stateInfo = rcStateInfo! } @objc func reloadKeyList() { keyList = SGlobalVars.rcHandle.getKeyList(homeInfo.homeId, deviceId: deviceInfo.deviceId) as! [GLKeyInfo] } func addOrStudyKey(_ keyType: GLKeyType, view: UIView) -> Void { selectKeyType = keyType for theKey in self.keyList { if theKey.keyId == Int32(keyType.rawValue) + 1{ let value = SGlobalVars.actionHandle.getRCValueString(Int8(theKey.keyId)) setMacroAction(value: value!) return } } if SGlobalVars.homeHandle.getHomeAdminIsMe(homeInfo.homeId) == false { self.alertMessage(NSLocalizedString("The key is not recode code, please ask the administrator to learn the key before it can be used.", comment: ""), withTitle: NSLocalizedString("Hint", comment: "")) return } showStudyAlert(keyType, view: view) } func showStudyAlert(_ keyType: GLKeyType, view: UIView) -> Void { let stateInfo = SGlobalVars.slaveHandle.getSlaveState(SGlobalVars.curHomeInfo.homeId, deviceIdSub: deviceInfo.deviceId)! let hostStateInfo = SGlobalVars.deviceHandle.getGLDeviceStateInfo(SGlobalVars.curHomeInfo.homeId, deviceId: stateInfo.hostDeviceId)! switch hostStateInfo.state { case .local: break case .offline : GlobarMethod.notifyError(withStatus: NSLocalizedString("Device isn't Connected", comment: "")) return default: //self.alertMessage(NSLocalizedString("If you want to do button learning, you need to do it under the LAN.", comment: ""), withTitle: NSLocalizedString("Unlearned key", comment: "")) break } var message = NSLocalizedString("The key is not valid, whether to record or create code immediately?", tableName: "RoomDevice") if hostStateInfo.type == .smartPi { message = NSLocalizedString("The key is not valid, whether to record code immediately?", tableName: "RoomDevice") } let alert = UIAlertController(title: NSLocalizedString("Hint", comment: ""), message: message, preferredStyle: .actionSheet) //动作取消 let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) let create = UIAlertAction(title: NSLocalizedString("Create new code", tableName: "RoomDevice"), style: .default) { (action) in self.showCreateKeyAlert(keyType , view: view) } let recordRC = UIAlertAction(title: NSLocalizedString("Record entity RC button", tableName: "RoomDevice"), style: .default) { (action) in self.studyKey(keyType) } if (alert.popoverPresentationController != nil) { alert.popoverPresentationController?.sourceView = view alert.popoverPresentationController?.sourceRect = view.bounds } alert.addAction(cancel) if hostStateInfo.type != .smartPi { alert.addAction(create) } alert.addAction(recordRC) present(alert, animated: true, completion: nil) } func showCreateKeyAlert(_ keyType: GLKeyType, view: UIView) -> Void { let keyId: Int32 = Int32(keyType.rawValue) + 1 let alert = UIAlertController(title: NSLocalizedString("Hint", comment: ""), message: NSLocalizedString("The key is not valid, whether to record or create code immediately?", tableName: "RoomDevice"), preferredStyle: .actionSheet) //动作取消 let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil) let customType = (GLCustomType.init(rawValue: Int(deviceInfo.subType)))! let actionRf315m = UIAlertAction(title: NSLocalizedString("RF315M", tableName: "RoomDevice"), style: .default, handler: { (action) -> Void in let data = SGlobalVars.rcHandle.createCode(.rf315m); let info = GLKeyInfo(keyId: keyId, studyType: 1, order: 0, icon: keyType, name: GlobarMethod.getKeyTypeName(keyType, andCustomType: customType)) if SGlobalVars.rcHandle.thinkerKeySetReq(self.homeInfo.homeId, deviceIdSub: self.deviceInfo.deviceId, action: .insert, keyInfo: info, data: data) == 0 { self.processTimerStart(3.0) } else { GlobarMethod.notifyNetworkError() } }) alert.addAction(actionRf315m) let actionRf433m = UIAlertAction(title: NSLocalizedString("RF433M", tableName: "RoomDevice"), style: .default, handler: { (action) -> Void in let data = SGlobalVars.rcHandle.createCode(.rf433m); let info = GLKeyInfo(keyId: keyId, studyType: 2, order: 0, icon: keyType, name: GlobarMethod.getKeyTypeName(keyType, andCustomType: customType)) if SGlobalVars.rcHandle.thinkerKeySetReq(self.homeInfo.homeId, deviceIdSub: self.deviceInfo.deviceId, action: .insert, keyInfo: info, data: data) == 0 { self.processTimerStart(3.0) } else { GlobarMethod.notifyNetworkError() } }) alert.addAction(actionRf433m) let actionLivo = UIAlertAction(title: NSLocalizedString("Livo Switch", tableName: "RoomDevice"), style: .default, handler: { (action) -> Void in let data = SGlobalVars.rcHandle.createCode(.livo); let info = GLKeyInfo(keyId: keyId, studyType: 1, order: 0, icon: keyType, name: GlobarMethod.getKeyTypeName(keyType, andCustomType: customType)) if SGlobalVars.rcHandle.thinkerKeySetReq(self.homeInfo.homeId, deviceIdSub: self.deviceInfo.deviceId, action: .insert, keyInfo: info, data: data) == 0 { self.processTimerStart(3.0) } else { GlobarMethod.notifyNetworkError() } }) if (alert.popoverPresentationController != nil) { alert.popoverPresentationController?.sourceView = view alert.popoverPresentationController?.sourceRect = view.bounds } alert.addAction(actionLivo) alert.addAction(cancel) present(alert, animated: true, completion: nil) } func studyKey(_ keyType: GLKeyType) -> Void { let customType = (GLCustomType.init(rawValue: Int(deviceInfo.subType)))! let keyId: Int32 = Int32(keyType.rawValue) + 1 let action: GLActionFullType = .insert let keyInfo = GLKeyInfo(keyId:keyId, studyType: 1, order: 0, icon: keyType, name: GlobarMethod.getKeyTypeName(keyType, andCustomType: customType)) TopStudyKeyTool.share().studyKey(deviceInfo, keyInfo: keyInfo!, action: action) } @objc func thinkerKeySetResp(_ notification: NSNotification) -> Void { processTimerStop() GlobarMethod.notifySuccess() let ackInfo = notification.object as! TopSlaveAckInfo if ackInfo.subDeviceId == self.deviceInfo.deviceId { keyList = SGlobalVars.rcHandle.getKeyList(homeInfo.homeId, deviceId: deviceInfo.deviceId) as! [GLKeyInfo] for theKey in self.keyList { if theKey.keyId == Int32(selectKeyType.rawValue) + 1{ let value = SGlobalVars.actionHandle.getRCValueString(Int8(theKey.keyId)) setMacroAction(value: value!) break } } } } // MARK: - 代理实现 func oneKeyCodeViewDidClickedBtn(_ keyType: GLKeyType, btn: UIButton) { self.addOrStudyKey(keyType, view: view) } func projectorCodeViewDelegate(_ keyType: GLKeyType, databaceType: GLDbIptvKeyType, view: UIView) { if deviceInfo.mainType == .custom { self.addOrStudyKey(keyType, view: view) return } } func airCleanCodeViewDidclickedBtn(_ keyType: GLKeyType, btn: UIButton) { self.addOrStudyKey(keyType, view: view) } func customSpecialViewDidClickedBtn(_ keyType: GLKeyType, view: UIView) { if deviceInfo.mainType == .custom { self.addOrStudyKey(keyType, view: view) return } } func acFanCodeViewDidclickedBtn(_ keyType: GLKeyType, btn: UIButton) { self.addOrStudyKey(keyType, view: btn) } func codeView(_ keyType: GLKeyType, key: Int8, view: UIView) { if key == 127 { self.showNumberView() return } if deviceInfo.mainType == .custom { self.addOrStudyKey(keyType, view: view) return } let value = SGlobalVars.actionHandle.getRCValueString(key) setMacroAction(value: value!) } func voiceBoxCodeViewDidClickedBtn(_ keyType: GLKeyType, view: UIView) { if deviceInfo.mainType == .custom { self.addOrStudyKey(keyType, view: view) } } func fANCodeViewDidclickedBtn(_ keyType: GLKeyType, btn: UIButton) { if deviceInfo.mainType == .custom { self.addOrStudyKey(keyType, view: btn) } } // MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() //设置文本 title = deviceInfo.name if view.size.width > view.size.height { ratio = view.size.height / view.size.width }else { ratio = view.size.width / view.size.height } self.initSubViews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.refreshSubViewFrame(self.view.frame.size) } func refreshSubViewFrame(_ size: CGSize) -> Void { if self.tVSTBNumberView != nil { self.tVSTBNumberView?.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height) } var width = size.height * ratio if width > size.width { width = size.width } let topBarHeight = (navigationController?.navigationBar.bounds.size.height)! let frame = CGRect.init(x: (size.width - width) * 0.5, y: 0, width: width, height: size.height - topBarHeight) if viewAC != nil { viewAC?.frame = frame return } if stbCodeView != nil { stbCodeView?.frame = frame return } if iptvCodeView != nil { iptvCodeView?.frame = frame return } if projectorCodeView != nil { projectorCodeView?.frame = frame return } if tvCodeView != nil { tvCodeView?.frame = frame return } if fanCodeView != nil { fanCodeView?.frame = frame return } if voiceBoxCodeView != nil { voiceBoxCodeView?.frame = frame return } if acFanCodeView != nil { acFanCodeView?.frame = frame return } if airCleanCodeView != nil { airCleanCodeView?.frame = frame return } if customSpecialView != nil { customSpecialView?.frame = frame return } if specialActionView != nil { specialActionView?.frame = frame return } } func initSubViews() -> Void { if deviceInfo.mainType == .database{ let databaseType = GLDatabaseType(rawValue: Int(deviceInfo.subType))! switch databaseType { case .AC: let viewAC = TopACCodeView() viewAC.delegate = self self.viewAC = viewAC let stateInfo = SGlobalVars.rcHandle.getRcState(homeInfo.homeId, deviceIdSub: deviceInfo.deviceId) as GLRcStateInfo viewAC.stateInfo = stateInfo self.view.addSubview(viewAC) self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .done, target: self, action: #selector(onClickSaveButton)) case .TV: let tvCodeView = TopTVCodeView() self.tvCodeView = tvCodeView tvCodeView.hideChannelBtn(true) tvCodeView.delegate = self self.view.addSubview(tvCodeView) case .STB: let viewSTB = TopSTBCodeView() viewSTB.delegate = self self.stbCodeView = viewSTB viewSTB.hideChannelBtn(true) self.view.addSubview(viewSTB) case .IPTV: let iptvCodeView = TopIPTVCodeView() self.iptvCodeView = iptvCodeView iptvCodeView.delegate = self view.addSubview(iptvCodeView) default: break } }else if deviceInfo.mainType == .custom{ let customType = GLCustomType(rawValue: Int(deviceInfo.subType))! switch customType { case .IPTV: let iptvCodeView = TopIPTVCodeView() iptvCodeView.delegate = self self.iptvCodeView = iptvCodeView view.addSubview(iptvCodeView) case .projector: let projectorCodeView = TopProjectorCodeView() // projectorCodeView.delegate = self self.projectorCodeView = projectorCodeView self.view.addSubview(projectorCodeView) case .TV: let tvCodeView = TopTVCodeView() self.tvCodeView = tvCodeView tvCodeView.hideChannelBtn(true) tvCodeView.delegate = self self.view.addSubview(tvCodeView) case .STB: let stbCodeView = TopSTBCodeView() self.stbCodeView = stbCodeView stbCodeView.delegate = self stbCodeView.hideChannelBtn(true) self.view.addSubview(stbCodeView) case .fan: let fanCodeView = TopFANCodeView() fanCodeView.delegate = self self.fanCodeView = fanCodeView self.view.addSubview(fanCodeView) case .soundbox: let voiceBoxCodeView = TopVoiceBoxCodeView() voiceBoxCodeView.delegate = self self.voiceBoxCodeView = voiceBoxCodeView self.view.addSubview(voiceBoxCodeView) case .acFan: let acFanCodeView = TopACFanCodeView() self.acFanCodeView = acFanCodeView acFanCodeView.delegate = self self.view.addSubview(acFanCodeView) case .airPurifier: let airCleanCodeView = TopAirCleanCodeView() self.airCleanCodeView = airCleanCodeView airCleanCodeView.delegate = self self.view.addSubview(airCleanCodeView) case .curtain, .rcLight,.oneKey: let customSpecialView = TopCustomSpecialView() self.customSpecialView = customSpecialView customSpecialView.delegate = self customSpecialView.deviceInfo = deviceInfo self.view.addSubview(customSpecialView) default: break } }else if deviceInfo.mainType == .geeklink{ let glType: GLGlDevType = GLGlDevType(rawValue: Int(deviceInfo.subType))! switch glType { case .plug, .plugPower, .plugFour: let specialActionView = TopSpecialActionView() self.specialActionView = specialActionView specialActionView.deviceInfo = deviceInfo specialActionView.delegate = self self.view.addSubview(specialActionView) default: break } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(reloadKeyList), name:NSNotification.Name("thinkerKeyGetResp"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(thinkerKeySetResp), name:NSNotification.Name("thinkerKeySetResp"), object: nil) //刷新数据 getRefreshData() reloadKeyList() } func showNumberView() -> Void { let tVSTBNumberView = TopTVSTBNumberView(frame: UIScreen.main.bounds) self.tVSTBNumberView = tVSTBNumberView tVSTBNumberView.delegate = self let scaleAnimation = CABasicAnimation(keyPath: "transform") scaleAnimation.fromValue = NSValue(caTransform3D: CATransform3DMakeScale(0, 0, 1)) scaleAnimation.toValue = NSValue(caTransform3D: CATransform3DMakeScale(1, 1, 1)) scaleAnimation.duration = 0.2; scaleAnimation.isCumulative = false; scaleAnimation.repeatCount = 1; scaleAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) tVSTBNumberView.layer.add(scaleAnimation, forKey: "myScale") self.view.addSubview(tVSTBNumberView) } override func getRefreshData() { SGlobalVars.rcHandle.thinkerKeyGetReq(homeInfo.homeId, deviceIdSub: deviceInfo.deviceId) } override func viewWillDisappear(_ animated: Bool) { //移除监听 super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name("thinkerKeyGetResp"), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name("thinkerKeySetResp"), object: nil) TopStudyKeyTool.share().stopStudy() } // MARK: - Local @objc func onClickSaveButton() { let value = SGlobalVars.actionHandle.getDBACValueString(tempStateInfo) setMacroAction(value: value!) } func setMacroAction(value: String) { switch type { case .macroAction: let task: TopTask = TopDataManager.shared.task! task.value = value for vc in (navigationController?.viewControllers)! { if vc.isKind(of: TopAddTaskVC.classForCoder()) { let theVC: TopAddTaskVC = vc as! TopAddTaskVC theVC.addTask(task: task) navigationController?.popToViewController(vc, animated: true) return } } default: let smartPiTimerAction = TopDataManager.shared.smartPiTimerAction! smartPiTimerAction.value = value for vc in (navigationController?.viewControllers)! { if vc.isKind(of: TopAddOREditTimingVC.classForCoder()) { let theVC: TopAddOREditTimingVC = vc as! TopAddOREditTimingVC theVC.addOrUpdateTask(smartPiTimerAction) navigationController?.popToViewController(vc, animated: true) return } } } } func specialActionViewDidClickedBtn(_ index: Int32) { if deviceInfo.mainType == .geeklink{ let glType: GLGlDevType = GLGlDevType(rawValue: Int(deviceInfo.subType))! switch glType { case .plug, .plugPower, .plugFour: if index == 0 { self.setMacroAction(value: "11") }else { self.setMacroAction(value: "10") } default: break } } } func iPTVCodeViewDelegate(_ keyType: GLKeyType, databaceType: GLDbIptvKeyType, view: UIView) { if deviceInfo.mainType == .custom { self.addOrStudyKey(keyType, view: view) return } let value = SGlobalVars.actionHandle.getRCValueString(Int8(databaceType.rawValue)) setMacroAction(value: value!) } func numberViewDidclickedBtn(_ index: Int, btn: UIButton) { if deviceInfo.mainType == .database { self.addDatabaseNumberKey(index) }else { self.addCustomNumberKey(index, view: btn) } } func addCustomNumberKey(_ index: Int, view: UIView) -> Void{ var tvTypeList = [GLKeyType]() tvTypeList.append(.CTL1) tvTypeList.append(.CTL2) tvTypeList.append(.CTL3) tvTypeList.append(.CTL4) tvTypeList.append(.CTL5) tvTypeList.append(.CTL6) tvTypeList.append(.CTL7) tvTypeList.append(.CTL8) tvTypeList.append(.CTL9) tvTypeList.append(.CTL0) self.addOrStudyKey(tvTypeList[index], view: view) } func addDatabaseNumberKey(_ index: Int) -> Void { let databaseType = GLDatabaseType(rawValue: Int(deviceInfo.subType))! if databaseType == .TV { var tvTypeList = [GLDbTvKeyType]() tvTypeList.append(.TV1) tvTypeList.append(.TV2) tvTypeList.append(.TV3) tvTypeList.append(.TV4) tvTypeList.append(.TV5) tvTypeList.append(.TV6) tvTypeList.append(.TV7) tvTypeList.append(.TV8) tvTypeList.append(.TV9) tvTypeList.append(.TV0) let value = SGlobalVars.actionHandle.getRCValueString(Int8(tvTypeList[index].rawValue)) setMacroAction(value: value!) } else { var stbTypeList = Array<GLDbStbKeyType>() stbTypeList.append(.STB1) stbTypeList.append(.STB2) stbTypeList.append(.STB3) stbTypeList.append(.STB4) stbTypeList.append(.STB5) stbTypeList.append(.STB6) stbTypeList.append(.STB7) stbTypeList.append(.STB8) stbTypeList.append(.STB9) stbTypeList.append(.STB0) let value = SGlobalVars.actionHandle.getRCValueString(Int8(stbTypeList[index].rawValue)) setMacroAction(value: value!) } } }
37.118881
310
0.570158
f9b96bc1fc1476c566ee2fef0e42be47e04faf31
7,589
import UIKit public protocol DayViewDelegate: AnyObject { func dayViewDidSelectEventView(_ eventView: EventView) func dayViewDidLongPressEventView(_ eventView: EventView) func dayView(dayView: DayView, didTapTimelineAt date: Date) func dayView(dayView: DayView, didLongPressTimelineAt date: Date) func dayViewDidBeginDragging(dayView: DayView) func dayViewDidTransitionCancel(dayView: DayView) func dayView(dayView: DayView, willMoveTo date: Date) func dayView(dayView: DayView, didMoveTo date: Date) func dayView(dayView: DayView, didUpdate event: EventDescriptor) } public class DayView: UIView, TimelinePagerViewDelegate { public weak var dataSource: EventDataSource? { get { return timelinePagerView.dataSource } set(value) { timelinePagerView.dataSource = value } } public weak var delegate: DayViewDelegate? /// Hides or shows header view public var isHeaderViewVisible = true { didSet { headerHeight = isHeaderViewVisible ? DayView.headerVisibleHeight : 0 dayHeaderView.isHidden = !isHeaderViewVisible setNeedsLayout() configureLayout() } } public var timelineScrollOffset: CGPoint { return timelinePagerView.timelineScrollOffset } private static let headerVisibleHeight: CGFloat = 88 public var headerHeight: CGFloat = headerVisibleHeight public var autoScrollToFirstEvent: Bool { get { return timelinePagerView.autoScrollToFirstEvent } set (value) { timelinePagerView.autoScrollToFirstEvent = value } } public let dayHeaderView: DayHeaderView public let timelinePagerView: TimelinePagerView public var state: DayViewState? { didSet { dayHeaderView.state = state timelinePagerView.state = state } } public var calendar: Calendar = Calendar.autoupdatingCurrent public var eventEditingSnappingBehavior: EventEditingSnappingBehavior { get { timelinePagerView.eventEditingSnappingBehavior } set { timelinePagerView.eventEditingSnappingBehavior = newValue } } private var style = CalendarStyle() public init(calendar: Calendar = Calendar.autoupdatingCurrent) { self.calendar = calendar self.dayHeaderView = DayHeaderView(calendar: calendar) self.timelinePagerView = TimelinePagerView(calendar: calendar) super.init(frame: .zero) configure() } override public init(frame: CGRect) { self.dayHeaderView = DayHeaderView(calendar: calendar) self.timelinePagerView = TimelinePagerView(calendar: calendar) super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { self.dayHeaderView = DayHeaderView(calendar: calendar) self.timelinePagerView = TimelinePagerView(calendar: calendar) super.init(coder: aDecoder) configure() } private func configure() { addSubview(timelinePagerView) addSubview(dayHeaderView) configureLayout() timelinePagerView.delegate = self if state == nil { let newState = DayViewState(date: Date(), calendar: calendar) newState.move(to: Date()) state = newState } } private func configureLayout() { if #available(iOS 11.0, *) { dayHeaderView.translatesAutoresizingMaskIntoConstraints = false timelinePagerView.translatesAutoresizingMaskIntoConstraints = false dayHeaderView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor).isActive = true dayHeaderView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor).isActive = true dayHeaderView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor).isActive = true let heightConstraint = dayHeaderView.heightAnchor.constraint(equalToConstant: headerHeight) heightConstraint.priority = .defaultLow heightConstraint.isActive = true timelinePagerView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor).isActive = true timelinePagerView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor).isActive = true timelinePagerView.topAnchor.constraint(equalTo: dayHeaderView.bottomAnchor).isActive = true timelinePagerView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } } public func updateStyle(_ newStyle: CalendarStyle) { style = newStyle dayHeaderView.updateStyle(style.header) timelinePagerView.updateStyle(style.timeline) } public func timelinePanGestureRequire(toFail gesture: UIGestureRecognizer) { timelinePagerView.timelinePanGestureRequire(toFail: gesture) } public func scrollTo(hour24: Float, animated: Bool = true) { timelinePagerView.scrollTo(hour24: hour24, animated: animated) } public func scrollToFirstEventIfNeeded(animated: Bool = true) { timelinePagerView.scrollToFirstEventIfNeeded(animated: animated) } public func scrollToTopIn8AMTo5PMView(y : Int) { timelinePagerView.scrollToTopIn8AMTo5PMView(y: y) } public func reloadData() { timelinePagerView.reloadData() } public func move(to date: Date) { state?.move(to: date) } override public func layoutSubviews() { super.layoutSubviews() if #available(iOS 11, *) {} else { dayHeaderView.frame = CGRect(origin: CGPoint(x: 0, y: layoutMargins.top), size: CGSize(width: bounds.width, height: headerHeight)) let timelinePagerHeight = bounds.height - dayHeaderView.frame.maxY timelinePagerView.frame = CGRect(origin: CGPoint(x: 0, y: dayHeaderView.frame.maxY), size: CGSize(width: bounds.width, height: timelinePagerHeight)) } } public func transitionToHorizontalSizeClass(_ sizeClass: UIUserInterfaceSizeClass) { dayHeaderView.transitionToHorizontalSizeClass(sizeClass) updateStyle(style) } public func create(event: EventDescriptor, animated: Bool = false) { timelinePagerView.create(event: event, animated: animated) } public func beginEditing(event: EventDescriptor, animated: Bool = false) { timelinePagerView.beginEditing(event: event, animated: animated) } public func endEventEditing() { timelinePagerView.endEventEditing() } // MARK: TimelinePagerViewDelegate public func timelinePagerDidSelectEventView(_ eventView: EventView) { delegate?.dayViewDidSelectEventView(eventView) } public func timelinePagerDidLongPressEventView(_ eventView: EventView) { delegate?.dayViewDidLongPressEventView(eventView) } public func timelinePagerDidBeginDragging(timelinePager: TimelinePagerView) { delegate?.dayViewDidBeginDragging(dayView: self) } public func timelinePagerDidTransitionCancel(timelinePager: TimelinePagerView) { delegate?.dayViewDidTransitionCancel(dayView: self) } public func timelinePager(timelinePager: TimelinePagerView, willMoveTo date: Date) { delegate?.dayView(dayView: self, willMoveTo: date) } public func timelinePager(timelinePager: TimelinePagerView, didMoveTo date: Date) { delegate?.dayView(dayView: self, didMoveTo: date) } public func timelinePager(timelinePager: TimelinePagerView, didLongPressTimelineAt date: Date) { delegate?.dayView(dayView: self, didLongPressTimelineAt: date) } public func timelinePager(timelinePager: TimelinePagerView, didTapTimelineAt date: Date) { delegate?.dayView(dayView: self, didTapTimelineAt: date) } public func timelinePager(timelinePager: TimelinePagerView, didUpdate event: EventDescriptor) { delegate?.dayView(dayView: self, didUpdate: event) } }
34.811927
110
0.745948
c167ff8791b8cba10865e3d435d9349ede27ef68
669
import Kingfisher import UIKit final class NovaTintImageProcessor: ImageProcessor { let identifier: String let tintColor: UIColor func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case let .image(kFCrossPlatformImage): return kFCrossPlatformImage.tinted(with: tintColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } init(tintColor: UIColor) { identifier = "io.novafoundation.novawallet.kf.tint(\(tintColor.hexRGBA))" self.tintColor = tintColor } }
30.409091
105
0.684604
f714aa4b1386a9a89540b00582f6619d45c138cb
955
import Foundation import CoreGraphics #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #endif public struct Color : Codable { public let red : CGFloat public let green : CGFloat public let blue : CGFloat public let alpha : CGFloat public init(from decoder: Decoder) throws { let hexCode = try decoder.singleValueContainer().decode(String.self) let scanner = Scanner(string: hexCode) var hexint : UInt32 = 0 scanner.scanHexInt32(&hexint) self.red = CGFloat((hexint & 0xff0000) >> 16) / 255.0 self.green = CGFloat((hexint & 0xff00) >> 8) / 255.0 self.blue = CGFloat((hexint & 0xff) >> 0) / 255.0 self.alpha = 1 } public func encode(to encoder: Encoder) throws { let string = String(format: "%02lX%02lX%02lX", lroundf(Float(red * 255.0)), lroundf(Float(green * 255.0)), lroundf(Float(blue * 255.0))) var container = encoder.singleValueContainer() try container.encode(string) } }
28.088235
140
0.66911
9b4b8706df65282c751baf28e746fe90e896b849
5,291
/* * Copyright (C) 2019-2022 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ import heresdk import UIKit class ViewController: UIViewController, ManeuverNotificationDelegate { @IBOutlet var mapView: MapView! private var routingEngine: RoutingEngine? private var visualNavigator: VisualNavigator? private var locationSimulator: LocationSimulator? override func viewDidLoad() { super.viewDidLoad() // Load the map scene using a map scheme to render the map with. mapView.mapScene.loadScene(mapScheme: MapScheme.normalDay, completion: onLoadScene) } private func onLoadScene(mapError: MapError?) { guard mapError == nil else { print("Error: Map scene not loaded, \(String(describing: mapError))") return } // Configure the map. let camera = mapView.camera camera.lookAt(point: GeoCoordinates(latitude: 52.518043, longitude: 13.405991), distanceInMeters: 1000 * 10) startGuidanceExample() } private func startGuidanceExample() { showDialog(title: "Navigation Quick Start", message: "This app routes to the HERE office in Berlin. See logs for guidance information.") // We start by calculating a car route. calculateRoute() } private func calculateRoute() { do { try routingEngine = RoutingEngine() } catch let engineInstantiationError { fatalError("Failed to initialize routing engine. Cause: \(engineInstantiationError)") } let startWaypoint = Waypoint(coordinates: GeoCoordinates(latitude: 52.520798, longitude: 13.409408)) let destinationWaypoint = Waypoint(coordinates: GeoCoordinates(latitude: 52.530905, longitude: 13.385007)) routingEngine!.calculateRoute(with: [startWaypoint, destinationWaypoint], carOptions: CarOptions()) { (routingError, routes) in if let error = routingError { print("Error while calculating a route: \(error)") return } // When routingError is nil, routes is guaranteed to contain at least one route. self.startGuidance(route: routes!.first!) } } private func startGuidance(route: Route) { do { // Without a route set, this starts tracking mode. try visualNavigator = VisualNavigator() } catch let engineInstantiationError { fatalError("Failed to initialize VisualNavigator. Cause: \(engineInstantiationError)") } // This enables a navigation view including a rendered navigation arrow. visualNavigator!.startRendering(mapView: mapView) // Hook in one of the many listeners. Here we set up a listener to get instructions on the maneuvers to take while driving. // For more details, please check the "Navigation" example app and the Developer's Guide. visualNavigator!.maneuverNotificationDelegate = self // Set a route to follow. This leaves tracking mode. visualNavigator!.route = route // VisualNavigator acts as LocationDelegate to receive location updates directly from a location provider. // Any progress along the route is a result of getting a new location fed into the VisualNavigator. setupLocationSource(locationDelegate: visualNavigator!, route: route) } // Conform to ManeuverNotificationDelegate. func onManeuverNotification(_ text: String) { print("ManeuverNotifications: \(text)") } private func setupLocationSource(locationDelegate: LocationDelegate, route: Route) { do { // Provides fake GPS signals based on the route geometry. try locationSimulator = LocationSimulator(route: route, options: LocationSimulatorOptions()) } catch let instantiationError { fatalError("Failed to initialize LocationSimulator. Cause: \(instantiationError)") } locationSimulator!.delegate = locationDelegate locationSimulator!.start() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() mapView.handleLowMemory() } private func showDialog(title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } }
39.485075
131
0.664525
7a7d0b66ff12f3ef3996f4f5a521ad759ea2faa8
196
import Foundation public struct StreamDeckAction<Payload: Encodable>: Encodable { let event: StreamDeckActionType let context: String let payload: Payload? let action: String? }
19.6
63
0.739796
18e27f5777ea805585fe051da36f57f9be0a8d99
2,820
// // AnswerModelSpec.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class AnswerModelSpec: QuickSpec { override func spec() { super.spec() describe("answer initialization") { context("answer") { it("is created form good dictionary") { let dict = JsonLibrary.answer(id: 2, title: "Title", nextMap: ["id": 5, "node_type": "question"]) let answer = try! AnswerFactory(with: dict).build() expect(answer.answerId).to(equal(2)) expect(answer.title).to(equal("Title")) expect(answer.nextNodeId).to(equal(5)) } it("is created form good dictionary without next map") { let dict = JsonLibrary.answer(id: 3, title: "Title") let answer = try! AnswerFactory(with: dict).build() expect(answer.answerId).to(equal(3)) expect(answer.title).to(equal("Title")) expect(answer.nextNodeId).to(beNil()) } it("is not allowing freeform when there is no \"explain_type\" key") { let answer = try! AnswerFactory(with: JsonLibrary.answer()).build() expect(answer.isFreeformCommentAllowed).to(beFalse()) } it("is not allowing freeform when there is empty \"explain_type\" key") { var dict = JsonLibrary.answer() dict["explain_type"] = "" let answer = try! AnswerFactory(with: dict).build() expect(answer.isFreeformCommentAllowed).to(beFalse()) } it("has allow freeform when there is non-empty \"explain_type\" key") { var dict = JsonLibrary.answer() dict["explain_type"] = "short" let answer = try! AnswerFactory(with: dict).build() expect(answer.isFreeformCommentAllowed).to(beTrue()) } it("throws error if there is no id") { let dict = JsonLibrary.answer(id: nil) let factory = AnswerFactory(with: dict) expect { try factory.build() }.to(throwError()) } it("throws error if there is wrong id") { var dict = JsonLibrary.answer(id: nil) dict["id"] = "text" let factory = AnswerFactory(with: dict) expect { try factory.build() }.to(throwError()) } it("throws error if there is no title") { let dict = JsonLibrary.answer(title: nil) let factory = AnswerFactory(with: dict) expect { try factory.build() }.to(throwError()) } } } } }
33.571429
107
0.578369
21e250b786514116b0a6d3a4af992807c3c3793e
752
import Vapor struct V: Content { } struct Wrapper<T: Content>: ResponseEncodable { private struct Container<T: Content>: Content { var message: String? var data: T? init(of data: T? = nil, _ message: String? = nil) { self.data = data self.message = message } } private var container: Container<T> var status: HTTPStatus init(of data: T? = nil, _ message: String? = nil, with status: HTTPStatus = .ok) { self.status = status self.container = Container(of: data, message) } func encode(for request: Request) -> EventLoopFuture<Response> { return container.encode(status: status, for: request) } }
24.258065
86
0.571809
d96b6b25928135590eecc2708f1b43a301a03ce6
517
// // MTPowerKaleidoTransition.swift // MTTransitions // // Created by alexis on 2022/4/5. // import Foundation public class MTPowerKaleidoTransition: MTTransition { public var scale: Float = 2.0 public var z: Float = 1.5 public var speed: Float = 5.0 override var fragmentName: String { return "PowerKaleidoFragment" } override var parameters: [String: Any] { return [ "scale": scale, "z": z, "speed": speed ] } }
17.233333
53
0.580271
8940af5a696dc11ecd32fba31991e1b383e66330
1,114
// // ConfigurationParseError.swift // DVPNApp // // Created by Lika Vorobyeva on 17.06.2021. // import Foundation enum ConfigurationParserState { case inInterfaceSection case inPeerSection case notInASection } enum ConfigurationParseError: Error { case invalidLine(String.SubSequence) case noInterface case multipleInterfaces case interfaceHasNoPrivateKey case interfaceHasInvalidPrivateKey(String) case interfaceHasInvalidListenPort(String) case interfaceHasInvalidAddress(String) case interfaceHasInvalidDNS(String) case interfaceHasInvalidMTU(String) case interfaceHasUnrecognizedKey(String) case peerHasNoPublicKey case peerHasInvalidPublicKey(String) case peerHasInvalidPreSharedKey(String) case peerHasInvalidAllowedIP(String) case peerHasInvalidEndpoint(String) case peerHasInvalidPersistentKeepAlive(String) case peerHasInvalidTransferBytes(String) case peerHasInvalidLastHandshakeTime(String) case peerHasUnrecognizedKey(String) case multiplePeersWithSamePublicKey case multipleEntriesForKey(String) }
28.564103
50
0.794434
091fb1c103abbceea266c418082bc1c1e9f1868b
754
// // Pass+Location.swift // // // Created by Jing Wei Li on 6/5/21. // import Foundation public extension Pass { /// [Documentation](https://developer.apple.com/documentation/walletpasses/pass/locations) struct Location: Codable { public let latitude: Double public let longitude: Double public let altitude: Double? public let relevantText: String? public init( latitude: Double, longitude: Double, altitude: Double? = nil, relevantText: String? = nil ) { self.latitude = latitude self.longitude = longitude self.altitude = altitude self.relevantText = relevantText } } }
23.5625
94
0.575597
f5507816b7a9cff7af25e83c91fdb8691bdd3259
2,281
// // OrderReturnRoutes.swift // Stripe // // Created by Andrew Edwards on 8/25/17. // // import NIO import NIOHTTP1 public protocol OrderReturnRoutes { /// Retrieves the details of an existing order return. Supply the unique order ID from either an order return creation request or the order return list, and Stripe will return the corresponding order information. /// /// - Parameter id: The identifier of the order return to be retrieved. /// - Returns: A `StripeOrderReturn`. /// - Throws: A `StripeError`. func retrieve(id: String) throws -> EventLoopFuture<StripeOrderReturn> /// Returns a list of your order returns. The returns are returned sorted by creation date, with the most recently created return appearing first. /// /// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/order_returns/list) /// - Returns: A `StripeOrderReturnList`. /// - Throws: A `StripeError` func listAll(filter: [String: Any]?) throws -> EventLoopFuture<StripeOrderReturnList> var headers: HTTPHeaders { get set } } extension OrderReturnRoutes { public func retrieve(id: String) throws -> EventLoopFuture<StripeOrderReturn> { return try retrieve(id: id) } public func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture<StripeOrderReturnList> { return try listAll(filter: filter) } } public struct StripeOrderReturnRoutes: OrderReturnRoutes { private let apiHandler: StripeAPIHandler public var headers: HTTPHeaders = [:] init(apiHandler: StripeAPIHandler) { self.apiHandler = apiHandler } public func retrieve(id: String) throws -> EventLoopFuture<StripeOrderReturn> { return try apiHandler.send(method: .GET, path: StripeAPIEndpoint.orderReturns(id).endpoint, headers: headers) } public func listAll(filter: [String: Any]?) throws -> EventLoopFuture<StripeOrderReturnList> { var queryParams = "" if let filter = filter { queryParams = filter.queryParameters } return try apiHandler.send(method: .GET, path: StripeAPIEndpoint.orderReturn.endpoint, query: queryParams, headers: headers) } }
37.393443
216
0.692679
dd66592160775962a82666e12327e4055180d7e9
2,639
// // ViewController.swift // ImageDownloader // // Created by David Thorn on 26.06.19. // Copyright © 2019 David Thorn. All rights reserved. // import UIKit let downloadUrl: URL = URL(string: "https://upload.wikimedia.org/wikipedia/commons/a/a2/Porsche_911_No_1000000%2C_70_Years_Porsche_Sports_Car%2C_Berlin_%281X7A3888%29.jpg")! class ViewController: UIViewController { var count: Int = 0 @IBOutlet weak var counter: UILabel! lazy var que: DispatchQueue = { return DispatchQueue.init(label: "ViewController.background" , attributes: .concurrent) }() lazy var que1: DispatchQueue = { return DispatchQueue.init(label: "ViewController.background.1" , attributes: .concurrent) }() @IBOutlet weak var downloadButton: UIButton! @IBOutlet weak var imageContainer: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.doCount() // self.que1.async { // let image = UIImage.init(data: try! Data(contentsOf: downloadUrl)) // DispatchQueue.main.async { // self.imageContainer.image = image // } // } } func doCount() { self.que.async { repeat { usleep(500) self.count += 1 DispatchQueue.main.async { self.counter.text = "Counter \(self.count) " } } while true } } @IBAction func downloadAction(_ sender: Any) { self.downloadButton.isEnabled = false URLSession.shared.dataTask(with: downloadUrl) { (data, response, error) in guard let httpResponse = response as? HTTPURLResponse else { fatalError("something went wrong here") } switch httpResponse.statusCode { case 200: guard let imageData = data else { fatalError("not image data") } guard let image = UIImage.init(data: imageData) else { fatalError("not valid image data") } DispatchQueue.main.async { self.imageContainer.image = image self.downloadButton.isEnabled = true self.counter.text = "Counter \(self.count) " } default: fatalError("not 200 response provided") } }.resume() } }
28.376344
173
0.526715
b9376e4a4c60559ee99e41774c50055fda2cee7b
217
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A<T where g:c}class B<T{func c}func c:A.b
36.166667
87
0.75576
1db720e882f534549ff7cac522e21e98d3e7d69f
2,932
import SwiftUI import SceneKit struct ContentView: View { @State var models = [ Model(id: 0, name: "Rumba Dancing", modelName: "RumbaDancing.dae"), Model(id: 1, name: "Samba Dancing 1", modelName: "SambaDancing1.dae"), Model(id: 2, name: "Samba Dancing 2", modelName: "SambaDancing2.dae"), Model(id: 3, name: "Hip Hop Dancing", modelName: "HipHopDancing.dae"), Model(id: 4, name: "Silly Dancing 1", modelName: "SillyDancing1.dae"), Model(id: 5, name: "Silly Dancing 2", modelName: "SillyDancing2.dae"), ] @State var index = 0 var body: some View { ZStack(alignment: .top) { Color("white").edgesIgnoringSafeArea(.all) ZStack(alignment: .bottom) { // 3D Models SceneView( scene: SCNScene(named: models[index].modelName), options: [.autoenablesDefaultLighting, .allowsCameraControl] ) // Controls HStack { Button(action: { withAnimation { if index > 0 { index -= 1 } } }, label: { Image(systemName: "arrow.left.circle.fill") .font(.system(size: 32, weight: .bold)) .foregroundColor(Color("dark")) .opacity(index == 0 ? 0.2 : 1) }) .disabled(index == 0 ? true : false) Spacer(minLength: 0) Button(action: { withAnimation { if index < models.count { index += 1 } } }, label: { Image(systemName: "arrow.right.circle.fill") .font(.system(size: 32, weight: .bold)) .foregroundColor(Color("dark")) .opacity(index == models.count - 1 ? 0.2 : 1) }) .disabled(index == models.count - 1 ? true : false) } .padding(.horizontal, 16) .padding(.bottom, 32) } .frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height) .ignoresSafeArea(.all, edges: .all) } .statusBar(hidden: true) } } // Data Model struct Model: Identifiable { var id : Int var name : String var modelName : String } #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif
33.318182
100
0.435198
e2005cd4ed6a9c823bec8adaecbfeec5ead76aee
8,947
// // RealmBarDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if NEEDS_CHARTS import Charts #endif import Realm import Realm.Dynamic public class RealmBarDataSet: RealmBarLineScatterCandleBubbleDataSet, IBarChartDataSet { public override func initialize() { self.highlightColor = NSUIColor.blackColor() } public required init() { super.init() } public override init(results: RLMResults?, yValueField: String, xIndexField: String?, label: String?) { super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label) } public init(results: RLMResults?, yValueField: String, xIndexField: String?, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label) } public convenience init(results: RLMResults?, yValueField: String, xIndexField: String?, stackValueField: String) { self.init(results: results, yValueField: yValueField, xIndexField: xIndexField, stackValueField: stackValueField, label: "DataSet") } public convenience init(results: RLMResults?, yValueField: String, stackValueField: String, label: String) { self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label) } public convenience init(results: RLMResults?, yValueField: String, stackValueField: String) { self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField) } public override init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, label: String?) { super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label) } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String, label: String?) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: nil) } public override func notifyDataSetChanged() { _cache.removeAll() ensureCache(0, end: entryCount - 1) self.calcStackSize(_cache as! [BarChartDataEntry]) super.notifyDataSetChanged() } // MARK: - Data functions and accessors internal var _stackValueField: String? /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet private var _stackSize = 1 internal override func buildEntryFromResultObject(object: RLMObject, atIndex: UInt) -> ChartDataEntry { let value = object[_yValueField!] let entry: BarChartDataEntry if value is RLMArray { var values = [Double]() for val in value as! RLMArray { values.append((val as! RLMObject)[_stackValueField!] as! Double) } entry = BarChartDataEntry(values: values, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int) } else { entry = BarChartDataEntry(value: value as! Double, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int) } return entry } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet private func calcStackSize(yVals: [BarChartDataEntry]!) { for i in 0 ..< yVals.count { if let vals = yVals[i].values { if vals.count > _stackSize { _stackSize = vals.count } } } } public override func calcMinMax(start start : Int, end: Int) { let yValCount = self.entryCount if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } ensureCache(start, end: endValue) if _cache.count == 0 { return } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MAX for i in start.stride(through: endValue, by: 1) { if let e = _cache[i - _cacheFirst] as? BarChartDataEntry { if !e.value.isNaN { if e.values == nil { if e.value < _yMin { _yMin = e.value } if e.value > _yMax { _yMax = e.value } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } /// - returns: the maximum number of bars that can be stacked upon another in this DataSet. public var stackSize: Int { return _stackSize } /// - returns: true if this DataSet is stacked (stacksize > 1) or not. public var isStacked: Bool { return _stackSize > 1 ? true : false } /// array of labels used to describe the different values of the stacked bars public var stackLabels: [String] = ["Stack"] // MARK: - Styling functions and accessors /// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width) public var barSpace: CGFloat = 0.15 /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value public var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn. public var barBorderWidth : CGFloat = 0.0 /// the color drawing borders around the bars. public var barBorderColor = NSUIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0) /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) public var highlightAlpha = CGFloat(120.0 / 255.0) // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmBarDataSet copy._stackSize = _stackSize copy.stackLabels = stackLabels copy.barSpace = barSpace copy.barShadowColor = barShadowColor copy.highlightAlpha = highlightAlpha return copy } }
34.148855
173
0.590701
2663e2236305ab0fe61d4ac52b84179151e793fb
206
import LightRoute final class OwnerRouter: OwnerRouterInput { weak var transitionHandler: TransitionHandler! func dismiss() { try! transitionHandler.closeCurrentModule().perform() } }
20.6
61
0.728155
3abf669d4a1c779ba01bbb745ea27a89c889657b
9,419
// // Request.swift // Remote // // Created by Dmitry Klimkin on 22/8/17. // Copyright © 2017 Dev4Jam. All rights reserved. import Foundation /// Define what kind of HTTP method must be used to carry out the `Request` /// /// - get: get (no body is allowed inside) /// - post: post /// - put: put /// - delete: delete /// - patch: patch public enum RequestMethod: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" case patch = "PATCH" } public struct MultipartData { public let parameters: [String: Any] public let files: [MultipartDataFile] public init(parameters: [String: Any], files: [MultipartDataFile]) { self.parameters = parameters self.files = files } } public struct MultipartDataFile { public let name: String public let mimeType: String public let data: Data public init(name: String, mimeType: String, data: Data) { self.name = name self.mimeType = mimeType self.data = data } } /// This define how the body should be encoded /// /// - none: no transformation is applied, data is sent raw as received in `body` param of the request. /// - json: attempt to serialize a `Dictionary` or a an `Array` as `json`. Other types are not supported and throw an exception. /// - urlEncoded: it expect a `Dictionary` as input and encode it as url encoded string into the body. /// - custom->: custom serializer. `Any` is accepted, `Data` is expected as output. public struct RequestBody { /// Data to carry out into the body of the request public let data: Any /// Type of encoding to use public let encoding: Encoding /// Encoding type /// /// - raw: no encoding, data is sent as received /// - json: json encoding /// - urlEncoded: url encoded string /// - custom: custom serialized data public enum Encoding { case rawData case rawString(_: String.Encoding?) case json case urlEncoded(_: String.Encoding?) case multipart(String) case custom(_: CustomEncoder) /// Encoder function typealias public typealias CustomEncoder = ((Any) -> (Data)) } /// Private initializa a new body /// /// - Parameters: /// - data: data /// - encoding: encoding type private init(_ data: Any, as encoding: Encoding = .json) { self.data = data self.encoding = encoding } /// Create a new body which will be encoded as JSON /// /// - Parameter data: any serializable to JSON object /// - Returns: RequestBody public static func json(_ data: Any) -> RequestBody { return RequestBody(data, as: .json) } /// Create a new body which will be encoded as url encoded string /// /// - Parameters: /// - data: a string of encodable data as url /// - encoding: encoding type to transform the string into data /// - Returns: RequestBody public static func urlEncoded(_ data: ParametersDict, encoding: String.Encoding? = .utf8) -> RequestBody { return RequestBody(data, as: .urlEncoded(encoding)) } /// Create a new body which will be sent in raw form /// /// - Parameter data: data to send /// - Returns: RequestBody public static func raw(data: Data) -> RequestBody { return RequestBody(data, as: .rawData) } /// Create a new body which will be sent as plain string encoded as you set /// /// - Parameter data: data to send /// - Returns: RequestBody public static func raw(string: String, encoding: String.Encoding? = .utf8) -> RequestBody { return RequestBody(string, as: .rawString(encoding)) } /// Create a new body which will be sent as multipart encoded data /// /// - Parameter: /// - boundary: boundary key /// - payload: payload to send /// - Returns: RequestBody public static func multipart(boundary: String, payload: MultipartData) -> RequestBody { return RequestBody(payload, as: .multipart(boundary)) } /// Create a new body which will be encoded with a custom function. /// /// - Parameters: /// - data: data to encode /// - encoder: encoder function /// - Returns: RequestBody public static func custom(_ data: Data, encoder: @escaping Encoding.CustomEncoder) -> RequestBody { return RequestBody(data, as: .custom(encoder)) } /// Encoded data to carry out with the request /// /// - Returns: Data public func encodedData() throws -> Data { switch self.encoding { case .rawData: return self.data as! Data case .rawString(let encoding): guard let string = (self.data as! String).data(using: encoding ?? .utf8) else { throw NetworkError.dataIsNotEncodable("can't encode data") } return string case .json: return try JSONSerialization.data(withJSONObject: self.data, options: .prettyPrinted) case .urlEncoded(let encoding): let encodedString = try (self.data as! ParametersDict).urlEncodedString() guard let data = encodedString.data(using: encoding ?? .utf8) else { throw NetworkError.dataIsNotEncodable(encodedString) } return data case .multipart(let boundary): guard let payload = data as? MultipartData else { throw NetworkError.dataIsNotEncodable("can't encode data") } let body = NSMutableData() let boundaryPrefix = "--\(boundary)\r\n" for (key, value) in payload.parameters { body.appendString(boundaryPrefix) body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.appendString("\(value)\r\n") } for file in payload.files { body.appendString(boundaryPrefix) body.appendString("Content-Disposition: form-data; name=\"\(file.name)\"\r\n") body.appendString("Content-Type: \(file.mimeType)\r\n\r\n") body.append(file.data) body.appendString("\r\n") } body.appendString("--\(boundary)--\r\n") return body as Data case .custom(let encodingFunc): return encodingFunc(self.data) } } /// Return the representation of the body as `String` /// /// - Parameter encoding: encoding use to read body's data. If not specified `utf8` is used. /// - Returns: String /// - Throws: throw an exception if string cannot be decoded as string public func encodedString(_ encoding: String.Encoding = .utf8) throws -> String { let encodedData = try self.encodedData() guard let stringRepresentation = String(data: encodedData, encoding: encoding) else { throw NetworkError.stringFailedToDecode("can't encode data") } return stringRepresentation } } public class Request: RequestProtocol, CustomStringConvertible { /// Endpoint for request public var endpoint: String /// Body of the request public var body: RequestBody? /// HTTP method of the request public var method: RequestMethod? /// Fields of the request public var fields: ParametersDict? /// URL of the request public var urlParams: ParametersDict? /// Headers of the request public var headers: HeadersDict? /// Cache policy public var cachePolicy: URLRequest.CachePolicy? /// Timeout of the request public var timeout: TimeInterval? public var isCacheable: Bool /// Initialize a new request /// /// - Parameters: /// - method: HTTP Method request (if not specified, `.get` is used) /// - endpoint: endpoint of the request /// - params: paramters to replace in endpoint /// - fields: fields to append inside the url /// - body: body to set public init(method: RequestMethod = .get, endpoint: String = "", params: ParametersDict? = nil, fields: ParametersDict? = nil, body: RequestBody? = nil, isCacheable: Bool = false) { self.method = method self.endpoint = endpoint self.urlParams = params self.fields = fields self.body = body self.isCacheable = isCacheable self.headers = [ "Content-Encoding": "UTF-8", "Content-Type": "application/json", "Accept": "application/json", "x-pretty-print": "2" ] } public var description: String { var text = "\(method?.rawValue ?? "") endpoint: \(endpoint)" do { if let f = fields { let fText = try f.urlEncodedString() text += "\nFields: " + fText } } catch { } do { if let f = urlParams { let fText = try f.urlEncodedString() text += "\nURL Params: " + fText } } catch { } return text } } extension NSMutableData { func appendString(_ string: String) { if let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false) { append(data) } } }
32.367698
128
0.598365
28ebdd2372b2daa37f082a410d2126aeacf3fd0c
672
// // SettingsLogOutCell.swift // Pretto // // Created by Francisco de la Pena on 7/11/15. // Copyright (c) 2015 Pretto. All rights reserved. // import UIKit class SettingsLogOutCell: UITableViewCell { @IBOutlet weak var logOutButton: UILabel! override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .None self.accessoryType = .None logOutButton.textColor = UIColor.prettoOrange() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
22.4
63
0.66369
116346a35dcaf56e568f67781e2a42d200a0401c
599
// // UsersLikeModel.swift // Targeter // // Created by Alexander Kolbin on 6/25/21. // Copyright © 2021 Alder. All rights reserved. // import Foundation class UsersLikeModel { var likesCount: Int? var uid: String? var timestamp: Int? } extension UsersLikeModel { static func transformToLikeModel(dict: [String:Any], uid: String) -> UsersLikeModel { let like = UsersLikeModel() like.likesCount = dict[Constants.Like.likesCount] as? Int like.uid = uid like.timestamp = dict[Constants.Like.lastLikeTimestamp] as? Int return like } }
22.185185
89
0.66611
fe65c8f66d455b222148d126ed10f955880f56c3
2,934
// // EKRatingMessageView.swift // SwiftEntryKit // // Created by Daniel Huri on 6/1/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit import QuickLayout public class EKRatingMessageView: UIView { private var message: EKRatingMessage private var selectedIndex: Int! { didSet { message.selectedIndex = selectedIndex let item = message.ratingItems[selectedIndex] set(title: item.title, description: item.description) } } private let messageContentView = EKMessageContentView() private let symbolsView = EKRatingSymbolsContainerView() private var buttonBarView: EKButtonBarView! public init(with message: EKRatingMessage) { self.message = message super.init(frame: UIScreen.main.bounds) setupMessageContentView() setupSymbolsView() setupButtonBarView() set(title: message.initialTitle, description: message.initialDescription) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func set(title: EKProperty.LabelContent, description: EKProperty.LabelContent) { self.messageContentView.titleContent = title self.messageContentView.subtitleContent = description UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.transitionCrossDissolve], animations: { SwiftEntryKit.layoutIfNeeded() }, completion: nil) } private func setupMessageContentView() { addSubview(messageContentView) messageContentView.verticalMargins = 20 messageContentView.horizontalMargins = 30 messageContentView.layoutToSuperview(axis: .horizontally, priority: .must) messageContentView.layoutToSuperview(.top, offset: 10) } private func setupSymbolsView() { addSubview(symbolsView) symbolsView.setup(with: message) { [unowned self] (index: Int) in self.message.selectedIndex = index self.message.selection?(index) self.selectedIndex = index self.animateIn() } symbolsView.layoutToSuperview(.centerX) symbolsView.layout(.top, to: .bottom, of: messageContentView, offset: 10, priority: .must) } private func setupButtonBarView() { buttonBarView = EKButtonBarView(with: message.buttonBarContent) buttonBarView.clipsToBounds = true buttonBarView.alpha = 0 addSubview(buttonBarView) buttonBarView.layout(.top, to: .bottom, of: symbolsView, offset: 30) buttonBarView.layoutToSuperview(.bottom) buttonBarView.layoutToSuperview(axis: .horizontally) } // MARK: Internal Animation private func animateIn() { layoutIfNeeded() buttonBarView.expand() } }
34.517647
155
0.675528
d7825602bdc4776c8d60462d7c4e6dbd2421f6a7
2,578
// // DownCommonMarkRenderable.swift // Down // // Created by Rob Phillips on 5/31/16. // Copyright © 2016 Glazed Donut, LLC. All rights reserved. // import Foundation import libcmark-gfm public protocol DownCommonMarkRenderable: DownRenderable { /** Generates a CommonMark Markdown string from the `markdownString` property - parameter options: `DownOptions` to modify parsing or rendering - parameter width: The width to break on - throws: `DownErrors` depending on the scenario - returns: CommonMark Markdown string */ func toCommonMark(_ options: DownOptions, width: Int32) throws -> String } public extension DownCommonMarkRenderable { /** Generates a CommonMark Markdown string from the `markdownString` property - parameter options: `DownOptions` to modify parsing or rendering, defaulting to `.Default` - parameter width: The width to break on, defaulting to 0 - throws: `DownErrors` depending on the scenario - returns: CommonMark Markdown string */ public func toCommonMark(_ options: DownOptions = .Default, width: Int32 = 0) throws -> String { let ast = try DownASTRenderer.stringToAST(markdownString, options: options) let commonMark = try DownCommonMarkRenderer.astToCommonMark(ast, options: options, width: width) cmark_node_free(ast) return commonMark } } public struct DownCommonMarkRenderer { /** Generates a CommonMark Markdown string from the given abstract syntax tree **Note:** caller is responsible for calling `cmark_node_free(ast)` after this returns - parameter options: `DownOptions` to modify parsing or rendering, defaulting to `.Default` - parameter width: The width to break on, defaulting to 0 - throws: `ASTRenderingError` if the AST could not be converted - returns: CommonMark Markdown string */ public static func astToCommonMark(_ ast: UnsafeMutablePointer<cmark_node>, options: DownOptions = .Default, width: Int32 = 0) throws -> String { guard let cCommonMarkString = cmark_render_commonmark(ast, options.rawValue, width) else { throw DownErrors.astRenderingError } defer { free(cCommonMarkString) } guard let commonMarkString = String(cString: cCommonMarkString, encoding: String.Encoding.utf8) else { throw DownErrors.astRenderingError } return commonMarkString } }
33.921053
110
0.676106
e8d18bd7aeb4f000b98d681d47f4d24732ef47fd
1,655
// // V1Collection.swift // App // // Created by Johnny Nguyen on 2017-10-05. // import Vapor import HTTP import Crypto public final class V1Collection: EmptyInitializable, RouteCollection { public init() { } public func build(_ builder: RouteBuilder) throws { // gets the versioning for future release let api = builder.grouped("api", "v1") //MARK: - Authentication let authController = AuthController() api.group("auth") { auth in auth.post("register", handler: authController.register) auth.post("login", handler: authController.login) auth.post("verify", handler: authController.verify) auth.post("resend", handler: authController.resend) } //MARK: - Users try api.grouped(TokenMiddleware()).resource("users", UserController.self) //MARK: - Friends let friendController = FriendController() api.grouped(TokenMiddleware()).group("users", ":userId") { friend in friend.resource("friends", friendController) friend.get("friends", ":friendId", handler: friendController.getFriend) friend.patch("friends", ":friendId", handler: friendController.updateFriend) friend.delete("friends", ":friendId", handler: friendController.removeFriend) friend.get("friends", "requests", handler: friendController.getFriendRequests) friend.get("friends", ":friendId", "requests", handler: friendController.getFriendRequest) } //MARK: - Meetup try api.grouped(TokenMiddleware()).resource("meetups", MeetupController.self) //MARK: - Invites try api.grouped(TokenMiddleware()).resource("invites", InviteController.self) } }
33.77551
96
0.693656
f844fbd55f5d829cd1231ce9ae864dbf76ab67d1
9,368
import Flutter import UIKit import HealthKit public class SwiftHealthPlugin: NSObject, FlutterPlugin { let healthStore = HKHealthStore() var healthDataTypes = [HKSampleType]() var heartRateEventTypes = Set<HKSampleType>() var allDataTypes = Set<HKSampleType>() var dataTypesDict: [String: HKSampleType] = [:] var unitDict: [String: HKUnit] = [:] // Health Data Type Keys let BODY_FAT_PERCENTAGE = "BODY_FAT_PERCENTAGE" let HEIGHT = "HEIGHT" let WEIGHT = "WEIGHT" let BODY_MASS_INDEX = "BODY_MASS_INDEX" let WAIST_CIRCUMFERENCE = "WAIST_CIRCUMFERENCE" let STEPS = "STEPS" let BASAL_ENERGY_BURNED = "BASAL_ENERGY_BURNED" let ACTIVE_ENERGY_BURNED = "ACTIVE_ENERGY_BURNED" let HEART_RATE = "HEART_RATE" let BODY_TEMPERATURE = "BODY_TEMPERATURE" let BLOOD_PRESSURE_SYSTOLIC = "BLOOD_PRESSURE_SYSTOLIC" let BLOOD_PRESSURE_DIASTOLIC = "BLOOD_PRESSURE_DIASTOLIC" let RESTING_HEART_RATE = "RESTING_HEART_RATE" let WALKING_HEART_RATE = "WALKING_HEART_RATE" let BLOOD_OXYGEN = "BLOOD_OXYGEN" let BLOOD_GLUCOSE = "BLOOD_GLUCOSE" let ELECTRODERMAL_ACTIVITY = "ELECTRODERMAL_ACTIVITY" let HIGH_HEART_RATE_EVENT = "HIGH_HEART_RATE_EVENT" let LOW_HEART_RATE_EVENT = "LOW_HEART_RATE_EVENT" let IRREGULAR_HEART_RATE_EVENT = "IRREGULAR_HEART_RATE_EVENT" public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flutter_health", binaryMessenger: registrar.messenger()) let instance = SwiftHealthPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { // Set up all data types initializeTypes() /// Handle checkIfHealthDataAvailable if (call.method.elementsEqual("checkIfHealthDataAvailable")){ checkIfHealthDataAvailable(call: call, result: result) } /// Handle requestAuthorization else if (call.method.elementsEqual("requestAuthorization")){ requestAuthorization(call: call, result: result) } /// Handle getData else if (call.method.elementsEqual("getData")){ getData(call: call, result: result) } } func checkIfHealthDataAvailable(call: FlutterMethodCall, result: @escaping FlutterResult) { result(HKHealthStore.isHealthDataAvailable()) } func requestAuthorization(call: FlutterMethodCall, result: @escaping FlutterResult) { let arguments = call.arguments as? NSDictionary let dataTypeKeys = (arguments?["dataTypeKeys"] as? Array) ?? [] var dataTypesToRequest = Set<HKSampleType>() for key in dataTypeKeys { let keyString = "\(key)" dataTypesToRequest.insert(dataTypeLookUp(key: keyString)) } if #available(iOS 11.0, *) { healthStore.requestAuthorization(toShare: nil, read: allDataTypes) { (success, error) in result(success) } } else { result(false)// Handle the error here. } } func getData(call: FlutterMethodCall, result: @escaping FlutterResult) { let arguments = call.arguments as? NSDictionary let dataTypeKey = (arguments?["dataTypeKey"] as? String) ?? "DEFAULT" let startDate = (arguments?["startDate"] as? NSNumber) ?? 0 let endDate = (arguments?["endDate"] as? NSNumber) ?? 0 // Convert dates from milliseconds to Date() let dateFrom = Date(timeIntervalSince1970: startDate.doubleValue / 1000) let dateTo = Date(timeIntervalSince1970: endDate.doubleValue / 1000) let dataType = dataTypeLookUp(key: dataTypeKey) let predicate = HKQuery.predicateForSamples(withStart: dateFrom, end: dateTo, options: .strictStartDate) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true) let query = HKSampleQuery(sampleType: dataType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]) { x, samplesOrNil, error in guard let samples = samplesOrNil as? [HKQuantitySample] else { result(FlutterError(code: "FlutterHealth", message: "Results are null", details: "\(error)")) return } if (samples != nil){ result(samples.map { sample -> NSDictionary in let unit = self.unitLookUp(key: dataTypeKey) return [ "value": sample.quantity.doubleValue(for: unit), "date_from": Int(sample.startDate.timeIntervalSince1970 * 1000), "date_to": Int(sample.endDate.timeIntervalSince1970 * 1000), ] }) } return } HKHealthStore().execute(query) } func unitLookUp(key: String) -> HKUnit { guard let unit = unitDict[key] else { return HKUnit.count() } return unit } func dataTypeLookUp(key: String) -> HKSampleType { guard let dataType_ = dataTypesDict[key] else { return HKSampleType.quantityType(forIdentifier: .bodyMass)! } return dataType_ } func initializeTypes() { unitDict[BODY_FAT_PERCENTAGE] = HKUnit.percent() unitDict[HEIGHT] = HKUnit.meter() unitDict[BODY_MASS_INDEX] = HKUnit.init(from: "") unitDict[WAIST_CIRCUMFERENCE] = HKUnit.meter() unitDict[STEPS] = HKUnit.count() unitDict[BASAL_ENERGY_BURNED] = HKUnit.kilocalorie() unitDict[ACTIVE_ENERGY_BURNED] = HKUnit.kilocalorie() unitDict[HEART_RATE] = HKUnit.init(from: "count/min") unitDict[BODY_TEMPERATURE] = HKUnit.degreeCelsius() unitDict[BLOOD_PRESSURE_SYSTOLIC] = HKUnit.millimeterOfMercury() unitDict[BLOOD_PRESSURE_DIASTOLIC] = HKUnit.millimeterOfMercury() unitDict[RESTING_HEART_RATE] = HKUnit.init(from: "count/min") unitDict[WALKING_HEART_RATE] = HKUnit.init(from: "count/min") unitDict[BLOOD_OXYGEN] = HKUnit.percent() unitDict[BLOOD_GLUCOSE] = HKUnit.init(from: "mg/dl") unitDict[ELECTRODERMAL_ACTIVITY] = HKUnit.siemen() unitDict[WEIGHT] = HKUnit.gramUnit(with: .kilo) // Set up iOS 11 specific types (ordinary health data types) if #available(iOS 11.0, *) { dataTypesDict[BODY_FAT_PERCENTAGE] = HKSampleType.quantityType(forIdentifier: .bodyFatPercentage)! dataTypesDict[HEIGHT] = HKSampleType.quantityType(forIdentifier: .height)! dataTypesDict[BODY_MASS_INDEX] = HKSampleType.quantityType(forIdentifier: .bodyMassIndex)! dataTypesDict[WAIST_CIRCUMFERENCE] = HKSampleType.quantityType(forIdentifier: .waistCircumference)! dataTypesDict[STEPS] = HKSampleType.quantityType(forIdentifier: .stepCount)! dataTypesDict[BASAL_ENERGY_BURNED] = HKSampleType.quantityType(forIdentifier: .basalEnergyBurned)! dataTypesDict[ACTIVE_ENERGY_BURNED] = HKSampleType.quantityType(forIdentifier: .activeEnergyBurned)! dataTypesDict[HEART_RATE] = HKSampleType.quantityType(forIdentifier: .heartRate)! dataTypesDict[BODY_TEMPERATURE] = HKSampleType.quantityType(forIdentifier: .bodyTemperature)! dataTypesDict[BLOOD_PRESSURE_SYSTOLIC] = HKSampleType.quantityType(forIdentifier: .bloodPressureSystolic)! dataTypesDict[BLOOD_PRESSURE_DIASTOLIC] = HKSampleType.quantityType(forIdentifier: .bloodPressureDiastolic)! dataTypesDict[RESTING_HEART_RATE] = HKSampleType.quantityType(forIdentifier: .restingHeartRate)! dataTypesDict[WALKING_HEART_RATE] = HKSampleType.quantityType(forIdentifier: .walkingHeartRateAverage)! dataTypesDict[BLOOD_OXYGEN] = HKSampleType.quantityType(forIdentifier: .oxygenSaturation)! dataTypesDict[BLOOD_GLUCOSE] = HKSampleType.quantityType(forIdentifier: .bloodGlucose)! dataTypesDict[ELECTRODERMAL_ACTIVITY] = HKSampleType.quantityType(forIdentifier: .electrodermalActivity)! dataTypesDict[WEIGHT] = HKSampleType.quantityType(forIdentifier: .bodyMass)! healthDataTypes = Array(dataTypesDict.values) } // Set up heart rate data types specific to the apple watch, requires iOS 12 if #available(iOS 12.2, *){ dataTypesDict[HIGH_HEART_RATE_EVENT] = HKSampleType.categoryType(forIdentifier: .highHeartRateEvent)! dataTypesDict[LOW_HEART_RATE_EVENT] = HKSampleType.categoryType(forIdentifier: .lowHeartRateEvent)! dataTypesDict[IRREGULAR_HEART_RATE_EVENT] = HKSampleType.categoryType(forIdentifier: .irregularHeartRhythmEvent)! heartRateEventTypes = Set([ HKSampleType.categoryType(forIdentifier: .highHeartRateEvent)!, HKSampleType.categoryType(forIdentifier: .lowHeartRateEvent)!, HKSampleType.categoryType(forIdentifier: .irregularHeartRhythmEvent)!, ]) } // Concatenate heart events and health data types (both may be empty) allDataTypes = Set(heartRateEventTypes + healthDataTypes) } }
46.84
143
0.675705
d7950375f09ae0cc8a77472cd0b817518cf887ca
1,033
// // IllnessStatusCode.swift // HeraldTest // // enum IllnessStatusCode : Int, CaseIterable { case susceptible = 1 case infected = 2 case transmittable = 3 case illAndTransmittable = 4 case illAndNonTransmittable = 5 case recovered = 6 case vaccinated = 7 case immune = 8 case nonTransmittable = 9 var name: String { switch self { case .susceptible: return "susceptible" case .infected: return "infected" case .transmittable: return "transmittable" case .illAndTransmittable: return "illAndTransmittable" case .illAndNonTransmittable: return "illAndNonTransmittable" case .recovered: return "recovered" case .vaccinated: return "vaccinated" case .immune: return "immune" case .nonTransmittable: return "nonTransmittable" } } class IllnessStatusCode { private var value:Int private init(_ val: Int) { self.value = val } } }
24.023256
69
0.617619
edb7e7754d0c197a1575f4462d22eb86695648d4
493
// // UIBarButtonItem+Rx.swift // MiniCash // // Created by Ahmed Mohamed Fareed on 3/4/17. // Copyright © 2017 Ahmed Mohamed Magdi. All rights reserved. // import Foundation import RxSwift import RxCocoa extension Reactive where Base: UIBarButtonItem { /// Bindable sink for `Color` property. public var image: UIBindingObserver<Base, UIImage?> { return UIBindingObserver(UIElement: self.base) { button, image in button.image = image } } }
21.434783
73
0.673428
d9c58b0449576fcddbcb30f4d1115ae452eecca6
29,803
// // ChannelViewController.swift // Odysee // // Created by Akinwale Ariwodola on 06/12/2020. // import CoreData import Firebase import OrderedCollections import SafariServices import UIKit class ChannelViewController: UIViewController, UIGestureRecognizerDelegate, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource, UITextViewDelegate { var channelClaim: Claim? var claimUrl: LbryUri? var subscribeUnsubscribeInProgress = false var livestreamTimer = Timer() let livestreamTimerInterval: Double = 60 // 1 minute @IBOutlet var thumbnailImageView: UIImageView! @IBOutlet var coverImageView: UIImageView! @IBOutlet var pageControl: UIPageControl! @IBOutlet var pageScrollView: UIScrollView! @IBOutlet var channelCommunityView: UIView! @IBOutlet var contentListView: UITableView! @IBOutlet var contentLoadingContainer: UIView! @IBOutlet var sortByLabel: UILabel! @IBOutlet var contentFromLabel: UILabel! @IBOutlet var titleLabel: UIPaddedLabel! @IBOutlet var followerCountLabel: UIPaddedLabel! @IBOutlet var noChannelContentView: UIView! @IBOutlet var noAboutContentView: UIView! @IBOutlet var websiteStackView: UIView! @IBOutlet var emailStackView: UIView! @IBOutlet var websiteLabel: UILabel! @IBOutlet var emailLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! @IBOutlet var followLabel: UILabel! @IBOutlet var followUnfollowIconView: UIImageView! @IBOutlet var bellView: UIView! @IBOutlet var bellIconView: UIImageView! @IBOutlet var resolvingView: UIView! @IBOutlet var resolvingImageView: UIImageView! @IBOutlet var resolvingLoadingIndicator: UIActivityIndicatorView! @IBOutlet var resolvingLabel: UILabel! @IBOutlet var resolvingCloseButton: UIButton! var sortByPicker: UIPickerView! var contentFromPicker: UIPickerView! var commentsViewPresented = false let pageSize: Int = 20 var currentPage: Int = 1 var lastPageReached: Bool = false var loadingContent: Bool = false var claims = OrderedSet<Claim>() var channels: [Claim] = [] var commentsDisabledChecked = false var commentsDisabled = false var commentsPageSize: Int = 50 var commentsCurrentPage: Int = 1 var commentsLastPageReached: Bool = false var commentsLoading: Bool = false var comments: [Comment] = [] var authorThumbnailMap = [String: URL]() var currentCommentAsIndex = -1 var currentSortByIndex = 1 // default to New content var currentContentFromIndex = 1 // default to Past week` override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.mainController.toggleHeaderVisibility(hidden: true) appDelegate.mainController.adjustMiniPlayerBottom(bottom: Helper.miniPlayerBottomWithoutTabBar()) if channelClaim != nil { checkFollowing() checkNotificationsDisabled() } if !Lbryio.isSignedIn(), pageControl.currentPage == 2 { pageControl.currentPage = 1 updateScrollViewForPage(page: pageControl.currentPage) } if Lbryio.isSignedIn() { loadChannels() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Analytics.logEvent( AnalyticsEventScreenView, parameters: [ AnalyticsParameterScreenName: "Channel", AnalyticsParameterScreenClass: "ChannelViewController", ] ) navigationController?.interactivePopGestureRecognizer?.isEnabled = true navigationController?.interactivePopGestureRecognizer?.delegate = self } override func viewDidLoad() { super.viewDidLoad() contentListView.register(ClaimTableViewCell.nib, forCellReuseIdentifier: "claim_cell") contentLoadingContainer.layer.cornerRadius = 20 titleLabel.layer.cornerRadius = 8 titleLabel.textInsets = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4) followerCountLabel.layer.cornerRadius = 8 followerCountLabel.textInsets = UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4) // Do any additional setup after loading the view thumbnailImageView.rounded() // TODO: If channelClaim is not set, resolve the claim url before displaying if channelClaim == nil, claimUrl != nil { resolveAndDisplayClaim() } else if channelClaim != nil { displayClaim() loadAndDisplayFollowerCount() loadContent() displayCommentsView() } else { displayNothingAtLocation() } } func displayCommentsView() { if commentsViewPresented || !commentsDisabledChecked { return } let vc = storyboard?.instantiateViewController(identifier: "comments_vc") as! CommentsViewController vc.claimId = channelClaim?.claimId! vc.commentsDisabled = commentsDisabled vc.isChannelComments = true vc.willMove(toParent: self) channelCommunityView.addSubview(vc.view) vc.view.frame = CGRect( x: 0, y: 0, width: channelCommunityView.bounds.width, height: channelCommunityView.bounds.height ) addChild(vc) vc.didMove(toParent: self) commentsViewPresented = true } func showClaimAndCheckFollowing() { displayClaim() loadAndDisplayFollowerCount() loadContent() displayCommentsView() checkFollowing() checkNotificationsDisabled() } func loadChannels() { if channels.count > 0 { return } Lbry.apiCall( method: Lbry.Methods.claimList, params: .init( claimType: [.channel], page: 1, pageSize: 999, resolve: true ) ) .subscribeResult(didLoadChannels) } func didLoadChannels(_ result: Result<Page<Claim>, Error>) { guard case let .success(page) = result else { return } channels.removeAll(keepingCapacity: true) channels.append(contentsOf: page.items) } func resolveAndDisplayClaim() { displayResolving() let url = claimUrl!.description channelClaim = Lbry.cachedClaim(url: url) if channelClaim != nil { DispatchQueue.main.async { self.showClaimAndCheckFollowing() } return } Lbry.apiCall( method: Lbry.Methods.resolve, params: .init(urls: [url]) ) .subscribeResult(didResolveClaim) } func didResolveClaim(_ result: Result<ResolveResult, Error>) { guard case let .success(resolve) = result, let claim = resolve.claims.values.first else { result.showErrorIfPresent() displayNothingAtLocation() return } channelClaim = claim showClaimAndCheckFollowing() } func displayResolving() { DispatchQueue.main.async { self.resolvingView.isHidden = false self.resolvingLoadingIndicator.isHidden = false self.resolvingImageView.image = UIImage(named: "spaceman_happy") self.resolvingLabel.text = String.localized("Resolving content...") self.resolvingCloseButton.isHidden = true } } func displayNothingAtLocation() { DispatchQueue.main.async { self.resolvingView.isHidden = false self.resolvingLoadingIndicator.isHidden = true self.resolvingImageView.image = UIImage(named: "spaceman_sad") self.resolvingLabel.text = String.localized("There's nothing at this location.") self.resolvingCloseButton.isHidden = false } } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } func checkCommentsDisabled(_ commentsDisabled: Bool) { DispatchQueue.main.async { self.commentsDisabled = !commentsDisabled self.displayCommentsView() } } func displayClaim() { resolvingView.isHidden = true if channelClaim?.value != nil { Lbryio.areCommentsEnabled( channelId: channelClaim!.claimId!, channelName: channelClaim!.name!, completion: { enabled in self.commentsDisabledChecked = true self.checkCommentsDisabled(!enabled) } ) if channelClaim?.value?.thumbnail != nil { thumbnailImageView.load(url: URL(string: (channelClaim?.value?.thumbnail?.url)!)!) } else { thumbnailImageView.image = UIImage(named: "spaceman") thumbnailImageView.backgroundColor = Helper.lightPrimaryColor } if channelClaim?.value?.cover != nil { coverImageView.load(url: URL(string: (channelClaim?.value?.cover?.url)!)!) } else { coverImageView.image = UIImage(named: "spaceman_cover") } titleLabel.text = channelClaim?.value?.title // about page let website = channelClaim?.value?.websiteUrl let email = channelClaim?.value?.email let description = channelClaim?.value?.description if (website ?? "").isBlank, (email ?? "").isBlank, (description ?? "").isBlank { websiteStackView.isHidden = true emailStackView.isHidden = true descriptionLabel.isHidden = true noAboutContentView.isHidden = false } else { websiteStackView.isHidden = (website ?? "").isBlank websiteLabel.text = website ?? "" emailStackView.isHidden = (email ?? "").isBlank emailLabel.text = email ?? "" descriptionLabel.isHidden = (description ?? "").isBlank descriptionLabel.text = description noAboutContentView.isHidden = true } } // schedule livestream timer livestreamTimer = Timer.scheduledTimer( timeInterval: livestreamTimerInterval, target: self, selector: #selector(checkLivestream), userInfo: nil, repeats: true ) } func loadAndDisplayFollowerCount() { var options = [String: String]() options["claim_id"] = channelClaim?.claimId try! Lbryio.get(resource: "subscription", action: "sub_count", options: options, completion: { data, error in guard let data = data, error == nil else { return } DispatchQueue.main.async { let formatter = Helper.interactionCountFormatter let followerCount = (data as! NSArray)[0] as! Int self.followerCountLabel.isHidden = false self.followerCountLabel.text = String( format: followerCount == 1 ? String.localized("%@ follower") : String.localized("%@ followers"), formatter.string(for: followerCount)! ) } }) } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == pageScrollView { let pageIndex = Int(round(scrollView.contentOffset.x / view.frame.width)) pageControl.currentPage = pageIndex } else if scrollView == contentListView { if contentListView.contentOffset .y >= (contentListView.contentSize.height - contentListView.bounds.size.height) { if !loadingContent, !lastPageReached { currentPage += 1 loadContent() } } } } func resetContent() { currentPage = 1 lastPageReached = false claims.removeAll() contentListView.reloadData() } func loadContent() { if loadingContent { return } DispatchQueue.main.async { self.contentLoadingContainer.isHidden = false } loadingContent = true noChannelContentView.isHidden = true let releaseTimeValue = currentSortByIndex == 2 ? Helper .buildReleaseTime(contentFrom: Helper.contentFromItemNames[currentContentFromIndex]) : nil Lbry.apiCall( method: Lbry.Methods.claimSearch, params: .init( claimType: [.stream], page: currentPage, pageSize: pageSize, releaseTime: releaseTimeValue, channelIds: [channelClaim?.claimId ?? ""], orderBy: Helper.sortByItemValues[currentSortByIndex] ) ) .subscribeResult(didLoadContent) } func didLoadContent(_ result: Result<Page<Claim>, Error>) { loadingContent = false contentLoadingContainer.isHidden = true guard case let .success(page) = result else { result.showErrorIfPresent() return } lastPageReached = page.isLastPage claims.append(contentsOf: page.items) contentListView.reloadData() checkNoContent() checkLivestream() } @objc func checkLivestream() { if loadingContent { return } loadingContent = true Lbry.apiCall( method: Lbry.Methods.claimSearch, params: .init( claimType: [.stream], page: 1, pageSize: pageSize, hasNoSource: true, channelIds: [channelClaim?.claimId ?? ""], orderBy: Helper.sortByItemValues[1] ) ) .subscribeResult(didCheckLivestream) } func didCheckLivestream(_ result: Result<Page<Claim>, Error>) { loadingContent = false guard case let .success(page) = result, let claim = page.items.first else { result.showErrorIfPresent() return } let url = URL(string: String(format: "https://api.live.odysee.com/v1/odysee/live/%@", channelClaim!.claimId!)) let session = URLSession.shared var req = URLRequest(url: url!) req.httpMethod = "GET" let task = session.dataTask(with: req, completionHandler: { data, response, error in guard let data = data, error == nil else { // handle error return } do { let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] if let livestreamData = response?["data"] as? [String: Any] { let isLive = livestreamData["live"] as? Bool ?? false if isLive { // only show the livestream claim at the top if the channel is actually live DispatchQueue.main.async { self.claims.insert(claim, at: 0) self.contentListView.reloadData() } return } } } catch { // pass } }) task.resume() } func checkNoContent() { noChannelContentView.isHidden = claims.count > 0 } func checkUpdatedSortBy() { let itemName = Helper.sortByItemNames[currentSortByIndex] sortByLabel.text = String(format: "%@ ▾", String(itemName.prefix(upTo: itemName.firstIndex(of: " ")!))) contentFromLabel.isHidden = currentSortByIndex != 2 } func checkUpdatedContentFrom() { contentFromLabel.text = String(format: "%@ ▾", String(Helper.contentFromItemNames[currentContentFromIndex])) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == contentListView { return claims.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == contentListView { let cell = tableView.dequeueReusableCell( withIdentifier: "claim_cell", for: indexPath ) as! ClaimTableViewCell let claim: Claim = claims[indexPath.row] cell.setClaim(claim: claim) return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if tableView == contentListView { let claim: Claim = claims[indexPath.row] let appDelegate = UIApplication.shared.delegate as! AppDelegate let vc = storyboard?.instantiateViewController(identifier: "file_view_vc") as! FileViewController vc.claim = claim appDelegate.mainNavigationController?.view.layer.add( Helper.buildFileViewTransition(), forKey: kCATransition ) appDelegate.mainNavigationController?.pushViewController(vc, animated: false) } } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView == sortByPicker { return Helper.sortByItemNames.count } else if pickerView == contentFromPicker { return Helper.contentFromItemNames.count } return 0 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView == sortByPicker { return Helper.sortByItemNames[row] } else if pickerView == contentFromPicker { return Helper.contentFromItemNames[row] } return nil } @IBAction func sortByLabelTapped(_ sender: Any) { let (picker, alert) = Helper.buildPickerActionSheet( title: String.localized("Sort content by"), dataSource: self, delegate: self, parent: self, handler: { _ in let selectedIndex = self.sortByPicker.selectedRow(inComponent: 0) let prevIndex = self.currentSortByIndex self.currentSortByIndex = selectedIndex if prevIndex != self.currentSortByIndex { self.checkUpdatedSortBy() self.resetContent() self.loadContent() } } ) sortByPicker = picker present(alert, animated: true, completion: { self.sortByPicker.selectRow(self.currentSortByIndex, inComponent: 0, animated: true) }) } @IBAction func closeTapped(_ sender: UIButton) { navigationController?.popViewController(animated: true) } @IBAction func contentFromLabelTapped(_ sender: Any) { let (picker, alert) = Helper.buildPickerActionSheet( title: String.localized("Content from"), dataSource: self, delegate: self, parent: self, handler: { _ in let selectedIndex = self.contentFromPicker.selectedRow(inComponent: 0) let prevIndex = self.currentContentFromIndex self.currentContentFromIndex = selectedIndex if prevIndex != self.currentContentFromIndex { self.checkUpdatedContentFrom() self.resetContent() self.loadContent() } } ) contentFromPicker = picker present(alert, animated: true, completion: { self.contentFromPicker.selectRow(self.currentContentFromIndex, inComponent: 0, animated: true) }) } @IBAction func backTapped(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBAction func pageChanged(_ sender: UIPageControl) { let page = sender.currentPage view.endEditing(true) updateScrollViewForPage(page: page) } func updateScrollViewForPage(page: Int) { var frame: CGRect = pageScrollView.frame frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0 pageScrollView.scrollRectToVisible(frame, animated: true) } @IBAction func websiteTapped(_ sender: Any) { var websiteUrl = websiteLabel.text ?? "" if !websiteUrl.isBlank { if !websiteUrl.starts(with: "http://"), !websiteUrl.starts(with: "https://") { websiteUrl = String(format: "http://%@", websiteUrl) } if let url = URL(string: websiteUrl) { let vc = SFSafariViewController(url: url) let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.mainController.present(vc, animated: true, completion: nil) } } } func checkFollowing() { DispatchQueue.main.async { if Lbryio.isFollowing(claim: self.channelClaim!) { // show unfollow and bell icons self.followLabel.isHidden = true self.bellView.isHidden = false self.followUnfollowIconView.image = UIImage(systemName: "heart.slash.fill") self.followUnfollowIconView.tintColor = UIColor.label } else { self.followLabel.isHidden = false self.bellView.isHidden = true self.followUnfollowIconView.image = UIImage(systemName: "heart") self.followUnfollowIconView.tintColor = UIColor.systemRed } } } func checkNotificationsDisabled() { if !Lbryio.isFollowing(claim: channelClaim!) { return } DispatchQueue.main.async { if Lbryio.isNotificationsDisabledForSub(claim: self.channelClaim!) { self.bellIconView.image = UIImage(systemName: "bell.fill") } else { self.bellIconView.image = UIImage(systemName: "bell.slash.fill") } } } @IBAction func shareActionTapped(_ sender: Any) { let url = LbryUri.tryParse(url: channelClaim!.shortUrl!, requireProto: false) if url != nil { let items = [url!.odyseeString] let vc = UIActivityViewController(activityItems: items, applicationActivities: nil) present(vc, animated: true) } } @IBAction func tipActionTapped(_ sender: Any) { if !Lbryio.isSignedIn() { showUAView() return } let vc = storyboard?.instantiateViewController(identifier: "support_vc") as! SupportViewController vc.claim = channelClaim! vc.modalPresentationStyle = .overCurrentContext present(vc, animated: true) } func showUAView() { let appDelegate = UIApplication.shared.delegate as! AppDelegate let vc = storyboard?.instantiateViewController(identifier: "ua_vc") as! UserAccountViewController appDelegate.mainNavigationController?.pushViewController(vc, animated: true) } @IBAction func followUnfollowActionTapped(_ sender: Any) { if !Lbryio.isSignedIn() { showUAView() return } subscribeOrUnsubscribe( claim: channelClaim!, notificationsDisabled: Lbryio.isNotificationsDisabledForSub(claim: channelClaim!), unsubscribing: Lbryio.isFollowing(claim: channelClaim!) ) } @IBAction func bellActionTapped(_ sender: Any) { if !Lbryio.isSignedIn() { showUAView() return } subscribeOrUnsubscribe( claim: channelClaim!, notificationsDisabled: !Lbryio.isNotificationsDisabledForSub(claim: channelClaim!), unsubscribing: false ) } func subscribeOrUnsubscribe(claim: Claim?, notificationsDisabled: Bool, unsubscribing: Bool) { if subscribeUnsubscribeInProgress { return } subscribeUnsubscribeInProgress = true do { var options = [String: String]() options["claim_id"] = claim?.claimId! if !unsubscribing { options["channel_name"] = claim?.name options["notifications_disabled"] = String(notificationsDisabled) } let subUrl: LbryUri = try LbryUri.parse(url: (claim?.permanentUrl!)!, requireProto: false) try Lbryio.get( resource: "subscription", action: unsubscribing ? "delete" : "new", options: options, completion: { data, error in self.subscribeUnsubscribeInProgress = false guard let _ = data, error == nil else { // print(error) self.showError(error: error) self.checkFollowing() self.checkNotificationsDisabled() return } if !unsubscribing { Lbryio.addSubscription( sub: LbrySubscription.fromClaim( claim: claim!, notificationsDisabled: notificationsDisabled ), url: subUrl.description ) self.addSubscription( url: subUrl.description, channelName: subUrl.channelName!, isNotificationsDisabled: notificationsDisabled, reloadAfter: true ) } else { Lbryio.removeSubscription(subUrl: subUrl.description) self.removeSubscription(url: subUrl.description, channelName: subUrl.channelName!) } self.checkFollowing() self.checkNotificationsDisabled() Lbryio.subscriptionsDirty = true Lbry.saveSharedUserState(completion: { success, err in guard err == nil else { // pass return } if success { // run wallet sync Lbry.pushSyncWallet() } }) } ) } catch { showError(error: error) } } func addSubscription(url: String, channelName: String, isNotificationsDisabled: Bool, reloadAfter: Bool) { // persist the subscription to CoreData DispatchQueue.main.async { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context: NSManagedObjectContext! = appDelegate.persistentContainer.viewContext context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy let subToSave = Subscription(context: context) subToSave.url = url subToSave.channelName = channelName subToSave.isNotificationsDisabled = isNotificationsDisabled appDelegate.saveContext() } } func removeSubscription(url: String, channelName: String) { // remove the subscription from CoreData DispatchQueue.main.async { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context: NSManagedObjectContext! = appDelegate.persistentContainer.viewContext let fetchRequest: NSFetchRequest<Subscription> = Subscription.fetchRequest() fetchRequest.predicate = NSPredicate(format: "url == %@", url) let subs = try! context.fetch(fetchRequest) for sub in subs { context.delete(sub) } do { try context.save() } catch { // pass } } } func showError(error: Error?) { DispatchQueue.main.async { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.mainController.showError(error: error) } } func showError(message: String?) { DispatchQueue.main.async { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.mainController.showError(message: message) } } func showMessage(message: String?) { DispatchQueue.main.async { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.mainController.showMessage(message: message) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
35.186541
118
0.588632
ab26317ade748287b18183918ded9c58ff36492d
681
// // Card.swift // Concentration // // Created by José Naves on 31/05/18. // Copyright © 2018 José Naves. All rights reserved. // import Foundation struct Card: Hashable { var hashValue: Int { return identifier } static func ==(lhs: Card, rhs: Card) -> Bool { return lhs.identifier == rhs.identifier } var isFaceUp = false var isMatched = false private var identifier: Int private static var identifierFactory = 0 private static func getUniqueIdentifier() -> Int { identifierFactory += 1 return identifierFactory } init() { self.identifier = Card.getUniqueIdentifier() } }
20.029412
54
0.621145
3326efd1bfb90ad152fea7975ec31d05a5ad04a7
1,806
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 992. Subarrays with K Different Integers // Given an array nums of positive integers, call a (contiguous, not necessarily distinct) subarray of nums good if the number of different integers in that subarray is exactly k. // (For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.) // Return the number of good subarrays of nums. // Example 1: // Input: nums = [1,2,1,2,3], k = 2 // Output: 7 // Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]. // Example 2: // Input: nums = [1,2,1,3,4], k = 3 // Output: 3 // Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]. // Note: // 1 <= nums.length <= 20000 // 1 <= nums[i] <= nums.length // 1 <= k <= nums.length func subarraysWithKDistinct(_ A: [Int], _ K: Int) -> Int { let k1 = subarraysWithAtMostKDistinct(A, K) let k2 = subarraysWithAtMostKDistinct(A, K - 1) let ans = k1 - k2 return ans } private func subarraysWithAtMostKDistinct(_ A: [Int], _ K: Int) -> Int { var left = 0 var right = 0 var map: [Int: Int] = [:] var ans = 0 while right < A.count { let rightVal = A[right] map[rightVal] = (map[rightVal] ?? 0) + 1 right += 1 while map.keys.count > K { let leftVal = A[left] map[leftVal]! -= 1 if map[leftVal] == 0 { map.removeValue(forKey: leftVal) } left += 1 } ans += (right - left) } return ans } }
32.25
183
0.527132
dd9240a775b91f4742dc8de25d651c6265caa4c1
671
// // BSNotification.swift // Bolts // // Created by Aamir on 22/03/18. // import UIKit class BSNotification: NSObject { var id:String! var text:String! var userID:String? var postID:String! var authorName:String! static func initWith(notifID:String, notifDict:[String:AnyObject]) -> BSNotification { let notif = BSNotification() notif.id = notifID notif.text = notifDict["text"] as? String ?? "" notif.userID = notifDict["user_id"] as? String ?? "" notif.postID = notifDict["post_id"] as? String ?? "" notif.authorName = notifDict["author_name"] as? String ?? "" return notif } }
25.807692
90
0.61997
ac266dc469252da85cbf6640e478e2846f27ce0a
1,548
// // MobileNetworkingController.swift // SmartCredentialsLibrary // // Created by Catalin Haidau on 03/07/2018. // Copyright © 2018 Deutsche Telekom. All rights reserved. // class MobileNetworkingController: NetworkingAPI { var completionHandler: CallServiceCompletionHandler? var mobileRequest: SSLRegisterBy3g4gRequest? func callService(with hostURL: URL, endPoint: String, methodType: MethodType, headers: [String : String], queryParams: [String : Any], bodyParams: String?, bodyParamsType: BodyParamsType?, certificateData: Data?, completionHandler: @escaping CallServiceCompletionHandler) { self.completionHandler = completionHandler mobileRequest = SSLRegisterBy3g4gRequest(hostURL: hostURL, endPoint: endPoint, methodType: methodType, body: bodyParams) mobileRequest?.delegate = self mobileRequest?.start() } } extension HTTPMobileHandler: SSLRegisterBy3g4gRequestDelegate { func secureSocketRequestFinished(with response: String) { completionHandler?(.success(result: response)) } func secureSocketRequestFinished(with error: SmartCredentialsAPIError) { completionHandler?(.failure(error: error)) } }
35.181818
81
0.585271