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
871a9ceef6b7e66b0e1cfdeb98fa7cac873b4ca3
701
// // RibbonViewModel.swift // Blog // // Created by Alexander Ivlev on 29/09/2019. // Copyright © 2019 ApostleLife. All rights reserved. // import Foundation import Common enum RibbonElementViewModel { case article(ArticleViewModel) case habr case github case youtube case presentation } struct ArticleViewModel { let title: String let image: ChangeableImage let shortDescription: String let date: Date //let author: Profile let likes: UInt let dislikes: UInt let numberOfReads: UInt let numberOfComments: UInt } struct HabrViewModel { } struct GitHubViewModel { } struct YouTubeViewModel { } struct PresentationViewModel { }
12.517857
54
0.704708
ef7033741ac65761db55cb6e4c4fc04606f91ca0
838
// // Response.swift // NetworkTrainee // // Copyright © 2020 E-SOFT. All rights reserved. // import Foundation public struct Response<T: Codable & Hashable> { public let success: Bool public let status: Int public let data: T public init(success: Bool, status: Int, data: T) { self.success = success self.status = status self.data = data } } extension Response: Codable, Hashable { enum CodingKeys: String, CodingKey { case success case status case data } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) success = try container.decode(Bool.self, forKey: .success) status = try container.decode(Int.self, forKey: .status) data = try container.decode(T.self, forKey: .data) } }
21.487179
67
0.655131
143984eb53b5a1d597798acedd047426fde7dfd4
4,281
// A playground demonstrating an image view that supports zooming. // https://schiavo.me/2019/pinch-to-zoom-image-view/ // Copyright (c) 2019 Julian Schiavo. All rights reserved. Licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit import PlaygroundSupport class ImageZoomView: UIScrollView, UIScrollViewDelegate { var imageView: UIImageView! var gestureRecognizer: UITapGestureRecognizer! convenience init(frame: CGRect, image: UIImage?) { self.init(frame: frame) var imageToUse: UIImage if let image = image { imageToUse = image } else if let url = Bundle.main.url(forResource: "image", withExtension: "jpeg"), let data = try? Data(contentsOf: url), let fileImage = UIImage(data: data) { imageToUse = fileImage } else { fatalError("No image was passed in and failed to find an image at the path.") } // Creates the image view and adds it as a subview to the scroll view imageView = UIImageView(image: imageToUse) imageView.frame = frame imageView.contentMode = .scaleAspectFill addSubview(imageView) setupScrollView(image: imageToUse) setupGestureRecognizer() } // Sets the scroll view delegate and zoom scale limits. // Change the `maximumZoomScale` to allow zooming more than 2x. func setupScrollView(image: UIImage) { delegate = self minimumZoomScale = 1.0 maximumZoomScale = 2.0 } // Sets up the gesture recognizer that receives double taps to auto-zoom func setupGestureRecognizer() { gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap)) gestureRecognizer.numberOfTapsRequired = 2 addGestureRecognizer(gestureRecognizer) } // Handles a double tap by either resetting the zoom or zooming to where was tapped @IBAction func handleDoubleTap() { if zoomScale == 1 { zoom(to: zoomRectForScale(maximumZoomScale, center: gestureRecognizer.location(in: gestureRecognizer.view)), animated: true) } else { setZoomScale(1, animated: true) } } // Calculates the zoom rectangle for the scale func zoomRectForScale(_ scale: CGFloat, center: CGPoint) -> CGRect { var zoomRect = CGRect.zero zoomRect.size.height = imageView.frame.size.height / scale zoomRect.size.width = imageView.frame.size.width / scale let newCenter = convert(center, from: imageView) zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0) zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0) return zoomRect } // Tell the scroll view delegate which view to use for zooming and scrolling func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } } // Create a ImageZoomView and present it in the live view let imageView = ImageZoomView(frame: CGRect(x: 0, y: 0, width: 300, height: 300), image: nil) imageView.layer.borderColor = UIColor.black.cgColor imageView.layer.borderWidth = 5 PlaygroundPage.current.liveView = imageView
46.532609
463
0.696333
7acb9d59c7394355a297e591f8a352b71c788c7d
273
// // ArgumentsService.swift // ipa-uploader // // Created by Ross Butler on 11/19/18. // import Foundation protocol ArgumentsService { func argumentsValid(_ arguments: [Argument<Any>]) -> Bool func processArguments(_ arguments: [String]) -> [Argument<Any>] }
19.5
67
0.692308
69eb6c8466f5f4a7bf46b053ae232b0e30d5b5c3
1,151
// // MainNavigationSceneDependencyProvider.swift // SmartUniversity // // Created by Tomas Skypala on 17/03/2020. // Copyright © 2020 Tomas Skypala. All rights reserved. // import UIKit final class MainNavigationSceneDependencyProvider: SceneDependencyProviding { let navigationController: NavigationController var sceneHandler: WindowSceneHandling? { self } var mainNavigationCoordinator: MainNavigationCoordinator? convenience init() { self.init(navigationController: UINavigationController()) } init(navigationController: NavigationController) { self.navigationController = navigationController navigationController.setNavigationBarHidden() } func makeRootViewController() -> UIViewController { navigationController } } extension MainNavigationSceneDependencyProvider: WindowSceneHandling { func windowWillBecomeVisible(_ window: UIWindow) { mainNavigationCoordinator = MainNavigationCoordinator(navigationController: navigationController) } func windowDidBecomeVisible(_ window: UIWindow) { mainNavigationCoordinator?.start() } }
26.159091
105
0.756733
f4071cd8297127c3071dc62bb5103d9e0ed447b4
2,992
// // FearViewController.swift // RSNTMNT // // Created by Anders Howerton on 10/14/15. // Copyright © 2015 Au. All rights reserved. // import UIKit class FearViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var fearDetailsTextView: UITextView! @IBOutlet weak var fearfulHeaderLabel: UILabel! @IBOutlet weak var newMeaningLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationController!.navigationBar.tintColor = UIColor.blackColor() self.fearfulHeaderLabel.font = UIFont(name: "Didot-Bold", size: 20.0) self.newMeaningLabel.font = UIFont(name: "Didot-Bold", size: 14.0) self.fearDetailsTextView.layer.borderWidth = 0.5 self.fearDetailsTextView.layer.cornerRadius = 10 self.fearDetailsTextView.layer.borderColor = UIColor.blackColor().CGColor self.fearDetailsTextView.textContainerInset = UIEdgeInsets(top: 8,left: 5,bottom: 8,right: 5) self.fearDetailsTextView.font = UIFont(name: "Helvetica-Light", size: 14.0) self.fearDetailsTextView.delegate = self self.fearDetailsTextView.returnKeyType = .Done let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = self.view.bounds gradient.colors = [UIColor( red:0.129, green:0.145, blue:0.290, alpha:1.000).CGColor,UIColor( red:0.659, green:0.714, blue:0.745, alpha:1.000).CGColor,UIColor( red:0.773, green:0.831, blue:0.792, alpha:1.000).CGColor,UIColor( red:0.773, green:0.831, blue:0.792, alpha:1.000).CGColor,UIColor( red:0.659, green:0.714, blue:0.745, alpha:1.000).CGColor,UIColor( red:0.129, green:0.145, blue:0.290, alpha:1.000).CGColor] gradient.startPoint = CGPoint(x: 0.50, y: 0.00) gradient.endPoint = CGPoint(x: 0.50, y: 1.00) self.view.layer.insertSublayer(gradient, atIndex: 0) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tap) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard() { view.endEditing(true) } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if(text == "\n") { textView.resignFirstResponder() return false } return true } @IBAction func closeMyPartTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } override func viewWillDisappear(animated: Bool) { Resentment.SharedInstance.details["fearDetails"] = fearDetailsTextView.text } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { Resentment.SharedInstance.details["fearDetails"] = fearDetailsTextView.text } }
40.432432
423
0.680481
4a2f7d8d2260be9bb976147334481db102c1ca83
9,276
// // GroupControlViewController.swift // Taskem // // Created by Wilson on 03/01/2018. // Copyright © 2018 WIlson. All rights reserved. // import UIKit import TaskemFoundation class ScheduleControlViewController: UICollectionViewController, ScheduleControlView, ThemeObservable { // MARK: IBOutlet // MARK: IBAction // MARK: let & var var presenter: ScheduleControlPresenter! var viewModel: ScheduleControlListViewModel = .init() weak var delegate: ScheduleControlViewDelegate? internal var navbar: ScheduleControlNavigationBar? { return navigationController?.navigationBar as? ScheduleControlNavigationBar } // MARK: class func override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.drawerPresentationController?.scrollViewForPullToDismiss = collectionView navigationController?.isToolbarHidden = false delegate?.onViewWillAppear() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) resolveSelection(animated: true) } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) delegate?.onTouchEditing(editing) prepareUI(isEditing: editing, animated: animated) } // MARK: func func applyTheme(_ theme: AppTheme) { collectionView.backgroundColor = theme.background view.backgroundColor = theme.background navigationController?.view.backgroundColor = theme.background } @objc private func processAddList() { delegate?.onTouchNew() } private func isSelected(at index: IndexPath) -> Bool { if viewModel[index].isSelected, !viewModel.isEditing { return true } return false } private func setEditingCells(_ editing: Bool) { for cell in collectionView.visibleCells { guard let index = collectionView.indexPath(for: cell), let cell = cell as? ScheduleControlGroupCell else { continue } cell.setup(viewModel[index], editing: editing) } } func display(_ viewModel: ScheduleControlListViewModel) { self.viewModel = viewModel collectionView.reloadData() isEditing = viewModel.isEditing navbar?.reloadData() } func resolveSelection(animated: Bool = true) { for cell in collectionView.visibleCells { guard let index = collectionView.indexPath(for: cell) else { continue } if isSelected(at: index) { collectionView.selectItem(at: index, animated: animated, scrollPosition: []) } else { collectionView.deselectItem(at: index, animated: animated) } } navbar?.reloadData() } func displaySpinner(_ isVisible: Bool) { showSpinner(isVisible) } } extension ScheduleControlViewController { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if viewModel.isEditing { collectionView.deselectItem(at: indexPath, animated: true) delegate?.onTouch(at: indexPath) } else { delegate?.onSelect(at: indexPath) } navbar?.reloadData() } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { delegate?.onDeselect(at: indexPath) navbar?.reloadData() } } extension ScheduleControlViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return viewModel.sections.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel[section].cells.count } override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return viewModel.isEditing } override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { delegate?.onMove(from: sourceIndexPath, to: destinationIndexPath) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(ScheduleControlGroupCell.self, indexPath) cell.setup(viewModel[indexPath], editing: viewModel.isEditing) // https://stackoverflow.com/questions/15330844/uicollectionview-select-and-deselect-issue if cell.isSelected { collectionView.selectItem(at: indexPath, animated: true, scrollPosition: []) } else { collectionView.deselectItem(at: indexPath, animated: true) } return cell } } extension ScheduleControlViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let totalSpace = flowLayout.sectionInset.left + flowLayout.sectionInset.right + flowLayout.minimumInteritemSpacing * 3 let size = (collectionView.bounds.width - totalSpace) / CGFloat(3) return CGSize(width: size, height: size) } } extension ScheduleControlViewController: DrawerPresentable { var shouldBeginTransitioning: Bool { return true } var drawerViewParticipants: [UIView] { return [] } var heightOfPartiallyExpandedDrawer: CGFloat { return 0 } } extension ScheduleControlViewController: ScheduleControlNavigationBarDataSource { func views(_ navbar: ScheduleControlNavigationBar) -> [ScheduleNavigationBarCell] { return viewModel.navbarContent.map { .init(data: $0) } } func subtitle(_ navbar: ScheduleControlNavigationBar) -> String { return viewModel.subtitle } } extension ScheduleControlViewController { private func setupUI() { setupCollection() setupNavBar() setupToolbar() observeAppTheme() } private func setupCollection() { collectionView.register(cell: ScheduleControlGroupCell.self) } private func setupNavBar() { navbar?.dataSource = self navbar?.contentView.onClear = { [weak self] in self?.delegate?.onTouchClearSelection() } } private func setupToolbar() { let new = UIBarButtonItem( title: "Add List", style: .plain, target: self, action: #selector(processAddList) ) let empty = UIBarButtonItem( barButtonSystemItem: .edit, target: nil, action: nil ) empty.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .normal) let space = UIBarButtonItem( barButtonSystemItem: .flexibleSpace, target: nil, action: nil ) let fixedSpace = UIBarButtonItem( barButtonSystemItem: .fixedSpace, target: nil, action: nil ) fixedSpace.width = 15 toolbarItems = [fixedSpace, empty , space, new, space, editButtonItem, fixedSpace] } private func prepareUI(isEditing: Bool, animated: Bool) { collectionView.allowsSelection = true collectionView.allowsMultipleSelection = !isEditing resolveSelection(animated: animated) let animator = UIViewPropertyAnimator.init(duration: 0.3, curve: .easeInOut) { self.navigationItem.title = "Your Lists" self.navbar?.setEditing(isEditing) self.setEditingCells(isEditing) self.setupToolbar() } animator.startAnimation() } } extension ScheduleControlViewController: CollectionUpdaterDelegate { func didBeginUpdate() { } func didEndUpdate() { } func willBeginUpdate(at index: IndexPath) { } func insertSections(at indexes: IndexSet) { collectionView.insertSections(indexes) } func reloadSections(at indexes: IndexSet) { collectionView.reloadSections(indexes) } func deleteSections(indexes: IndexSet) { collectionView.deleteSections(indexes) } func insertRows(at indexes: [IndexPath]) { collectionView.insertItems(at: indexes) } func updateRows(at indexes: [IndexPath]) { collectionView.reloadItems(at: indexes) } func deleteRows(at indexes: [IndexPath]) { collectionView.deleteItems(at: indexes) } func moveRow(from: IndexPath, to index: IndexPath) { collectionView.moveItem(at: from, to: index) } }
31.876289
160
0.650927
2f07e4fe9bf755f9755fcf0618e5c0ce3fb2ddc1
2,582
// // StyleTypeMenuView.swift // artbum // // Created by shreyas gupta on 01/08/20. // Copyright © 2020 shreyas gupta. All rights reserved. // import SwiftUI struct StyleTypeMenu: View{ //remembers the current selection @Binding var selection: Int @Binding var appleMusicBrandingToggleValue: Bool @EnvironmentObject var playlistData: AppViewModel var menuItemNameArr:[String] = ["Gradients", "Unsplash", "Patterns", "Images"] @ViewBuilder var body: some View{ VStack(alignment: .leading){ appleMusicBrandingToggle(toggleValue: self.$appleMusicBrandingToggleValue) .padding(.leading, 25) .padding(.trailing, 25) .padding(.bottom, 10) ScrollView(.horizontal, showsIndicators: false){ HStack{ ForEach(0..<menuItemNameArr.count){ index in self.getStyleTypeMenuItem(for: index).onTapGesture{ withAnimation(.easeInOut(duration: 0.2)){ self.onTapSelectionChange(for: index) } } .fixedSize(horizontal: false, vertical: true) } } .padding(.leading, 20) } .frame(alignment: .leading) if(selection == 0){ ScrollView(.horizontal, showsIndicators: false){ HStack{ ForEach(0..<self.playlistData.AlbumStyleArr.count){ index in PlaylistStyleButton(style: self.playlistData.AlbumStyleArr[index]).onTapGesture{ self.playlistData.chooseStyle(button: self.playlistData.AlbumStyleArr[index]) } } } .padding(.leading, 20) .padding(.bottom, 20) } } } } func getStyleTypeMenuItem(for index: Int) -> some View{ let isActive = self.selection == index return VStack{ Text(self.menuItemNameArr[index]) .font(.system(size: 22.0, weight: .semibold, design: .rounded)) .foregroundColor(isActive ? Color.black : Color.gray) .fixedSize(horizontal: false, vertical: true) .padding(5) } } func onTapSelectionChange(for index: Int){ self.selection = index } }
35.861111
109
0.512393
e997af21fba867af0339a3554dc28221c39863bf
7,170
// // ArrangeTests.swift // ArrangeTests // // Created by krzat on 29/10/16. // Copyright © 2016 krzat. All rights reserved. // import XCTest import Arrange class BigView : UIView {} extension CGRect { func assertEqual(to expected : CGRect, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(self, expected, file:file, line:line) } } class ArrangeTests: 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 testOneToOne(_ arrangement : [ArrangementItem], expected : CGRect, file: StaticString = #file, line: UInt = #line) { let view = bigView() let subview = smallView() view.arrange(arrangement, subview) view.layoutIfNeeded() XCTAssertEqual(subview.frame, expected, file:file, line:line) } func testPadding() { testOneToOne([.fill(1)], expected: CGRect(x: 1, y: 1, width: 98, height: 98)) testOneToOne([.fill(-1)], expected: CGRect(x: -1, y: -1, width: 102, height: 102)) testOneToOne([.left(1), .top(1)], expected: CGRect(x: 1, y: 1, width: 10, height: 10)) testOneToOne([.right(1), .bottom(1)], expected: CGRect(x: 89, y: 89, width: 10, height: 10)) } func testScrollable() { let view = UIView() let height = view.heightAnchor.constraint(equalToConstant: 110) //height.priority = UILayoutPriorityRequired-1 height.isActive = true let container = bigView().arrange( [.scrollable], view ) let scrollView = container.subviews.first as? UIScrollView container.layoutIfNeeded() XCTAssertNotNil(scrollView) XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 100, height: 110)) XCTAssertEqual(scrollView!.frame, CGRect(x: 0, y: 0, width: 100, height: 100)) XCTAssertTrue(scrollView!.subviews.contains(view.superview!) || scrollView!.subviews.contains(view)) } func testDefaultStacking() { let top = smallView() let middle = unsizedView() let bottom = smallView() let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)).arrange( [], top, middle, bottom ) container.layoutIfNeeded() XCTAssertEqual(top.frame, CGRect(x: 0, y: 0, width: 100, height: 10)) XCTAssertEqual(middle.frame, CGRect(x: 0, y: 10, width: 100, height: 80)) XCTAssertEqual(bottom.frame, CGRect(x: 0, y: 90, width: 100, height: 10)) } func bigView() -> UIView { return BigView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) } func smallView() -> UIView { let subview = UIView() let width = subview.widthAnchor.constraint(equalToConstant: 10) width.priority = UILayoutPriorityDefaultLow width.isActive = true let height = subview.heightAnchor.constraint(equalToConstant: 10) height.priority = UILayoutPriorityDefaultLow height.isActive = true return subview } func unsizedView() -> UIView { return UIView() } func testOverlay() { let a = unsizedView() let b = unsizedView() let container = bigView() container.arrange([.overlaying], a,b) container.layoutIfNeeded() XCTAssertEqual(a.frame, container.bounds) XCTAssertEqual(b.frame, container.bounds) } func testEqualize() { let a = unsizedView() let b = unsizedView() let container = bigView() do { container.arrange( [.equalSizes], a, b ) container.layoutIfNeeded() XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 100, height: 50)) XCTAssertEqual(b.frame, CGRect(x: 0, y: 50, width: 100, height: 50)) } do { container.arrange( [.equalSizes, .horizontal], a, b ) container.layoutIfNeeded() XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 50, height: 100)) XCTAssertEqual(b.frame, CGRect(x: 50, y: 0, width: 50, height: 100)) } } func testCentered() { testOneToOne( [.centered], expected: CGRect(x: 45, y: 45, width: 10, height: 10) ) testOneToOne( [.centeredVertically, .left(0)], expected: CGRect(x: 0, y: 45, width: 10, height: 10) ) testOneToOne( [.centeredHorizontally, .top(0)], expected: CGRect(x: 45, y: 0, width: 10, height: 10) ) } func testStyle() { let view = UILabel().style{ $0.text = "x" } XCTAssertEqual(view.text, "x") } func testTopAndSides() { let big = bigView() let small = smallView() big.arrange([.topAndSides(0)], small) big.layoutIfNeeded() XCTAssertEqual(small.frame, CGRect(x: 0, y: 0, width: 100, height: 10)) } func testCustomExtension() { let view = bigView() view.arrange([.hidden]) assert(view.isHidden) } func testViewControllerArrange() { let viewController = UIViewController() viewController.view = bigView() let view = smallView() viewController.arrange([.topAndSides(0)], view) viewController.view.layoutIfNeeded() XCTAssertEqual(view.superview, viewController.view) XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 100, height: 10)) //smallView should be aligned to layoutGuides, but offsets will not be visible in the test } func testCustomAnchor() { let big = bigView() let center = smallView() big.arrange([.centered], center) let other = smallView() let closure : Arrangement.Closure = { $0.bottomAnchor = center.topAnchor } big.arrange([.before(closure)], other) big.layoutIfNeeded() XCTAssertEqual(other.frame, CGRect(x: 0, y: 0, width: 100, height: 45)) } func testStackViewCustomization() { let big = bigView() let a = smallView() let b = smallView() let closure : Arrangement.Closure = { $0.stackView?.spacing = 20 } big.arrange([.after(closure), .equalSizes], a, b) big.layoutIfNeeded() XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 100, height: 40)) } } extension ArrangementItem { static var hidden : ArrangementItem { return .after({ context in context.superview.isHidden = true }) } }
29.751037
125
0.562762
1e1be74400647083cea16da41bef36be50ba99c5
4,381
// // StudyTasks.swift // // Created for the CardinalKit Framework. // Copyright © 2019 Stanford University. All rights reserved. // // EDIT TASKSAMPLES import ResearchKit /** This file contains some sample `ResearchKit` tasks that you can modify and use throughout your project! */ struct TaskSamples { /** Active tasks created with short-hand constructors from `ORKOrderedTask` */ static let sampleTappingTask: ORKOrderedTask = { let intendedUseDescription = "Finger tapping is a universal way to communicate." return ORKOrderedTask.twoFingerTappingIntervalTask(withIdentifier: "TappingTask", intendedUseDescription: intendedUseDescription, duration: 10, handOptions: .both, options: ORKPredefinedTaskOption()) }() static let sampleWalkingTask: ORKOrderedTask = { let intendedUseDescription = "Tests ability to walk" return ORKOrderedTask.shortWalk(withIdentifier: "ShortWalkTask", intendedUseDescription: intendedUseDescription, numberOfStepsPerLeg: 20, restDuration: 30, options: ORKPredefinedTaskOption()) }() /** Coffee Task Example for 9/2 Workshop */ static let sampleCoffeeTask: ORKOrderedTask = { var steps = [ORKStep]() // Coffee Step let healthScaleAnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 5, minimumValue: 0, defaultValue: 3, step: 1, vertical: false, maximumValueDescription: "A Lot 😬", minimumValueDescription: "None 😴") let healthScaleQuestionStep = ORKQuestionStep(identifier: "CoffeeScaleQuestionStep", title: "Coffee Intake", question: "How many cups of coffee do you drink per day?", answer: healthScaleAnswerFormat) steps += [healthScaleQuestionStep] //SUMMARY let summaryStep = ORKCompletionStep(identifier: "SummaryStep") summaryStep.title = "Thank you for tracking your coffee." summaryStep.text = "We appreciate your caffeinated energy! check out the results chart." steps += [summaryStep] return ORKOrderedTask(identifier: "SurveyTask-Coffee", steps: steps) }() /** Sample task created step-by-step! */ static let sampleSurveyTask: ORKOrderedTask = { var steps = [ORKStep]() // Instruction step let instructionStep = ORKInstructionStep(identifier: "IntroStep") instructionStep.title = "Daily Questionnaire" instructionStep.text = "Please complete this survey daily to assess your own health." steps += [instructionStep] //How would you rate your health today? let healthScaleAnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 5, minimumValue: 1, defaultValue: 3, step: 1, vertical: false, maximumValueDescription: "Excellent", minimumValueDescription: "Poor") let healthScaleQuestionStep = ORKQuestionStep(identifier: "HealthScaleQuestionStep", title: "Question #1", question: "How would you rate your overall health today:", answer: healthScaleAnswerFormat) steps += [healthScaleQuestionStep] //How would you rate your mental health today? let mentalhealthScaleAnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 5, minimumValue: 1, defaultValue: 3, step: 1, vertical: false, maximumValueDescription: "Excellent", minimumValueDescription: "Poor") let mentalhealthScaleQuestionStep = ORKQuestionStep(identifier: "mentalHealthScaleQuestionStep", title: "Question #2", question: "How would you rate your mental health today:", answer: mentalhealthScaleAnswerFormat) steps += [mentalhealthScaleQuestionStep] let booleanAnswer = ORKBooleanAnswerFormat(yesString: "Yes", noString: "No") let booleanQuestionStep = ORKQuestionStep(identifier: "QuestionStep", title: "Question #3", question: "Is this map of your daily activity accurate? If NO, why not?", answer: booleanAnswer) steps += [booleanQuestionStep] //SUMMARY let summaryStep = ORKCompletionStep(identifier: "SummaryStep") summaryStep.title = "Thank you." summaryStep.text = "We appreciate your time." steps += [summaryStep] return ORKOrderedTask(identifier: "SurveyTask-Assessment", steps: steps) }() }
45.635417
223
0.689112
33b1bc31010767f90c8ea9844534e83bb43d0ee1
3,174
//: [Previous](@previous) import Foundation import UIKit import PlaygroundSupport //MARK : - RSA Keys var RSA_P=0 var RSA_Q=0 var RSA_N=0 var RSA_M=0 var RSA_E=0 var RSA_D=0 //MARK: - Other variables used within the process var r=2 var c=0 var gcd_answer=0 //MARK: - Exponent extension precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ^^ : PowerPrecedence func ^^ (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power))) } //MARK: - Retrieve primes func getPrimes() -> [Int] { var numbers = [Int](2..<150) for i in 0..<148 { let prime = numbers[i] guard prime > 0 else { continue } for multiple in stride(from: 2*prime-2, to: 148, by: prime) { numbers[multiple] = 0 } } return numbers.filter {$0 > 0} } //MARK: - Greatest common divisior func gcd( a:Int, b:Int) -> Int { var b = b var a = a var t = 0 while b != 0 { t = b b = a % b a = t } return a } //MARK: - Primes var primes:[Int] = getPrimes() //MARK: - LET'S START ! print("Let's start !") print("You are now going to create your keys. In order to do this, you need to choose two prime numbers which we will call p and q.") print("For this example, we'll pick a random prime 'p' within the first seven prime numbers.") RSA_P = primes[Int(arc4random_uniform(UInt32(5)+1))] print("Your prime is p =", RSA_P) print("Again, we'll pick a random prime 'q' also within the first seven prime numbers.") RSA_Q = primes[Int(arc4random_uniform(UInt32(5)+2))] print("Your prime is q =", RSA_Q) print("We have now our two prime numbers. We need to calculate 'n' which is very simple : n = p*q. Let's see what we get :") RSA_N = RSA_P * RSA_Q print("N which is the first part of our keys is :", RSA_N) print("We now need to create m to prepare our other values. Again, m is very easy to find as m = (p-1) * (q-1).") RSA_M = (RSA_P-1) * (RSA_Q-1) print("M is equal to :", RSA_M) print("Now, we need to determine e which is coprime to m. To do this, we need to find verify that 1 is the only common divisor. In this case, the value are coprime and this is what we want.") while gcd_answer != 1 { var gcd_value = gcd(a: r, b: RSA_M) if gcd_value == 1 { gcd_answer = 1 RSA_E = r break; } else { r=r+1 } } print("We have now e, the second part of our public key which is :", RSA_E) print("We just need now d and we can start encrypting and decrypting messages.") print("d must follow this equation : d*e = 1 + c*m, it is equal to d = (1 + c*m)/e, but we need to determine c (an Integer) to then divide it by e like in the equation just before.") while ((1 + c*RSA_M)%RSA_E) != 0 { c=c+1 } print("We have now our value of c which is :", c) RSA_D=((1 + c*RSA_M)/RSA_E) print("Finished ! We have our last value d which is :", RSA_D) print("We have now all our keys ! Let's summarize this :") print("PUBLIC KEY : n=\(RSA_N) ; e=\(RSA_E)") print("PRIVATE KEY : n=\(RSA_N) ; d=\(RSA_D)") print("Let's switch to next page to encrypt and decrypt a small message.") //: [Next](@next)
26.672269
191
0.640202
9c34cdcfc6531e20e3a6b37be17e039a5132c922
4,621
// // FormTableDelegate.swift // MySampleApp // // // Copyright 2017 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.15 // // import Foundation import UIKit /** The form table delegate class which handles loading of cells in the table. */ class FormTableDelegate: NSObject { var numberOfCells: Int { get { if let cells = cells { return cells.count } return 0 } } override init() { super.init() cells = [] } fileprivate var cells: [FormTableCell]? /** Inserts the cell into table as a `TableInputCell`. @param cell the `UserPoolsCell` to be inserted into table as a row */ func add(cell: FormTableCell) { self.cells?.append(cell) } } // MARK:- UITableViewDelegate extension FormTableDelegate: UITableViewDelegate { /** Fetches the value entered by the user in the row. @param tableView the tableView object @param cell the `FormTableCell` whose value is to be retrieved @return the string value entered by user */ func getValue(_ tableView: UITableView, for cell: FormTableCell) -> String? { let position = cells!.index { $0.placeHolder! == cell.placeHolder! } let indexPath = IndexPath(item: position!, section: 0) let currentCell = tableView.cellForRow(at: indexPath) as! TableInputCell return currentCell.inputBox?.text } /** Fetches the table cell for specified `FormTableCell` @param tableView the tableView object @param cell the `FormTableCell` whose value is to be retrieved @return the `TableInputCell` object for specified `FormTableCell` */ func getCell(_ tableView: UITableView, for cell: FormTableCell) -> TableInputCell? { let position = cells!.index { $0.placeHolder! == cell.placeHolder! } let indexPath = IndexPath(item: position!, section: 0) let currentCell = tableView.cellForRow(at: indexPath) as! TableInputCell return currentCell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfCells } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let currentCell = tableView.cellForRow(at: indexPath) as! TableInputCell currentCell.onTap() } } // MARK:- UITableViewDataSource extension FormTableDelegate : UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FormTableCell", for: indexPath) as! TableInputCell let formTableCell = cells![indexPath.row] cell.placeHolderLabel?.text = formTableCell.placeHolder cell.headerLabel?.text = formTableCell.placeHolder?.uppercased() cell.inputBox?.autocorrectionType = .no cell.inputBox?.spellCheckingType = .no if (formTableCell.type == InputType.password) { cell.inputBox?.isSecureTextEntry = true let showButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 20)) showButton.setTitle("Show", for: .normal) showButton.addTarget(self, action: #selector(showPassword(button:)), for: .touchUpInside) cell.inputBox?.rightViewMode = .always cell.inputBox?.rightView = showButton showButton.titleLabel?.font = UIFont.systemFont(ofSize: 14.0) showButton.setTitleColor(UIColor.darkGray, for: .normal) } if (formTableCell.type == InputType.staticText) { cell.placeHolderView.isHidden = true cell.inputBox.text = formTableCell.staticText } return cell } @objc func showPassword(button: UIButton) { let textField = button.superview as! UITextField if (textField.isSecureTextEntry) { textField.isSecureTextEntry = false button.setTitle("Hide", for: .normal) } else { textField.isSecureTextEntry = true button.setTitle("Show", for: .normal) } } }
33.007143
116
0.64077
ebf075266dc2bc3cb911f02028ad8940321405bf
8,377
// // StringHelpers.swift // Helium // // Created by Samuel Beek on 16/03/16. // Copyright © 2016 Jaden Geller. All rights reserved. // import Foundation import CoreAudioKit extension String { func replacePrefix(_ prefix: String, replacement: String) -> String { if hasPrefix(prefix) { return replacement + substring(from: prefix.endIndex) } else { return self } } func indexOf(_ target: String) -> Int { let range = self.range(of: target) if let range = range { return self.distance(from: self.startIndex, to: range.lowerBound) } else { return -1 } } func isValidURL() -> Bool { let urlRegEx = "((file|https|http)()://)((\\w|-)+)(([.]|[/])((\\w|-)+))+" let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx]) return predicate.evaluate(with: self) } } // From http://nshipster.com/nsregularexpression/ extension String { /// An `NSRange` that represents the full range of the string. var nsrange: NSRange { return NSRange(location: 0, length: utf16.count) } /// Returns a substring with the given `NSRange`, /// or `nil` if the range can't be converted. func substring(with nsrange: NSRange) -> String? { guard let range = nsrange.toRange() else { return nil } #if swift(>=4.0) let start = UTF16Index(range.lowerBound) let end = UTF16Index(range.upperBound) return String(utf16[start..<end]) #else return self[0..<range.count] #endif } /// Returns a range equivalent to the given `NSRange`, /// or `nil` if the range can't be converted. func range(from nsrange: NSRange) -> Range<Index>? { guard let range = nsrange.toRange() else { return nil } #if swift(>=4.0) let utf16Start = UTF16Index(range.lowerBound) let utf16End = UTF16Index(range.upperBound) guard let start = Index(utf16Start, within: self), let end = Index(utf16End, within: self) else { return nil } return start..<end #else return self.startIndex..<self.index(self.startIndex, offsetBy: range.count) #endif } } extension String { subscript (bounds: CountableClosedRange<Int>) -> String { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(startIndex, offsetBy: bounds.upperBound) return String(self[start...end]) } subscript (bounds: CountableRange<Int>) -> String { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(startIndex, offsetBy: bounds.upperBound) return String(self[start..<end]) } } // From https://stackoverflow.com/questions/12837965/converting-nsdictionary-to-xml /* extension Any { func xmlString() -> String { if let booleanValue = (self as? Bool) { return String(format: (booleanValue ? "true" : "false")) } else if let intValue = (self as? Int) { return String(format: "%d", intValue) } else if let floatValue = (self as? Float) { return String(format: "%f", floatValue) } else if let doubleValue = (self as? Double) { return String(format: "%f", doubleValue) } else { return String(format: "<%@>", self) } } } */ func toLiteral(_ value: Any) -> String { if let booleanValue = (value as? Bool) { return String(format: (booleanValue ? "1" : "0")) } else if let intValue = (value as? Int) { return String(format: "%d", intValue) } else if let floatValue = (value as? Float) { return String(format: "%f", floatValue) } else if let doubleValue = (value as? Double) { return String(format: "%f", doubleValue) } else if let stringValue = (value as? String) { return stringValue } else if let dictValue: Dictionary<AnyHashable,Any> = (value as? Dictionary<AnyHashable,Any>) { return dictValue.xmlString(withElement: "Dictionary", isFirstElement: false) } else { return ((value as AnyObject).description) } } extension Array { func xmlString(withElement element: String, isFirstElemenet: Bool) -> String { var xml = String.init() xml.append(String(format: "<%@>\n", element)) self.forEach { (value) in if let array: Array<Any> = (value as? Array<Any>) { xml.append(array.xmlString(withElement: "Array", isFirstElemenet: false)) } else if let dict: Dictionary<AnyHashable,Any> = (value as? Dictionary<AnyHashable,Any>) { xml.append(dict.xmlString(withElement: "Dictionary", isFirstElement: false)) } else {/* if let booleanValue = (value as? Bool) { xml.append(String(format: (booleanValue ? "true" : "false"))) } else if let intValue = (value as? Int) { xml.append(String(format: "%d", intValue)) } else if let floatValue = (value as? Float) { xml.append(String(format: "%f", floatValue)) } else if let doubleValue = (value as? Double) { xml.append(String(format: "%f", doubleValue)) } else { xml.append(String(format: "<%@>", value as! CVarArg)) }*/ Swift.print("value: \(value)") xml.append(toLiteral(value)) } } xml.append(String(format: "<%@>\n", element)) return xml } } extension Dictionary { // Return an XML string from the dictionary func xmlString(withElement element: String, isFirstElement: Bool) -> String { var xml = String.init() if isFirstElement { xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") } xml.append(String(format: "<%@>\n", element)) for node in self.keys { let value = self[node] if let array: Array<Any> = (value as? Array<Any>) { xml.append(array.xmlString(withElement: node as! String, isFirstElemenet: false)) } else if let dict: Dictionary<AnyHashable,Any> = (value as? Dictionary<AnyHashable,Any>) { xml.append(dict.xmlString(withElement: node as! String, isFirstElement: false)) } else { xml.append(String(format: "<%@>", node as! CVarArg)) xml.append(toLiteral(value as Any)) xml.append(String(format: "</%@>\n", node as! CVarArg)) } } xml.append(String(format: "</%@>\n", element)) return xml } func xmlHTMLString(withElement element: String, isFirstElement: Bool) -> String { let xml = self.xmlString(withElement: element, isFirstElement: isFirstElement) return xml.replacingOccurrences(of: "&", with: "&amp", options: .literal, range: nil) } } extension NSString { class func string(fromAsset: String) -> String { let asset = NSDataAsset.init(name: fromAsset) let data = NSData.init(data: (asset?.data)!) let text = String.init(data: data as Data, encoding: String.Encoding.utf8) return text! } } extension NSAttributedString { class func string(fromAsset: String) -> String { let asset = NSDataAsset.init(name: fromAsset) let data = NSData.init(data: (asset?.data)!) let text = String.init(data: data as Data, encoding: String.Encoding.utf8) return text! } } struct UAHelpers { static func isValid(uaString: String) -> Bool { // From https://stackoverflow.com/questions/20569000/regex-for-http-user-agent let regex = try! NSRegularExpression(pattern: ".+?[/\\s][\\d.]+") return (regex.firstMatch(in: uaString, range: uaString.nsrange) != nil) } }
32.343629
97
0.557598
e5e8f7ad3ed2343d4f8c2d3c998beb42f74aa372
2,390
// // Account.swift // WebDAV-Swift // // Created by Isaac Lyons on 10/29/20. // import Foundation //MARK: WebDAVAccount public protocol WebDAVAccount: Hashable { var username: String? { get } var baseURL: String? { get } } //MARK: UnwrappedAccount internal struct UnwrappedAccount: Hashable { var username: String var baseURL: URL init?<Account: WebDAVAccount>(account: Account) { guard let username = account.username, let baseURLString = account.baseURL, var baseURL = URL(string: baseURLString) else { return nil } switch baseURL.scheme { case nil: baseURL = URL(string: "https://" + baseURLString) ?? baseURL case "https": break default: var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) components?.scheme = "https" baseURL = components?.url ?? baseURL } self.username = username self.baseURL = baseURL } /// Description of the unwrapped account in the format "username@baseURL". var description: String { "\(username)@\(baseURL.absoluteString)" } /// Description of the unwrapped account in the format "username@baseURL" /// with the baseURL encoded. /// /// Replaces slashes with colons (for easier reading on macOS) /// and other special characters with their percent encoding. /// - Note: Only the baseURL is encoded. The username and @ symbol are unchanged. var encodedDescription: String? { guard let encodedURL = baseURL.absoluteString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return nil } return "\(username)@\(encodedURL.replacingOccurrences(of: "%2F", with: ":"))" } } //MARK: AccountPath public struct AccountPath: Hashable, Codable { static let slash = CharacterSet(charactersIn: "/") var username: String? var baseURL: String? var path: String init<Account: WebDAVAccount>(account: Account, path: String) { self.username = account.username self.baseURL = account.baseURL self.path = path.trimmingCharacters(in: AccountPath.slash) } } //MARK: SimpleAccount public struct SimpleAccount: WebDAVAccount { public var username: String? public var baseURL: String? }
29.146341
135
0.64477
904478454dde8d2c7090d554d88fb1274af75359
2,198
// // AppDelegate.swift // Memorable Places // // Created by Jafar Yormahmadzoda on 18/03/2017. // Copyright © 2017 Jafar Yormahmadzoda. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.765957
285
0.757507
677749bae7fafc577e8edbcb3a364121c97eb391
983
// // Router.swift // Gloden Palace Casino // // Created by albutt on 2018/11/30. // Copyright © 2018 海创中盈. All rights reserved. // import Foundation import URLNavigator /// 简单封装的Router class Router { static var shared: Router! var navigator: Navigator { return _navigator } private var _navigator: Navigator init(navigator: Navigator) { self._navigator = navigator } static var topMost: UIViewController? { if let topMost = UIViewController.topMost { var topViewController = topMost.parent while topViewController?.parent != nil { topViewController = topViewController?.parent } if let navigationController = topViewController as? UINavigationController, let last = navigationController.viewControllers.last { topViewController = last } return topViewController } return nil } }
24.575
87
0.622584
1eb2b041bd8c093358712e9f2aed56468f956486
805
// SPDX-License-Identifier: MIT // Copyright © 2018-2019 WireGuard LLC. All Rights Reserved. import Cocoa class ErrorPresenter: ErrorPresenterProtocol { static func showErrorAlert(title: String, message: String, from sourceVC: AnyObject?, onPresented: (() -> Void)?, onDismissal: (() -> Void)?) { let alert = NSAlert() alert.messageText = title alert.informativeText = message onPresented?() if let sourceVC = sourceVC as? NSViewController { NSApp.activate(ignoringOtherApps: true) sourceVC.view.window!.makeKeyAndOrderFront(nil) alert.beginSheetModal(for: sourceVC.view.window!) { _ in onDismissal?() } } else { alert.runModal() onDismissal?() } } }
33.541667
147
0.61118
e220595778888b43f57e421b185df7bbd4408398
1,358
// // AppDelegate.swift // RotaryStepSequencer // // Created by Bobby George on 5/20/21. // 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.702703
179
0.747423
e8f077bf52444ce5335013037a245d264a642415
15,892
// // Downloader.swift // PokeAlmanac // // Created by 倉重ゴルプ ダニエル on 2016/04/19. // Copyright © 2016年 Daniel Kurashige-Gollub. All rights reserved. // import Foundation import Alamofire import JSONJoy // // TODO(dkg): The current callback-based approach for downloading data is really not well suited for this app. // It is too fickle and prone to "oopps, my UI (and callback) was deallocated while I was still busy" kind of errors. // A much better approach would be either of the following: // // - Futures/Promises, with cancelation tokens // - Observer pattern via the NSNotificationCenter (all downloads would run in different (background) threads and notify // the UI via notifications that the UI has to subscribe to // private let API_BASE_URL = "http://pokeapi.co/api/v2" private let API_POKEMON_URL = API_BASE_URL + "/pokemon" // TODO(dkg): figure out how to "include" the actual resource name for each error case - maybe custom constructor or // some meta-programming magic? public enum APIError: String { case NoError = "OK" case APINoJSONResponse = "API returned no JSON." case APILimitReached = "API limit was reached for this resource." case APIResponseTimeout = "The API did not return a response in time." case API404 = "The API could not find the requested resource." case APIOther = "The API returned an unknwon error." case APIJSONTransformationFailed = "The JSON response could not be transformed into an object." case APICouldNotSaveToCacheOrFile = "Could not save the API response to the cache or a file." case APINoSpriteForThisType = "No sprite for this type." } public enum PokemonSpriteType: String { case FrontDefault, FrontShiny, FrontFemale, FrontShinyFemale case BackDefault, BackShiny, BackFemale, BackShinyFemale } // NOTE(dkg): - This class should be unaware about threads - the caller should handle this // - Also note that Alamofire is async(!!!) - therefore this class is as well // - The downloader class saves all downloaded data to the cache db (or as files in case of binary data) public class Downloader: NSObject { private let manager: Manager public override init() { manager = Alamofire.Manager.sharedInstance // TODO(dkg): maybe this setting would be nice to have in the UI in a settings view controller manager.session.configuration.timeoutIntervalForRequest = 15.0 // 15.0 seconds timeout super.init() } public func startDownload(type: APIType, offset: Int = 0, limit: Int = 20, id: Int = API_LIST_REQUEST_ID, completed: (json: String?, error: APIError) -> Void) { log("download start") var url: String? = nil; switch(type) { case .ListPokemon: url = "\(API_POKEMON_URL)/?limit=\(limit)&offset=\(offset)" break case .Pokemon: url = "\(API_POKEMON_URL)/\(id)/" default: assertionFailure("TODO! Implement this case \(type)") break } if let requestUrl = url { startDownload(requestUrl, completed: completed) } else { assertionFailure("WARNING: url not set for download!") } } public func startDownload(url: String, completed: (json: String?, error: APIError) -> Void) { log("startDowloadList request: \(url)") let request = manager.request(NSURLRequest(URL: NSURL(string: url)!)) request.responseString { response in log("Request is success: \(response.result.isSuccess)") if response.result.isSuccess { completed(json: response.result.value, error: .NoError) } else { completed(json: nil, error: .APIOther) // TODO(dkg): Figure out the real error here and pass it on accordingly. } } } public func startDownloadPokemonList(offset: Int = 0, limit: Int = 20, completed: (resourceList: NamedAPIResourceList?, error: APIError) -> Void) { log("startDownloadPokemons(\(offset), \(limit))") startDownload(.ListPokemon, offset: offset, limit: limit, completed: { json, error in // log("download done!!!! \(json)") log("one download done") if let dataString = json { // This json is a list of links for the actual Pokemon endpoint that gives us the individual // Pokemon data. We need to manually download each of those. let db = DB() db.insertOrUpdateCachedResponse(APIType.ListPokemon, json: dataString, offset: offset, limit: limit) let resourceList = Transformer().jsonToNamedAPIResourceList(dataString) if let list = resourceList { completed(resourceList: list, error: .NoError) // // TODO(dkg): would need Futures/Promises here for this // for resource in resourceList.results { // downloadPokemon(resource.url) // } } else { logWarn("Could not convert JSON to NamedAPIResourceList.") completed(resourceList: nil, error: .APIJSONTransformationFailed) } } else { logWarn("Could not get data from request - no valid response") completed(resourceList: nil, error: .APINoJSONResponse) } }) } public func downloadPokemon(id: Int, completed: (pokemon: Pokemon?, error: APIError) -> Void) { startDownload(APIType.Pokemon, id: id, completed: { json, error in self.cachePokemonAndTransform(json, error: error, completed: completed) }) } public func downloadPokemon(url: String, completed: (pokemon: Pokemon?, error: APIError) -> Void) { startDownload(url, completed: { json, error in self.cachePokemonAndTransform(json, error: error, completed: completed) }) } private func cachePokemonAndTransform(json: String?, error: APIError, completed: (pokemon: Pokemon?, error: APIError) -> Void) { if let dataString = json { log("downloaded pokemon json") let db = DB() let id = extractIdFromJson(dataString) db.insertOrUpdateCachedResponse(APIType.Pokemon, json: dataString, id: id) if let pokemon = Transformer().jsonToPokemonModel(dataString) { // also save the pokemon in our special pokemon table db.savePokemon(pokemon) completed(pokemon: pokemon, error: .NoError) } else { logWarn("Could not convert Pokemon JSON to Pokemon object. \(error)") completed(pokemon: nil, error: .APIJSONTransformationFailed) } } else { logWarn("Could not get data from request - no valid response") completed(pokemon: nil, error: .APINoJSONResponse) } } // TODO(dkg): Move this into Utils.swift? public func extractIdFromJson(json: String) -> Int { let data: NSData = json.dataUsingEncoding(NSUTF8StringEncoding)! do { let apiId = try APIID(JSONDecoder(data)) return apiId.id } catch { // TODO(dkg): fallbacks - actually not needed any longer, should be removed let pattern: String = "\"id\":(\\d)," let id = extractIdFromText(json, pattern: pattern) if id != 0 { return id } var range = json.rangeOfString(",")! var text = json.substringToIndex(range.endIndex.advancedBy(-1)) range = text.rangeOfString(":")! text = text.substringFromIndex(range.startIndex.advancedBy(1)) let oid = Int(text) if let idi = oid { return idi } } logWarn("Could not find id in json!") logWarn(json) return 0 } // TODO(dkg): Move this into Utils.swift? public func extractIdFromUrl(url: String) -> Int { // "http://pokeapi.co/api/v2/pokemon/3/ ==> return 3 // log("url from id \(url)") let pattern: String = "(\\d*)\\/$" return extractIdFromText(url, pattern: pattern) } // TODO(dkg): Move this into Utils.swift? private func extractIdFromText(text: String, pattern: String) -> Int { do { let regex = try NSRegularExpression(pattern: pattern, options: []) let nsString = text as NSString let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length)) if results.count > 0 { let firstMatch = results[0] let possibleId = nsString.substringWithRange(firstMatch.rangeAtIndex(1)) return Int(possibleId)! } return 0 } catch let error as NSError { logWarn("could not find or convert id from text: \(error.localizedDescription)") return 0 } } public func getPokemonSpriteFromCache(pokemonJson: String, type: PokemonSpriteType = .FrontDefault) -> UIImage? { // TODO(dkg): add autoreleasepool here? if let pokemon = Transformer().jsonToPokemonModel(pokemonJson) { return getPokemonSpriteFromCache(pokemon) } else { return nil } } public func getPokemonSpriteFromCache(pokemonId: Int, type: PokemonSpriteType = .FrontDefault) -> UIImage? { // TODO(dkg): add autoreleasepool here? if let pokemon = Transformer().jsonToPokemonModel(DB().getPokemonJSON(pokemonId)) { return getPokemonSpriteFromCache(pokemon) } else { return nil } } public func getPokemonSpriteFromCache(pokemon: Pokemon, type: PokemonSpriteType = .FrontDefault) -> UIImage? { // "sprites":{"back_female":null,"back_shiny_female":null,"back_default":"http://pokeapi.co/media/sprites/pokemon/back/2.png", ... if let fileName = createPokemonSpriteFilename(pokemon, type: type) { if fileExists(fileName) { // log("filename exists: \(fileName)") return UIImage(contentsOfFile: fileName) } else { log("filename does not exists: \(fileName)") } } else { log("no sprite \(type) for pokemon \(pokemon.name)") } return nil } // TODO(dkg): improve error handling public func downloadPokemonSprite(pokemonJson: String, type: PokemonSpriteType = .FrontDefault, completed: (sprite: UIImage?, type: PokemonSpriteType, error: APIError) -> Void) { // TODO(dkg): add autoreleasepool here? if let pokemon = Transformer().jsonToPokemonModel(pokemonJson) { downloadPokemonSprite(pokemon, type: type, completed: completed) } else { log("could not load or convert Pokemon for JSON data") completed(sprite: nil, type: type, error: APIError.APIJSONTransformationFailed) } } public func downloadPokemonSprite(pokemonId: Int, type: PokemonSpriteType = .FrontDefault, completed: (sprite: UIImage?, type: PokemonSpriteType, error: APIError) -> Void) { // TODO(dkg): add autoreleasepool here? if let pokemon = Transformer().jsonToPokemonModel(DB().getPokemonJSON(pokemonId)) { downloadPokemonSprite(pokemon, type: type, completed: completed) } else { log("could not load or convert Pokemon for ID \(pokemonId)") completed(sprite: nil, type: type, error: APIError.APIJSONTransformationFailed) } } public func downloadPokemonSprite(pokemon: Pokemon, type: PokemonSpriteType = .FrontDefault, completed: (sprite: UIImage?, type: PokemonSpriteType, error: APIError) -> Void) { if let fileName = createPokemonSpriteFilename(pokemon, type: type) { if let url = getPokemonSpriteUrl(pokemon, type: type) { Alamofire.request(.GET, url) .responseData { response in log("Request is success: \(response.result.isSuccess)") if response.result.isSuccess { if let data: NSData = response.result.value { if data.writeToFile(fileName, atomically: true) { log("wrote file : \(fileName)") completed(sprite: UIImage(data: data)!, type: type, error: .NoError) } else { completed(sprite: nil, type: type, error: .APICouldNotSaveToCacheOrFile) } return } } completed(sprite: nil, type: type, error: .APIOther) // TODO(dkg): Figure out the real error here and pass it on accordingly. } } else { log("could not get url for sprite download") completed(sprite: nil, type: type, error: APIError.APIOther) } } else { // log("could not create filename for sprite download") completed(sprite: nil, type: type, error: APIError.APINoSpriteForThisType) } } private func getPokemonSpriteUrl(pokemon: Pokemon, type: PokemonSpriteType = .FrontDefault) -> String? { var spriteUrl: String? = nil switch (type) { case .BackFemale: spriteUrl = pokemon.sprites.back_female break case .BackShinyFemale: spriteUrl = pokemon.sprites.back_shiny_female break case .BackDefault: spriteUrl = pokemon.sprites.back_default break case .BackShiny: spriteUrl = pokemon.sprites.back_shiny break case .FrontFemale: spriteUrl = pokemon.sprites.front_female break case .FrontShinyFemale: spriteUrl = pokemon.sprites.front_shiny_female break case .FrontDefault: spriteUrl = pokemon.sprites.front_default break case .FrontShiny: spriteUrl = pokemon.sprites.front_shiny break default: assertionFailure("unknown enum value for PokemonSpriteType! \(type)") } return spriteUrl } // need to somehow figure out a unique filename per pokemon per sprite type private func createPokemonSpriteFilename(pokemon: Pokemon, type: PokemonSpriteType = .FrontDefault) -> String? { // "sprites": { "back_default":"http://pokeapi.co/media/sprites/pokemon/back/2.png", ...} if let url = getPokemonSpriteUrl(pokemon, type: type) { if let range = url.rangeOfString("://") { let folder = applicationDocumentsFolder() as NSString let urlFile = url.substringFromIndex(range.endIndex) as NSString let path = folder.stringByAppendingPathComponent(urlFile.stringByDeletingLastPathComponent) as NSString let name = urlFile.lastPathComponent // log("path name \(path) \(name)") if createFolderIfNotExists(path as String) { let fileName = path.stringByAppendingPathComponent(name) return fileName } } } return nil } }
42.265957
182
0.590863
1acdee3dd6103bd26422486ae5bf267ddde37d1e
4,707
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation class ConvAddReluParam<P: PrecisionProtocol>: OpParam { required init(opDesc: PMOpDesc, inScope: Scope) throws { do { filter = try ConvAddReluParam.inputFilter(paraInputs: opDesc.paraInputs, from: inScope) input = try ConvAddReluParam.input(inputs: opDesc.inputs, from: inScope) output = try ConvAddReluParam.outputOut(outputs: opDesc.outputs, from: inScope) stride = try ConvAddReluParam.getAttr(key: "strides", attrs: opDesc.attrs) paddings = try ConvAddReluParam.getAttr(key: "paddings", attrs: opDesc.attrs) dilations = try ConvAddReluParam.getAttr(key: "dilations", attrs: opDesc.attrs) groups = try ConvAddReluParam.getAttr(key: "groups", attrs: opDesc.attrs) do { axis = try ConvAddReluParam.getAttr(key: "axis", attrs: opDesc.attrs) } catch { axis = -1 } do { y = try ConvAddReluParam.inputY(inputs: opDesc.paraInputs, from: inScope) } catch { do { let yTensor: Tensor<P> = try ConvAddReluParam.inputY(inputs: opDesc.paraInputs, from: inScope) let device = input.metalTexture!.device y = try Texture.init(device: device, inDim: yTensor.dim) let value: [P] = Array(UnsafeBufferPointer(start: yTensor.data.pointer, count: yTensor.dim.numel())) y?.metalTexture = try device.tensor2texture(value: value, dim: yTensor.dim.dims, transpose: [0, 1, 2, 3], inComputePrecision: GlobalConfig.shared.computePrecision) self.yTensor = yTensor } catch { } } } catch let error { throw error } } let input: Texture let filter: Tensor<P> var output: Texture let stride: [Int32] let paddings: [Int32] let dilations: [Int32] let groups: Int let axis: Int var y: Texture? var yTensor: Tensor<P>? open class func hasY() -> Bool { return true } } class ConvAddReluOp<P: PrecisionProtocol>: Operator<ConvAddReluKernel<P>, ConvAddReluParam<P>>, Runable, Creator, InferShaperable, Fusion { typealias OpType = ConvAddReluOp<P> static func fusionNode() -> Node { let beginNode = Node.init(inType: gConvType) _ = beginNode --> Node.init(inType: gElementwiseAddType) --> Node.init(inType: gReluType) return beginNode } static func change() -> [String : [(from: String, to: String)]] { return [:] } static func fusionType() -> String { return gConvAddReluType } func inferShape() { let inDims = para.input.dim let filterDim = para.filter.dim let strides = para.stride let paddings = para.paddings let dilations = para.dilations var outDim = [inDims[0]] for i in 0..<strides.count { let dilation: Int = Int(dilations[i]) let filterSize: Int = filterDim[i + 1] let inputSize: Int = inDims[i + 1] let padding: Int = Int(paddings[i]) let stride: Int = Int(strides[i]) let dKernel = dilation * (filterSize - 1) + 1 let outputSize = (inputSize + 2 * padding - dKernel) / stride + 1 outDim.append(outputSize) } outDim.append(filterDim[0]) para.output.dim = Dim.init(inDim: outDim) } func runImpl(device: MTLDevice, buffer: MTLCommandBuffer) throws { try kernel.compute(commandBuffer: buffer, param: para) } func delogOutput() { print(" \(type) output: ") print(para.output.metalTexture ?? "") do { let output = try para.output.metalTexture?.toTensor(dim: (n: para.output.tensorDim[0], c: para.output.tensorDim[1], h: para.output.tensorDim[2], w: para.output.tensorDim[3])).strideArray() ?? [] print(output) } catch _ { } } }
38.581967
206
0.604207
c1136147d579ce2e96453e9b692adfefd58fff59
1,745
// // StorageModel.swift // 06-earthquake // // Created by koogawa on 2019/12/28. // Copyright © 2019 LmLab.net. All rights reserved. // import Foundation import FirebaseStorage final class StorageModel { func fetchImage(imagePath: String, completion: @escaping (Result<UIImage, Error>) -> Void) { Storage.storage().reference() .child(imagePath) .getData(maxSize: 2 * 1024 * 1024) { data, error in guard error == nil, let data = data, let image = UIImage(data: data) else { completion(.failure(error!)) return } completion(.success(image)) } } func uploadImage(uid: String, image: UIImage, completion: @escaping (Result<String, Error>) -> Void) { guard let data = image.jpegData(compressionQuality: 0.5) else { return } let storage = Storage.storage() let storageRef = storage.reference() let millsec = Date().timeIntervalSince1970 let imagePath = "photos/\(uid)/\(Int(millsec))" let imageRef = storageRef.child(imagePath) let metadata = StorageMetadata() metadata.contentType = "image/jpeg" imageRef.putData(data, metadata: metadata) { _, error in guard error == nil else { completion(.failure(error!)) return } completion(.success(imagePath)) } } func deleteImage(imagePath: String, completion: @escaping (Error?) -> Void) { let storage = Storage.storage() let storageRef = storage.reference(withPath: imagePath) storageRef.delete { (error) in completion(error) } } }
32.314815
106
0.578797
e29c3a5867be4c31148185d9c5b2f1d5917d9309
2,383
// // AppDelegate.swift // Youtube // // Created by Luis F Ruiz Arroyave on 8/8/16. // Copyright © 2016 NextU. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.makeKeyAndVisible() let layout = UICollectionViewFlowLayout() window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout)) 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:. } }
44.12963
285
0.741922
5b8521f79c2b101f0c005f70a6f30be2a3962e4f
897
// // Array+Shuffle.swift // Avatars // // Created by Robin Malhotra on 23/08/17. // Copyright © 2017 Robin Malhotra. All rights reserved. // import Foundation extension Sequence { /// Returns an array with the contents of this sequence, shuffled. func shuffled() -> [Element] { var result = Array(self) result.shuffle() return result } } func *<T>(left: Array<T>, right: Int) -> Array<T> { return Array((0..<right).map { _ in return left }.joined()) } extension MutableCollection { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) let i = index(firstUnshuffled, offsetBy: d) swapAt(firstUnshuffled, i) } } }
21.357143
91
0.675585
2f1d762743a4c17cd9aa34749596e7af4360945d
5,941
import Foundation // swiftlint:disable type_name public class lang_ro: RelativeFormatterLang { /// Romanian public static let identifier: String = "ro" public required init() {} public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? { let mod100 = Int(value) % 100 switch value { case 0: return .few case 1: return .one default: if mod100 > 1 && mod100 <= 19 { return .few } } return .other } public var flavours: [String: Any] { return [ RelativeFormatter.Flavour.long.rawValue: self._long, RelativeFormatter.Flavour.narrow.rawValue: self._narrow, RelativeFormatter.Flavour.short.rawValue: self._short ] } private var _short: [String: Any] { return [ "year": [ "previous": "anul trecut", "current": "anul acesta", "next": "anul viitor", "past": [ "one": "acum {0} an", "few": "acum {0} ani", "other": "acum {0} de ani" ], "future": [ "one": "peste {0} an", "few": "peste {0} ani", "other": "peste {0} de ani" ] ], "quarter": [ "previous": "trim. trecut", "current": "trim. acesta", "next": "trim. viitor", "past": "acum {0} trim.", "future": "peste {0} trim." ], "month": [ "previous": "luna trecută", "current": "luna aceasta", "next": "luna viitoare", "past": [ "one": "acum {0} lună", "other": "acum {0} luni" ], "future": [ "one": "peste {0} lună", "other": "peste {0} luni" ] ], "week": [ "previous": "săptămâna trecută", "current": "săptămâna aceasta", "next": "săptămâna viitoare", "past": "acum {0} săpt.", "future": "peste {0} săpt." ], "day": [ "previous": "ieri", "current": "azi", "next": "mâine", "past": [ "one": "acum {0} zi", "few": "acum {0} zile", "other": "acum {0} de zile" ], "future": [ "one": "peste {0} zi", "few": "peste {0} zile", "other": "peste {0} de zile" ] ], "hour": [ "current": "ora aceasta", "past": "acum {0} h", "future": "peste {0} h" ], "minute": [ "current": "minutul acesta", "past": "acum {0} min.", "future": "peste {0} min." ], "second": [ "current": "acum", "past": "acum {0} sec.", "future": "peste {0} sec." ], "now": "acum" ] } private var _narrow: [String: Any] { return [ "year": [ "previous": "anul trecut", "current": "anul acesta", "next": "anul viitor", "past": [ "one": "-{0} an", "other": "-{0} ani" ], "future": [ "one": "+{0} an", "other": "+{0} ani" ] ], "quarter": [ "previous": "trim. trecut", "current": "trim. acesta", "next": "trim. viitor", "past": "-{0} trim.", "future": "+{0} trim." ], "month": [ "previous": "luna trecută", "current": "luna aceasta", "next": "luna viitoare", "past": [ "one": "-{0} lună", "other": "-{0} luni" ], "future": [ "one": "+{0} lună", "other": "+{0} luni" ] ], "week": [ "previous": "săptămâna trecută", "current": "săptămâna aceasta", "next": "săptămâna viitoare", "past": "-{0} săpt.", "future": "+{0} săpt." ], "day": [ "previous": "ieri", "current": "azi", "next": "mâine", "past": [ "one": "-{0} zi", "other": "-{0} zile" ], "future": [ "one": "+{0} zi", "other": "+{0} zile" ] ], "hour": [ "current": "ora aceasta", "past": "-{0} h", "future": "+{0} h" ], "minute": [ "current": "minutul acesta", "past": "-{0} m", "future": "+{0} m" ], "second": [ "current": "acum", "past": "-{0} s", "future": "+{0} s" ], "now": "acum" ] } private var _long: [String: Any] { return [ "year": [ "previous": "anul trecut", "current": "anul acesta", "next": "anul viitor", "past": [ "one": "acum {0} an", "few": "acum {0} ani", "other": "acum {0} de ani" ], "future": [ "one": "peste {0} an", "few": "peste {0} ani", "other": "peste {0} de ani" ] ], "quarter": [ "previous": "trimestrul trecut", "current": "trimestrul acesta", "next": "trimestrul viitor", "past": [ "one": "acum {0} trimestru", "few": "acum {0} trimestre", "other": "acum {0} de trimestre" ], "future": [ "one": "peste {0} trimestru", "few": "peste {0} trimestre", "other": "peste {0} de trimestre" ] ], "month": [ "previous": "luna trecută", "current": "luna aceasta", "next": "luna viitoare", "past": [ "one": "acum {0} lună", "few": "acum {0} luni", "other": "acum {0} de luni" ], "future": [ "one": "peste {0} lună", "few": "peste {0} luni", "other": "peste {0} de luni" ] ], "week": [ "previous": "săptămâna trecută", "current": "săptămâna aceasta", "next": "săptămâna viitoare", "past": [ "one": "acum {0} săptămână", "few": "acum {0} săptămâni", "other": "acum {0} de săptămâni" ], "future": [ "one": "peste {0} săptămână", "few": "peste {0} săptămâni", "other": "peste {0} de săptămâni" ] ], "day": [ "previous": "ieri", "current": "azi", "next": "mâine", "past": [ "one": "acum {0} zi", "few": "acum {0} zile", "other": "acum {0} de zile" ], "future": [ "one": "peste {0} zi", "few": "peste {0} zile", "other": "peste {0} de zile" ] ], "hour": [ "current": "ora aceasta", "past": [ "one": "acum {0} oră", "few": "acum {0} ore", "other": "acum {0} de ore" ], "future": [ "one": "peste {0} oră", "few": "peste {0} ore", "other": "peste {0} de ore" ] ], "minute": [ "current": "minutul acesta", "past": [ "one": "acum {0} minut", "few": "acum {0} minute", "other": "acum {0} de minute" ], "future": [ "one": "peste {0} minut", "few": "peste {0} minute", "other": "peste {0} de minute" ] ], "second": [ "current": "acum", "past": [ "one": "acum {0} secundă", "few": "acum {0} secunde", "other": "acum {0} de secunde" ], "future": [ "one": "peste {0} secundă", "few": "peste {0} secunde", "other": "peste {0} de secunde" ] ], "now": "acum" ] } }
19.288961
83
0.508669
08d09cb50c08b750976bd779697f66a3d0e7c81b
4,984
// // field-support.swift // jocool // // Created by tong on 16/6/11. // Copyright © 2016年 zhuxietong. All rights reserved. // import Foundation public class JoRule { public var reg:String? public var nil_msg:String public var err_msg:String? public init(reg:String?,nil_msg:String,err_msg:String?) { self.reg = reg self.nil_msg = nil_msg self.err_msg = err_msg } } public func check(string value:String?,rule:JoRule) ->(match:Bool,reason:String) { if let reg = rule.reg { var ok:Bool = false if let a_value = value { ok = a_value.valid(byReg:reg) if ok { return (true,"ok") } else { if a_value == "" { return (false,rule.nil_msg) } else { if let msg = rule.err_msg { return (false,msg) } else { return (false,"内容不匹配(swift)") } } } } else { return (false,"\(rule.nil_msg)..") } } else { return(true,"no reg check") } // return (false,"swift end") } public protocol JoField{ associatedtype valueT var _name:String {get set} var _rule:JoRule? {get set} var _defaultV:String? {get set} var _need:Bool {get set} var _hiden:Bool {get set} var _ID:String {get set} var _value:valueT? {get set} var toValue:(_ s_value:String?) -> valueT? { get set} var toString:(_ t_value:valueT?) -> String? {get set} func getValue() ->(ID:String,value:valueT?,validate:Bool) } public class ObjField<T,K,V>:NSObject,JoField, ExpressibleByDictionaryLiteral{ public typealias Key = K public typealias Value = V public typealias valueT = T public var _name:String = "#" public var _rule:JoRule? public var _defaultV:String? = nil public var _need:Bool = true public var _hiden:Bool = false public var _ID:String = "" public var _value: valueT? = nil public var toString: (_ t_value: valueT?) -> String? = { if let v = $0 { return "\(v)" } return nil } public var toValue: (_ s_value: String?) -> valueT? = {_ in return nil } init(id ID:String="",defaultV:String?=nil,need:Bool=true,hiden:Bool=false,rule:JoRule?=nil) { self._rule = rule self._defaultV = defaultV self._need = need self._hiden = hiden self._ID = ID } public required init(dictionaryLiteral elements: (Key, Value)...) { super.init() for (k,v) in elements { if let pk = k as? String { let sk = "\(pk)" self.setValueOfProperty(property: sk, value: v) // if let anyobj = v as? AnyObject // { // self.setValueOfProperty(property: sk, value: anyobj) // } if let bv = v as? Bool { switch sk { case "_need": self._need = bv case "_hiden": self._hiden = bv default: break } } } } } func __stringValue() -> String? { return self.toString(self._value) } public func getValue() ->(ID:String,value:valueT?,validate:Bool) { if let s_rule = self._rule { let result = check(string: self.__stringValue(), rule: s_rule) if result.match { return (self._ID,self._value,true) } else { if _need { result.reason.alert() return (self._ID,self._value,false) } else { if let valueStr = self.__stringValue() { if valueStr.len > 0 { result.reason.alert() return (self._ID,self._value,false) } } return (self._ID,self._value,true) } } } return (self._ID,self._value,true) } }
23.181395
97
0.421549
ab09750201b9ece255fd4e391f6a1bf490f468fa
1,403
// // UserRouter.swift // gitap // // Created by Koichi Sato on 1/7/17. // Copyright © 2017 Koichi Sato. All rights reserved. // import Foundation import Alamofire enum userRouter: URLRequestConvertible { case fetchAuthenticatedUser() func asURLRequest() throws -> URLRequest { var method: HTTPMethod { switch self { case .fetchAuthenticatedUser: return .get } } let url: URL = { let relativePath: String switch self { case .fetchAuthenticatedUser(): relativePath = "/user" } var url = URL(string: githubBaseURLString)! url.appendPathComponent(relativePath) return url }() let params: ([String: Any]?) = { switch self { case .fetchAuthenticatedUser: return nil } }() var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.rawValue // Set Oauth token if we have one if let token = GitHubAPIManager.shared.OAuthToken { urlRequest.setValue("token \(token)", forHTTPHeaderField: "Authorization") } let encoding = JSONEncoding.default return try encoding.encode(urlRequest, with: params) } }
25.509091
86
0.538845
48fca2a608d3bf4743bd0298b0c3eeff1f52dadf
3,339
// // JSCommentStyleGudie.swift // LoveYou // // Created by WengHengcong on 2016/10/20. // Copyright © 2016年 JungleSong. All rights reserved. // //以下是为了测试注释 //参考:http://nshipster.cn/swift-documentation/ import Foundation /// 🚲 一个两轮的,人力驱动的交通工具. class Bicycle { /** 车架样式. - Road: 用于街道或步道. - Touring: 用于长途. - Cruiser: 用于城镇周围的休闲之旅. - Hybrid: 用于通用运输. */ enum Style { case Road, Touring, Cruiser, Hybrid } /** 转换踏板功率为运动的机制。 - Fixed: 一个单一的,固定的齿轮。 - Freewheel: 一个可变速,脱开的齿轮。 */ enum Gearing { case Fixed case Freewheel(speeds: Int) } /** 用于转向的硬件。 - Riser: 一个休闲车把。 - Café: 一个正常车把。 - Drop: 一个经典车把. - Bullhorn: 一个超帅车把. */ enum Handlebar { case Riser, Café, Drop, Bullhorn } enum KJKJ { case ik } /// 自行车的风格 let style: Style /// 自行车的齿轮 let gearing: Gearing /// 自行车的车把 let handlebar: Handlebar /// 车架大小, 厘米为单位. let frameSize: Int /// 自行车行驶的旅程数 private(set) var numberOfTrips: Int /// 自行车总共行驶的距离,米为单位 private(set) var distanceTravelled: Double /** 使用提供的部件及规格初始化一个新自行车。 :param: style 自行车的风格 :param: gearing 自行车的齿轮 :param: handlebar 自行车的车把 :param: centimeters 自行车的车架大小,单位为厘米 :returns: 一个漂亮的,全新的,为你度身定做. */ init(style: Style, gearing: Gearing, handlebar: Handlebar, frameSize centimeters: Int) { self.style = style self.gearing = gearing self.handlebar = handlebar self.frameSize = centimeters self.numberOfTrips = 0 self.distanceTravelled = 0 } /** 把自行车骑出去遛一圈 :param: meters 行驶的距离,单位为米 */ func travel(distance meters: Double) { if meters > 0 { distanceTravelled += meters numberOfTrips+=1 } } } // MARK: Printable extension Bicycle { var description: String { var descriptors: [String] = [] switch self.style { case .Road: descriptors.append("A road bike for streets or trails") case .Touring: descriptors.append("A touring bike for long journeys") case .Cruiser: descriptors.append("A cruiser bike for casual trips around town") case .Hybrid: descriptors.append("A hybrid bike for general-purpose transportation") } switch self.gearing { case .Fixed: descriptors.append("with a single, fixed gear") case .Freewheel(let n): descriptors.append("with a \(n)-speed freewheel gear") } switch self.handlebar { case .Riser: descriptors.append("and casual, riser handlebars") case .Café: descriptors.append("and upright, café handlebars") case .Drop: descriptors.append("and classic, drop handlebars") case .Bullhorn: descriptors.append("and powerful bullhorn handlebars") } descriptors.append("on a \(frameSize)\" frame") // FIXME: // FIXME: 使用格式化的距离 descriptors.append("with a total of \(distanceTravelled) meters traveled over \(numberOfTrips) trips.") // TODO: // DEBUG: // TODO: 允许自行车被命名吗? return descriptors[0] } }
21.681818
111
0.573525
67275452def89be681fa25c2e8ca5ab5624a079b
4,015
// // GScrollView.swift // travelMap // // Created by green on 15/7/8. // Copyright (c) 2015年 com.city8. All rights reserved. // import UIKit class IndexUITapGestureRecognizer:UITapGestureRecognizer{ var index:Int = 0 } @IBDesignable class GScrollView: UIScrollView { var dataSource = [POIModel]() { willSet { self.setNeedsDisplay() } } @IBInspectable var verticalBuffer:CGFloat = 4 @IBInspectable var horizontalBuffer:CGFloat = 4 @IBInspectable var ratio:CGFloat = 0.5 @IBInspectable var selectIndex:Int? { willSet { for (var i=0;i<self.subviews.count;i++){ if i == newValue { (self.subviews[i] as! UIView).layer.borderColor = self.selectColor.CGColor (self.subviews[i] as! UIView).layer.borderWidth = 1 selectFunc(index: i) } else { (self.subviews[i] as! UIView).layer.borderWidth = 0 unselectFunc(index: i) } } } } @IBInspectable var selectColor = UIColor.redColor() var selectFunc:(index:Int) -> () = {index in } var unselectFunc:(index:Int) -> () = {index in } private var width:CGFloat! override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.yellowColor() } override func drawRect(rect: CGRect) { reset() if dataSource.count > 0 { self.selectIndex = 0 } } private func reset() { for subV in self.subviews { subV.removeFromSuperview() } var x: CGFloat = horizontalBuffer for (var i=0;i<dataSource.count;i++) { let height: CGFloat = self.frame.size.height - (2 * verticalBuffer) width = height / ratio let y: CGFloat = verticalBuffer // let subV = UIView(frame: CGRectMake(x, y, width, height)) let subV = NSBundle.mainBundle().loadNibNamed("ScrollSubView", owner: nil, options: nil).first! as! ScrollSubView subV.nameL.text = dataSource[i].poiName subV.indexL.text = "\(i+1)" subV.frame = CGRectMake(x, y, width, height) self.addSubview(subV) if i == selectIndex { subV.layer.borderColor = selectColor.CGColor subV.layer.borderWidth = 1 } subV.backgroundColor = UIColor.whiteColor() self.addSubview(subV) x += width + horizontalBuffer // 增加收拾 let singleRecognizer = IndexUITapGestureRecognizer(target: self, action: Selector("singleTap:")) singleRecognizer.numberOfTapsRequired = 1 singleRecognizer.index = i subV.addGestureRecognizer(singleRecognizer) } self.contentSize = CGSizeMake(x, self.frame.size.height) } func singleTap(recognizer:IndexUITapGestureRecognizer){ if selectIndex == recognizer.index { self.selectIndex = nil } else { self.selectIndex = recognizer.index } } // MARK: - 对外方法 func focus(index: Int?) { if index != nil && index < self.subviews.count { // 位置使选中成为第一个 let v = self.subviews[index!] as! UIView let midx = CGRectGetMidX(v.frame) let x = midx - width/2 - horizontalBuffer self.scrollRectToVisible(CGRectMake(x, 1, UIScreen.mainScreen().bounds.size.width, 1), animated: true) } self.selectIndex = index } }
28.884892
125
0.513574
e2ee7de74a722cd47eb01313829a086256bb0946
5,387
// // OAuthViewController.swift // DS11WB // // Created by Anthony on 17/3/10. // Copyright © 2017年 SLZeng. All rights reserved. // import UIKit import SVProgressHUD class OAuthViewController: UIViewController { // MARK:- 控件的属性 @IBOutlet weak var webView: UIWebView! // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 1.设置导航栏的内容 setupNavigationBar() // 2.加载网页 loadPage() } } // MARK:- 设置UI界面 extension OAuthViewController { fileprivate func setupNavigationBar() { // 1.设置左侧的item navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.closeItemClick)) // 2.设置右侧的item navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OAuthViewController.fillItemClick)) // 3.设置标题 title = "登录页面" } /** 加载网页 */ fileprivate func loadPage() { // 1.获取登录页面的URLString let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_Redirect_URI)" // 2.创建对应NSURL guard let url = URL(string: urlString) else { return } // 3.创建NSURLRequest对象 let request = URLRequest(url: url) // 4.加载request对象 webView.loadRequest(request) } } // MARK:- 事件监听处理 extension OAuthViewController { @objc fileprivate func closeItemClick() { dismiss(animated: true, completion: nil) } @objc fileprivate func fillItemClick() { // 1.书写js代码 : javascript / java --> 雷锋和雷峰塔 let jsCode = "document.getElementById('userId').value='\(WB_APP_UserId)';document.getElementById('passwd').value='\(WB_APP_Passwd)';" // 2.执行js代码 webView.stringByEvaluatingJavaScript(from: jsCode) } } // MARK: - UIWebView代理 extension OAuthViewController: UIWebViewDelegate { /// webView开始加载网页 func webViewDidStartLoad(_ webView: UIWebView) { SVProgressHUD.showInfo(withStatus: "正在拼命加载网页...") SVProgressHUD.setDefaultMaskType(.black) } /// webView网页加载完成 func webViewDidFinishLoad(_ webView: UIWebView) { SVProgressHUD.dismiss() } /// webView加载网页失败 func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { SVProgressHUD.dismiss() } // 当准备加载某一个页面时,会执行该方法 // 返回值: true -> 继续加载该页面 false -> 不会加载该页面 func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { // 1.获取加载网页的NSURL guard let url = request.url else { return true } // 2.获取url中的字符串 let urlString = url.absoluteString as NSString // 3.判断该字符串中是否包含code guard urlString.contains("code=") else { return true } // 4.将code截取出来 let code = urlString.components(separatedBy: "code=").last! // 5.加载accessToken loadAccessToken(code) return false } } // MARK:- 请求数据 extension OAuthViewController { /// 加载AccessToken fileprivate func loadAccessToken(_ code : String) { NetworkTools.shareInstance.loadAccessToken(code) { (result, error) -> () in // 1.错误校验 if error != nil { myLog(error) return } // 2.拿到结果 guard let accountDict = result else { myLog("没有获取授权后的数据") return } // 3.将字典转成模型对象 let account = UserAccount(dict: accountDict) // 4.请求用户信息 self.loadUserInfo(account) } } /// 请求用户信息 fileprivate func loadUserInfo(_ account : UserAccount) { // 1.获取AccessToken guard let accessToken = account.access_token else { return } // 2.获取uid guard let uid = account.uid else { return } // 3.发送网络请求 NetworkTools.shareInstance.loadUserInfo(accessToken, uid: uid) { (result, error) -> () in // 1.错误校验 if error != nil { myLog(error) return } // 2.拿到用户信息的结果 guard let userInfoDict = result else { return } // 3.从字典中取出昵称和用户头像地址 account.screen_name = userInfoDict["screen_name"] as? String account.avatar_large = userInfoDict["avatar_large"] as? String // 4.将account对象保存 NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareIntance.accountPath) // 5.将account对象设置到单例对象中 UserAccountViewModel.shareIntance.account = account // 6.退出当前控制器 self.dismiss(animated: true, completion: { () -> Void in NotificationCenter.default.post(name: Notification.Name(rawValue: SLRootViewControllerChange), object: self, userInfo: ["message": true]) }) } } }
27.070352
155
0.560052
22634e4e28d9b3189ee1a8c183d3b814da125911
1,131
// // UITextFieldStyleExtension+Tests.swift // MyCoreUIFrameworkTests_iOS // // Created by Tom Baranes on 26/04/2020. // import UIKit import XCTest @testable import MyCoreUIFramework final class UITextFieldStyleTests: XCTestCase { // MARK: Properties private var textFieldStyles: [TextFieldStyle] { TextFieldStyle.allCases } private lazy var textField: UITextField = { let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 20)) textField.text = "test" return textField }() // MARK: Life Cycle override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } } // MARK: - Tests Style extension UITextFieldStyleTests { func testTextFieldStyle_beforeSettingIt() { XCTAssertNil(textField.style, "textField style must be nil per default") } func testTextFieldStyles() { TextFieldStyle.allCases.forEach { textField.style = $0 XCTAssertNotNil(textField.style) XCTAssertEqual(textField.textColor, $0.textColor) } } }
20.563636
86
0.647215
6a5c3c5c1aea005d42b6f2931df4fb7ea1af3b49
891
// // PreworkTests.swift // PreworkTests // // Created by Nourhan on 22/03/2021. // import XCTest @testable import Prework class PreworkTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.205882
111
0.662177
ab4cc727f6d24de763a5b45221dff7d68f82d546
10,032
import RxSwift import HdWalletKit import HsToolKit import Foundation public class BinanceChainKit { private let disposeBag = DisposeBag() private let balanceManager: BalanceManager private let transactionManager: TransactionManager private let reachabilityManager: ReachabilityManager private let segWitHelper: SegWitBech32 private let networkType: NetworkType private let logger: Logger? public let account: String private let lastBlockHeightSubject = PublishSubject<Int>() private let syncStateSubject = PublishSubject<SyncState>() private var assets = [Asset]() public var syncState: SyncState = .notSynced(error: BinanceChainKit.SyncError.notStarted) { didSet { syncStateSubject.onNext(syncState) } } public var lastBlockHeight: Int? { didSet { if let lastBlockHeight = lastBlockHeight { lastBlockHeightSubject.onNext(lastBlockHeight) } } } public var binanceBalance: Decimal { balanceManager.balance(symbol: "BNB")?.amount ?? 0 } init(account: String, balanceManager: BalanceManager, transactionManager: TransactionManager, reachabilityManager: ReachabilityManager, segWitHelper: SegWitBech32, networkType: NetworkType, logger: Logger? = nil) { self.account = account self.balanceManager = balanceManager self.transactionManager = transactionManager self.reachabilityManager = reachabilityManager self.segWitHelper = segWitHelper self.networkType = networkType self.logger = logger lastBlockHeight = balanceManager.latestBlock?.height reachabilityManager.reachabilityObservable .observeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) .subscribe(onNext: { [weak self] _ in self?.refresh() }) .disposed(by: disposeBag) } private func asset(symbol: String) -> Asset? { assets.first { $0.symbol == symbol } } } // Public API Extension extension BinanceChainKit { public func register(symbol: String) -> Asset { let balance = balanceManager.balance(symbol: symbol)?.amount ?? 0 let asset = Asset(symbol: symbol, balance: balance) assets.append(asset) return asset } public func unregister(asset: Asset) { assets.removeAll { $0 == asset } } public func refresh() { guard reachabilityManager.isReachable else { syncState = .notSynced(error: ReachabilityManager.ReachabilityError.notReachable) return } guard syncState != .syncing else { logger?.debug("Already syncing balances") return } logger?.debug("Syncing") syncState = .syncing balanceManager.sync(account: account) transactionManager.sync(account: account) } public var lastBlockHeightObservable: Observable<Int> { lastBlockHeightSubject.asObservable() } public var syncStateObservable: Observable<SyncState> { syncStateSubject.asObservable() } public func validate(address: String) throws { try _ = segWitHelper.decode(addr: address) } public func transactionsSingle(symbol: String, fromTransactionHash: String? = nil, limit: Int? = nil) -> Single<[TransactionInfo]> { transactionManager.transactionsSingle(symbol: symbol, fromTransactionHash: fromTransactionHash, limit: limit).map { $0.map { transaction in TransactionInfo(transaction: transaction) } } } public func transaction(symbol: String, hash: String) -> TransactionInfo? { transactionManager.transaction(symbol: symbol, hash: hash).map { TransactionInfo(transaction: $0) } } public func sendSingle(symbol: String, to: String, amount: Decimal, memo: String) -> Single<String> { logger?.debug("Sending \(amount) \(symbol) to \(to)") return transactionManager.sendSingle(account: account, symbol: symbol, to: to, amount: amount, memo: memo) .do(onSuccess: { [weak self] hash in guard let kit = self else { return } kit.transactionManager.blockHeightSingle(forTransaction: hash).subscribe( onSuccess: { blockHeight in kit.refresh() }, onError: { error in kit.logger?.error("Transaction send error: \(error)") }) .disposed(by: kit.disposeBag) }) } public var statusInfo: [(String, Any)] { [ ("Synced Until", balanceManager.latestBlock?.time ?? "N/A"), ("Last Block Height", balanceManager.latestBlock?.height ?? "N/A"), ("Sync State", syncState.description), ("RPC Host", networkType.endpoint), ] } } extension BinanceChainKit: IBalanceManagerDelegate { func didSync(balances: [Balance], latestBlockHeight: Int) { for balance in balances { asset(symbol: balance.symbol)?.balance = balance.amount } lastBlockHeight = latestBlockHeight syncState = .synced } func didFailToSync(error: Error) { syncState = .notSynced(error: error) } } extension BinanceChainKit: ITransactionManagerDelegate { func didSync(transactions: [Transaction]) { let transactionsMap = Dictionary(grouping: transactions, by: { $0.symbol }) for (symbol, transactions) in transactionsMap { asset(symbol: symbol)?.transactionsSubject.onNext(transactions.map { TransactionInfo(transaction: $0) }) } } } extension BinanceChainKit { public static func instance(words: [String], networkType: NetworkType = .mainNet, walletId: String, minLogLevel: Logger.Level = .error) throws -> BinanceChainKit { let logger = Logger(minLogLevel: minLogLevel) let uniqueId = "\(walletId)-\(networkType)" let storage: IStorage = try Storage(databaseDirectoryUrl: dataDirectoryUrl(), databaseFileName: "binance-chain-\(uniqueId)") let hdWallet = HDWallet(seed: Mnemonic.seed(mnemonic: words), coinType: 714, xPrivKey: 0, xPubKey: 0) let segWitHelper = SegWitBech32(hrp: networkType.addressPrefix) let wallet = try Wallet(hdWallet: hdWallet, segWitHelper: segWitHelper) let apiProvider = BinanceChainApiProvider(networkManager: NetworkManager(logger: logger), endpoint: networkType.endpoint) let accountSyncer = AccountSyncer(apiProvider: apiProvider, logger: logger) let balanceManager = BalanceManager(storage: storage, accountSyncer: accountSyncer, logger: logger) let transactionManager = TransactionManager(storage: storage, wallet: wallet, apiProvider: apiProvider, accountSyncer: accountSyncer, logger: logger) let reachabilityManager = ReachabilityManager() let binanceChainKit = BinanceChainKit(account: wallet.address, balanceManager: balanceManager, transactionManager: transactionManager, reachabilityManager: reachabilityManager, segWitHelper: segWitHelper, networkType: networkType, logger: logger) balanceManager.delegate = binanceChainKit transactionManager.delegate = binanceChainKit return binanceChainKit } public static func clear(exceptFor excludedFiles: [String]) throws { let fileManager = FileManager.default let fileUrls = try fileManager.contentsOfDirectory(at: dataDirectoryUrl(), includingPropertiesForKeys: nil) for filename in fileUrls { if !excludedFiles.contains(where: { filename.lastPathComponent.contains($0) }) { try fileManager.removeItem(at: filename) } } } private static func dataDirectoryUrl() throws -> URL { let fileManager = FileManager.default let url = try fileManager .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("binance-chain-kit", isDirectory: true) try fileManager.createDirectory(at: url, withIntermediateDirectories: true) return url } } extension BinanceChainKit { public enum SyncState: Equatable, CustomStringConvertible { case synced case syncing case notSynced(error: Error) public static func ==(lhs: SyncState, rhs: SyncState) -> Bool { switch (lhs, rhs) { case (.synced, .synced): return true case (.syncing, .syncing): return true case (.notSynced(let lhsError), .notSynced(let rhsError)): return "\(lhsError)" == "\(rhsError)" default: return false } } public var description: String { switch self { case .synced: return "synced" case .syncing: return "syncing" case .notSynced(let error): return "not synced: \(error)" } } } public enum NetworkType { case mainNet case testNet var addressPrefix: String { switch self { case .mainNet: return "bnb" case .testNet: return "tbnb" } } var endpoint: String { switch self { case .mainNet: return "https://dex.binance.org" case .testNet: return "https://testnet-dex.binance.org" } } } public enum ApiError: Error { case noTransactionReturned case wrongTransaction } public enum SyncError: Error { case notStarted } public enum CoderError: Error { case bitsConversionFailed case hrpMismatch(String, String) case checksumSizeTooLow case dataSizeMismatch(Int) case encodingCheckFailed } }
33.891892
254
0.638955
2fa10eff64943f46081c5f664c96376e26d99b9e
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import b}class B<T where B:a{func a{}}func b{func b:y
37.166667
87
0.753363
db28c00921628974a37cd7877d41eaf576de82c5
677
// // ViewController.swift // NxEnabledExample // // Created by Nikita Ermolenko on 03/10/2017. // Copyright © 2017 Nikita Ermolenko. All rights reserved. // import UIKit import NxEnabled class ViewController: UIViewController { @IBOutlet weak var testTextField: UITextField! @IBOutlet weak var testTextView: UITextView! @IBOutlet weak var testButton: UIButton! deinit { testButton.clearBag() } override func viewDidLoad() { super.viewDidLoad() testButton.isEnabled(by: testTextField, testTextView) { (value1, value2) -> Bool in return value1.count > 5 && value2.count > 5 } } }
22.566667
91
0.651403
23354f80065f9b4a4f5bf3c677c6ba5790ef88c3
1,798
// // ProfileView.swift // Paradise Scrap // // Created by Jordain Gijsbertha on 02/12/2020. // import SwiftUI struct ProfileView: View { @State var showAlert = false var body: some View { List{ Section(header: Text("About")) { if let user = FirebaseService.shared.authenticationState { VStack(alignment: .leading, spacing: 10){ Text("User").font(.caption).foregroundColor(.secondary).padding(.top) Text("\(user.name)").font(.subheadline).fontWeight(.bold) Text("Email").font(.caption).foregroundColor(.secondary).padding(.top) Text("\(user.email)").font(.subheadline).fontWeight(.bold).padding(.bottom) } } } Section(header: Text("")) { Button(action: {showAlert = true }, label: { Text("Sign out").foregroundColor(.red).fontWeight(.semibold) }).alert(isPresented: $showAlert) { () -> Alert in let primaryButton = Alert.Button.destructive(Text("Cancel")) { } let secondaryButton = Alert.Button.default(Text("Yes")) { FirebaseService.shared.clearAllSessionData() } return Alert(title: Text("Are your sure you want to log out?"), message: Text(""), primaryButton: primaryButton, secondaryButton: secondaryButton) } } }.listStyle(InsetGroupedListStyle()).navigationTitle("Profile") } } struct ProfileView_Previews: PreviewProvider { static var previews: some View { ProfileView() } }
35.254902
166
0.525028
f758c7a6f0a1e24b9401887c357643d47e8cb169
4,981
// // Multicast.swift // PublisherKit // // Created by Raghav Ahuja on 11/03/20. // extension Publishers { /// A publisher that uses a subject to deliver elements to multiple subscribers. final public class Multicast<Upstream: Publisher, SubjectType: Subject>: ConnectablePublisher where Upstream.Output == SubjectType.Output, Upstream.Failure == SubjectType.Failure { public typealias Output = Upstream.Output public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. final public let upstream: Upstream /// A closure to create a new Subject each time a subscriber attaches to the multicast publisher. final public let createSubject: () -> SubjectType private var _subject: SubjectType? private var subject: SubjectType { lock.lock() if let subject = _subject { return subject } let subject = createSubject() _subject = subject lock.unlock() return subject } private let lock = Lock() /// Creates a multicast publisher that applies a closure to create a subject that delivers elements to subscribers. /// - Parameter upstream: The publisher from which this publisher receives elements. /// - Parameter createSubject: A closure to create a new Subject each time a subscriber attaches to the multicast publisher. public init(upstream: Upstream, createSubject: @escaping () -> SubjectType) { self.upstream = upstream self.createSubject = createSubject } public func receive<S: Subscriber>(subscriber: S) where Output == S.Input, Failure == S.Failure { subject.subscribe(Inner(downstream: subscriber, upstream: upstream)) } final public func connect() -> Cancellable { upstream.subscribe(subject) } } } extension Publishers.Multicast { // MARK: MULTICAST SINK private final class Inner<Downstream: Subscriber>: Subscriber, Subscription, CustomStringConvertible, CustomPlaygroundDisplayConvertible, CustomReflectable where Output == Downstream.Input, Failure == Downstream.Failure { typealias Input = Upstream.Output typealias Failure = Upstream.Failure private enum SubscriptionStatus { case awaiting(upstream: Upstream, downstream: Downstream) case subscribed(upstream: Upstream, downstream: Downstream, subscription: Subscription) case terminated } private var status: SubscriptionStatus private let lock = Lock() init(downstream: Downstream, upstream: Upstream) { status = .awaiting(upstream: upstream, downstream: downstream) } func receive(subscription: Subscription) { lock.lock() guard case .awaiting(let upstream, let downstream) = status else { lock.unlock(); return } status = .subscribed(upstream: upstream, downstream: downstream, subscription: subscription) lock.unlock() downstream.receive(subscription: self) } func receive(_ input: Input) -> Subscribers.Demand { lock.lock() guard case .subscribed(_, let downstream, let subscription) = status else { lock.unlock(); return .none } lock.unlock() let newDemand = downstream.receive(input) if newDemand > 0 { subscription.request(newDemand) } return newDemand } func receive(completion: Subscribers.Completion<Failure>) { lock.lock() guard case .subscribed(_, let downstream, _) = status else { lock.unlock(); return } status = .terminated lock.unlock() downstream.receive(completion: completion) } func request(_ demand: Subscribers.Demand) { lock.lock() guard case .subscribed(_, _, let subscription) = status else { lock.unlock(); return } lock.unlock() subscription.request(demand) } func cancel() { lock.lock() guard case .subscribed(_, _, let subscription) = status else { lock.unlock(); return } status = .terminated lock.unlock() subscription.cancel() } var description: String { "Multicast" } var playgroundDescription: Any { description } var customMirror: Mirror { Mirror(self, children: []) } } }
35.077465
225
0.579201
5d52a59e37f77964880341d9b848e63f2d8af105
4,735
// // Copyright © 2020 Essential Developer. All rights reserved. // import XCTest import FeedAPIChallenge class LoadFeedFromRemoteUseCaseTests: XCTestCase { // *********************** // // Follow the TDD process: // // 1. Uncomment and run one test at a time (run tests with CMD+U). // 2. Do the minimum to make the test pass and commit. // 3. Refactor if needed and commit again. // // Repeat this process until all tests are passing. // // *********************** func test_init_doesNotRequestDataFromURL() { let (_, client) = makeSUT() XCTAssertTrue(client.requestedURLs.isEmpty) } // func test_loadTwice_requestsDataFromURLTwice() { // let url = URL(string: "https://a-given-url.com")! // let (sut, client) = makeSUT(url: url) // // sut.load { _ in } // sut.load { _ in } // // XCTAssertEqual(client.requestedURLs, [url, url]) // } // // func test_load_deliversConnectivityErrorOnClientError() { // let (sut, client) = makeSUT() // // expect(sut, toCompleteWith: .failure(.connectivity), when: { // let clientError = NSError(domain: "Test", code: 0) // client.complete(with: clientError) // }) // } // // func test_load_deliversInvalidDataErrorOnNon200HTTPResponse() { // let (sut, client) = makeSUT() // // let samples = [199, 201, 300, 400, 500] // // samples.enumerated().forEach { index, code in // expect(sut, toCompleteWith: .failure(.invalidData), when: { // let json = makeItemsJSON([]) // client.complete(withStatusCode: code, data: json, at: index) // }) // } // } // // func test_load_deliversInvalidDataErrorOn200HTTPResponseWithInvalidJSON() { // let (sut, client) = makeSUT() // // expect(sut, toCompleteWith: .failure(.invalidData), when: { // let invalidJSON = Data("invalid json".utf8) // client.complete(withStatusCode: 200, data: invalidJSON) // }) // } // // func test_load_deliversInvalidDataErrorOn200HTTPResponseWithPartiallyValidJSONItems() { // let (sut, client) = makeSUT() // // let validItem = makeItem( // id: UUID(), // imageURL: URL(string: "http://another-url.com")! // ).json // // let invalidItem = ["invalid": "item"] // // let items = [validItem, invalidItem] // // expect(sut, toCompleteWith: .failure(.invalidData), when: { // let json = makeItemsJSON(items) // client.complete(withStatusCode: 200, data: json) // }) // } // // func test_load_deliversSuccessWithNoItemsOn200HTTPResponseWithEmptyJSONList() { // let (sut, client) = makeSUT() // // expect(sut, toCompleteWith: .success([]), when: { // let emptyListJSON = makeItemsJSON([]) // client.complete(withStatusCode: 200, data: emptyListJSON) // }) // } // // func test_load_deliversSuccessWithItemsOn200HTTPResponseWithJSONItems() { // let (sut, client) = makeSUT() // // let item1 = makeItem( // id: UUID(), // imageURL: URL(string: "http://a-url.com")!) // // let item2 = makeItem( // id: UUID(), // description: "a description", // location: "a location", // imageURL: URL(string: "http://another-url.com")!) // // let items = [item1.model, item2.model] // // expect(sut, toCompleteWith: .success(items), when: { // let json = makeItemsJSON([item1.json, item2.json]) // client.complete(withStatusCode: 200, data: json) // }) // } // // func test_load_doesNotDeliverResultAfterSUTInstanceHasBeenDeallocated() { // let url = URL(string: "http://any-url.com")! // let client = HTTPClientSpy() // var sut: RemoteFeedLoader? = RemoteFeedLoader(url: url, client: client) // // var capturedResults = [RemoteFeedLoader.Result]() // sut?.load { capturedResults.append($0) } // // sut = nil // client.complete(withStatusCode: 200, data: makeItemsJSON([])) // // XCTAssertTrue(capturedResults.isEmpty) // } // MARK: - Helpers private func makeSUT(url: URL = URL(string: "https://a-url.com")!, file: StaticString = #filePath, line: UInt = #line) -> (sut: RemoteFeedLoader, client: HTTPClientSpy) { let client = HTTPClientSpy() let sut = RemoteFeedLoader(url: url, client: client) trackForMemoryLeaks(sut, file: file, line: line) trackForMemoryLeaks(client, file: file, line: line) return (sut, client) } private func makeItem(id: UUID, description: String? = nil, location: String? = nil, imageURL: URL) -> (model: FeedImage, json: [String: Any]) { let item = FeedImage(id: id, description: description, location: location, url: imageURL) let json = [ "image_id": id.uuidString, "image_desc": description, "image_loc": location, "image_url": imageURL.absoluteString ].compactMapValues { $0 } return (item, json) } private func makeItemsJSON(_ items: [[String: Any]]) -> Data { let json = ["items": items] return try! JSONSerialization.data(withJSONObject: json) } }
29.59375
171
0.661035
fb05e84832cd79c14c5aa2ccd5d0c929ec01002c
2,371
// // Project Secured MQTT Publisher // Copyright 2021 Tracmo, Inc. ("Tracmo"). // Open Source Project Licensed under MIT License. // Please refer to https://github.com/tracmo/open-tls-iot-client // for the license and the contributors information. // import Foundation import Combine import CryptoSwift enum AES128ECBTextEncrypter { enum EncrypterError: Error { case keyFormatIncorrect } static func encryptedTimestampInHex(keyInHex: String) -> AnyPublisher<String, Error> { // byte 4~7 let timestampToSeconds = Int(Date().timeIntervalSince1970) let littleEndianTimestampByteValues = [0, 8, 16, 24].map { UInt8((timestampToSeconds >> $0) & 0xFF) } // byte 0~3 & byte 8~14 -> total 11 bytes let randomByteValues: [UInt8] = (0..<11).map { _ in UInt8((0..<256).randomElement()!) } // byte 0~3: random // byte 4~7: little endian timestamp to seconds // byte 8~14: random let byte0To14Values = randomByteValues.inserted(contentsOf: littleEndianTimestampByteValues, at: 4) // byte 15: (sum of byte 0~14) & 0xFF let byte0To14ValuesTotal: Int = byte0To14Values.reduce(0) { $0 + Int($1) } let byte15Value = UInt8(byte0To14ValuesTotal & 0xFF) let textToEncryptInHex = byte0To14Values.appended(byte15Value) .map { String(format: "%02x", $0) } .joined() return encryptedTextInHex(textInHex: textToEncryptInHex, keyInHex: keyInHex) } static private func encryptedTextInHex(textInHex: String, keyInHex: String) -> AnyPublisher<String, Error> { Future<String, Error> { promise in do { let aes = try AES(key: .init(hex: keyInHex), blockMode: ECB(), padding: .noPadding) let encryptedText = try aes.encrypt(.init(hex: textInHex)) let encryptedTextInHex = encryptedText.toHexString() promise(.success(encryptedTextInHex)) } catch AES.Error.invalidKeySize { promise(.failure(EncrypterError.keyFormatIncorrect)) } catch { promise(.failure(error)) } } .eraseToAnyPublisher() } }
37.634921
112
0.591312
619f45e9ec687c0a8f60659fc9b5ad4518d25d9c
2,489
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: protoex.fbe // Version: 1.4.0.0 import ChronoxorFbe // Fast Binary Encoding OrderMessage model public class OrderMessageModel: Model { public let model: FieldModelOrderMessage public override init(buffer: Buffer = Buffer()) { model = FieldModelOrderMessage(buffer: buffer, offset: 4) super.init(buffer: buffer) } // Model size public func fbeSize() -> Int { model.fbeSize + model.fbeExtra } // Model type public var fbeType: Int = fbeTypeConst static let fbeTypeConst: Int = FieldModelOrderMessage.fbeTypeConst // Check if the struct value is valid public func verify() -> Bool { if buffer.offset + model.fbeOffset - 4 > buffer.size { return false } let fbeFullSize = Int(readUInt32(offset: model.fbeOffset - 4)) if fbeFullSize < model.fbeSize { return false } return model.verify() } // Create a new model (begin phase) public func createBegin() throws -> Int { return try buffer.allocate(size: 4 + model.fbeSize) } // Create a new model (end phase) public func createEnd(fbeBegin: Int) -> Int { let fbeEnd = buffer.size let fbeFullSize = fbeEnd - fbeBegin write(offset: model.fbeOffset - 4, value: UInt32(fbeFullSize)) return fbeFullSize } // Serialize the struct value public func serialize(value: OrderMessage) throws -> Int { let fbeBegin = try createBegin() try model.set(value: value) return createEnd(fbeBegin: fbeBegin) } // Deserialize the struct value public func deserialize() -> OrderMessage { var value = OrderMessage(); _ = deserialize(value: &value); return value } public func deserialize(value: inout OrderMessage) -> Int { if buffer.offset + model.fbeOffset - 4 > buffer.size { value = OrderMessage() return 0 } let fbeFullSize = Int(readUInt32(offset: model.fbeOffset - 4)) if fbeFullSize < model.fbeSize { assertionFailure("Model is broken!") value = OrderMessage() return 0 } value = model.get(fbeValue: &value) return fbeFullSize } // Move to the next struct value public func next(prev: Int) { model.fbeShift(size: prev) } }
30.728395
122
0.631177
2fc9ad496940d0a1499ad1d4ab6f43de8ab69e6c
529
// // NewsCell.swift // MyUnimol // // Created by Giovanni Grano on 19/03/16. // Copyright © 2016 Giovanni Grano. All rights reserved. // import UIKit class NewsCell: UITableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var body: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
18.892857
63
0.642722
c130844a3bf8a430f862293fc8c5dc36f7307cc3
2,186
// // CachedRemoteResource.swift // Pickery // // Created by Okan Arikan on 7/4/16. // // import Foundation import RealmSwift /// The local cached representation for a remote asset class CachedRemoteResource: CachedModel { /// The signature of the parent asset that this resurce belongs to @objc dynamic var parentSignature : String = "" @objc dynamic var fileName : String? @objc dynamic var type : String = "" @objc dynamic var mimeType : String = "" @objc dynamic var pixelWidth = Int(0) @objc dynamic var pixelHeight = Int(0) @objc dynamic var durationSeconds = Double(0) @objc dynamic var numBytes = Int(0) @objc dynamic var placeholder : Data? /// The name of the key we're storing this resource in //var key : String { return signature + "_" + fileName } /// Parse the meta data and create the asset object convenience init(parentSignature: String, data: [ String : Any ]) throws { try self.init(data: data) self.parentSignature = parentSignature self.fileName = data[MetaInfoKey.fileName.rawValue] as? String self.type = try data.metaValue(key: MetaInfoKey.entryType.rawValue) self.mimeType = try data.metaValue(key: MetaInfoKey.mimeType.rawValue) self.numBytes = try data.metaValue(key: MetaInfoKey.numBytes.rawValue) self.pixelWidth = data[MetaInfoKey.pixelWidth.rawValue] as? Int ?? 0 self.pixelHeight = data[MetaInfoKey.pixelHeight.rawValue] as? Int ?? 0 self.durationSeconds = data[MetaInfoKey.durationSeconds.rawValue] as? Double ?? 0 // Do we have a placeholder? if let placeholder = data[MetaInfoKey.placeholder.rawValue] as? String { self.placeholder = Data(base64Encoded: placeholder) } } /// The indexed properties override class func indexedProperties() -> [String] { return super.indexedProperties() + [ "parentSignature" ] } }
41.245283
94
0.606587
dd9a19dd6f61afe5c27c5b3d0f64d758aabb8040
2,496
// // CancellationTest.swift // ArchitectureTests // // Created by Jackson Utsch on 7/15/21. // import XCTest import Combine import CombineSchedulers @testable import Architecture final class CancellationTest: XCTestCase { struct CancelToken: Hashable {} var cancellables: Set<AnyCancellable> = [] func testCancellation() { var values: [Int] = [] let subject = PassthroughSubject<Int, Never>() let effect = subject .eraseToAnyPublisher() .cancellable(id: CancelToken()) effect .sink { values.append($0) } .store(in: &self.cancellables) XCTAssertEqual(values, []) subject.send(1) XCTAssertEqual(values, [1]) subject.send(2) XCTAssertEqual(values, [1, 2]) AnyPublisher<Void, Never> .cancel(id: CancelToken()) .sink { _ in } .store(in: &cancellables) subject.send(3) XCTAssertEqual(values, [1, 2]) } func testCancellationFromStore() { let scheduler = DispatchQueue.test struct CanelID: Hashable { } enum LocalAction { case delayInc case inc case cancel } let store = Store<Int, LocalAction, AnySchedulerOf<DispatchQueue>>( initialState: 0, reducer: { s, a, e in switch a { case .delayInc: return Just(LocalAction.inc) .eraseToAnyPublisher() .defered(for: 5.0, on: e) .cancellable(id: CanelID()) case .inc: s += 1 return .none case .cancel: return .cancel(id: CanelID()) } }, environment: scheduler.eraseToAnyScheduler() ) store.send(.delayInc) store.send(.cancel) scheduler.advance(by: 5.0) XCTAssertEqual(store.state, 0) } func testCancellationFromTestStore() { let sch = DispatchQueue.test struct CanelID: Hashable { } enum LocalAction { case delayInc case inc case cancel } let store = TestStore<Int, LocalAction, AnySchedulerOf<DispatchQueue>>( initialState: 0, reducer: { s, a, e in switch a { case .delayInc: return Just(LocalAction.inc) .eraseToAnyPublisher() .defered(for: 5.0, on: e) .cancellable(id: CanelID()) case .inc: s += 1 return .none case .cancel: return .cancel(id: CanelID()) } }, environment: sch.eraseToAnyScheduler() ) store.assert(.inc, mutates: { $0 += 1 }) store.assert(.delayInc) store.assert(.cancel) sch.advance(by: 5.0) XCTAssertEqual(store.state, 1) store.assert(.delayInc) sch.advance(by: 5.0) store.assertReceived(.inc, mutated: { $0 += 1 }) XCTAssertEqual(store.state, 2) } }
22.088496
73
0.652644
e463f678c983f490e1f8bb90b7a01598a8e9c73b
2,006
import UIKit import MapboxMaps @objc(CameraAnimatorsExample) public class CameraAnimatorsExample: UIViewController, ExampleProtocol { internal var mapView: MapView! // Store the CameraAnimators so that the do not fall out of scope. lazy var zoomAnimator: CameraAnimator = { let animator = mapView.cameraManager.makeCameraAnimator(duration: 4, curve: .easeInOut) { [unowned self] in self.mapView.zoom = 14 } animator.addCompletion { [unowned self] (_) in self.pitchAnimator.startAnimation() } return animator }() lazy var pitchAnimator: CameraAnimator = { let animator = mapView.cameraManager.makeCameraAnimator(duration: 2, curve: .easeInOut) { [unowned self] in self.mapView.pitch = 55 } animator.addCompletion { [unowned self] (_) in self.bearingAnimator.startAnimation() } return animator }() lazy var bearingAnimator: CameraAnimator = { let animator = mapView.cameraManager.makeCameraAnimator(duration: 4, curve: .easeInOut) { [unowned self] in self.mapView.bearing = -45 } animator.addCompletion { (_) in print("All animations complete!") } return animator }() override public func viewDidLoad() { super.viewDidLoad() mapView = MapView(frame: view.bounds) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) // Center the map over New York City. let newYork = CLLocationCoordinate2D(latitude: 40.7128, longitude: -74.0060) mapView.cameraManager.setCamera(to: CameraOptions(center: newYork)) // Allows the delegate to receive information about map events. mapView.on(.mapLoaded) { [weak self] _ in guard let self = self else { return } self.zoomAnimator.startAnimation(afterDelay: 1) self.finish() } } }
30.393939
115
0.637587
eb08c1064f279b908703f39b2f8b92153be41b8d
1,111
// // BpiParser.swift // CoinDeskProvider // // Created by Vladimir Abramichev on 22/07/2018. // Copyright © 2018 Vladimir Abramichev. All rights reserved. // import Foundation import Common class BpiParser { func parse(data: Data) -> Response<PriceIndex> { guard let raw = try? JSONDecoder().decode(BipServerResponse.self, from: data) else { return .failure(CoilDeskProviderError.parsingError) } guard let timestamp = Date(isoString: raw.time.updatedISO) else { return .failure(CoilDeskProviderError.incorrectData) } let collection = raw.bpi.values.map({ (item) -> PriceIndex in let value = item.rate.replacingOccurrences(of: ",", with: "") return PriceIndex(code: item.code, rate: value) }) let result = BpiResponse(timestamp: timestamp, bpi: collection) return .success(result: result) } } extension PriceIndex { init(code: String, rate: String) { self.code = code self.rate = rate } }
26.452381
83
0.59946
bf839513209de1aba29e1bae6e009bc6140406ac
438
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class B<T where B:a{let a{class d<f{let v:T.n
43.8
78
0.744292
dd24e1e78975f515496bd9d4fb7331c1a6f6b28c
649
// // Hike.swift // Landmarks // // Created by Samuel Besemun Adjei on 28/01/2021. // import Foundation struct Hike: Codable, Hashable, Identifiable { var id: Int var name: String var distance: Double var difficulty: Int var observations: [Observation] static var formatter = LengthFormatter() var distanceText: String { return Hike.formatter .string(fromValue: distance, unit: .kilometer) } struct Observation: Codable, Hashable { var distanceFromStart: Double var elevation: Range<Double> var pace: Range<Double> var heartRate: Range<Double> } }
20.28125
58
0.645609
285201d986b5e5d4a983ec7abb9012f4973bde2d
2,998
// // PacketTunnelProvider.swift // TunnelExtension // // Created by Roopesh Chander S on 27/12/21. // import NetworkExtension import WireGuardKit enum PacketTunnelProviderError: String, Error { case invalidProtocolConfiguration case cantParseWgQuickConfig } class PacketTunnelProvider: NEPacketTunnelProvider { private lazy var adapter: WireGuardAdapter = { return WireGuardAdapter(with: self) { [weak self] _, message in self?.log(message) } }() func log(_ message: String) { NSLog("WireGuard Tunnel: %@\n", message) } override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { log("Starting tunnel") guard let protocolConfiguration = self.protocolConfiguration as? NETunnelProviderProtocol, let providerConfiguration = protocolConfiguration.providerConfiguration, let wgQuickConfig = providerConfiguration["wgQuickConfig"] as? String else { log("Invalid provider configuration") completionHandler(PacketTunnelProviderError.invalidProtocolConfiguration) return } guard let tunnelConfiguration = try? TunnelConfiguration(fromWgQuickConfig: wgQuickConfig) else { log("wg-quick config not parseable") completionHandler(PacketTunnelProviderError.cantParseWgQuickConfig) return } adapter.start(tunnelConfiguration: tunnelConfiguration) { [weak self] adapterError in guard let self = self else { return } if let adapterError = adapterError { self.log("WireGuard adapter error: \(adapterError.localizedDescription)") } else { let interfaceName = self.adapter.interfaceName ?? "unknown" self.log("Tunnel interface is \(interfaceName)") } completionHandler(adapterError) } } override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { log("Stopping tunnel") adapter.stop { [weak self] error in guard let self = self else { return } if let error = error { self.log("Failed to stop WireGuard adapter: \(error.localizedDescription)") } completionHandler() #if os(macOS) // HACK: We have to kill the tunnel process ourselves because of a macOS bug exit(0) #endif } } override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) { // Add code here to handle the message. if let handler = completionHandler { handler(messageData) } } override func sleep(completionHandler: @escaping () -> Void) { // Add code here to get ready to sleep. completionHandler() } override func wake() { // Add code here to wake up. } }
34.068182
109
0.630754
1e10f3e931a0e88ca3599db5e551fab8fcc7466a
6,253
// // UIView+constraints.swift // HDAugmentedReality // // Created by Danijel Huis on 30/05/2019. // import UIKit extension UIView { internal func pinToSuperview(leading: CGFloat?, trailing: CGFloat?, top: CGFloat?, bottom: CGFloat?, width: CGFloat?, height: CGFloat? ) { let view = self guard let superview = view.superview else { return } if let leading = leading { view.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: leading).isActive = true } if let trailing = trailing { superview.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: trailing).isActive = true } if let top = top { view.topAnchor.constraint(equalTo: superview.topAnchor, constant: top).isActive = true } if let bottom = bottom { superview.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: bottom).isActive = true } if let width = width { view.widthAnchor.constraint(equalToConstant: width).isActive = true } if let height = height { view.heightAnchor.constraint(equalToConstant: height).isActive = true} } internal func pinToLayoutGuide(_ layoutGuide: UILayoutGuide, leading: CGFloat?, trailing: CGFloat?, top: CGFloat?, bottom: CGFloat?, width: CGFloat?, height: CGFloat? ) { let view = self if let leading = leading { view.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: leading).isActive = true } if let trailing = trailing { layoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: trailing).isActive = true } if let top = top { view.topAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: top).isActive = true } if let bottom = bottom { layoutGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: bottom).isActive = true } if let width = width { view.widthAnchor.constraint(equalToConstant: width).isActive = true } if let height = height { view.heightAnchor.constraint(equalToConstant: height).isActive = true} } /** Returns constraint with given attribute. Supported attributes: - .width - .height */ internal func findConstraint(attribute: NSLayoutConstraint.Attribute) -> NSLayoutConstraint? { if attribute == .height || attribute == .width { for constraint in self.constraints { let typeString = String(describing: type(of: constraint)) if typeString == "NSContentSizeLayoutConstraint" { continue } if constraint.firstItem === self, constraint.firstAttribute == attribute, constraint.secondAttribute == .notAnAttribute { return constraint } } } else { print("findConstraint called with unsupported attribute. Only .width and .height attributes are supported.") } return nil } } internal extension UIView { /** Loads view from nib. Type is inferred by return type. XIB: View must be instance of this class. Owner is not used. (e.g. like UITableViewCell) - Parameter nibName: Name of nib file, if nil it will be assumed same as type name. - Parameter tag: Tag of the view to load, if nil it is not used. - Parameter owner: Owner of xib. */ class func loadFromNib<T: UIView>(_ nibName: String?, tag: Int?, owner: Any?) -> T? { guard let nib = self.loadNibFromContainingBundle(nibName: nibName) else { return nil } let views = nib.instantiate(withOwner: owner, options: nil).compactMap { $0 as? UIView } let matchView = views.first(where: { ($0 is T) && (tag == nil || $0.tag == tag) }) as? T return matchView } /** Loads view from nib and adds it to self as subview. Also sets owner to self. XIB: View must be UIView (or subclass). Owner must be instance of this class. - Parameter nibName: Name of nib file, if nil it will be assumed same as type name. */ @objc func addSubviewFromNib(nibName: String? = nil) { let baseView = self if baseView.subviews.count == 0 { let view: UIView? = type(of: self).loadFromNib(nibName, tag: nil, owner: self) if let view = view { view.translatesAutoresizingMaskIntoConstraints = false baseView.addSubview(view) let leadingTrailing = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["view":view]) let topBottom = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["view":view]) baseView.addConstraints(leadingTrailing) baseView.addConstraints(topBottom) } } else { print("setupFromNib: Base view has subviews, aborting.") } } //========================================================================================================================================================== // MARK: Utility //========================================================================================================================================================== /** Assumed nibName as type name. */ @objc class var typeName: String { let name = "\(self)".components(separatedBy: ".").last ?? "" return name } /** Searches for bundle that contains this class and loads nib from it. */ @objc class func loadNibFromContainingBundle(nibName: String?) -> UINib? { let nibName = nibName ?? self.typeName let bundle = Bundle(for: self as AnyClass) guard let _ = bundle.path(forResource: nibName, ofType: "nib") else { return nil } let nib = UINib(nibName: nibName, bundle: bundle) return nib } }
43.124138
180
0.5842
2048690dcc21b3ce3e2d25e8d546485e82e0301b
757
// // Observer.swift // Patterns // // Created by 杨晴贺 on 2017/3/25. // Copyright © 2017年 Silence. All rights reserved. // import Foundation // 观察者 class Observer: Hashable { var name: String var sub: Subject var hashValue: Int { return "\(name)".hashValue } static func ==(l: Observer, r: Observer) -> Bool { return l.hashValue == r.hashValue } init(_ name: String, _ sub: Subject){ self.name = name self.sub = sub } func update() {} } // 看股票 class StockObserver: Observer { override func update() { print("\(name) 关闭股票,继续工作") } } // 看 NBA class NBAObserver: Observer { override func update() { print("\(name) 关闭 NBA,继续工作") } }
16.456522
54
0.560106
6271708d77fcd8d679005b48716afef29d70997f
572
// // Person.swift // Lookout // // Created by Chunkai Chan on 2016/9/26. // Copyright © 2016年 Chunkai Chan. All rights reserved. // import Foundation class Person { var name: String var phoneNumber: String var trackID: String var email: String var photo: NSData? init(name: String, phoneNumber: String, trackID: String, email: String, photo: NSData) { self.name = name self.phoneNumber = phoneNumber self.trackID = trackID self.email = email self.photo = photo } }
19.724138
92
0.59965
8fdd31be9e172f006e97d56d92467befa66a68e6
7,078
// // PopupDialogContainerView.swift // Pods // // Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk) // Author - Martin Wildfeuer (http://www.mwfire.de) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit /// The main view of the popup dialog final public class PopupDialogContainerView: UIView { // MARK: - Appearance /// The background color of the popup dialog override public dynamic var backgroundColor: UIColor? { get { return container.backgroundColor } set { container.backgroundColor = newValue } } /// The corner radius of the popup view @objc public dynamic var cornerRadius: Float { get { return Float(shadowContainer.layer.cornerRadius) } set { let radius = CGFloat(newValue) shadowContainer.layer.cornerRadius = radius container.layer.cornerRadius = radius } } /// Enable / disable shadow rendering @objc public dynamic var shadowEnabled: Bool { get { return shadowContainer.layer.shadowRadius > 0 } set { shadowContainer.layer.shadowRadius = newValue ? 5 : 0 } } /// The shadow color @objc public dynamic var shadowColor: UIColor? { get { guard let color = shadowContainer.layer.shadowColor else { return nil } return UIColor(cgColor: color) } set { shadowContainer.layer.shadowColor = newValue?.cgColor } } // MARK: - Views /// The shadow container is the basic view of the PopupDialog /// As it does not clip subviews, a shadow can be applied to it internal lazy var shadowContainer: UIView = { let shadowContainer = UIView(frame: .zero) shadowContainer.translatesAutoresizingMaskIntoConstraints = false shadowContainer.backgroundColor = UIColor.clear shadowContainer.layer.shadowColor = UIColor.black.cgColor shadowContainer.layer.shadowRadius = 5 shadowContainer.layer.shadowOpacity = 0.4 shadowContainer.layer.shadowOffset = CGSize(width: 0, height: 0) shadowContainer.layer.cornerRadius = 4 return shadowContainer }() /// The container view is a child of shadowContainer and contains /// all other views. It clips to bounds so cornerRadius can be set internal lazy var container: UIView = { let container = UIView(frame: .zero) container.translatesAutoresizingMaskIntoConstraints = false container.backgroundColor = UIColor.white container.clipsToBounds = true container.layer.cornerRadius = 4 return container }() // The container stack view for buttons internal lazy var buttonStackView: UIStackView = { let buttonStackView = UIStackView() buttonStackView.translatesAutoresizingMaskIntoConstraints = false buttonStackView.distribution = .fillEqually buttonStackView.spacing = 0 return buttonStackView }() // The main stack view, containing all relevant views internal lazy var stackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [self.buttonStackView]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 0 return stackView }() // The preferred width for iPads fileprivate let preferredWidth: CGFloat // MARK: - Constraints /// The center constraint of the shadow container internal var centerYConstraint: NSLayoutConstraint? // MARK: - Initializers internal init(frame: CGRect, preferredWidth: CGFloat) { self.preferredWidth = preferredWidth super.init(frame: frame) setupViews() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View setup internal func setupViews() { // Add views addSubview(shadowContainer) shadowContainer.addSubview(container) container.addSubview(stackView) // Layout views let views = ["shadowContainer": shadowContainer, "container": container, "stackView": stackView] var constraints = [NSLayoutConstraint]() // Shadow container constraints if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { let metrics = ["preferredWidth": preferredWidth] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=40)-[shadowContainer(==preferredWidth@900)]-(>=40)-|", options: [], metrics: metrics, views: views) } else { constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=10,==20@900)-[shadowContainer(<=340,>=300)]-(>=10,==20@900)-|", options: [], metrics: nil, views: views) } constraints += [NSLayoutConstraint(item: shadowContainer, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)] centerYConstraint = NSLayoutConstraint(item: shadowContainer, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) if let centerYConstraint = centerYConstraint { constraints.append(centerYConstraint) } // Container constraints constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[container]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[container]|", options: [], metrics: nil, views: views) // Main stack view constraints constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: [], metrics: nil, views: views) // Activate constraints NSLayoutConstraint.activate(constraints) } }
41.151163
188
0.681548
29d284b1f6b9ab511ac2b9e096d40261bfee363b
386
import Foundation import StoreKit final class MStoreKit:NSObject { weak var model:MStore? weak var request:SKProductsRequest? deinit { clean() } //MARK: internal func start() { SKPaymentQueue.default().add(self) } func clean() { SKPaymentQueue.default().remove(self) request?.cancel() } }
14.296296
45
0.567358
1816a30eec5f89e1cc2b639f0b9f868649feb8d4
3,958
// // KSChartValueView.swift // ZeroShare // // Created by saeipi on 2019/8/27. // Copyright © 2019 saeipi. All rights reserved. // import UIKit class KSChartValueView: KSBaseView { private var openLabel: UILabel! private var highLabel: UILabel! private var lowLabel: UILabel! private var closeLabel: UILabel! private var chgLabel: UILabel! private var dateLabel: UILabel! var dateFormart:String = "yyyy-MM-dd HH:mm:ss" override func configureDefaultValue() { self.backgroundColor = KS_Const_Color_Menu_Background } override func createChildViews() { openLabel = UILabel.init(textFont: KS_Const_Font_Normal_12, alignment: NSTextAlignment.left) highLabel = UILabel.init(textFont: KS_Const_Font_Normal_12, alignment: NSTextAlignment.left) lowLabel = UILabel.init(textFont: KS_Const_Font_Normal_12, alignment: NSTextAlignment.left) closeLabel = UILabel.init(textFont: KS_Const_Font_Normal_12, alignment: NSTextAlignment.left) chgLabel = UILabel.init(textFont: KS_Const_Font_Normal_12, alignment: NSTextAlignment.left) dateLabel = UILabel.init(textColor: KS_Const_Color_Chart_Ink, textFont: KS_Const_Font_Normal_12, alignment: NSTextAlignment.left) self.addSubview(openLabel) self.addSubview(highLabel) self.addSubview(lowLabel) self.addSubview(closeLabel) self.addSubview(chgLabel) self.addSubview(dateLabel) let margin:CGFloat = 8 let LS = (self.frame.width - margin * 4.0) / 3 let LH = 22 openLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(margin) make.width.equalTo(LS) make.height.equalTo(LH) make.bottom.equalTo(self.snp.centerY).offset(2) } closeLabel.snp.makeConstraints { (make) in make.left.equalTo(openLabel.snp.left) make.width.equalTo(LS) make.height.equalTo(LH) make.top.equalTo(self.snp.centerY).offset(-2) } highLabel.snp.makeConstraints { (make) in make.left.equalTo(openLabel.snp.right).offset(margin) make.width.equalTo(LS) make.height.equalTo(LH) make.top.equalTo(openLabel.snp.top) } chgLabel.snp.makeConstraints { (make) in make.left.equalTo(highLabel.snp.left) make.width.equalTo(LS) make.height.equalTo(LH) make.top.equalTo(closeLabel.snp.top) } lowLabel.snp.makeConstraints { (make) in make.left.equalTo(highLabel.snp.right).offset(margin) make.width.equalTo(LS) make.height.equalTo(LH) make.top.equalTo(openLabel.snp.top) } dateLabel.snp.makeConstraints { (make) in make.left.equalTo(lowLabel.snp.left) make.width.equalTo(LS) make.height.equalTo(LH) make.top.equalTo(closeLabel.snp.top) } } let openTitle = String.ks_localizde("ks_app_global_text_open") + ": " let closeTitle = String.ks_localizde("ks_app_global_text_close") + ": " let highTitle = String.ks_localizde("ks_app_global_text_maxhigh") + ": " let lowTitle = String.ks_localizde("ks_app_global_text_maxlow") + ": " let changeTitle = String.ks_localizde("ks_app_global_text_chg") + ": " func update(value: KSChartItem) { self.showKit() value.setOpenValue(textLabel: openLabel,extra: openTitle) value.setCloseValue(textLabel: closeLabel,extra: closeTitle) value.setHighValue(textLabel: highLabel,extra: highTitle) value.setLowValue(textLabel: lowLabel,extra: lowTitle) value.setChangePercentValue(textLabel: chgLabel, extra: changeTitle) dateLabel.text = Date.ks_formatTimeStamp(timeStamp: value.time, format: dateFormart) } }
39.979798
138
0.65336
9b2e0128dbf2f7cef7729c5f0fbe5e661503201f
495
// // MMNavigationController.swift // YCNavigationBarSwiftDemo // // Created by xu.shuifeng on 2020/5/20. // Copyright © 2020 alexiscn. All rights reserved. // import UIKit import YCNavigationBarSwift class MMNavigationController: UINavigationController { } extension MMNavigationController { override var yc_enableYCNavigationBar: Bool { get { return true } set { super.yc_enableYCNavigationBar = newValue } } }
17.678571
54
0.658586
484264fdd7c0f33ecd7f7ba76d63398bc5be011a
1,711
import Foundation class StockHttpClient: HttpClient { let endpoint: String let urlSession: URLSession init(endpoint: String) { self.endpoint = endpoint let urlSessionConfig = URLSessionConfiguration.default urlSessionConfig.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData urlSession = URLSession(configuration: urlSessionConfig) } func get(url: String, handler: @escaping (String, Error?) -> Void) { print("[StockHttpClient] get: \(url)") let task = urlSession.dataTask( with: URL(string: "\(endpoint)\(url)")! ) {(data, response, error) in if let error = error { handler("", error) return } if let response = response as? HTTPURLResponse { if response.statusCode < 200 || response.statusCode >= 400 { handler("", HttpError(url: url, statusCode: response.statusCode)) return } } else { handler("", UnableToDecodeResponse()) return } guard let data = data, let dataString = String(data: data, encoding: .utf8) else { print("[StockHttpClient] unable to decode response") handler("", UnableToDecodeResponse()) return } handler(dataString, nil) } task.resume() } } class UnableToDecodeResponse: Error { } struct HttpError: Error { let url: String let statusCode: Int }
28.516667
85
0.519579
7af5da9eb5c6dee86d425df55e1a15d2d9cd2e7a
1,121
/* UIViewExtension.swift PopupDatePicker Created by DessLi on 2019/05/11. Copyright © 2019. All rights reserved. */ import UIKit extension UIView { func addLayout(attributes attr1s: [NSLayoutConstraint.Attribute], relatedBy relation: NSLayoutConstraint.Relation = .equal, toItem: Any?, multiplier: CGFloat = 1, constants: [CGFloat]) { if translatesAutoresizingMaskIntoConstraints == true { translatesAutoresizingMaskIntoConstraints = false } for (i,attr1) in attr1s.enumerated() { var attr2: NSLayoutConstraint.Attribute = attr1 var toItem = toItem if attr1 == .width || attr1 == .height { toItem = nil attr2 = .notAnAttribute } let constant = constants[i] let constraint = NSLayoutConstraint.init(item: self, attribute: attr1, relatedBy: relation, toItem: toItem, attribute: attr2, multiplier: 1, constant: constant) NSLayoutConstraint.activate([constraint]) } } }
33.969697
172
0.600357
6a413c6099783d9351fc764cc123b99d3dbda179
4,293
// // Plugin.swift // // // Created by Jonathan Gerber on 15.02.20. // Copyright © 2020 Byrds & Bytes GmbH. All rights reserved. import Foundation import Capacitor import Contacts @objc(ContactsPlugin) public class ContactsPlugin: CAPPlugin { @objc func echo(_ call: CAPPluginCall) { print("ios Code rached") _ = call.getString("value") ?? "" call.resolve([ "value": "hello" ]) } @objc func getPermissions(_ call: CAPPluginCall) { print("checkPermission was triggered in Swift") Permissions.contactPermission { granted in switch granted { case true: call.resolve([ "granted": true ]) default: call.resolve([ "granted": false ]) } } } @objc func getContacts(_ call: CAPPluginCall) { var contactsArray : [PluginCallResultData] = []; Permissions.contactPermission { granted in if granted { do { let contacts = try Contacts.getContactFromCNContact() for contact in contacts { var phoneNumbers: [PluginCallResultData] = [] var emails: [PluginCallResultData] = [] for number in contact.phoneNumbers { let numberToAppend = number.value.stringValue let label = number.label ?? "" let labelToAppend = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label) phoneNumbers.append([ "label": labelToAppend, "number": numberToAppend ]) } for email in contact.emailAddresses { let emailToAppend = email.value as String let label = email.label ?? "" let labelToAppend = CNLabeledValue<NSString>.localizedString(forLabel: label) emails.append([ "label": labelToAppend, "address": emailToAppend ]) } let dateFormatter = DateFormatter() // You must set the time zone from your default time zone to UTC +0, // which is what birthdays in Contacts are set to. dateFormatter.timeZone = TimeZone(identifier: "UTC") dateFormatter.dateFormat = "YYYY-MM-dd" var contactResult: PluginCallResultData = [ "contactId": contact.identifier, "displayName": "\(contact.givenName) \(contact.familyName)", "phoneNumbers": phoneNumbers, "emails": emails, ] if let photoThumbnail = contact.thumbnailImageData { contactResult["photoThumbnail"] = "data:image/png;base64,\(photoThumbnail.base64EncodedString())" if let birthday = contact.birthday?.date { contactResult["birthday"] = dateFormatter.string(from: birthday) } if !contact.organizationName.isEmpty { contactResult["organizationName"] = contact.organizationName contactResult["organizationRole"] = contact.jobTitle } } contactsArray.append(contactResult) } call.resolve([ "contacts": contactsArray ]) } catch let error as NSError { call.reject("Generic Error", error as? String) } } else { call.reject("User denied access to contacts") } } } }
39.385321
125
0.454461
ef07f60d42df891a689f29ddc330d836914fde3e
874
// // UserProfileViewModel.swift // iosApp // // Created by Chinthaka on 05/04/2021. // Copyright © 2021 orgName. All rights reserved. // import Foundation import shared class UserProfileViewModel { private let sharedViewModel: SharedViewModel = SharedViewModel() public func editUserProfile(firstName : String,lastName:String ,completion: @escaping (UserProfileScreenState)->()) { let userProfile = UserProfile(firstName: firstName,lastName: lastName) self.sharedViewModel.stateProvider.getUserProfileState(user: userProfile) { (state : UserProfileScreenState) in completion(state) } } func initProfile(completion: @escaping (UserProfileScreenState)->()){ self.sharedViewModel.stateProvider.doInitProfileScreen { (state: UserProfileScreenState) in completion(state) } } }
30.137931
121
0.70595
1677d9a3c07002d6a122f828616a682ae580040a
2,140
// // AppDelegate.swift // PresentTumblrAnimator // // Created by ios on 16/9/23. // Copyright © 2016年 ios. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:. } }
45.531915
285
0.754206
6791ef49528fefd4869a0e8aacac23d24330e353
209
// // main.swift // ReplaceString // // Created by 张行 on 2018/11/28. // Copyright © 2018 张行. All rights reserved. // import Foundation let replaceString = ZHReplaceString() replaceString.replaceString()
16.076923
45
0.708134
9027a71d9946c6bef35f7ac767b1453c949a3652
1,014
// // StringInflectorRule.swift // ModelSynchroLibrary // // Created by Jonathan Samudio on 2/5/19. // import Foundation struct StringInflectionRule { let replacement: String let regex: NSRegularExpression? init(pattern: String, options: NSRegularExpression.Options, replacement: String) { self.regex = try? NSRegularExpression(pattern: pattern, options: options) self.replacement = replacement } func evaluate(string: inout String) -> Bool { let range = NSRange(location: 0, length: string.count) let mutableString = NSMutableString(string: string) let result = self.regex?.replaceMatches(in: mutableString, options: NSRegularExpression.MatchingOptions.reportProgress, range: range, withTemplate: self.replacement) string = String(mutableString) return result != 0 } }
32.709677
108
0.599606
89d05d45d843dc71ebe670345fb23770a60f9a8e
11,355
// // DefaultAnimations.swift // Spruce // // Copyright (c) 2017 WillowTree, Inc. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit /// Direction that a slide animation should use. /// /// - up: start the view below its current position, and then slide upwards to where it currently is /// - down: start the view above its current position, and then slide downwards to where it currently is /// - left: start the view to the right of its current position, and then slide left to where it currently is /// - right: start the view to the left of its current position, and then slide right to where it currently is public enum SlideDirection { /// start the view below its current position, and then slide upwards to where it currently is case up /// start the view above its current position, and then slide downwards to where it currently is case down /// start the view to the right of its current position, and then slide left to where it currently is case left /// start the view to the left of its current position, and then slide right to where it currently is case right } /// How much the angle of an animation should change. This value changes based off of which type of `StockAnimation` is used. /// /// - slightly: slightly animate the object /// - moderately: the object should move a moderate amount /// - severely: the object should move very noticeably /// - toAngle: provide your own angle value that you feel the object should rotate public enum Angle { /// slightly animate the object case slightly /// the object should move a moderate amount case moderately /// the object should move very noticeably case severely /// provide your own value that you feel the object should move. The value you should provide should be a `Double` case toAngle(CGFloat) } /// How much the scale of an animation should change. This value changes based off of which type of `StockAnimation` is used. /// /// - slightly: slightly animate the object /// - moderately: the object should scale a moderate amount /// - severely: the object should scale very noticeably /// - toScale: provide your own scale value that you feel the object should grow/shrink public enum Scale { /// slightly animate the object case slightly /// the object should scale a moderate amount case moderately /// the object should scale very noticeably case severely /// provide your own scale value that you feel the object should grow/shrink case toScale(CGFloat) } /// How much the distance of a view animation should change. This value changes based off of which type of `StockAnimation` is used. /// /// - slightly: slightly move the object /// - moderately: the object should move a moderate amount /// - severely: the object should move very noticeably /// - byPoints: provide your own distance value that you feel the object should slide over public enum Distance { /// slightly move the object case slightly /// the object should move a moderate amount case moderately /// the object should move very noticeably case severely /// provide your own distance value that you feel the object should slide over case byPoints(CGFloat) } /// A few stock animations that you can use with Spruce. We want to make it really easy for you to include animations so we tried to include the basics. Use these stock animations to `slide`, `fade`, `spin`, `expand`, or `contract` your views. public enum StockAnimation { /// Have your view slide to where it currently is. Provide a `SlideDirection` and `Size` to determine what the animation should look like. case slide(SlideDirection, Distance) /// Fade the view in case fadeIn /// Spin the view in the direction of the size. Provide a `Size` to define how much the view should spin case spin(Angle) /// Have the view grow in size. Provide a `Size` to define by which scale the view should grow case expand(Scale) /// Have the view shrink in size. Provide a `Size` to define by which scale the view should shrink case contract(Scale) /// Provide custom prepare and change functions for the view to animate case custom(prepareFunction: PrepareHandler, animateFunction: ChangeFunction) /// Given the `StockAnimation`, how should Spruce prepare your view for animation. Since we want all of the views to end the animation where they are supposed to be positioned, we have to reverse their animation effect. var prepareFunction: PrepareHandler { get { switch self { case .slide: let offset = slideOffset return { view in let currentTransform = view.transform let offsetTransform = CGAffineTransform(translationX: offset.x, y: offset.y) view.transform = currentTransform.concatenating(offsetTransform) } case .fadeIn: return { view in view.alpha = 0.0 } case .spin: let angle = spinAngle return { view in let currentTransform = view.transform let spinTransform = CGAffineTransform(rotationAngle: angle) view.transform = currentTransform.concatenating(spinTransform) } case .expand, .contract: let scale = self.scale return { view in let currentTransform = view.transform let scaleTransform = CGAffineTransform(scaleX: scale, y: scale) view.transform = currentTransform.concatenating(scaleTransform) } case .custom(let prepare, _): return prepare } } } /// Reset any of the transforms on the view so that the view will end up in its original position. If a `custom` animation is used, then that animation `ChangeFunction` is returned. var animationFunction: ChangeFunction { get { switch self { case .slide: return { view in view.transform = CGAffineTransform(translationX: 0.0, y: 0.0) } case .fadeIn: return { view in view.alpha = 1.0 } case .spin: return { view in view.transform = CGAffineTransform(rotationAngle: 0.0) } case .expand, .contract: return { view in view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) } case .custom(_, let animation): return animation } } } /// Given the animation is a `slide`, return the slide offset var slideOffset: CGPoint { get { switch self { case .slide(let direction, let size): switch (direction, size) { case (.up, .slightly): return CGPoint(x: 0.0, y: 10.0) case (.up, .moderately): return CGPoint(x: 0.0, y: 30.0) case (.up, .severely): return CGPoint(x: 0.0, y: 50.0) case (.up, .byPoints(let value)): return CGPoint(x: 0.0, y: -value) case (.down, .slightly): return CGPoint(x: 0.0, y: -10.0) case (.down, .moderately): return CGPoint(x: 0.0, y: -30.0) case (.down, .severely): return CGPoint(x: 0.0, y: -50.0) case (.down, .byPoints(let value)): return CGPoint(x: 0.0, y: -value) case (.left, .slightly): return CGPoint(x: 10.0, y: 0.0) case (.left, .moderately): return CGPoint(x: 30.0, y: 0.0) case (.left, .severely): return CGPoint(x: 50.0, y: 0.0) case (.left, .byPoints(let value)): return CGPoint(x: -value, y: 0.0) case (.right, .slightly): return CGPoint(x: -10.0, y: 0.0) case (.right, .moderately): return CGPoint(x: -30.0, y: 0.0) case (.right, .severely): return CGPoint(x: -50.0, y: 0.0) case (.right, .byPoints(let value)): return CGPoint(x: -value, y: 0.0) } default: return CGPoint.zero } } } /// Given the animation is a `spin`, then this will return the angle that the view should spin. var spinAngle: CGFloat { get { switch self { case .spin(let size): switch size { case .slightly: return CGFloat(M_PI_4) case .moderately: return CGFloat(M_PI_2) case .severely: return CGFloat(M_PI) case .toAngle(let value): return value } default: return 0.0 } } } /// Given the animation is either `expand` or `contract`, this will return the scale from which the view should grow/shrink var scale: CGFloat { switch self { case .contract(let size): switch size { case .slightly: return 1.1 case .moderately: return 1.3 case .severely: return 1.5 case .toScale(let value): return value } case .expand(let size): switch size { case .slightly: return 0.9 case .moderately: return 0.7 case .severely: return 0.5 case .toScale(let value): return value } default: return 0.0 } } }
39.155172
243
0.58362
3a10bffb80d7cc3be02f1faeecc803c9a7332422
2,889
import Foundation import DateToolsSwift class Tweet { // MARK: Properties var id: Int? // For favoriting, retweeting & replying var text: String? // Text content of tweet var favoriteCount: Int? // Update favorite count label var favorited: Bool? // Configure favorite button var retweetCount: Int? // Update favorite count label var retweeted: Bool? // Configure retweet button var user: User? // Author of the Tweet var createdAtString: String? // String representation of date posted var createdAtStringLong: String? // String representation of date posted // var replyCount: Int? // Update favorite count label // For Retweets var retweetedByUser: User? // user who retweeted if tweet is retweet init(dictionary: [String: Any]) { var dictionary = dictionary // Is this a re-tweet? if let originalTweet = dictionary["retweeted_status"] as? [String: Any] { let userDictionary = dictionary["user"] as! [String: Any] self.retweetedByUser = User(dictionary: userDictionary) // Change tweet to original tweet dictionary = originalTweet } id = (dictionary["id"] as! Int) text = (dictionary["text"] as! String) favoriteCount = dictionary["favorite_count"] as? Int favorited = dictionary["favorited"] as? Bool retweetCount = (dictionary["retweet_count"] as! Int) retweeted = (dictionary["retweeted"] as! Bool) // replyCount = (dictionary["reply_count"] as! Int) // initialize user let user = dictionary["user"] as! [String: Any] self.user = User(dictionary: user) // Format createdAt date string let createdAtOriginalString = dictionary["created_at"] as! String let formatter = DateFormatter() // Configure the input format to parse the date string formatter.dateFormat = "E MMM d HH:mm:ss Z y" // Convert String to Date let date = formatter.date(from: createdAtOriginalString) createdAtString = date?.shortTimeAgoSinceNow // Configure output format formatter.dateStyle = .short formatter.timeStyle = .short // Convert Date to String and set the createdAtString property createdAtStringLong = formatter.string(from: date!) } /* static func tweets(with array: [[String: Any]]) -> [Tweet] { var tweets: [Tweet] = [] for tweetDictionary in array { let tweet = Tweet(dictionary: tweetDictionary) tweets.append(tweet) } return tweets }*/ //FLATMAP static func tweets(with array: [[String: Any]]) -> [Tweet] { return array.flatMap({ (dictionary) -> Tweet in Tweet(dictionary: dictionary) }) } }
37.038462
81
0.619938
fc4c086fd0701788a33eb821a1eba79eb5013df6
2,333
// // LaunchViewController.swift // iOSExcelAccounting // // Created by cyc on 2020/5/4. // Copyright © 2020 cyc. All rights reserved. // import UIKit import AVFoundation class LaunchViewController: UIViewController { @IBOutlet weak var cycLogo: UIImageView! @IBOutlet weak var cycText: UILabel! /// **must** define instance variable outside, because .play() will deallocate AVAudioPlayer immediately and you won't hear a thing var player: AVAudioPlayer? var isSkipped: Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. cycLogo.alpha = 0 cycText.alpha = 0 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 3, animations: { self.cycLogo.alpha = 1 self.cycText.alpha = 1 }) { (finished) in if !self.isSkipped{ self.performSegue(withIdentifier: "launched", sender: self) } } guard let url = Bundle.main.url(forResource: "RobotVoice", withExtension: "wav") else { print("Cannot find RobotVoice.wav!") return } do { /// this codes for making this app ready to takeover the device audio try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback) try AVAudioSession.sharedInstance().setActive(true) player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue) player!.play() } catch let error as NSError { print("error: \(error.localizedDescription)") } } /// skip to the first page when user taps @IBAction func userTaps(_ sender: Any) { isSkipped = true player?.stop() self.performSegue(withIdentifier: "launched", sender: self) } /* // 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. } */ }
31.958904
135
0.624946
f8851c8d12a31d1c360317061a53342298858959
1,206
// // CirclePushDelegate.swift // TransitionAnimationDemo // // Created by 路贵斌 on 16/5/30. // Copyright © 2016年 GirlCunt. All rights reserved. // /* 1.将要发生转场的时候,就会询问代理,这次要执行什么样的动画效果(即返回对应的遵守了动画转场协议的动画控制器) 2.如果是交互式的转场,还要返回实现了交互动画控制协议的实例对象 */ import UIKit class CirclePushDelegate: NSObject,UINavigationControllerDelegate { var interactive : MyPercentInteractive? func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { let type:CircleTransitionType = operation == .Push ? CircleTransitionType.NavTransitionPush :CircleTransitionType.NavTransitionPop return CirclePushAnimationController(type: type) } func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactive?.interation == true ? interactive : nil; } }
37.6875
281
0.784411
b93803909f1227d271e73cd1b161d67a7a316528
2,150
// --- Parameters // For `func`s, default is no external parameter name func addTwo(a: Int, b: Int) -> Int { return a + b } addTwo(3, 4) // external names func addTwoWithNames(first a: Int, second b: Int) -> Int { return a + b } addTwoWithNames(first:3, second:4) // external name shorthand func addTwoWithSameName(#first: Int, #second: Int) -> Int { return first + second } addTwoWithSameName(first:3, second:4) // named output tuples func getStatusWithNames() -> (code:Int, message:String) { return (200, "Success") } let status2 = getStatusWithNames() println("Code: \(status2.code) Message: \(status2.message)") // -- Parameter naming in classes / structs // * init: initializers' parameters all use internal name as external names // * addTwo(a,b): for class methods, first param has no external name, others use internal name as external name // * addTwoMore: can have differing external and internal names, remove external names with _ class AdditionClass { init(a:Int, b:Int) { } func addTwo(a: Int, b: Int) -> Int { return a+b } func addTwoMore(first a: Int, _ b: Int) -> Int { return a+b } } let addition = AdditionClass(a:1, b:2) addition.addTwo(1, b:2) addition.addTwoMore(first:1, 2) // -- Variadic parameters func mean(numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } mean(1,2,3,4) // -- constant and variable parameters // * parameters passed in as constant unless you use 'var', which will give you a /copy/ of that value /* func addDashesInFront(s: String, count: Int) -> String { for _ in 1...count { s = "-" + s } return s } */ func addDashesInFront(var s: String, count: Int) -> String { for _ in 1...count { s = "-" + s } return s } var stringArg = "Hello" addDashesInFront(stringArg, 5) stringArg // -- Pass by Reference // * Done automatically for classes, NOT structs or basic types var h = 0 func addOne(a: Int) -> Int { return a + 1 } addOne(h) h func addOneDirectly(inout a: Int) { a += 1 } addOneDirectly(&h) h
23.11828
112
0.654419
4aee8e4d807b7eaea22444bbc9fffda74cd47ed4
9,018
// // BottomPlayV.swift // petit // // Created by Jz D on 2020/10/28. // Copyright © 2020 swift. All rights reserved. // import UIKit import SnapKit enum Orientation{ case lhs case rhs } protocol BottomPlayBoardProxy: class { func change(interval t: TimeInterval) func change(times num: Int) func enterPlay() func secondPlay() func to(page direction: Orientation) } class BottomPlayV: UIView { weak var delegate: BottomPlayBoardProxy? let niMaH: CGFloat = 10 private lazy var playB: UIButton = { let b = UIButton() b.setImage(UIImage(named: "my_p_play"), for: .normal) return b }() lazy var lhsGoB: UIButton = { let b = UIButton() b.setTitle("上一篇", for: .normal) b.setTitleColor(UIColor(rgb: 0x575A61), for: .normal) b.titleLabel?.font = UIFont.semibold(ofSize: 12) b.backgroundColor = UIColor(rgb: 0xF0F4F8) b.corner(2) return b }() lazy var rhsGoB: UIButton = { let b = UIButton() b.setTitle("下一篇", for: .normal) b.setTitleColor(UIColor(rgb: 0x575A61), for: .normal) b.titleLabel?.font = UIFont.semibold(ofSize: 12) b.backgroundColor = UIColor(rgb: 0xF0F4F8) b.corner(2) return b }() lazy var secondPlayB: UIButton = { let b = UIButton() b.isHidden = true b.setTitle("暂停一下", for: .normal) b.setTitle("继续播放", for: .selected) b.setTitleColor(UIColor.white, for: .normal) b.titleLabel?.font = UIFont.semibold(ofSize: 12) b.backgroundColor = UIColor(rgb: 0x0080FF) b.corner(2) return b }() lazy var repeatB: UIButton = { let b = UIButton() b.isHidden = true b.setTitle("重复:x1", for: .normal) b.setTitleColor(UIColor(rgb: 0x575A61), for: .normal) b.titleLabel?.font = UIFont.semibold(ofSize: 12) b.titleLabel?.textAlignment = .center b.backgroundColor = UIColor(rgb: 0xF0F4F8) b.corner(2) return b }() lazy var intervalB: InnerL = { let b = InnerL() b.isHidden = true b.text = BottomPopData.interval[BottomPopData.interval.count - 1].interval b.font = UIFont.semibold(ofSize: 12) b.textColor = UIColor(rgb: 0x575A61) b.textAlignment = .left b.isUserInteractionEnabled = true b.backgroundColor = UIColor(rgb: 0xF0F4F8) b.corner(2) return b }() lazy var lhsPopInterval: BottomPopP = { let p = BottomPopP() p.kind = .interval p.delegate = self return p }() lazy var rhsPopRepeat: BottomPopP = { let p = BottomPopP() p.kind = .times p.delegate = self return p }() var topLhsIntervalConstraint: ConstraintMakerEditable? var topRhsTimesConstraint: ConstraintMakerEditable? override init(frame: CGRect) { super.init(frame: frame) forLayout() doEvents() } func forLayout(){ backgroundColor = UIColor.white let bg = UIView() bg.backgroundColor = UIColor.white let upBg = UIView() upBg.backgroundColor = UIColor.white addSubs([lhsPopInterval, rhsPopRepeat, bg, upBg]) upBg.addSubs([playB, lhsGoB, rhsGoB , repeatB, intervalB, secondPlayB ]) upBg.snp.makeConstraints { (m) in m.leading.trailing.top.equalToSuperview() m.bottom.equalToSuperview().offset(niMaH.neg) } bg.snp.makeConstraints { (m) in m.edges.equalToSuperview() } playB.snp.makeConstraints { (m) in m.size.equalTo(CGSize(width: 50, height: 50)) m.centerX.equalToSuperview() m.centerY.equalToSuperview().offset(-2) } lhsGoB.snp.makeConstraints { (m) in m.size.equalTo(CGSize(width: 70, height: 35)) m.leading.equalToSuperview().offset(15) m.centerY.equalToSuperview() } rhsGoB.snp.makeConstraints { (m) in m.size.top.equalTo(lhsGoB) m.trailing.equalToSuperview().offset(15.neg) } repeatB.snp.makeConstraints { (m) in m.size.equalTo(CGSize(width: 80, height: 45)) m.centerY.equalToSuperview().offset(-7) m.trailing.equalToSuperview().offset(15.neg) } intervalB.snp.makeConstraints { (m) in m.size.equalTo(repeatB) m.centerY.equalTo(repeatB) m.leading.equalToSuperview().offset(15) } secondPlayB.snp.makeConstraints { (m) in m.size.equalTo(repeatB) m.centerY.equalTo(repeatB) m.centerX.equalToSuperview() } lhsPopInterval.snp.makeConstraints { (m) in m.size.equalTo(CGSize(width: 75, height: lhsPopInterval.lhsH)) m.leading.equalToSuperview().offset(15) topLhsIntervalConstraint = m.top.equalToSuperview() } rhsPopRepeat.snp.makeConstraints { (m) in m.size.equalTo(lhsPopInterval) m.trailing.equalToSuperview().offset(-15) topRhsTimesConstraint = m.top.equalToSuperview() } } func doEvents(){ let tap = UITapGestureRecognizer() intervalB.addGestureRecognizer(tap) tap.rx.event.bind { (event) in self.goPopRhs() self.fuckEnIngLhs() }.disposed(by: rx.disposeBag) repeatB.rx.tap.subscribe(onNext: { () in self.goPopLhs() self.riYingTimesRhs() }).disposed(by: rx.disposeBag) playB.rx.tap.subscribe(onNext: { () in self.delegate?.enterPlay() self.ggg() }).disposed(by: rx.disposeBag) lhsGoB.rx.tap.subscribe(onNext: { () in self.delegate?.to(page: .lhs) self.ggg() }).disposed(by: rx.disposeBag) rhsGoB.rx.tap.subscribe(onNext: { () in self.delegate?.to(page: .rhs) self.ggg() }).disposed(by: rx.disposeBag) secondPlayB.rx.tap.subscribe(onNext: { () in self.delegate?.secondPlay() self.ggg() }).disposed(by: rx.disposeBag) } func ggg(){ goPopRhs() goPopLhs() } required init?(coder: NSCoder) { fatalError() } func p_play(second reallyP: Bool){ secondPlayB.isSelected = reallyP } func p_startAgain(){ lhsGoB.isHidden = false rhsGoB.isHidden = false repeatB.isHidden = true intervalB.isHidden = true secondPlayB.isHidden = true playB.isHidden = false } func p_pause(){ lhsGoB.isHidden = true rhsGoB.isHidden = true playB.isHidden = true secondPlayB.isHidden = false repeatB.isHidden = false intervalB.isHidden = false } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // if the button is hidden/disabled/transparent it can't be hit if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil } let frameInterval = lhsPopInterval.frame let frameTimes = rhsPopRepeat.frame var index = 9 if bounds.contains(point){ index = 0 } if frameInterval.origin.y < 0, frameInterval.contains(point){ index = 1 } if frameTimes.origin.y < 0, frameTimes.contains(point){ index = 2 } switch index { case 0: for piece in subviews.reversed(){ let realP = piece.convert(point, from: self) let hit = piece.hitTest(realP, with: event) if let v = hit{ return v } } return self case 1: if frameInterval.origin.y < 0{ let realP = lhsPopInterval.convert(point, from: self) return lhsPopInterval.hitTest(realP, with: event) } case 2: if frameTimes.origin.y < 0{ let realP = rhsPopRepeat.convert(point, from: self) return rhsPopRepeat.hitTest(realP, with: event) } default: () } return nil } }
24.842975
94
0.526724
18e7f5d49fe1a1bdb6e417226a457e40cdd019cd
226
// // ResponseData.swift // Top Filmes // // Created by Code Red on 12/07/19. // Copyright © 2019 particular. All rights reserved. // import Foundation struct ResponseData : Decodable{ var results : [Filme]? = nil }
16.142857
53
0.668142
2939e4298fd97695c9eb0f28c9dd07ad3e4ff84c
835
// // GroceryLists.swift // Grocery // // Created by Mike Kari Anderson on 7/22/18. // Copyright © 2018 Mike Kari Anderson. All rights reserved. // import Foundation import FirebaseDatabase class GroceryLists { var ref: DatabaseReference var root: DatabaseReference var produce: GroceryItems var list: GroceryList? var listItems: GroceryListItems? init(_ ref: DatabaseReference) { self.ref = ref self.root = ref.parent! self.produce = GroceryItems(root.child("items")) ref.observeSingleEvent(of: .value) { snapshot in self.list = GroceryList(snapshot) self.listItems = GroceryListItems(snapshot.ref.child("items")) self.listItems?.loadRecords() { _ in } } } }
23.857143
74
0.602395
f58f1416460e680c00aaaef7eedf6f34fa5a67ec
2,286
// // AccountEntryXDR.swift // stellarsdk // // Created by Rogobete Christian on 12.02.18. // Copyright © 2018 Soneso. All rights reserved. // import Foundation public struct AccountEntryXDR: XDRCodable { let accountID: PublicKey public let balance: Int64 public let sequenceNumber: UInt64 public let numSubEntries:UInt32 public var inflationDest: PublicKey? public let flags:UInt32 public let homeDomain:String? public let thresholds:WrappedData4 public let signers: [SignerXDR] public let reserved: Int32 = 0 public init(accountID: PublicKey, balance:Int64, sequenceNumber:UInt64, numSubEntries:UInt32, inflationDest:PublicKey? = nil, flags:UInt32, homeDomain:String? = nil, thresholds: WrappedData4, signers: [SignerXDR]) { self.accountID = accountID self.balance = balance self.sequenceNumber = sequenceNumber self.numSubEntries = numSubEntries self.inflationDest = inflationDest self.flags = flags self.homeDomain = homeDomain self.thresholds = thresholds self.signers = signers } public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() accountID = try container.decode(PublicKey.self) balance = try container.decode(Int64.self) sequenceNumber = try container.decode(UInt64.self) numSubEntries = try container.decode(UInt32.self) inflationDest = try container.decode(Array<PublicKey>.self).first flags = try container.decode(UInt32.self) homeDomain = try container.decode(String.self) thresholds = try container.decode(WrappedData4.self) signers = try container.decode(Array<SignerXDR>.self) _ = try container.decode(Int32.self) } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(accountID) try container.encode(balance) try container.encode(sequenceNumber) try container.encode(numSubEntries) try container.encode(inflationDest) try container.encode(flags) try container.encode(thresholds) try container.encode(signers) try container.encode(reserved) } }
36.285714
219
0.691601
5dc36fe317306aa2699a32ea81efa6ae2bfbeed9
261
// // ResponseDomain.swift // CarTypes // // Created by Deepak Arora on 02.04.20. // Copyright © 2020 Deepak Arora. All rights reserved. // import Foundation struct ResponseDomain { var currentPage: Int let totalPages: Int var items: [DomainItem] }
16.3125
55
0.701149
f8725e0a21de2704274e98de0b29fb86f107ccfe
2,572
/// Copyright (c) 2021 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import SwiftUI struct WelcomeMessageView: View { var body: some View { Label( title: { VStack { Text("Welcome to") .font(.headline) .bold() Text("Kuchi") .font(.largeTitle) .bold() } .foregroundColor(.red) .lineLimit(2) .multilineTextAlignment(.leading) .padding(.horizontal) }, icon: { LogoImage() } ) .labelStyle(HorizontallyAlignedLabelStyle()) } } struct WelcomeMessageView_Previews: PreviewProvider { static var previews: some View { WelcomeMessageView() } }
39.569231
83
0.688958
484a1c6019d9b5e719f7900dddd7f1ee0cd3ac3d
9,083
// // AKMorphingOscillator.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2018 AudioKit. All rights reserved. // /// This is an oscillator with linear interpolation that is capable of morphing /// between an arbitrary number of wavetables. /// open class AKMorphingOscillator: AKNode, AKToggleable, AKComponent { public typealias AKAudioUnitType = AKMorphingOscillatorAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(generator: "morf") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var waveformArray = [AKTable]() fileprivate var phase: Double fileprivate var frequencyParameter: AUParameter? fileprivate var amplitudeParameter: AUParameter? fileprivate var indexParameter: AUParameter? fileprivate var detuningOffsetParameter: AUParameter? fileprivate var detuningMultiplierParameter: AUParameter? /// Lower and upper bounds for Frequency public static let frequencyRange = 0.0 ... 22_050.0 /// Lower and upper bounds for Amplitude public static let amplitudeRange = 0.0 ... 1.0 /// Lower and upper bounds for Index public static let indexRange = 0.0 ... 3.0 /// Lower and upper bounds for Detuning Offset public static let detuningOffsetRange = -1_000.0 ... 1_000.0 /// Lower and upper bounds for Detuning Multiplier public static let detuningMultiplierRange = 0.9 ... 1.11 /// Initial value for Frequency public static let defaultFrequency = 440.0 /// Initial value for Amplitude public static let defaultAmplitude = 0.5 /// Initial value for Index public static let defaultIndex = 0.0 /// Initial value for Detuning Offset public static let defaultDetuningOffset = 0.0 /// Initial value for Detuning Multiplier public static let defaultDetuningMultiplier = 1.0 /// Initial value for Phase public static let defaultPhase = 0.0 /// Ramp Duration represents the speed at which parameters are allowed to change @objc open dynamic var rampDuration: Double = AKSettings.rampDuration { willSet { internalAU?.rampDuration = newValue } } /// Frequency (in Hz) @objc open dynamic var frequency: Double = defaultFrequency { willSet { if frequency == newValue { return } if internalAU?.isSetUp ?? false { if let existingToken = token { frequencyParameter?.setValue(Float(newValue), originator: existingToken) return } } internalAU?.setParameterImmediately(.frequency, value: newValue) } } /// Amplitude (typically a value between 0 and 1). @objc open dynamic var amplitude: Double = defaultAmplitude { willSet { if amplitude == newValue { return } if internalAU?.isSetUp ?? false { if let existingToken = token { amplitudeParameter?.setValue(Float(newValue), originator: existingToken) return } } internalAU?.setParameterImmediately(.amplitude, value: newValue) } } /// Index of the wavetable to use (fractional are okay). @objc open dynamic var index: Double = defaultIndex { willSet { if index == newValue { return } let transformedValue = Float(newValue) / Float(waveformArray.count - 1) if internalAU?.isSetUp ?? false { if let existingToken = token { indexParameter?.setValue(Float(transformedValue), originator: existingToken) return } } internalAU?.setParameterImmediately(.index, value: Double(transformedValue)) } } /// Frequency offset in Hz. @objc open dynamic var detuningOffset: Double = defaultDetuningOffset { willSet { if detuningOffset == newValue { return } if internalAU?.isSetUp ?? false { if let existingToken = token { detuningOffsetParameter?.setValue(Float(newValue), originator: existingToken) return } } internalAU?.setParameterImmediately(.detuningOffset, value: newValue) } } /// Frequency detuning multiplier @objc open dynamic var detuningMultiplier: Double = defaultDetuningMultiplier { willSet { if detuningMultiplier == newValue { return } if internalAU?.isSetUp ?? false { if let existingToken = token { detuningMultiplierParameter?.setValue(Float(newValue), originator: existingToken) return } } internalAU?.setParameterImmediately(.detuningMultiplier, value: newValue) } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying ?? false } // MARK: - Initialization /// Initialize the oscillator with defaults public convenience override init() { self.init(waveformArray: [AKTable(.triangle), AKTable(.square), AKTable(.sine), AKTable(.sawtooth)]) } /// Initialize this Morpher node /// /// - Parameters: /// - waveformArray: An array of exactly four waveforms /// - frequency: Frequency (in Hz) /// - amplitude: Amplitude (typically a value between 0 and 1). /// - index: Index of the wavetable to use (fractional are okay). /// - detuningOffset: Frequency offset in Hz. /// - detuningMultiplier: Frequency detuning multiplier /// - phase: Initial phase of waveform, expects a value 0-1 /// @objc public init( waveformArray: [AKTable], frequency: Double = defaultFrequency, amplitude: Double = defaultAmplitude, index: Double = defaultIndex, detuningOffset: Double = defaultDetuningOffset, detuningMultiplier: Double = defaultDetuningMultiplier, phase: Double = defaultPhase) { self.waveformArray = waveformArray self.frequency = frequency self.amplitude = amplitude self.phase = phase self.index = index self.detuningOffset = detuningOffset self.detuningMultiplier = detuningMultiplier _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in guard let strongSelf = self else { AKLog("Error: self is nil") return } strongSelf.avAudioNode = avAudioUnit strongSelf.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType for (i, waveform) in waveformArray.enumerated() { strongSelf.internalAU?.setupIndividualWaveform(UInt32(i), size: Int32(waveform.count)) for (j, sample) in waveform.enumerated() { strongSelf.internalAU?.setIndividualWaveform(UInt32(i), withValue: sample, at: UInt32(j)) } } } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } frequencyParameter = tree["frequency"] amplitudeParameter = tree["amplitude"] indexParameter = tree["index"] detuningOffsetParameter = tree["detuningOffset"] detuningMultiplierParameter = tree["detuningMultiplier"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.setParameterImmediately(.frequency, value: frequency) internalAU?.setParameterImmediately(.amplitude, value: amplitude) internalAU?.setParameterImmediately(.index, value: Float(index) / Float(waveformArray.count - 1)) internalAU?.setParameterImmediately(.detuningOffset, value: detuningOffset) internalAU?.setParameterImmediately(.detuningMultiplier, value: detuningMultiplier) } /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
36.332
109
0.62072
1cf37d4ced0b882f2ea34ff94f1e3027a2a4d0d2
2,085
// // UserRepository.swift // base-app-ios // // Created by Roberto Frontado on 2/18/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import RxSwift import ObjectMapper import RxCache class UserRepository: Repository { static let FIRST_ID_QUERIED = 0 static let USERS_PER_PAGE = 50 static let MAX_USERS_TO_LOAD = 300 override init(restApi: RestApi, rxProviders: RxCache) { super.init(restApi: restApi, rxProviders: rxProviders) } func searchByUserName(_ nameUser: String) -> Observable<User> { return restApi.getUserByName(nameUser) .flatMap { (response) -> Observable<User> in if let error: Observable<User> = self.handleError(response) { return error } do { let responseUser: User = try response.mapObject(User.self) return Observable.just(responseUser) } catch { return self.buildObservableError("Error mapping the response") } } } func getUsers(_ lastIdQueried: Int?, refresh: Bool) -> Observable<[User]> { var oLoader = restApi.getUsers(lastIdQueried, perPage: UserRepository.USERS_PER_PAGE) .flatMap { (response) -> Observable<[User]> in if let error: Observable<[User]> = self.handleError(response) { return error } do { let responseUser: [User] = try response.mapArray(User.self) return Observable.just(responseUser) } catch { return self.buildObservableError("Error mapping the response") } } if lastIdQueried == UserRepository.FIRST_ID_QUERIED { let provider = RxCacheProviders.getUsers(evict: refresh) oLoader = rxProviders.cache(oLoader, provider: provider) } return oLoader } }
32.076923
93
0.557794
90b21c3331f0077915df83a759d2fded8e946ee7
1,475
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4 // Non-final classes where Codable conformance is added in extensions should // only be able to derive conformance for Encodable. class SimpleClass { // expected-note {{did you mean 'init'?}} var x: Int = 1 var y: Double = .pi static var z: String = "foo" func foo() { // They should receive a synthesized CodingKeys enum. let _ = SimpleClass.CodingKeys.self // The enum should have a case for each of the vars. let _ = SimpleClass.CodingKeys.x let _ = SimpleClass.CodingKeys.y // Static vars should not be part of the CodingKeys enum. let _ = SimpleClass.CodingKeys.z // expected-error {{type 'SimpleClass.CodingKeys' has no member 'z'}} } } extension SimpleClass : Codable {} // expected-error 2 {{implementation of 'Decodable' for non-final class cannot be automatically synthesized in extension because initializer requirement 'init(from:)' can only be satisfied by a 'required' initializer in the class definition}} // They should not receive synthesized init(from:), but should receive an encode(to:). let _ = SimpleClass.init(from:) // expected-error {{type 'SimpleClass' has no member 'init(from:)'}} let _ = SimpleClass.encode(to:) // The synthesized CodingKeys type should not be accessible from outside the // struct. let _ = SimpleClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
46.09375
277
0.730169
7a898e7da9d9966006945b38ca82e86b0b3f9265
4,949
// // CIPerspectiveTransform.swift (AUTOMATICALLY GENERATED FILE) // CIFilterFactory // // MIT license // // 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. // // Automatically generated on 2020-07-09 00:57:49 +0000. Do not edit. import AVFoundation import CoreImage import CoreML import Foundation public extension CIFilter { @available(macOS 10.4, iOS 6, *) @inlinable @objc static func PerspectiveTransform() -> CIFilterFactory.CIPerspectiveTransform? { return CIFilterFactory.CIPerspectiveTransform() } } @available(macOS 10.4, iOS 6, *) @objc public extension CIFilterFactory { /// /// Perspective Transform /// /// Alters the geometry of an image to simulate the observer changing viewing position. You can use the perspective filter to skew an image. /// /// **Links** /// /// [CIPerspectiveTransform Online Documentation](http://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/CIPerspectiveTransform) /// /// [CIFilter.io documentation](https://cifilter.io/CIPerspectiveTransform/) /// @objc(CIFilterFactory_CIPerspectiveTransform) class CIPerspectiveTransform: FilterCore { @objc public init?() { super.init(name: "CIPerspectiveTransform") } // MARK: - Inputs /// /// The image to use as an input image. For filters that also use a background image, this is the foreground image. /// /// Class: CIImage /// Type: CIAttributeTypeImage @objc public dynamic var inputImage: CIImage? { get { return self.keyedValue("inputImage") } set { self.setKeyedValue(newValue, for: "inputImage") } } /// /// The top left coordinate to map the image to. /// /// Class: CIVector /// Type: CIAttributeTypePosition /// Default: [118 484] @objc public dynamic var inputTopLeft: CIFilterFactory.Point? { get { return CIFilterFactory.Point(with: self.filter, key: "inputTopLeft") } set { self.setKeyedValue(newValue?.vector, for: "inputTopLeft") } } /// /// The top right coordinate to map the image to. /// /// Class: CIVector /// Type: CIAttributeTypePosition /// Default: [646 507] @objc public dynamic var inputTopRight: CIFilterFactory.Point? { get { return CIFilterFactory.Point(with: self.filter, key: "inputTopRight") } set { self.setKeyedValue(newValue?.vector, for: "inputTopRight") } } /// /// The bottom right coordinate to map the image to. /// /// Class: CIVector /// Type: CIAttributeTypePosition /// Default: [548 140] @objc public dynamic var inputBottomRight: CIFilterFactory.Point? { get { return CIFilterFactory.Point(with: self.filter, key: "inputBottomRight") } set { self.setKeyedValue(newValue?.vector, for: "inputBottomRight") } } /// /// The bottom left coordinate to map the image to. /// /// Class: CIVector /// Type: CIAttributeTypePosition /// Default: [155 153] @objc public dynamic var inputBottomLeft: CIFilterFactory.Point? { get { return CIFilterFactory.Point(with: self.filter, key: "inputBottomLeft") } set { self.setKeyedValue(newValue?.vector, for: "inputBottomLeft") } } // MARK: - Convenience initializer @objc public convenience init?( inputImage: CIImage, inputTopLeft: CIFilterFactory.Point = CIFilterFactory.Point(x: 118.0, y: 484.0), inputTopRight: CIFilterFactory.Point = CIFilterFactory.Point(x: 646.0, y: 507.0), inputBottomRight: CIFilterFactory.Point = CIFilterFactory.Point(x: 548.0, y: 140.0), inputBottomLeft: CIFilterFactory.Point = CIFilterFactory.Point(x: 155.0, y: 153.0) ) { self.init() self.inputImage = inputImage self.inputTopLeft = inputTopLeft self.inputTopRight = inputTopRight self.inputBottomRight = inputBottomRight self.inputBottomLeft = inputBottomLeft } } }
33.666667
215
0.706405
46d6cc5ecd60bb6aa93a1f6637727c5b972f707b
452
class Solution { func isPowerOfFour(_ n: Int) -> Bool { if n == 0 { return false //Exceptional case 0 } if n == 1 { //Exceptional case 4^0 = 1 return true } if n % 4 == 0 { return isPowerOfFour(n/4) //Recursive Case check if 4^(n-1) is power of 4. } else { return false //Return false if it's not. } } }
30.133333
93
0.431416
5082bd8f4fb06bd01cbf2889446126eb36f34120
1,981
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import DummyModule return d } self] = i> { typealias C { return ") } } get { } } func b: C { return b: String)(array: a { private class func compose() -> U : C { self.advance() } } d<T -> Any, x { } func g> Any, length: a { } } func b: A().init(A(false) } } typealias f = true as BooleanType) } struct X.f == g> Int { protocol b = b<d.e where l.a() private class A : H.g = 0 } "foobar"ab"[] return p: (AnyObject)() { struct c = 1] return nil self.A, y: T! { return d) -> <T : Int { } typealias B) } a(b() } } return ! protocol e == b(Any) -> T : T.init(n: Int = b> { struct A { (b(_ = { typealias f == a()] { get { i: (g<T.Generator..Type) { switch x } protocol e { case C: (A<d) -> (T>) { var f) } var b> { ((start: AnyObject) -> Any) -> { convenience init(n: SequenceType> (b> Any { class a { typealias E } } return $0) ->(range.b = j> (z([c(_ c<T> { } var a } enum B : b<f == B) -> (x) -> : A { import Foundation func a<U : Any, g<U { } struct c { } } public var a: A { class func b.startIndex) let d } protocol P { return self.endIndex - range: C({ import Foundation } } } func b: a { } let f == true as [[T, i> d.d<T : d = F } } func b: c) { } } typealias F = 1]()) b("\(.a<T -> String { } protocol d = b: B<h: String class A { func f() -> <T : e: a { for b = { } func a: Int = h struct c<I : (b: k.Element>? extension NSSet { protocol b : T> : T) { } } return "") } } } } })) -> Any) { class A where S() get } let i(i<U -> Any, g = e() + seq: T) -> T>(c = c: a { protocol A = B class A { })) import Foundation e == F>() func b: d where I) -> : C { } self.join(c<d: Array<T : H.c { protocol c { return [T) -> [1) let g == b<c: A { (n: ("foo"cd"]) } } } struct A { } } } } } } "cd") convenience init() get { return g<T> Any { } protocol b { } } var b: Any) { } struct A<T where T.f : Bool) { func b return "
12.780645
87
0.553761
031d42fb3adf898e5da354c8fc0926feea990555
2,455
// // ListSourcesViewController.swift // NewsAPISwift // // Created by lucas lima on 6/3/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import NewsAPISwift class ListSourcesViewController: UITableViewController { let newsAPI = NewsAPI(apiKey: "f9fa20fea27f44b79b2c779acdef4421") var sources = [NewsSource]() { didSet { DispatchQueue.main.async { self.tableView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() title = "NewsAPISwift" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) newsAPI.getSources { result in switch result { case .success(let sourceList): self.sources = sourceList case .failure(let error): fatalError("\(error)") } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.destination is ListArticlesViewController { let articlesViewController = segue.destination as! ListArticlesViewController articlesViewController.newsAPI = newsAPI articlesViewController.source = sources[tableView.indexPathForSelectedRow!.row] } } // override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let articlesViewController = UIStoryboard(name: "Main", bundle: nil) // .instantiateViewController(withIdentifier: "ListArticlesViewController") as! ListArticlesViewController // // articlesViewController.newsAPI = newsAPI // articlesViewController.source = sources[indexPath.row] // // navigationController?.pushViewController(articlesViewController, animated: true) // } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sources.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SourceCell", for: indexPath) cell.textLabel?.text = sources[indexPath.row].name return cell } }
31.474359
117
0.644399
391cdc626dad236f7d9541681e42bef18f4dd37a
518
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck import Foundation enum S<T where f: end: Int = b(".Iterator.b : AnyObject> Any) -> Int = i> String { func a: NSObject {
43.166667
82
0.733591
fc36cf380377e3e573f52a9f5c0fcc5b9da564fd
470
// // BusinessAnnotation.swift // Yelp // // Created by Nghia Nguyen on 7/15/17. // Copyright © 2017 Timothy Lee. All rights reserved. // import UIKit import MapKit class BusinessAnnotation: NSObject, MKAnnotation { var business: Business var coordinate: CLLocationCoordinate2D { return business.getLocation() } init(business: Business) { self.business = business } var title: String? { return business.name! } }
19.583333
77
0.661702
ccda3a67889de3f31f1909cbb2a116ba4c961365
1,130
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // import Foundation class AppSettings { private var settings: [String: Any] = [:] var communicationTokenFetchUrl: String { return settings["communicationTokenFetchUrl"] as! String } var isAADAuthEnabled: Bool { return settings["isAADAuthEnabled"] as! Bool } var aadClientId: String { return settings["aadClientId"] as! String } var aadTenantId: String { return settings["aadTenantId"] as! String } var aadRedirectURI: String { return settings["aadRedirectURI"] as! String } var aadScopes: [String] { return settings["aadScopes"] as! [String] } init() { if let url = Bundle.main.url(forResource: "AppSettings", withExtension: "plist") { do { let data = try Data(contentsOf: url) settings = try (PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any])! } catch { print(error) } } } }
23.541667
115
0.595575
625609723d7b1a4d094d668d0e0294f4dbe96703
214
// // PaymentType.swift // kevin.iOS // // Created by Edgar Žigis on 8/1/21. // Copyright © 2021 kevin.. All rights reserved. // import Foundation public enum KevinPaymentType { case bank case card }
14.266667
49
0.663551
f56998b215c773ab2c8a7ff2e80d6d342a6dab91
239
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{protocol d:C{{}{}protocol C{{}protocol A{{}}func e:a}func p(a:A?
47.8
87
0.736402
1a930407e32fd9c66bfb9f0581768bd0b0d0872b
1,425
// // KamaConfig.swift // KamaUIKit // // Created by Prakash Raman on 13/02/16. // Copyright © 2016 1985. All rights reserved. // import Foundation import UIKit import SnapKit class KitBaseViewController : UIViewController { override func viewDidLoad() { super.viewDidLoad() determineBackButton() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func pushViewController(viewController: UIViewController){ self.navigationController?.pushViewController(viewController, animated: true) } func determineBackButton(){ let count = self.navigationController?.viewControllers.count var name = "menu" var action = "openmenu:" if count > 1 { name = "back" action = "goback:" } let icon = UIImage(named: name)?.imageWithRenderingMode(.AlwaysOriginal) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: icon, landscapeImagePhone: .None, style: .Plain, target: self, action: Selector(action)) } func goback(sender: AnyObject? = nil){ self.navigationController?.popViewControllerAnimated(true) } func openmenu(sender: AnyObject? = nil){ let parent = self.parentViewController?.parentViewController as! KitMenuViewController parent.toggleMenu() } }
26.886792
159
0.649123
efc137da3613274d7fddf696ef21a22c887ccebf
3,208
// // ViewController.swift // iBeaconPeripheralDemo // // Created by yamaguchi on 2016/12/12. // Copyright © 2016年 h.yamaguchi. All rights reserved. // import UIKit import CoreBluetooth import CoreLocation class ViewController: UIViewController { fileprivate var peripheralManager: CBPeripheralManager? fileprivate var beaconRegion: CLBeaconRegion? fileprivate var stateLabel: UILabel! fileprivate var startButton: UIButton! fileprivate var stopbutton: UIButton! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidLoad() { super.viewDidLoad() self.peripheralManager = CBPeripheralManager() self.peripheralManager?.delegate = self; self.stateLabel = UILabel() self.stateLabel.frame = CGRect(x: 0, y: 100, width: self.view.frame.width, height: 50) self.stateLabel.textAlignment = .center self.stateLabel.font = UIFont.systemFont(ofSize: 25) self.stateLabel.text = "未送信" self.view.addSubview(self.stateLabel) self.startButton = UIButton(type: .roundedRect) self.startButton.frame = CGRect(x: 0, y: 250, width: self.view.frame.width / 2, height: 50) self.startButton.setTitle("Start", for: .normal) self.startButton.titleLabel?.font = UIFont.systemFont(ofSize: 20) self.startButton.addTarget(self, action: #selector(start), for: .touchUpInside) self.view.addSubview(self.startButton) self.stopbutton = UIButton(type: .roundedRect) self.stopbutton.frame = CGRect(x: self.view.frame.width / 2, y: 250, width: self.view.frame.width / 2, height: 50) self.stopbutton.setTitle("Stop", for: .normal) self.stopbutton.titleLabel?.font = UIFont.systemFont(ofSize: 20) self.stopbutton.addTarget(self, action: #selector(stop), for: .touchUpInside) self.view.addSubview(self.stopbutton) } func start() { let uuid = NSUUID(uuidString: "D947DF5D-2FB7-417E-B34B-2D1F72A8DE40") self.beaconRegion = CLBeaconRegion(proximityUUID: uuid as! UUID, major: 1, minor: 1, identifier: "ibeacon Demo") let peripheralData = NSDictionary(dictionary: self.beaconRegion!.peripheralData(withMeasuredPower: nil)) as! [String: Any] self.peripheralManager!.startAdvertising(peripheralData) self.stateLabel.text = "送信中" self.startButton.isEnabled = false self.stopbutton.isEnabled = true } func stop() { self.peripheralManager?.stopAdvertising() self.stateLabel.text = "未送信" self.startButton.isEnabled = true self.stopbutton.isEnabled = false } } extension ViewController: CBPeripheralManagerDelegate { func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { NSLog(">> peripheralManagerDidUpdateState") self.start() } func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { print(">> peripheralManagerDidStartAdvertising") } }
34.494624
122
0.663965
696e6d9c3cb7a5c574e9d0e6be7704619bbaab0b
2,373
// // Matcher.swift // Match3Kit // // Created by Alexey on 15.02.2020. // Copyright © 2020 Alexey. All rights reserved. // /// Matches detector open class Matcher<Filling: GridFilling> { public private(set) var fillings: Set<Filling> public let minSeries: Int internal final func addFillings(_ fillings: Set<Filling>) { self.fillings.formUnion(fillings) } internal final func removeFillings(_ fillings: Set<Filling>) { self.fillings.subtract(fillings) } public required init(fillings: Set<Filling>, minSeries: Int) { self.minSeries = minSeries self.fillings = fillings } public func findAllMatches(on grid: Grid<Filling>) -> Set<Index> { findMatched(on: grid, indices: grid.allIndices()) } public func findMatched<Indices: Collection>(on grid: Grid<Filling>, indices: Indices) -> Set<Index> where Indices.Element == Index { indices.reduce(Set()) { result, index in result.union(findMatches(on: grid, at: index)) } } public func findMatches(on grid: Grid<Filling>, at index: Index) -> Set<Index> { let cell = grid.cell(at: index) guard fillings.contains(cell.filling) else { return Set() } func matchCellsInRow(sequence: UnfoldFirstSequence<Index>) -> [Index] { sequence.prefix { grid.size.isOnBounds($0) && match(cell: grid.cell(at: $0), with: cell) } } let verticalIndicies = matchCellsInRow(sequence: index.upperSequence()) + matchCellsInRow(sequence: index.lowerSequence()) let horizontalIndicies = matchCellsInRow(sequence: index.rightSequence()) + matchCellsInRow(sequence: index.leftSequence()) var result = Set<Index>() if verticalIndicies.count + 1 >= minSeries { result.formUnion(verticalIndicies) } if horizontalIndicies.count + 1 >= minSeries { result.formUnion(horizontalIndicies) } if !result.isEmpty { result.insert(index) } return result } open func match(cell: Grid<Filling>.Cell, with cellToMatch: Grid<Filling>.Cell) -> Bool { cell.filling == cellToMatch.filling } }
32.067568
113
0.597556
d61f79a6f5cf378b1f2dcba7b44f495fd6edb7a7
992
// // SwiftHintToastTests.swift // SwiftHintToastTests // // Created by 周际航 on 2017/4/13. // Copyright © 2017年 com.maramara. All rights reserved. // import XCTest @testable import SwiftHintToast class SwiftHintToastTests: 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. } } }
26.810811
111
0.641129
4606b08b086880b1e8e5126001452bc44fbcb446
828
// // BuiltCampaignControllerTriggerHasPriorRewardResponseFilterMinAge.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public struct BuiltCampaignControllerTriggerHasPriorRewardResponseFilterMinAge: Codable { public var seconds: Int64? public var zero: Bool? public var negative: Bool? public var units: [BuiltCampaignControllerTriggerHasPriorRewardResponseFilterMinAgeUnits]? public var nano: Int? public init(seconds: Int64? = nil, zero: Bool? = nil, negative: Bool? = nil, units: [BuiltCampaignControllerTriggerHasPriorRewardResponseFilterMinAgeUnits]? = nil, nano: Int? = nil) { self.seconds = seconds self.zero = zero self.negative = negative self.units = units self.nano = nano } }
27.6
187
0.728261
876ac8984eea2480ef535ece6959b70f229f06c0
205
// // ReviewsListResponse.swift // COpenSSL // // Created by Tatiana Tsygankova on 30/06/2019. // import Foundation struct ReviewsListResponse: Codable { var page: Int var reviews: [Review] }
14.642857
48
0.692683
560256e825a6999f7e25b34c205bce718578bb4c
216
// // Gorilla.swift // Generics // // Created by Hesham Salman on 1/30/17. // Copyright © 2017 View The Space. All rights reserved. // import Foundation public struct Gorilla: Primate { public init() { } }
15.428571
57
0.657407
6a528aa97acaf80b639acc96deb88787a6b381d8
2,628
// // UIColor+StripeUICore.swift // StripeUICore // // Created by Ramon Torres on 11/8/21. // import UIKit @_spi(STP) public extension UIColor { /// Increases the brightness of the color by the given `amount`. /// /// The brightness of the resulting color will be clamped to a max value of`1.0`. /// - Parameter amount: Adjustment amount (range: 0.0 - 1.0.) /// - Returns: Adjusted color. func lighten(by amount: CGFloat) -> UIColor { return byModifyingBrightness { min($0 + amount, 1) } } /// Decreases the brightness of the color by the given `amount`. /// /// The brightness of the resulting color will be clamped to a min value of`0.0`. /// - Parameter amount: Adjustment amount (range: 0.0 - 1.0.) /// - Returns: Adjusted color. func darken(by amount: CGFloat) -> UIColor { return byModifyingBrightness { max($0 - amount, 0) } } static func dynamic(light: UIColor, dark: UIColor) -> UIColor { if #available(iOS 13.0, *) { return UIColor(dynamicProvider: { switch $0.userInterfaceStyle { case .light, .unspecified: return light case .dark: return dark @unknown default: return light } }) } return light } } // MARK: - Helpers private extension UIColor { /// Transforms the brightness and returns the resulting color. /// /// - Parameter transform: A block for transforming the brightness. /// - Returns: Updated color. func byModifyingBrightness(_ transform: @escaping (CGFloat) -> CGFloat) -> UIColor { // Similar to `UIColor.withAlphaComponent()`, the returned color must be dynamic. This ensures // that the color automatically adapts between light and dark mode. return .dynamic { _ in var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return UIColor( hue: hue, saturation: saturation, brightness: transform(brightness), alpha: alpha ) } } static func dynamic(_ provider: @escaping (UITraitCollection?) -> UIColor) -> UIColor { if #available(iOS 13.0, *) { return UIColor(dynamicProvider: { provider($0) }) } else { return provider(nil) } } }
30.917647
102
0.570015
23f5db288dc7dc2cf2482d972a9d9c75d542f81e
2,910
// // StockCenter.swift // XIMDBPodLib_Example // // Created by xiaofengmin on 2019/10/10. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import XIMDatabase class StockCenter: NSObject { lazy var stockTableA:StockTable = { let table = StockTable.init() return table }() lazy var stockTableB:DescriptionTable = { let table = DescriptionTable.init() return table }() override init() { super.init() } func insertDemo() -> Void { let _ = stockTableA.insert(conditions: [ "stockcode":"300033", "stockname":"同花顺", "stockmarket":56 ]) let _ = stockTableB.insert(conditions: [ "stockcode":"300033", "stockdescription":"第三方交易机构", ]) let _ = stockTableA.insert(conditions: [ "stockcode":"300037", "stockname":"同花顺", "stockmarket":56 ]) let _ = stockTableA.insert(conditions: [ "stockcode":"300038", "stockname":"同花顺-1", "stockmarket":56 ]) let _ = stockTableA.insert(conditions: [ "stockcode":"300039", "stockname":"同花顺-2", "stockmarket":56 ]) let _ = stockTableA.insert(conditions: [ "stockcode":"300040", "stockname":"同花顺", "stockmarket":56 ]) let _ = stockTableA.update(conditions: ["stockname":"10jqka"], whereString: "stockcode", whereValue: "300040") let info = stockTableA.search(whereString: "stockcode", whereValue: "300033") { (FMResultSet) -> Any in var stock = StockBase() stock.stockCode = FMResultSet.string(forColumn: "stockcode") stock.stockName = FMResultSet.string(forColumn: "stockname") stock.stockMarket = Int(FMResultSet.int(forColumn: "stockmarket")) return stock }?.first as? DatabaseRecordProtocol let desc = stockTableB.search(whereString: "stockcode", whereValue: "300033") { (FMResultSet) -> Any in var stock = StockDesc() stock.stockCode = FMResultSet.string(forColumn: "stockcode") stock.stockDecription = FMResultSet.string(forColumn: "stockdescription") return stock }?.first as? DatabaseRecordProtocol //插入nil 会崩溃 let stockInfo2 = StockInfo().mergeRecord(record: info!, override: true).mergeRecord(record: desc!, override: true) let _ = stockTableA.fetch(sql: "select * from stockTable where stockname = '10jqka'") let _ = stockTableA.delete(whereString: "stockcode", whereValue: "300037") let _ = stockTableA.clear() let _ = stockTableB.clear() } }
31.290323
122
0.558763
899ec056e4507cbad2dd7099032fc24477ff66da
1,854
// // Processes.swift // SyncthingBar // // Created by John on 11/11/2016. // Copyright © 2016 Olive Toast Software Ltd. All rights reserved. // //import Darwin import Foundation enum ProcessesError: Error { case procListError } struct ProcInfo { let pid: Int32 let path: String } struct Processes { static func listPids() -> [Int32] { let pnum = proc_listpids(UInt32(PROC_ALL_PIDS), 0, nil, 0) var pids = [pid_t](repeating: 0, count: Int(pnum)) _ = pids.withUnsafeMutableBufferPointer { ptr in proc_listpids(UInt32(PROC_ALL_PIDS), 0, ptr.baseAddress, pnum * Int32(MemoryLayout<pid_t>.size)) } return pids } static func list() -> [ProcInfo] { var list = [ProcInfo]() for pid in self.listPids() { if pid == 0 { continue } let cpath = UnsafeMutablePointer<CChar>.allocate(capacity: Int(MAXPATHLEN)) proc_pidpath(pid, cpath, UInt32(MAXPATHLEN)) if strlen(cpath) > 0 { let path = String(cString: cpath) list.append(ProcInfo(pid: pid, path: path)) } } return list } static func find(processName: String) -> ProcInfo? { for pid in self.listPids() { if pid == 0 { continue } let cpath = UnsafeMutablePointer<CChar>.allocate(capacity: Int(MAXPATHLEN)) proc_pidpath(pid, cpath, UInt32(MAXPATHLEN)) guard strlen(cpath) > 0 else { continue } let path = String(cString: cpath) let url = URL(fileURLWithPath: path) if url.lastPathComponent == processName { return ProcInfo(pid: pid, path: path) } } return nil } }
24.077922
108
0.551241
4aa1b3537cc73ee01ac12166b18f3f242de66254
594
// // NavigatorFlowHeader.swift // Navigator_Example // // Created by liuxc on 2019/7/3. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import UIKit class NavigatorFlowHeader: UICollectionReusableView { lazy var sceneNameLabel: UILabel = { let label = UILabel(frame: self.bounds) label.textAlignment = .left label.textColor = .black label.backgroundColor = .white label.numberOfLines = 0 label.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.addSubview(label) return label }() }
23.76
66
0.670034
f4fbd610851a12ccefab26c130b2909c5ce974f6
438
// // Glider // Fast, Lightweight yet powerful logging system for Swift. // // Created by Daniele Margutti // Email: [email protected] // Web: http://www.danielemargutti.com // // Copyright ©2021 Daniele Margutti. All rights reserved. // Licensed under MIT License. // import Foundation /// A generic recordable data. public protocol LoggableRecord { /// Level of the log. var level: LogLevel { get } }
19.909091
60
0.682648
1ce475397d01a8df466fd4c1347ab93200ad22cd
2,361
/// Copyright (c) 2022 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import SwiftUI struct ContentView: View { var body: some View { ZStack { Color.teal .ignoresSafeArea() Image("ozma") .resizable() .scaledToFit() .frame(width: 250) .clipShape(Circle()) .overlay { Circle() .stroke(lineWidth: 8) .foregroundColor(.white) } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
39.35
83
0.715375
6a7c342771af7ecbe76266f55e8f7320767bc368
3,180
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // 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 public class FeedParser: NSObject, XMLParserDelegate { public typealias ParseCallback = (([ASEntry]?, ParseError?)->(Void)) public typealias Attrs = [String : String] static let AtomNS = "http://www.w3.org/2005/Atom" static let StatusNetNS = "http://status.net/schema/api/1/" static let PoCoNS = "http://portablecontacts.net/spec/1.0" static let ActivityStreamNS = "http://activitystrea.ms/spec/1.0/" static let OStatusNS = "http://ostatus.org/schema/1.0" static let ThreadNS = "http://purl.org/syndication/thread/1.0" var parser: XMLParser? var callback: ParseCallback? var parsedEntries: [ASEntry] = [] var childParser: NSObject? // strong reference so it doesn't get dealloced public func parseEntries(data: Data, callback: @escaping ParseCallback) { parsedEntries = [] self.callback = callback parser = XMLParser(data: data) if let p = parser { self.parser = p p.delegate = self p.shouldProcessNamespaces = true p.shouldReportNamespacePrefixes = false p.shouldResolveExternalEntities = false p.parse() } else { callback(nil, ParseError(reason: "Could not make parser")) } } public func parserDidStartDocument(_ parser: XMLParser) { } public func parserDidEndDocument(_ parser: XMLParser) { callback?(parsedEntries, nil) } public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { if namespaceURI == FeedParser.AtomNS && elementName == "entry" { let entryParser = EntryParser(parser: parser, namespace: FeedParser.AtomNS, tagName: "entry", attrs: attributeDict) { entry in if let e = entry { self.parsedEntries.append(e) } self.parser?.delegate = self } childParser = entryParser self.parser?.delegate = entryParser // let it take over for now } } static func dateFromTimestamp(string: String?) -> Date? { guard let string = string else { return nil } // Put this in its own function in case we need to tweak later // Hopefully ISO8601 will cover everything we need let formatter = ISO8601DateFormatter() return formatter.date(from: string) } }
39.75
186
0.647799
8afbdaa9a8fa10e3689798727de1d41d61ac838d
2,567
// // ISOValue+SonyPTPPropValueConvertible.swift // Rocc // // Created by Simon Mitchell on 08/11/2019. // Copyright © 2019 Simon Mitchell. All rights reserved. // import Foundation extension ISO.Value: SonyPTPPropValueConvertable { var type: PTP.DeviceProperty.DataType { return .uint32 } var code: PTP.DeviceProperty.Code { return .ISO } init?(sonyValue: PTPDevicePropertyDataType) { guard let binaryInt = sonyValue.toInt else { return nil } switch binaryInt { case 0x00ffffff: self = .auto case 0x01ffffff: self = .multiFrameNRAuto case 0x02ffffff: self = .multiFrameNRHiAuto default: var buffer = ByteBuffer() buffer.append(DWord(binaryInt)) guard let value = buffer[word: 0] else { return nil } guard let type = buffer[word: 2] else { self = .native(Int(value)) return } switch type { case 0x0000: self = .native(Int(value)) case 0x1000: self = .extended(Int(value)) case 0x0100: self = .multiFrameNR(Int(value)) case 0x0200: self = .multiFrameNRHi(Int(value)) default: self = .native(Int(value)) } } } var sonyPTPValue: PTPDevicePropertyDataType { switch self { case .auto: return DWord(0x00ffffff) case .multiFrameNRAuto: return DWord(0x01ffffff) case .multiFrameNRHiAuto: return DWord(0x02ffffff) case .extended(let value): var data = ByteBuffer() data.append(Word(value)) data.append(Word(0x1000)) return data[dWord: 0] ?? DWord(value) case .native(let value): var data = ByteBuffer() data.append(Word(value)) data.append(Word(0x0000)) return data[dWord: 0] ?? DWord(value) case .multiFrameNR(let value): var data = ByteBuffer() data.append(Word(value)) data.append(Word(0x0100)) return data[dWord: 0] ?? DWord(value) case .multiFrameNRHi(let value): var data = ByteBuffer() data.append(Word(value)) data.append(Word(0x0200)) return data[dWord: 0] ?? DWord(value) } } }
28.522222
57
0.518504
0a73c9d6fd4a246cdae0f99ea3ae5415da95a95e
732
// // HeadlinesInteractor.swift // MacaWarta // // Created by Prima Santosa on 08/11/20. // import Foundation import Combine protocol HeadlinesUseCase { func getHeadlines( in country: String, page: Int, isConnected: Bool ) -> AnyPublisher<(articles: [ArticleModel], canLoadMore: Bool), Error> } class HeadlinesInteractor: HeadlinesUseCase { private var repository: WartaRepository init(repository: WartaRepository) { self.repository = repository } func getHeadlines( in country: String, page: Int, isConnected: Bool ) -> AnyPublisher<(articles: [ArticleModel], canLoadMore: Bool), Error> { return repository.getHeadlines(in: country, page: page, isConnected: isConnected) } }
21.529412
85
0.710383