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
564be8d8c7b10b64c79f1338294e098df9a49354
1,275
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/Foo.swiftmodule -emit-abi-descriptor-path %t/abi.json %S/Inputs/ConstExtraction/SimpleReferences.swift // RUN: %api-digester -deserialize-sdk -input-paths %t/abi.json -o %t.result // RUN: %FileCheck %s < %t/abi.json // CHECK: "offset": 249, // CHECK-NEXT: "length": 10, // CHECK-NEXT: "value": "\"abc\"", // CHECK-NEXT: "decl": "global_str" // CHECK: "kind": "IntegerLiteral", // CHECK-NEXT: "offset": 266, // CHECK-NEXT: "length": 10, // CHECK-NEXT: "value": "3", // CHECK-NEXT: "decl": "global_int" // CHECK: "kind": "FloatLiteral", // CHECK-NEXT: "offset": 283, // CHECK-NEXT: "length": 12, // CHECK-NEXT: "value": "3.2", // CHECK-NEXT: "decl": "global_float" // CHECK: "kind": "BooleanLiteral", // CHECK-NEXT: "offset": 302, // CHECK-NEXT: "length": 12, // CHECK-NEXT: "value": "false", // CHECK-NEXT: "decl": "class_bool" // CHECK: "kind": "Array", // CHECK-NEXT: "offset": 321, // CHECK-NEXT: "length": 11, // CHECK-NEXT: "value": "[2, 2, 3]", // CHECK-NEXT: "decl": "class_arr" // CHECK: "kind": "Dictionary", // CHECK-NEXT: "offset": 339, // CHECK-NEXT: "length": 12, // CHECK-NEXT: "value": "[(2, 1), (2, 1), (3, 1)]", // CHECK-NEXT: "decl": "class_dict"
30.357143
152
0.597647
1e44ed1f08032fcc9a207b5597f55228366356ef
322
// // ResponseDeserializer.swift // DRNet // // Created by Dariusz Rybicki on 02/11/14. // Copyright (c) 2014 Darrarski. All rights reserved. // import Foundation public protocol ResponseDeserializer { func deserializeResponseData(response: Response) -> (deserializedData: AnyObject?, errors: [NSError]?) }
21.466667
106
0.720497
0eb09d10aec343501b504470d48a2411b930a271
507
// // Enums.swift // Pirate Fleet // // Created by Jarrod Parkes on 8/26/15. // Copyright © 2015 Udacity. All rights reserved. // // MARK: - PlayerType enum PlayerType { case human, computer } // MARK: - ShipPieceOrientation enum ShipPieceOrientation { case endUp, endDown, endLeft, endRight, bodyVert, bodyHorz } // MARK: - Difficulty enum Difficulty: Int { case basic = 0, advanced } // MARK: - ShipSize enum ShipSize: Int { case small = 2, medium = 3, large = 4, xLarge = 5 }
15.84375
62
0.654832
08a075cd303c8723095919e6624fed5e143b1400
1,363
//Copyright (c) 2017 pikachu987 <[email protected]> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import UIKit public class PKCCrop: NSObject { public func cropViewController(_ image: UIImage, tag: Int = 0) -> PKCCropViewController{ let pkcCropVC = PKCCropViewController(image, tag: tag) return pkcCropVC } }
37.861111
92
0.757887
0339115c8a6df9c1ff7b70b625a1d646b86a357f
14,856
// // OfferEditTableViewController.swift // nextStudents // // Copyright © 2020 Tim Kohlstadt, Benedict Zendel. All rights reserved. // import UIKit import Firebase import FirebaseFirestore import ImagePicker class OfferEditTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate { // MARK: - Variables var pickerData = [["5", "10", "15", "30", "60"], ["1", "2", "3", "4", "5", "10", "15", "20", "24"], ["Min.", "Std."]] var pickerDataShown = [String]() var currentOffer: Offer? var imageViews = [UIImageView]() var deletedImages = [String]() var addedImages = [UIImageView]() // MARK: - IBOutlets @IBOutlet weak var offerNeedControl: UISegmentedControl! @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var descriptionTextField: UITextField! @IBOutlet weak var timePickerView: UIPickerView! @IBOutlet weak var createBarButtonItem: UIBarButtonItem! @IBOutlet weak var cancelBarButtonItem: UIBarButtonItem! @IBOutlet weak var deleteOfferCell: UITableViewCell! @IBOutlet weak var newOfferImageView: UIImageView! @IBOutlet weak var imageScrollView: UIScrollView! // MARK: - UIViewController events override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Must be set for func textFieldShouldReturn() titleTextField.delegate = self descriptionTextField.delegate = self if currentOffer != nil { titleTextField.text = currentOffer!.title createBarButtonItem.title = "Speichern" navigationItem.title = currentOffer!.title offerNeedControl.selectedSegmentIndex = currentOffer!.type == "Biete" ? 0 : 1 descriptionTextField.text = currentOffer!.description timePickerView.selectRow(pickerData[2].firstIndex(of: currentOffer!.timeFormat)!, inComponent: 1, animated: true) self.pickerView(self.timePickerView, didSelectRow: pickerData[2].firstIndex(of: currentOffer!.timeFormat)!, inComponent: 1) timePickerView.selectRow(pickerDataShown.firstIndex(of: currentOffer!.duration)!, inComponent: 0, animated: true) deleteOfferCell.isHidden = false MainController.dataService.getOfferPicturesReferences(for: currentOffer!.uid, completion: { references in for reference in references { MainController.dataService.getOfferPicture(from: reference, completion: { image in let newView = UIImageView(image: image) newView.accessibilityIdentifier = reference.name newView.frame.size.width = 115 newView.frame.size.height = 106 newView.contentMode = .scaleAspectFit let tapGesture = UITapGestureRecognizer(target: self, action: #selector(OfferEditTableViewController.imageTappedDelete(gesture:))) newView.addGestureRecognizer(tapGesture) newView.isUserInteractionEnabled = true self.imageViews.insert(newView, at: 0) self.imageScrollView.insertSubview(newView, at: 0) self.imageScrollView.contentSize.width = self.imageScrollView.frame.size.width + CGFloat(self.imageViews.count - 1) * self.newOfferImageView.frame.size.width + CGFloat(self.imageViews.count - 1) * 5.0 self.layoutImages(animated: false) }) } }) } } override func viewDidLoad() { super.viewDidLoad() timePickerView.delegate = self timePickerView.dataSource = self let tapGesture = UITapGestureRecognizer(target: self, action: #selector(OfferEditTableViewController.imageTapped(gesture:))) // Add it to the image view newOfferImageView.addGestureRecognizer(tapGesture) // Make sure imageView can be interacted with by user newOfferImageView.isUserInteractionEnabled = true } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return pickerDataShown.count } else { return pickerData[2].count } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return pickerDataShown[row] } else { return pickerData[2][row] } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 1 { pickerDataShown = pickerData[pickerView.selectedRow(inComponent: component)] pickerView.reloadComponent(0) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { switch identifier { case "backToOffers": let vc = segue.destination as! OffersTableViewController if vc.allOffers.count > OffersTableViewController.offersArray.count { vc.allOffers = OffersTableViewController.offersArray } default: break } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 6 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } @IBAction func touchCancel(_ sender: UIBarButtonItem) { performSegue(withIdentifier: "backToOffers", sender: nil) } @IBAction func touchDelete(_ sender: UIButton) { let alert = UIAlertController( title: "Wollen Sie das Angebot wirklich löschen?", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction( title: "Ja", style: .default, handler: { (UIAlertAction) in MainController.dataService.deleteOffer(for: self.currentOffer!.uid) // Remove Offer object from array if let existingOffer = OffersTableViewController.offersArray.firstIndex(where: { $0.uid == self.currentOffer!.uid }) { OffersTableViewController.offersArray.remove(at: existingOffer) } self.performSegue(withIdentifier: "backToOffers", sender: nil) })) alert.addAction(UIAlertAction( title: "Abbrechen", style: .default, handler: nil)) self.present(alert, animated: true) } // MARK: - Methods @objc func imageTapped(gesture: UIGestureRecognizer) { // If the tapped view is a UIImageView then set it to imageview if (gesture.view as? UIImageView) != nil { let pickerController = ImagePickerController() pickerController.delegate = self present(pickerController, animated: true, completion: nil) } } @objc func imageTappedDelete(gesture: UIGestureRecognizer) { // If the tapped view is a UIImageView then set it to imageview if let gestureView = gesture.view as? UIImageView { if let index = imageViews.firstIndex(of: gestureView) { let deletedView = imageViews.remove(at: index) deletedView.removeFromSuperview() layoutImages(animated: true) if let identifier = deletedView.accessibilityIdentifier { deletedImages.append(identifier) } } if let index = addedImages.firstIndex(of: gestureView) { addedImages.remove(at: index) } } } private func layoutImages(animated: Bool) { var latestView = newOfferImageView for view in imageViews { let newX = latestView!.frame.origin.x + latestView!.frame.size.width + 5.0 let newY: CGFloat = imageScrollView.frame.origin.y + (imageScrollView.frame.size.height - view.frame.size.height) / 2 if animated { UIView.animate(withDuration: 0.5) { view.frame.origin = CGPoint(x: newX, y: newY) } } else { view.frame.origin = CGPoint(x: newX, y: newY) } latestView = view } } @IBAction func touchCreate(_ sender: UIBarButtonItem) { if titleTextField.text != nil && titleTextField.text != "" && descriptionTextField.text != nil && descriptionTextField.text != "" { // Show an animated waiting circle let indicatorView = self.activityIndicator(style: .medium, center: self.view.center) self.view.addSubview(indicatorView) indicatorView.startAnimating() if currentOffer != nil { saveOffer() } else { createOffer() } self.performSegue(withIdentifier: "backToOffers", sender: nil) } else { let alert = Utility.displayAlert(withTitle: "Fehler", withMessage: "Titel und Beschreibung müssen ausgefüllt sein.", withSignOut: false) self.present(alert, animated: true, completion: nil) } } private func createOffer() { let dict: [String: Any] = [ "date": Timestamp(), "title": titleTextField.text!, "type": offerNeedControl.titleForSegment(at: offerNeedControl.selectedSegmentIndex)!, "description": descriptionTextField.text!, "duration": pickerDataShown[timePickerView.selectedRow(inComponent: 0)], "timeFormat" : pickerData[2][timePickerView.selectedRow(inComponent: 1)] ] MainController.dataService.createOffer(with: dict, completion: { newOfferId in if let newOfferId = newOfferId { self.uploadImages(images: self.addedImages, for: newOfferId) } }) } private func saveOffer() { let dict: [String: Any] = [ "title": titleTextField.text ?? "", "type": offerNeedControl.titleForSegment(at: offerNeedControl.selectedSegmentIndex)!, "description": descriptionTextField.text ?? "", "duration": pickerDataShown[timePickerView.selectedRow(inComponent: 0)], "timeFormat" : pickerData[2][timePickerView.selectedRow(inComponent: 1)] ] MainController.dataService.updateOffer(with: dict, offerID: currentOffer!.uid) if !deletedImages.isEmpty { for imageID in deletedImages { MainController.dataService.deleteOfferPicture(for: currentOffer!.uid, imageID: imageID) } } self.uploadImages(images: self.addedImages, for: currentOffer!.uid) } private func uploadImages(currentOfferUID: String) { uploadImages(images: imageViews, for: currentOfferUID) } private func uploadImages(images: [UIImageView], for offerID: String) { if images.count > 0 { for view in images { if let image = view.image { MainController.dataService.uploadOfferPicture(image: image, offerID: offerID, completion: { // Don't go back to the offers TableView until the new image has been completely uploaded self.performSegue(withIdentifier: "backToOffers", sender: nil) }) } } } else { // Perform segue without having to wait for an image to be uploaded self.performSegue(withIdentifier: "backToOffers", sender: nil) } } private func activityIndicator(style: UIActivityIndicatorView.Style = .medium, frame: CGRect? = nil, center: CGPoint? = nil) -> UIActivityIndicatorView { let activityIndicatorView = UIActivityIndicatorView(style: style) if let frame = frame { activityIndicatorView.frame = frame } if let center = center { activityIndicatorView.center = center } return activityIndicatorView } // This function is called when you click return key in the text field. func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Resign the first responder from textField to close the keyboard. textField.resignFirstResponder() return true } } // MARK: - Extensions extension OfferEditTableViewController: ImagePickerDelegate { func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {} func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) { var latestView = newOfferImageView for image in images { let newView = UIImageView(image: image) newView.frame.size.width = 115 newView.frame.size.height = 106 newView.contentMode = .scaleAspectFit imageScrollView.insertSubview(newView, at: 0) latestView = newView let tapGesture = UITapGestureRecognizer(target: self, action: #selector(OfferEditTableViewController.imageTappedDelete(gesture:))) latestView!.addGestureRecognizer(tapGesture) latestView!.isUserInteractionEnabled = true imageViews.insert(latestView!, at: 0) addedImages.append(latestView!) } imageScrollView.contentSize.width = imageScrollView.frame.size.width + CGFloat(imageViews.count - 1) * newOfferImageView.frame.size.width + CGFloat(imageViews.count - 1) * 5.0 layoutImages(animated: true) presentedViewController?.dismiss(animated: true, completion: nil) } func cancelButtonDidPress(_ imagePicker: ImagePickerController) { presentedViewController?.dismiss(animated: true, completion: nil) } }
40.813187
154
0.597604
f82e5c14a98a4277b827da9572798be713f79643
362
// // CoursePlayer.swift // PPPlayer_Example // // Created by 王小涛 on 2019/2/20. // Copyright © 2019 CocoaPods. All rights reserved. // import RxSwift struct PBCourse {} class CoursePlayer { // // var course = PublishSubject<PBCourse>() // // private let items: [Pla] // // init() { // course.subscribe(onNext: { // // }) // } }
13.923077
52
0.582873
e449fd0130c688011b7814418040a23188002962
495
// // AppDelegate.swift // Gemini // // Created by Vitaliy Malakhovskiy on 7/10/16. // Copyright © 2016 Vitalii Malakhovskyi. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! let viewController = ViewControllerFactory.defaultViewController() func applicationDidFinishLaunching(aNotification: NSNotification) { window.contentView?.addSubview(viewController.view) } }
23.571429
71
0.751515
f55dd5f466ca477d73808f3fb2d3a3e2b21cd3ce
7,423
//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import RxSwift import RxCocoa import Then import RxFeedback import RxGesture import EventBlankKit class SessionDetailsCell: UITableViewCell, ClassIdentifier { @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var twitterLabel: UILabel! @IBOutlet weak var websiteLabel: UILabel! @IBOutlet weak var btnToggleIsFavorite: UIButton! @IBOutlet weak var descriptionTextView: UITextView! @IBOutlet weak var sessionTitleLabel: UITextView! @IBOutlet weak var trackTitleLabel: UILabel! private var reuseBag = DisposeBag() private var viewModel: SessionDetailsCellViewModel! { didSet { populateFromViewModel() } } enum Event { case openPhoto, openTwitter, openWebsite, refresh case setIsFavorite(Bool) } static func createWith(_ dataSource: SectionedViewDataSourceType, tableView: UITableView, index: IndexPath, session: Session) -> SessionDetailsCell { return tableView.dequeueReusableCell(SessionDetailsCell.self).then { cell in cell.reuseBag = DisposeBag() cell.viewModel = SessionDetailsCellViewModel(session: session) cell.willAppear() } } override func awakeFromNib() { super.awakeFromNib() btnToggleIsFavorite.setImage(UIImage(named: "like-full")?.withRenderingMode(.alwaysTemplate), for: .selected) descriptionTextView.delegate = self } private func willAppear() { Observable<Any>.system( initialState: viewModel, reduce: updateState, scheduler: MainScheduler.instance, scheduledFeedback: bindUI) .subscribe() .disposed(by: reuseBag) //activate model viewModel.activate() } private func updateState(state: SessionDetailsCellViewModel, event: Event) -> SessionDetailsCellViewModel { switch event { case .openPhoto: showPhoto?() case .openTwitter: openTwitter() case .openWebsite: if let website = viewModel.session.speaker?.url, let websiteURL = URL(string: website) { openWebsite?(websiteURL) } case .refresh: populateFromViewModel() case .setIsFavorite(let isFavorite): viewModel.updateIsFavorite(isFavorite: isFavorite) btnToggleIsFavorite.animateSelect(scale: 0.8, completion: nil) _ = Notifications.toggleNotification(for: viewModel.session, on: isFavorite) .subscribe(onError: { print($0) }) } return state } private var bindUI: ((RxFeedback.ObservableSchedulerContext<SessionDetailsCellViewModel>) -> Observable<Event>) { return RxFeedback.bind(self) { this, state in let subscriptions = [ // favorite button this.viewModel.isFavorite .bind(to: this.btnToggleIsFavorite.rx.isSelected) ] let events = [ // tap image this.userImage.rx.tapGesture() .when(.recognized) .map { _ in Event.openPhoto }, // tap twitter button this.twitterLabel.rx.tapGesture() .when(.recognized) .map { _ in Event.openTwitter }, // tap website button this.websiteLabel.rx.tapGesture() .when(.recognized) .map { _ in Event.openWebsite }, // refresh cell data Observable.from(object: this.viewModel.session) .map { _ in Event.refresh }, //bind UI this.viewModel.isFavorite .sample(this.btnToggleIsFavorite.rx.tap) .map { isFavorite in Event.setIsFavorite(!isFavorite) } ] return RxFeedback.Bindings(subscriptions: subscriptions, events: events) } } func populateFromViewModel() { let session = viewModel.session nameLabel.text = session.speaker?.name let time = shortStyleDateFormatter.string(from: session.date) var textAttributes = [NSAttributedStringKey: Any]() textAttributes[NSAttributedStringKey.font] = UIFont.systemFont(ofSize: 22) sessionTitleLabel.attributedText = NSAttributedString( string: "\(time) \(session.title)\n", attributes: textAttributes) trackTitleLabel.text = (session.track?.track ?? "") + "\n" if let twitter = session.speaker?.twitter, !twitter.isEmpty { twitterLabel.text = twitter.hasPrefix("@") ? twitter : "@"+twitter } else { twitterLabel.text = nil } websiteLabel.text = session.speaker?.url //only way to force textview autosizing I found descriptionTextView.text = session.sessionDescription + "\n\n" if let photoUrl = session.speaker?.photoUrl, let url = URL(string: photoUrl) { let size = userImage.bounds.size userImage.kf.indicatorType = .activity userImage.kf.setImage(with: url, placeholder: nil, options: [.transition(.fade(0.1))], completionHandler: { [weak self] (image, error, cacheType, imageUrl) in guard let image = image else { return } self?.showPhoto = { PhotoPopupView.showImage(image, inView: UIApplication.shared.windows.first!) } image.asyncToSize(.fillSize(size), cornerRadius: size.width/2, completion: { result in self?.userImage.image = result }) }) } //theme let event = EventData.default(in: RealmProvider.event) sessionTitleLabel.textColor = event.mainColor trackTitleLabel.textColor = event.mainColor.lighter(amount: 0.1).desaturated() //check if in the past if Date().compare(.isLater(than: session.date)) { sessionTitleLabel.textColor = sessionTitleLabel.textColor?.desaturated(amount: 0.5).lighter() trackTitleLabel.textColor = sessionTitleLabel.textColor } } private var showPhoto: (()->Void)? var openWebsite: ((URL)->Void)? func openTwitter() { if let twitter = viewModel.session.speaker?.twitter { openWebsite?(twitterUrl(twitter)) } } } extension SessionDetailsCell { func textView(_ textView: UITextView, shouldInteractWithURL URL: Foundation.URL, inRange characterRange: NSRange) -> Bool { openWebsite?(URL) return false } }
36.566502
170
0.612556
ffbbb2dc67098cdeefb84cf2ee79ded61e03011c
12,724
// Generated by Lona Compiler 0.6.0 import AppKit import Foundation // MARK: - ImageWithBackgroundColor private class ImageWithBackgroundColor: LNAImageView { var fillColor = NSColor.clear override func draw(_ dirtyRect: NSRect) { fillColor.set() bounds.fill() super.draw(dirtyRect) } } // MARK: - PrimaryAxisFillSiblings public class PrimaryAxisFillSiblings: NSBox { // MARK: Lifecycle public init(_ parameters: Parameters) { self.parameters = parameters super.init(frame: .zero) setUpViews() setUpConstraints() update() } public convenience init() { self.init(Parameters()) } public required init?(coder aDecoder: NSCoder) { self.parameters = Parameters() super.init(coder: aDecoder) setUpViews() setUpConstraints() update() } // MARK: Public public var parameters: Parameters { didSet { if parameters != oldValue { update() } } } // MARK: Private private var horizontalView = NSBox() private var leftCardView = NSBox() private var imageView = ImageWithBackgroundColor() private var titleView = LNATextField(labelWithString: "") private var subtitleView = LNATextField(labelWithString: "") private var spacerView = NSBox() private var rightCardView = NSBox() private var image1View = ImageWithBackgroundColor() private var title1View = LNATextField(labelWithString: "") private var subtitle1View = LNATextField(labelWithString: "") private var titleViewTextStyle = TextStyles.body2 private var subtitleViewTextStyle = TextStyles.body1 private var title1ViewTextStyle = TextStyles.body2 private var subtitle1ViewTextStyle = TextStyles.body1 private func setUpViews() { boxType = .custom borderType = .noBorder contentViewMargins = .zero horizontalView.boxType = .custom horizontalView.borderType = .noBorder horizontalView.contentViewMargins = .zero leftCardView.boxType = .custom leftCardView.borderType = .noBorder leftCardView.contentViewMargins = .zero spacerView.boxType = .custom spacerView.borderType = .noBorder spacerView.contentViewMargins = .zero rightCardView.boxType = .custom rightCardView.borderType = .noBorder rightCardView.contentViewMargins = .zero titleView.lineBreakMode = .byWordWrapping subtitleView.lineBreakMode = .byWordWrapping title1View.lineBreakMode = .byWordWrapping subtitle1View.lineBreakMode = .byWordWrapping addSubview(horizontalView) horizontalView.addSubview(leftCardView) horizontalView.addSubview(spacerView) horizontalView.addSubview(rightCardView) leftCardView.addSubview(imageView) leftCardView.addSubview(titleView) leftCardView.addSubview(subtitleView) rightCardView.addSubview(image1View) rightCardView.addSubview(title1View) rightCardView.addSubview(subtitle1View) fillColor = Colors.teal50 horizontalView.fillColor = Colors.teal100 imageView.image = #imageLiteral(resourceName: "icon_128x128") imageView.fillColor = Colors.teal200 titleView.attributedStringValue = titleViewTextStyle.apply(to: "Title") titleViewTextStyle = TextStyles.body2 titleView.attributedStringValue = titleViewTextStyle.apply(to: titleView.attributedStringValue) subtitleView.attributedStringValue = subtitleViewTextStyle.apply(to: "Subtitle") subtitleViewTextStyle = TextStyles.body1 subtitleView.attributedStringValue = subtitleViewTextStyle.apply(to: subtitleView.attributedStringValue) spacerView.fillColor = #colorLiteral(red: 0.847058823529, green: 0.847058823529, blue: 0.847058823529, alpha: 1) image1View.image = #imageLiteral(resourceName: "icon_128x128") image1View.fillColor = Colors.teal200 title1View.attributedStringValue = title1ViewTextStyle.apply(to: "Title") title1ViewTextStyle = TextStyles.body2 title1View.attributedStringValue = title1ViewTextStyle.apply(to: title1View.attributedStringValue) subtitle1View.attributedStringValue = subtitle1ViewTextStyle.apply(to: "Subtitle") subtitle1ViewTextStyle = TextStyles.body1 subtitle1View.attributedStringValue = subtitle1ViewTextStyle.apply(to: subtitle1View.attributedStringValue) } private func setUpConstraints() { translatesAutoresizingMaskIntoConstraints = false horizontalView.translatesAutoresizingMaskIntoConstraints = false leftCardView.translatesAutoresizingMaskIntoConstraints = false spacerView.translatesAutoresizingMaskIntoConstraints = false rightCardView.translatesAutoresizingMaskIntoConstraints = false imageView.translatesAutoresizingMaskIntoConstraints = false titleView.translatesAutoresizingMaskIntoConstraints = false subtitleView.translatesAutoresizingMaskIntoConstraints = false image1View.translatesAutoresizingMaskIntoConstraints = false title1View.translatesAutoresizingMaskIntoConstraints = false subtitle1View.translatesAutoresizingMaskIntoConstraints = false let horizontalViewTopAnchorConstraint = horizontalView.topAnchor.constraint(equalTo: topAnchor, constant: 10) let horizontalViewBottomAnchorConstraint = horizontalView .bottomAnchor .constraint(equalTo: bottomAnchor, constant: -10) let horizontalViewLeadingAnchorConstraint = horizontalView .leadingAnchor .constraint(equalTo: leadingAnchor, constant: 10) let horizontalViewTrailingAnchorConstraint = horizontalView .trailingAnchor .constraint(equalTo: trailingAnchor, constant: -10) let leftCardViewRightCardViewWidthAnchorSiblingConstraint = leftCardView .widthAnchor .constraint(equalTo: rightCardView.widthAnchor) let leftCardViewHeightAnchorParentConstraint = leftCardView .heightAnchor .constraint(lessThanOrEqualTo: horizontalView.heightAnchor) let spacerViewHeightAnchorParentConstraint = spacerView .heightAnchor .constraint(lessThanOrEqualTo: horizontalView.heightAnchor) let rightCardViewHeightAnchorParentConstraint = rightCardView .heightAnchor .constraint(lessThanOrEqualTo: horizontalView.heightAnchor) let leftCardViewLeadingAnchorConstraint = leftCardView .leadingAnchor .constraint(equalTo: horizontalView.leadingAnchor) let leftCardViewTopAnchorConstraint = leftCardView.topAnchor.constraint(equalTo: horizontalView.topAnchor) let leftCardViewBottomAnchorConstraint = leftCardView.bottomAnchor.constraint(equalTo: horizontalView.bottomAnchor) let spacerViewLeadingAnchorConstraint = spacerView.leadingAnchor.constraint(equalTo: leftCardView.trailingAnchor) let spacerViewTopAnchorConstraint = spacerView.topAnchor.constraint(equalTo: horizontalView.topAnchor) let rightCardViewTrailingAnchorConstraint = rightCardView .trailingAnchor .constraint(equalTo: horizontalView.trailingAnchor) let rightCardViewLeadingAnchorConstraint = rightCardView .leadingAnchor .constraint(equalTo: spacerView.trailingAnchor) let rightCardViewTopAnchorConstraint = rightCardView.topAnchor.constraint(equalTo: horizontalView.topAnchor) let rightCardViewBottomAnchorConstraint = rightCardView .bottomAnchor .constraint(equalTo: horizontalView.bottomAnchor) let imageViewTopAnchorConstraint = imageView.topAnchor.constraint(equalTo: leftCardView.topAnchor) let imageViewLeadingAnchorConstraint = imageView.leadingAnchor.constraint(equalTo: leftCardView.leadingAnchor) let imageViewTrailingAnchorConstraint = imageView.trailingAnchor.constraint(equalTo: leftCardView.trailingAnchor) let titleViewTopAnchorConstraint = titleView.topAnchor.constraint(equalTo: imageView.bottomAnchor) let titleViewLeadingAnchorConstraint = titleView.leadingAnchor.constraint(equalTo: leftCardView.leadingAnchor) let titleViewTrailingAnchorConstraint = titleView.trailingAnchor.constraint(equalTo: leftCardView.trailingAnchor) let subtitleViewBottomAnchorConstraint = subtitleView.bottomAnchor.constraint(equalTo: leftCardView.bottomAnchor) let subtitleViewTopAnchorConstraint = subtitleView.topAnchor.constraint(equalTo: titleView.bottomAnchor) let subtitleViewLeadingAnchorConstraint = subtitleView.leadingAnchor.constraint(equalTo: leftCardView.leadingAnchor) let subtitleViewTrailingAnchorConstraint = subtitleView .trailingAnchor .constraint(equalTo: leftCardView.trailingAnchor) let spacerViewHeightAnchorConstraint = spacerView.heightAnchor.constraint(equalToConstant: 0) let spacerViewWidthAnchorConstraint = spacerView.widthAnchor.constraint(equalToConstant: 8) let image1ViewTopAnchorConstraint = image1View.topAnchor.constraint(equalTo: rightCardView.topAnchor) let image1ViewLeadingAnchorConstraint = image1View.leadingAnchor.constraint(equalTo: rightCardView.leadingAnchor) let image1ViewTrailingAnchorConstraint = image1View.trailingAnchor.constraint(equalTo: rightCardView.trailingAnchor) let title1ViewTopAnchorConstraint = title1View.topAnchor.constraint(equalTo: image1View.bottomAnchor) let title1ViewLeadingAnchorConstraint = title1View.leadingAnchor.constraint(equalTo: rightCardView.leadingAnchor) let title1ViewTrailingAnchorConstraint = title1View.trailingAnchor.constraint(equalTo: rightCardView.trailingAnchor) let subtitle1ViewBottomAnchorConstraint = subtitle1View.bottomAnchor.constraint(equalTo: rightCardView.bottomAnchor) let subtitle1ViewTopAnchorConstraint = subtitle1View.topAnchor.constraint(equalTo: title1View.bottomAnchor) let subtitle1ViewLeadingAnchorConstraint = subtitle1View .leadingAnchor .constraint(equalTo: rightCardView.leadingAnchor) let subtitle1ViewTrailingAnchorConstraint = subtitle1View .trailingAnchor .constraint(equalTo: rightCardView.trailingAnchor) let imageViewHeightAnchorConstraint = imageView.heightAnchor.constraint(equalToConstant: 100) let image1ViewHeightAnchorConstraint = image1View.heightAnchor.constraint(equalToConstant: 100) leftCardViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow spacerViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow rightCardViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow NSLayoutConstraint.activate([ horizontalViewTopAnchorConstraint, horizontalViewBottomAnchorConstraint, horizontalViewLeadingAnchorConstraint, horizontalViewTrailingAnchorConstraint, leftCardViewRightCardViewWidthAnchorSiblingConstraint, leftCardViewHeightAnchorParentConstraint, spacerViewHeightAnchorParentConstraint, rightCardViewHeightAnchorParentConstraint, leftCardViewLeadingAnchorConstraint, leftCardViewTopAnchorConstraint, leftCardViewBottomAnchorConstraint, spacerViewLeadingAnchorConstraint, spacerViewTopAnchorConstraint, rightCardViewTrailingAnchorConstraint, rightCardViewLeadingAnchorConstraint, rightCardViewTopAnchorConstraint, rightCardViewBottomAnchorConstraint, imageViewTopAnchorConstraint, imageViewLeadingAnchorConstraint, imageViewTrailingAnchorConstraint, titleViewTopAnchorConstraint, titleViewLeadingAnchorConstraint, titleViewTrailingAnchorConstraint, subtitleViewBottomAnchorConstraint, subtitleViewTopAnchorConstraint, subtitleViewLeadingAnchorConstraint, subtitleViewTrailingAnchorConstraint, spacerViewHeightAnchorConstraint, spacerViewWidthAnchorConstraint, image1ViewTopAnchorConstraint, image1ViewLeadingAnchorConstraint, image1ViewTrailingAnchorConstraint, title1ViewTopAnchorConstraint, title1ViewLeadingAnchorConstraint, title1ViewTrailingAnchorConstraint, subtitle1ViewBottomAnchorConstraint, subtitle1ViewTopAnchorConstraint, subtitle1ViewLeadingAnchorConstraint, subtitle1ViewTrailingAnchorConstraint, imageViewHeightAnchorConstraint, image1ViewHeightAnchorConstraint ]) } private func update() {} } // MARK: - Parameters extension PrimaryAxisFillSiblings { public struct Parameters: Equatable { public init() {} } } // MARK: - Model extension PrimaryAxisFillSiblings { public struct Model: LonaViewModel, Equatable { public var id: String? public var parameters: Parameters public var type: String { return "PrimaryAxisFillSiblings" } public init(id: String? = nil, parameters: Parameters) { self.id = id self.parameters = parameters } public init(_ parameters: Parameters) { self.parameters = parameters } public init() { self.init(Parameters()) } } }
42.555184
120
0.793933
28282311372eae3b09bda84d4e02205f31ebbe65
699
// // DetailVC.swift // AdvancedTableView // // Created by cemal tüysüz on 19.12.2021. // import UIKit class DetailVC: UIViewController { @IBOutlet weak var productDetailTitle: UILabel! @IBOutlet weak var productDetailımage: UIImageView! @IBOutlet weak var productDetailPrice: UILabel! var product:Product? override func viewDidLoad() { super.viewDidLoad() if let p = product { productDetailTitle.text = p.productName! productDetailımage.image = UIImage(named: p.productImage!) productDetailPrice.text = "\(p.productPrice!)₺" } } @IBAction func addToChart(_ sender: Any) { } }
22.548387
70
0.632332
90b0f4cd4ccf1cc1ac230258c65a350d49987142
1,244
// // SwiftUIView.swift // PasscodeLock // // Created by Devonly on 3/23/21. // Copyright © 2021 Yanko Dimitrov. All rights reserved. // import SwiftUI public struct PasscodeLockView: View, UIViewControllerRepresentable { public typealias LockState = PasscodeLockViewController.LockState @Environment(\.presentationMode) var present @Binding var isSucceed: Bool let type: LockState let configuration: PasscodeLockConfigurationType public init(isSucceed: Binding<Bool>, type: LockState, configuration: PasscodeLockConfigurationType) { self._isSucceed = isSucceed self.type = type self.configuration = configuration } public func makeUIViewController(context: Context) -> PasscodeLockViewController { let uiViewController = PasscodeLockViewController(state: type, configuration: configuration) uiViewController.successCallback = { lock in isSucceed = true } uiViewController.dismissCompletionCallback = { present.wrappedValue.dismiss() } return uiViewController } public func updateUIViewController(_ uiViewController: PasscodeLockViewController, context: Context) { } }
31.1
106
0.70418
46bb15119ef352253146d851630d2c78023e113e
34
print("result: \(promise.result)")
34
34
0.705882
76341714466d4b3e51e8bca7a5f5cb8450bcf5b7
618
// 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 protocol A { func f: a(x: C = B struct q: Collection where B : b<T== "[B, x in x in 0) ->(g: B, AnyObject, U) protocol a { func d<B : b func n<Int) -> String { } import Foundatio: Any, self.f { } protocol b { typealias e: d(m
30.9
78
0.699029
f5a5c191c4010b4f93696539d8be448fc7684856
27,156
// // Tool.swift // Drafter // // Created by Alex Veledzimovich on 11/11/19. // Copyright © 2019 Alex Veledzimovich. All rights reserved. // import Cocoa let tools: [Tool] = [ Drag(), Line(), Triangle(), Rectangle(), Pentagon(), Hexagon(), Star(), Arc(), Oval(), Stylus(), Vector(), Text() ] let toolsKeys: [String: Tool] = [ "m": tools[0], "l": tools[1], "t": tools[2], "r": tools[3], "p": tools[4], "h": tools[5], "s": tools[6], "a": tools[7], "o": tools[8], "d": tools[9], "v": tools[10], "f": tools[11]] protocol Drawable { var tag: Int { get } var name: String { get } func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent?) func move(shift: Bool, fn: Bool) func drag(shift: Bool, fn: Bool) func down(ctrl: Bool) func up(editDone: Bool) } class Tool: Drawable { var tag: Int {-1} var cursor: NSCursor {NSCursor.arrow} static var view: SketchPad? func useTool(_ action: @autoclosure () -> Void) { Tool.view!.editedPath = NSBezierPath() action() if Tool.view!.filledCurve { Tool.view!.editedPath.close() } Tool.view!.editDone = true } func flipSize(topLeft: CGPoint, bottomRight: CGPoint) -> (wid: CGFloat, hei: CGFloat) { return (bottomRight.x - topLeft.x, bottomRight.y - topLeft.y) } func appendStraightCurves(points: [CGPoint]) { Tool.view!.controlPoints = [] Tool.view!.editedPath.move(to: points[0]) for i in 0..<points.count { let pnt = points[i] Tool.view!.controlPoints.append( ControlPoint(Tool.view!, cp1: pnt, cp2: pnt, mp: pnt)) if i == points.count-1 { Tool.view!.editedPath.curve(to: points[0], controlPoint1: points[0], controlPoint2: points[0]) } else { Tool.view!.editedPath.curve(to: points[i+1], controlPoint1: points[i+1], controlPoint2: points[i+1]) } } } var mpPoints: [CGPoint] { return [Tool.view!.startPos] } // MARK: Protocol var name: String {"shape"} func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { } func move(shift: Bool, fn: Bool) { var mpPoints: [CGPoint] = [] if let mp = Tool.view!.movePoint { mpPoints.append(mp.position) } for cp in Tool.view!.controlPoints { mpPoints.append(cp.mp.position) } var mPos = Tool.view!.startPos var snap = CGPoint() if let pos = mpPoints.first, shift { Tool.view!.locationX.isHidden = true Tool.view!.locationY.isHidden = true Tool.view!.startPos = Tool.view!.shiftAngle( topLeft: pos, bottomRight: Tool.view!.startPos) mPos = pos Tool.view!.setLabel(key: "x", pos: mPos, dist: Tool.view!.startPos.magnitude( origin: mPos)) Tool.view!.rulers.appendCustomRule(move: mPos, line: Tool.view!.startPos) } else { snap = Tool.view!.snapToRulers(points: [Tool.view!.startPos], curves: Tool.view!.curves, curvePoints: mpPoints, fn: fn) } Tool.view!.startPos.x -= snap.x Tool.view!.startPos.y -= snap.y Tool.view!.snapMouseToRulers(snap: snap, pos: Tool.view!.startPos) if let mp = Tool.view!.movePoint, let cp1 = Tool.view!.controlPoint1 { Tool.view!.moveCurvedPath(move: mp.position, to: Tool.view!.startPos, cp1: mp.position, cp2: cp1.position) } } func drag(shift: Bool, fn: Bool) { let snap = Tool.view!.snapToRulers( points: [Tool.view!.finPos], curves: Tool.view!.curves, curvePoints: mpPoints, fn: fn) Tool.view!.finPos.x -= snap.x Tool.view!.finPos.y -= snap.y Tool.view!.snapMouseToRulers(snap: snap, pos: Tool.view!.finPos) } func down(ctrl: Bool) { Tool.view!.controlPoints = [] Tool.view!.editedPath.removeAllPoints() } func up(editDone: Bool) { if let curve = Tool.view!.selectedCurve { Tool.view!.clearControls(curve: curve) } else { if Tool.view!.groups.count>1 { Tool.view!.selectedCurve = Tool.view!.groups[0] } } if editDone { Tool.view!.newCurve() } if let curve = Tool.view!.selectedCurve, !curve.canvas.isHidden { curve.reset() Tool.view!.createControls(curve: curve) } } } class Drag: Tool { override var tag: Int {0} override var name: String {"drag"} func action(topLeft: CGPoint, bottomRight: CGPoint) { let size = self.flipSize(topLeft: topLeft, bottomRight: bottomRight) Tool.view!.curvedPath.appendRect(NSRect( x: topLeft.x, y: topLeft.y, width: size.wid, height: size.hei)) if let curve = Tool.view!.selectedCurve, curve.edit { for point in curve.points { if Tool.view!.curvedPath.bounds.contains(point.mp.position) { point.showControlDots( dotMag: Tool.view!.dotMag, lineWidth: Tool.view!.lineWidth) if !curve.controlDots.contains(point) { curve.controlDots.append(point) } } } } else { Tool.view!.groups.removeAll() for cur in Tool.view!.curves where ( !cur.lock && !cur.canvas.isHidden) { let curves = cur.groupRect(curves: cur.groups) if Tool.view!.curvedPath.bounds.contains(curves) && !Tool.view!.groups.contains(cur) { Tool.view!.groups.append(contentsOf: cur.groups) } } for cur in Tool.view!.groups { Tool.view!.curvedPath.append(cur.path) } } } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { Tool.view!.clearPathLayer(layer: Tool.view!.curveLayer, path: Tool.view!.curvedPath) if let curve = Tool.view!.selectedCurve, !curve.edit, !curve.lock { Tool.view!.dragCurve(deltaX: event?.deltaX ?? 0, deltaY: event?.deltaY ?? 0, shift: shift, fn: fn) } else { self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos) } } override func drag(shift: Bool, fn: Bool) { Tool.view!.clearRulers() } override func move(shift: Bool, fn: Bool) { Tool.view!.clearRulers() } override func down(ctrl: Bool) { Tool.view!.clearPathLayer(layer: Tool.view!.curveLayer, path: Tool.view!.curvedPath) Tool.view!.selectCurve(pos: Tool.view!.startPos, ctrl: ctrl) } } class Line: Tool { override var cursor: NSCursor {NSCursor.crosshair} override var tag: Int {1} override var name: String {"line"} func action(topLeft: CGPoint, bottomRight: CGPoint) { Tool.view!.editedPath.move(to: topLeft) Tool.view!.editedPath.curve(to: bottomRight, controlPoint1: bottomRight, controlPoint2: bottomRight) Tool.view!.editedPath.move(to: bottomRight) Tool.view!.controlPoints = [ ControlPoint(Tool.view!, cp1: topLeft, cp2: topLeft, mp: topLeft), ControlPoint(Tool.view!, cp1: bottomRight, cp2: bottomRight, mp: bottomRight)] } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action( topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos)) Tool.view!.filledCurve = false } override func drag(shift: Bool, fn: Bool) { let par = Tool.view! if shift { par.locationX.isHidden = true par.locationY.isHidden = true par.finPos = par.shiftAngle(topLeft: par.startPos, bottomRight: par.finPos) par.setLabel(key: "x", pos: par.startPos, dist: par.finPos.magnitude(origin: par.startPos)) par.rulers.appendCustomRule(move: par.startPos, line: par.finPos) } else { super.drag(shift: shift, fn: fn) } } } class Triangle: Tool { override var cursor: NSCursor {NSCursor.crosshair} override var tag: Int {2} func action(topLeft: CGPoint, bottomRight: CGPoint, sides: Int, shift: Bool) { let size = self.flipSize(topLeft: topLeft, bottomRight: bottomRight) let signWid: CGFloat = size.wid > 0 ? 1 : -1 let signHei: CGFloat = size.hei > 0 ? 1 : -1 var wid = abs(size.wid) var hei = abs(size.hei) if shift { let maxSize = wid > hei ? wid : hei wid = maxSize hei = maxSize } let cx: CGFloat = signWid > 0 ? topLeft.x + wid/2 : topLeft.x - wid/2 let cy: CGFloat = signHei > 0 ? topLeft.y + hei/2 : topLeft.y - hei/2 var points: [CGPoint] = [CGPoint(x: cx, y: topLeft.y)] let midWid = signWid * wid/2 let midHei = signHei * hei/2 if sides == 3 { points.append(contentsOf: [CGPoint(x: cx + midWid, y: cy+midHei), CGPoint(x: cx - midWid, y: cy+midHei) ]) } else if sides == 5 { let pentWid = signWid * wid * (0.381966011727603 * 0.5) let pentHei = signHei * hei * 0.381966011727603 points.append(contentsOf: [CGPoint(x: cx + midWid, y: cy - midHei + pentHei), CGPoint(x: cx + midWid - pentWid, y: cy+midHei), CGPoint(x: cx - midWid + pentWid, y: cy+midHei), CGPoint(x: cx - midWid, y: cy - midHei + pentHei) ]) } else if sides == 6 { let hexHei = signHei * hei * 0.25 points.append(contentsOf: [CGPoint(x: cx + midWid, y: cy - midHei + hexHei), CGPoint(x: cx + midWid, y: cy + midHei - hexHei), CGPoint(x: cx, y: cy + midHei), CGPoint(x: cx - midWid, y: cy + midHei - hexHei), CGPoint(x: cx - midWid, y: cy - midHei + hexHei) ]) } else if sides == 10 { let pentWid = signWid * wid * (0.381966011727603 * 0.5) let pentHei = signHei * hei * 0.381966011727603 let starMinWid = signWid * wid * 0.116788321167883 let starMaxWid = signWid * wid * 0.187956204379562 let starMinHei = signHei * hei * 0.62043795620438 let starMaxHei = signHei * hei * 0.755474452554745 points.append(contentsOf: [CGPoint(x: cx + starMinWid, y: cy - midHei + pentHei), CGPoint(x: cx + midWid, y: cy - midHei + pentHei), CGPoint(x: cx + starMaxWid, y: cy - midHei + starMinHei), CGPoint(x: cx + midWid - pentWid, y: cy+midHei), CGPoint(x: cx, y: cy-midHei+starMaxHei), CGPoint(x: cx - midWid + pentWid, y: cy+midHei), CGPoint(x: cx - starMaxWid, y: cy - midHei + starMinHei), CGPoint(x: cx - midWid, y: cy - midHei + pentHei), CGPoint(x: cx - starMinWid, y: cy - midHei + pentHei) ]) } if points.count>0 { self.appendStraightCurves(points: points) } } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos, sides: 3, shift: shift)) } } class Rectangle: Tool { override var cursor: NSCursor {NSCursor.crosshair} override var tag: Int {3} func action(topLeft: CGPoint, bottomRight: CGPoint, shift: Bool = false) { var botLeft: CGPoint var topRight: CGPoint if topLeft.x < bottomRight.x && topLeft.y > bottomRight.y { botLeft = CGPoint(x: topLeft.x, y: bottomRight.y) topRight = CGPoint(x: bottomRight.x, y: topLeft.y) } else if topLeft.x < bottomRight.x && topLeft.y < bottomRight.y { botLeft = CGPoint(x: topLeft.x, y: topLeft.y) topRight = CGPoint(x: bottomRight.x, y: bottomRight.y) } else if topLeft.x > bottomRight.x && topLeft.y > bottomRight.y { botLeft = CGPoint(x: bottomRight.x, y: bottomRight.y) topRight = CGPoint(x: topLeft.x, y: topLeft.y) } else { botLeft = CGPoint(x: bottomRight.x, y: topLeft.y) topRight = CGPoint(x: topLeft.x, y: bottomRight.y) } let size = self.flipSize(topLeft: botLeft, bottomRight: topRight) var wid = size.wid var hei = size.hei if shift { let maxSize = abs(size.wid) > abs(size.hei) ? abs(size.wid) : abs(size.hei) wid = maxSize hei = maxSize } if shift && (topLeft.x < bottomRight.x) && (topLeft.y > bottomRight.y) { botLeft.y = topRight.y - hei } else if shift && (topLeft.x > bottomRight.x) && (topLeft.y < bottomRight.y) { botLeft.x = topRight.x - wid } else if shift && (topLeft.x > bottomRight.x) && (topLeft.y > bottomRight.y) { botLeft.x = topRight.x - wid botLeft.y = topRight.y - hei } let points: [CGPoint] = [ CGPoint(x: botLeft.x, y: botLeft.y + hei), CGPoint(x: botLeft.x, y: botLeft.y), CGPoint(x: botLeft.x + wid, y: botLeft.y), CGPoint(x: botLeft.x + wid, y: botLeft.y + hei)] Tool.view!.controlPoints = [] Tool.view!.editedPath.move(to: points[0]) for i in 0..<points.count { let pnt = points[i] Tool.view!.controlPoints.append( ControlPoint(Tool.view!, cp1: pnt, cp2: pnt, mp: pnt)) Tool.view!.controlPoints.append( ControlPoint(Tool.view!, cp1: pnt, cp2: pnt, mp: pnt)) Tool.view!.editedPath.curve(to: pnt, controlPoint1: pnt, controlPoint2: pnt) if i == points.count-1 { Tool.view!.editedPath.curve(to: points[0], controlPoint1: points[0], controlPoint2: points[0]) } else { Tool.view!.editedPath.curve(to: points[i+1], controlPoint1: points[i+1], controlPoint2: points[i+1]) } } Tool.view!.roundedCurve = CGPoint(x: 0, y: 0) } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos, shift: shift)) } } class Pentagon: Triangle { override var tag: Int {4} override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos, sides: 5, shift: shift)) } } class Hexagon: Triangle { override var tag: Int {5} override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos, sides: 6, shift: shift)) } } class Star: Triangle { override var tag: Int {6} override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos, sides: 10, shift: shift)) } } class Arc: Tool { override var cursor: NSCursor {NSCursor.crosshair} override var tag: Int {7} func action(topLeft: CGPoint, bottomRight: CGPoint) { let size = self.flipSize(topLeft: topLeft, bottomRight: bottomRight) let delta = remainder(abs(size.hei/2), 360) let startAngle = -delta let endAngle = delta Tool.view!.editedPath.move(to: topLeft) Tool.view!.editedPath.appendArc(withCenter: topLeft, radius: size.wid, startAngle: startAngle, endAngle: endAngle, clockwise: false) let mPnt = Tool.view!.editedPath.findPoint(0) let lPnt = Tool.view!.editedPath.findPoint(1) Tool.view!.editedPath = Tool.view!.editedPath.placeCurve( at: 1, with: [lPnt[0], lPnt[0], lPnt[0]], replace: false) let fPnt = Tool.view!.editedPath.findPoint( Tool.view!.editedPath.elementCount-1) Tool.view!.editedPath = Tool.view!.editedPath.placeCurve( at: Tool.view!.editedPath.elementCount, with: [fPnt[2], fPnt[2], mPnt[0]]) let points = Tool.view!.editedPath.findPoints(.curveTo) let lst = points.count-1 if lst > 0 { Tool.view!.controlPoints = [ ControlPoint(Tool.view!, cp1: points[lst][2], cp2: points[lst][2], mp: points[lst][2]), ControlPoint(Tool.view!, cp1: points[1][0], cp2: points[0][2], mp: points[0][2])] } if lst > 1 { for i in 1..<lst-1 { Tool.view!.controlPoints.append( ControlPoint(Tool.view!, cp1: points[i+1][0], cp2: points[i][1], mp: points[i][2])) } Tool.view!.controlPoints.append( ControlPoint(Tool.view!, cp1: points[lst-1][2], cp2: points[lst-1][1], mp: points[lst-1][2])) } } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos)) } } class Oval: Tool { override var cursor: NSCursor {NSCursor.crosshair} override var tag: Int {8} func action(topLeft: CGPoint, bottomRight: CGPoint, shift: Bool = false) { let size = self.flipSize(topLeft: topLeft, bottomRight: bottomRight) var wid = size.wid var hei = size.hei if shift { let maxSize = abs(size.wid) > abs(size.hei) ? abs(size.wid) : abs(size.hei) let signWid: CGFloat = wid>0 ? 1 : -1 let signHei: CGFloat = hei>0 ? 1 : -1 wid = maxSize * signWid hei = maxSize * signHei } Tool.view!.editedPath.appendOval( in: NSRect(x: topLeft.x, y: topLeft.y, width: wid, height: hei)) let points = Tool.view!.editedPath.findPoints(.curveTo) if points.count == 4 { Tool.view!.controlPoints = [ ControlPoint(Tool.view!, cp1: points[0][0], cp2: points[3][1], mp: points[3][2]), ControlPoint(Tool.view!, cp1: points[1][0], cp2: points[0][1], mp: points[0][2]), ControlPoint(Tool.view!, cp1: points[2][0], cp2: points[1][1], mp: points[1][2]), ControlPoint(Tool.view!, cp1: points[3][0], cp2: points[2][1], mp: points[2][2])] } } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.useTool(self.action(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos, shift: shift)) } } class Stylus: Line { override var cursor: NSCursor {setCursor.stylus} override var tag: Int {9} override var name: String {"line"} override func action(topLeft: CGPoint, bottomRight: CGPoint) { Tool.view!.editedPath.curve(to: bottomRight, controlPoint1: bottomRight, controlPoint2: bottomRight) Tool.view!.controlPoints.append( ControlPoint(Tool.view!, cp1: bottomRight, cp2: bottomRight, mp: bottomRight)) } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { let par = Tool.view! if abs(par.startPos.x - par.finPos.x) > setEditor.dotSize || abs(par.startPos.y - par.finPos.y) > setEditor.dotSize { self.action(topLeft: par.startPos, bottomRight: par.finPos) par.startPos = par.finPos par.editDone = true } par.filledCurve = false } override var mpPoints: [CGPoint] { return [] } override func down(ctrl: Bool) { Tool.view!.controlPoints = [] Tool.view!.editedPath.removeAllPoints() Tool.view!.editedPath.move(to: Tool.view!.startPos) Tool.view!.controlPoints.append( ControlPoint(Tool.view!, cp1: Tool.view!.startPos, cp2: Tool.view!.startPos, mp: Tool.view!.startPos)) } override func up(editDone: Bool) { if Tool.view!.editDone { Tool.view!.editedPath.move(to: Tool.view!.startPos) } else { Tool.view!.controlPoints = [] Tool.view!.editedPath.removeAllPoints() } super.up(editDone: editDone) } } class Vector: Line { override var cursor: NSCursor {setCursor.vector} override var tag: Int {10} override var name: String {"shape"} func action(topLeft: CGPoint) { let par = Tool.view! if let mp = par.movePoint, let cp1 = par.controlPoint1, let cp2 = par.controlPoint2 { par.moveCurvedPath(move: mp.position, to: topLeft, cp1: cp1.position, cp2: topLeft) par.addSegment(mp: mp, cp1: cp1, cp2: cp2) } par.movePoint = Dot(par, pos: topLeft) par.layer?.addSublayer(par.movePoint!) par.controlPoint1 = Dot(par, pos: topLeft, strokeColor: setEditor.fillColor, fillColor: setEditor.strokeColor) par.layer?.addSublayer(par.controlPoint1!) par.controlPoint2 = Dot(par, pos: topLeft, strokeColor: setEditor.fillColor, fillColor: setEditor.strokeColor) par.layer?.addSublayer(Tool.view!.controlPoint2!) par.clearPathLayer(layer: par.controlLayer, path: par.controlPath) if let mp = par.movePoint { let options: NSTrackingArea.Options = [ .mouseEnteredAndExited, .activeInActiveApp] let area = NSTrackingArea(rect: NSRect(x: mp.frame.minX, y: mp.frame.minY, width: mp.frame.width, height: mp.frame.height), options: options, owner: par) par.addTrackingArea(area) } if par.editedPath.elementCount==0 { par.editedPath.move(to: topLeft) } } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { if Tool.view!.editDone { return } Tool.view!.dragCurvedPath(topLeft: Tool.view!.startPos, bottomRight: Tool.view!.finPos, opt: opt) } override var mpPoints: [CGPoint] { let par = Tool.view! var points: [CGPoint] = [par.startPos] if let mp = par.movePoint { points.append(mp.position) } for cp in par.controlPoints { points.append(cp.mp.position) } return points } override func down(ctrl: Bool) { self.action(topLeft: Tool.view!.startPos) } override func up(editDone: Bool) { if let curve = Tool.view!.selectedCurve, curve.edit || editDone { Tool.view!.clearControls(curve: curve) } if editDone { Tool.view!.newCurve() } if let curve = Tool.view!.selectedCurve, curve.edit || editDone { curve.reset() Tool.view!.createControls(curve: curve) } } } class Text: Tool { override var cursor: NSCursor {NSCursor.crosshair} override var tag: Int {11} override var name: String {"text"} func action(pos: CGPoint? = nil) { let topLeft = pos ?? Tool.view!.startPos let deltaX = topLeft.x-Tool.view!.bounds.minX let deltaY = topLeft.y-Tool.view!.bounds.minY Tool.view!.fontUI.inputField.setFrameOrigin(CGPoint( x: deltaX * Tool.view!.zoomed, y: deltaY * Tool.view!.zoomed)) Tool.view!.fontUI.inputField.show() } override func create(fn: Bool, shift: Bool, opt: Bool, event: NSEvent? = nil) { self.action(pos: Tool.view!.finPos) } override var mpPoints: [CGPoint] { return [] } override func down(ctrl: Bool) { self.action(pos: Tool.view!.startPos) } }
36.946939
78
0.508138
f46e3b25a88fdf9433a31752bfba0b8bc855489c
1,270
// The MIT License (MIT) // // Copyright (c) 2016 Joakim Gyllström // // 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 protocol BinaryRepresentable { func layoutFor(state: Bool?, style: UIUserInterfaceStyle) }
43.793103
81
0.765354
e53fd679e229dcaa5b1c67bafd117e889b35a792
555
// // ProfileHighlight.swift // CompositionalDiffablePlayground // // Created by Filip Němeček on 16/01/2021. // import UIKit struct ProfileHighlight: Hashable { let id = UUID() let image: UIImage } extension ProfileHighlight { func hash(into hasher: inout Hasher) { hasher.combine(id) } } extension ProfileHighlight { static var demoHighlights: [ProfileHighlight] { let imageNames = (1...7).map({ "flower\($0)" }) return imageNames.map({ ProfileHighlight(image: UIImage(named: $0)!) }) } }
19.821429
79
0.646847
f519570793c9bc8c1ecbe073cc5d46ccb50c5b35
7,524
// 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 // #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation private func disposeTLS(_ ctx: UnsafeMutablePointer<Void>?) -> Void { Unmanaged<AnyObject>.fromOpaque(ctx!).release() } internal class NSThreadSpecific<T: AnyObject> { private var NSThreadSpecificKeySet = false private var NSThreadSpecificKeyLock = NSLock() private var NSThreadSpecificKey = pthread_key_t() private var key: pthread_key_t { NSThreadSpecificKeyLock.lock() if !NSThreadSpecificKeySet { withUnsafeMutablePointer(&NSThreadSpecificKey) { key in NSThreadSpecificKeySet = pthread_key_create(key, disposeTLS) == 0 } } NSThreadSpecificKeyLock.unlock() return NSThreadSpecificKey } internal func get(_ generator: (Void) -> T) -> T { let specific = pthread_getspecific(self.key) if specific != nil { return Unmanaged<T>.fromOpaque(specific!).takeUnretainedValue() } else { let value = generator() pthread_setspecific(self.key, Unmanaged<AnyObject>.passRetained(value).toOpaque()) return value } } internal func set(_ value: T) { let specific = pthread_getspecific(self.key) var previous: Unmanaged<T>? if specific != nil { previous = Unmanaged<T>.fromOpaque(specific!) } if let prev = previous { if prev.takeUnretainedValue() === value { return } } pthread_setspecific(self.key, Unmanaged<AnyObject>.passRetained(value).toOpaque()) if let prev = previous { prev.release() } } } internal enum _NSThreadStatus { case Initialized case Starting case Executing case Finished } private func NSThreadStart(_ context: UnsafeMutablePointer<Void>?) -> UnsafeMutablePointer<Void>? { let unmanaged: Unmanaged<NSThread> = Unmanaged.fromOpaque(context!) let thread = unmanaged.takeUnretainedValue() NSThread._currentThread.set(thread) thread._status = _NSThreadStatus.Executing thread.main() thread._status = _NSThreadStatus.Finished unmanaged.release() return nil } public class NSThread : NSObject { static internal var _currentThread = NSThreadSpecific<NSThread>() public static func currentThread() -> NSThread { return NSThread._currentThread.get() { return NSThread(thread: pthread_self()) } } /// Alternative API for detached thread creation /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative to creation via selector /// - Note: Since this API is under consideration it may be either removed or revised in the near future public class func detachNewThread(_ main: (Void) -> Void) { let t = NSThread(main) t.start() } public class func isMultiThreaded() -> Bool { return true } public class func sleepUntilDate(_ date: NSDate) { let start_ut = CFGetSystemUptime() let start_at = CFAbsoluteTimeGetCurrent() let end_at = date.timeIntervalSinceReferenceDate var ti = end_at - start_at let end_ut = start_ut + ti while (0.0 < ti) { var __ts__ = timespec(tv_sec: LONG_MAX, tv_nsec: 0) if ti < Double(LONG_MAX) { var integ = 0.0 let frac: Double = withUnsafeMutablePointer(&integ) { integp in return modf(ti, integp) } __ts__.tv_sec = Int(integ) __ts__.tv_nsec = Int(frac * 1000000000.0) } let _ = withUnsafePointer(&__ts__) { ts in nanosleep(ts, nil) } ti = end_ut - CFGetSystemUptime() } } public class func sleepForTimeInterval(_ interval: NSTimeInterval) { var ti = interval let start_ut = CFGetSystemUptime() let end_ut = start_ut + ti while 0.0 < ti { var __ts__ = timespec(tv_sec: LONG_MAX, tv_nsec: 0) if ti < Double(LONG_MAX) { var integ = 0.0 let frac: Double = withUnsafeMutablePointer(&integ) { integp in return modf(ti, integp) } __ts__.tv_sec = Int(integ) __ts__.tv_nsec = Int(frac * 1000000000.0) } let _ = withUnsafePointer(&__ts__) { ts in nanosleep(ts, nil) } ti = end_ut - CFGetSystemUptime() } } public class func exit() { pthread_exit(nil) } internal var _main: (Void) -> Void = {} #if os(OSX) || os(iOS) private var _thread: pthread_t? = nil #elseif os(Linux) private var _thread = pthread_t() #endif internal var _attr = pthread_attr_t() internal var _status = _NSThreadStatus.Initialized internal var _cancelled = false /// - Note: this differs from the Darwin implementation in that the keys must be Strings public var threadDictionary = [String:AnyObject]() internal init(thread: pthread_t) { // Note: even on Darwin this is a non-optional pthread_t; this is only used for valid threads, which are never null pointers. _thread = thread } public init(_ main: (Void) -> Void) { _main = main let _ = withUnsafeMutablePointer(&_attr) { attr in pthread_attr_init(attr) } } public func start() { precondition(_status == .Initialized, "attempting to start a thread that has already been started") _status = .Starting if _cancelled { _status = .Finished return } withUnsafeMutablePointers(&_thread, &_attr) { thread, attr in let ptr = Unmanaged.passRetained(self) pthread_create(thread, attr, NSThreadStart, ptr.toOpaque()) } } public func main() { _main() } public var stackSize: Int { get { var size: Int = 0 return withUnsafeMutablePointers(&_attr, &size) { attr, sz in pthread_attr_getstacksize(attr, sz) return sz.pointee } } set { // just don't allow a stack size more than 1GB on any platform var s = newValue if (1 << 30) < s { s = 1 << 30 } let _ = withUnsafeMutablePointer(&_attr) { attr in pthread_attr_setstacksize(attr, s) } } } public var executing: Bool { return _status == .Executing } public var finished: Bool { return _status == .Finished } public var cancelled: Bool { return _cancelled } public func cancel() { _cancelled = true } public class func callStackReturnAddresses() -> [NSNumber] { NSUnimplemented() } public class func callStackSymbols() -> [String] { NSUnimplemented() } }
31.219917
158
0.597687
4aeb6ca402b75e3a67d320aa63081a35ece660a8
2,098
// // ButtonStyle.swift // twitterclone // // Created by Stephen Wall on 5/18/21. // import SwiftUI struct EditButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .frame(width: 360, height: 40) .background(Color.blue) .foregroundColor(.white) .cornerRadius(20) } } struct FollowButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .frame(width: 180, height: 40) .background(Color.blue) .foregroundColor(.white) .cornerRadius(20) } } struct MessageButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .frame(width: 180, height: 40) .background(Color.purple) .foregroundColor(.white) .cornerRadius(20) } } struct SignInButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .font(.headline) .foregroundColor(.blue) .frame(width: 325, height: 50) .background(Color.white) .clipShape(Capsule()) .padding() } } struct TweetButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .padding(.horizontal) .padding(.vertical, 8) .background(Color.blue) .foregroundColor(.white) .clipShape(Capsule()) } } struct ButtonStyle_Previews: PreviewProvider { static var previews: some View { VStack(spacing: 40) { // Edit Button("Edit", action: {}) .buttonStyle(EditButtonStyle()) // Follow/ Message HStack { Button("Follow", action: {}) .buttonStyle(FollowButtonStyle()) Button("Message", action: {}) .buttonStyle(MessageButtonStyle()) } // Log In VStack { Button("Log In", action: {}) .buttonStyle(SignInButtonStyle()) } .background(Color(#colorLiteral(red: 0.1131996438, green: 0.631419003, blue: 0.9528219104, alpha: 1))) } } }
24.395349
108
0.636797
717a896db90fbf297e692905e3d70f9523d2aace
976
// // UIHelper.swift // GHFollowers // // Created by Mr Kes on 11/18/21. // Copyright © 2021 Sean Allen. All rights reserved. // import UIKit // struct UIHelper - we don't want empty UIHelper initialization, ex: let helper = UIHelper() so we made it enum enum UIHelper { static func createThreeColumnFlowLayout(in view: UIView) -> UICollectionViewFlowLayout { let width = view.bounds.width let padding: CGFloat = 12 let minimumItemSpacing: CGFloat = 10 let availableWidth = width - (padding * 2) - (minimumItemSpacing * 2) let itemWidth = availableWidth / 3 let flowLayout = UICollectionViewFlowLayout() flowLayout.sectionInset = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding) flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth + 40) return flowLayout } }
34.857143
112
0.619877
394abbcd28fcd234eb45d45bbb89e7479cfec533
19,105
//===--- OpenLocationCode.swift - Open Location Code encoding/decoding-----===// // // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //===----------------------------------------------------------------------===// // // Convert between decimal degree coordinates and Open Location Codes. Shorten // and recover Open Location Codes for a given reference location. // // Exposes the Swift objects in OpenLocationCode.swift as NSObject visible in // Objective-C. The reason that OpenLocationCode and OpenLocationCodeArea don't // descend from NSObject directly is that such classes can't be used in Swift // for Linux and this time. It also allows for more "pure" swift paradigms to // be employed for those objects, such as the declaring OpenLocationCodeArea // as a struct, and more customization for the Objective-C representation // such as with default parameters. // // Authored by William Denniss. // //===----------------------------------------------------------------------===// import Foundation #if !os(Linux) /// Convert between decimal degree coordinates and plus codes. Shorten and /// recover plus codes for a given reference location. /// /// Open Location Codes are short, 10-11 character codes that can be used /// instead of street addresses. The codes can be generated and decoded offline, /// and use a reduced character set that minimises the chance of codes including /// words. /// /// Codes are able to be shortened relative to a nearby location. This means /// that in many cases, only four to seven characters of the code are needed. /// To recover the original code, the same location is not required, as long as /// a nearby location is provided. /// /// Codes represent rectangular areas rather than points, and the longer the /// code, the smaller the area. A 10 character code represents a 13.5x13.5 /// meter area (at the equator. An 11 character code represents approximately /// a 2.8x3.5 meter area. /// /// Two encoding algorithms are used. The first 10 characters are pairs of /// characters, one for latitude and one for latitude, using base 20. Each pair /// reduces the area of the code by a factor of 400. Only even code lengths are /// sensible, since an odd-numbered length would have sides in a ratio of 20:1. /// /// At position 11, the algorithm changes so that each character selects one /// position from a 4x5 grid. This allows single-character refinements. /// /// # Swift Example /// ``` /// import OpenLocationCode /// /// // ... /// /// // Encode a location with default code length. /// if let code = OpenLocationCode.encode(latitude: 37.421908, /// longitude: -122.084681) { /// print("Open Location Code: \(code)") /// } /// /// // Encode a location with specific code length. /// if let code10Digit = OpenLocationCode.encode(latitude: 37.421908, /// longitude: -122.084681, /// codeLength: 10) { /// print("Open Location Code: \(code10Digit)") /// } /// /// // Decode a full code: /// if let coord = OpenLocationCode.decode("849VCWC8+Q48") { /// print("Center is \(coord.latitudeCenter), \(coord.longitudeCenter)") /// } /// /// // Attempt to trim the first characters from a code: /// if let shortCode = OpenLocationCode.shorten(code: "849VCWC8+Q48", /// latitude: 37.4, /// longitude: -122.0) { /// print("Short code: \(shortCode)") /// } /// /// // Recover the full code from a short code: /// if let fullCode = OpenLocationCode.recoverNearest(shortcode: "CWC8+Q48", /// referenceLatitude: 37.4, /// referenceLongitude: -122.0) { /// print("Recovered full code: \(fullCode)") /// } /// ``` /// # Objective-C Examples /// ``` /// @import OpenLocationCode; /// /// // ... /// /// // Encode a location with default code length. /// NSString *code = [OLCConverter encodeLatitude:37.421908 /// longitude:-122.084681]; /// NSLog(@"Open Location Code: %@", code); /// /// // Encode a location with specific code length. /// NSString *code10Digit = [OLCConverter encodeLatitude:37.421908 /// longitude:-122.084681 /// codeLength:10]; /// NSLog(@"Open Location Code: %@", code10Digit); /// /// // Decode a full code: /// OLCArea *coord = [OLCConverter decode:@"849VCWC8+Q48"]; /// NSLog(@"Center is %.6f, %.6f", coord.latitudeCenter, coord.longitudeCenter); /// /// // Attempt to trim the first characters from a code: /// NSString *shortCode = [OLCConverter shortenCode:@"849VCWC8+Q48" /// latitude:37.4 /// longitude:-122.0]; /// NSLog(@"Short Code: %@", shortCode); /// /// // Recover the full code from a short code: /// NSString *recoveredCode = [OLCConverter recoverNearestWithShortcode:@"CWC8+Q48" /// referenceLatitude:37.4 /// referenceLongitude:-122.1]; /// NSLog(@"Recovered Full Code: %@", recoveredCode); /// ``` /// @objc public class OLCConverter: NSObject { /// Determines if a code is valid. /// To be valid, all characters must be from the Open Location Code character /// set with at most one separator. The separator can be in any even-numbered /// position up to the eighth digit. /// /// - Parameter code: The Open Location Code to test. /// - Returns: true if the code is a valid Open Location Code. @objc(isValidCode:) public static func isValid(code: String) -> Bool { return OpenLocationCode.isValid(code: code) } /// Determines if a code is a valid short code. /// A short Open Location Code is a sequence created by removing four or more /// digits from an Open Location Code. It must include a separator /// character. /// /// - Parameter code: The Open Location Code to test. /// - Returns: true if the code is a short Open Location Code. @objc(isShortCode:) public static func isShort(code: String) -> Bool { return OpenLocationCode.isShort(code: code) } // Determines if a code is a valid full Open Location Code. // Not all possible combinations of Open Location Code characters decode to // valid latitude and longitude values. This checks that a code is valid // and also that the latitude and longitude values are legal. If the prefix // character is present, it must be the first character. If the separator // character is present, it must be after four characters. /// /// - Parameter code: The Open Location Code to test. /// - Returns: true if the code is a full Open Location Code. @objc(isFullCode:) public static func isFull(code: String) -> Bool { return OpenLocationCode.isFull(code: code) } /// Encode a location using the grid refinement method into an OLC string. /// The grid refinement method divides the area into a grid of 4x5, and uses a /// single character to refine the area. This allows default accuracy OLC /// codes to be refined with just a single character. /// /// - Parameter latitude: A latitude in signed decimal degrees. /// - Parameter longitude: A longitude in signed decimal degrees. /// - Parameter codeLength: The number of characters required. /// - Returns: Open Location Code representing the given grid. @objc(encodeGridForLatitude:longitude:codeLength:) public static func encodeGrid(latitude: Double, longitude: Double, codeLength: Int) -> String { return OpenLocationCode.encodeGrid(latitude:latitude, longitude:longitude, codeLength:codeLength) } /// Encode a location into an Open Location Code. /// Produces a code of the specified length, or the default length if no /// length is provided. /// The length determines the accuracy of the code. The default length is /// 10 characters, returning a code of approximately 13.5x13.5 meters. Longer /// codes represent smaller areas, but lengths > 14 are sub-centimetre and so /// 11 or 12 are probably the limit of useful codes. /// /// - Parameter latitude: A latitude in signed decimal degrees. Will be /// clipped to the range -90 to 90. /// - Parameter longitude: A longitude in signed decimal degrees. Will be /// normalised to the range -180 to 180. /// - Parameter codeLength: The number of significant digits in the output /// code, not including any separator characters. Possible values are; /// `2`, `4`, `6`, `8`, `10`, `11`, `12`, `13` and above. Lower values /// indicate a larger area, higher values a more precise area. /// You can also shorten a code after encoding for codes used with a /// reference point (e.g. your current location, a city, etc). /// /// - Returns: Open Location Code for the given coordinate. @objc(encodeLatitude:longitude:codeLength:) public static func encode(latitude: Double, longitude: Double, codeLength: Int) -> String? { return OpenLocationCode.encode(latitude:latitude, longitude:longitude, codeLength:codeLength) } /// Encode a location into an Open Location Code. /// Produces a code of the specified length, or the default length if no /// length is provided. /// The length determines the accuracy of the code. The default length is /// 10 characters, returning a code of approximately 13.5x13.5 meters. Longer /// codes represent smaller areas, but lengths > 14 are sub-centimetre and so /// 11 or 12 are probably the limit of useful codes. /// /// - Parameter latitude: A latitude in signed decimal degrees. Will be /// clipped to the range -90 to 90. /// - Parameter longitude: A longitude in signed decimal degrees. Will be /// normalised to the range -180 to 180. /// /// - Returns: Open Location Code for the given coordinate. @objc(encodeLatitude:longitude:) public static func encode(latitude: Double, longitude: Double) -> String? { return OpenLocationCode.encode(latitude:latitude, longitude:longitude) } /// Decodes an Open Location Code into the location coordinates. /// Returns a OpenLocationCodeArea object that includes the coordinates of the /// bounding box - the lower left, center and upper right. /// /// - Parameter code: The Open Location Code to decode. /// - Returns: A CodeArea object that provides the latitude and longitude of /// two of the corners of the area, the center, and the length of the /// original code. @objc public static func decode(_ code: String) -> OLCArea? { guard let area = OpenLocationCode.decode(code) else { return nil } return OLCArea.init(area) } /// Recover the nearest matching code to a specified location. /// Given a short Open Location Code of between four and seven characters, /// this recovers the nearest matching full code to the specified location. /// The number of characters that will be prepended to the short code, depends /// on the length of the short code and whether it starts with the separator. /// If it starts with the separator, four characters will be prepended. If it /// does not, the characters that will be prepended to the short code, where S /// is the supplied short code and R are the computed characters, are as /// follows: /// ``` /// SSSS -> RRRR.RRSSSS /// SSSSS -> RRRR.RRSSSSS /// SSSSSS -> RRRR.SSSSSS /// SSSSSSS -> RRRR.SSSSSSS /// ``` /// /// Note that short codes with an odd number of characters will have their /// last character decoded using the grid refinement algorithm. /// /// - Parameter shortcode: A valid short OLC character sequence. /// - Parameter referenceLatitude: The latitude (in signed decimal degrees) to /// use to find the nearest matching full code. /// - Parameter referenceLongitude: The longitude (in signed decimal degrees) /// to use to find the nearest matching full code. /// - Returns: The nearest full Open Location Code to the reference location /// that matches the short code. If the passed code was not a valid short /// code, but was a valid full code, it is returned unchanged. @objc public static func recoverNearest(shortcode: String, referenceLatitude: Double, referenceLongitude: Double) -> String? { return OpenLocationCode.recoverNearest(shortcode:shortcode, referenceLatitude:referenceLatitude, referenceLongitude:referenceLongitude) } /// Remove characters from the start of an OLC code. /// This uses a reference location to determine how many initial characters /// can be removed from the OLC code. The number of characters that can be /// removed depends on the distance between the code center and the reference /// location. /// The minimum number of characters that will be removed is four. If more /// than four characters can be removed, the additional characters will be /// replaced with the padding character. At most eight characters will be /// removed. The reference location must be within 50% of the maximum range. /// This ensures that the shortened code will be able to be recovered using /// slightly different locations. /// /// - Parameter code: A full, valid code to shorten. /// - Parameter latitude: A latitude, in signed decimal degrees, to use as the /// reference point. /// - Parameter longitude: A longitude, in signed decimal degrees, to use as /// the reference point. /// - Parameter maximumTruncation: The maximum number of characters to remove. /// - Returns: Either the original code, if the reference location was not /// close enough, or the original. @objc(shortenCode:latitude:longitude:maximumTruncation:) public static func shorten(code: String, latitude: Double, longitude: Double, maximumTruncation: Int) -> String? { return OpenLocationCode.shorten(code:code, latitude:latitude, longitude:longitude, maximumTruncation:maximumTruncation) } /// Remove characters from the start of an OLC code. /// This uses a reference location to determine how many initial characters /// can be removed from the OLC code. The number of characters that can be /// removed depends on the distance between the code center and the reference /// location. /// The minimum number of characters that will be removed is four. If more /// than four characters can be removed, the additional characters will be /// replaced with the padding character. At most eight characters will be /// removed. The reference location must be within 50% of the maximum range. /// This ensures that the shortened code will be able to be recovered using /// slightly different locations. /// /// - Parameter code: A full, valid code to shorten. /// - Parameter latitude: A latitude, in signed decimal degrees, to use as the /// reference point. /// - Parameter longitude: A longitude, in signed decimal degrees, to use as /// the reference point. /// - Returns: Either the original code, if the reference location was not /// close enough, or the original. @objc(shortenCode:latitude:longitude:) public static func shorten(code: String, latitude: Double, longitude: Double) -> String? { return OpenLocationCode.shorten(code:code, latitude:latitude, longitude:longitude) } } /// Coordinates of a decoded Open Location Code. /// The coordinates include the latitude and longitude of the lower left and /// upper right corners and the center of the bounding box for the area the /// code represents. @objc public class OLCArea: NSObject { /// The latitude of the SW corner in degrees. @objc public var latitudeLo: Double = 0 /// The longitude of the SW corner in degrees. @objc public var longitudeLo: Double = 0 /// The latitude of the NE corner in degrees. @objc public var latitudeHi: Double = 0 /// The longitude of the NE corner in degrees. @objc public var longitudeHi: Double = 0 /// The number of significant characters that were in the code. /// This excludes the separator. @objc public var codeLength: Int = 0 /// The latitude of the center in degrees. @objc public var latitudeCenter: Double = 0 /// latitude_center: The latitude of the center in degrees. @objc public var longitudeCenter: Double = 0 /// - Parameter latitudeLo: The latitude of the SW corner in degrees. /// - Parameter longitudeLo: The longitude of the SW corner in degrees. /// - Parameter latitudeHi: The latitude of the NE corner in degrees. /// - Parameter longitudeHi: The longitude of the NE corner in degrees. /// - Parameter codeLength: The number of significant characters that were in /// the code. @objc init(latitudeLo: Double, longitudeLo: Double, latitudeHi: Double, longitudeHi: Double, codeLength: Int) { self.latitudeLo = latitudeLo self.longitudeLo = longitudeLo self.latitudeHi = latitudeHi self.longitudeHi = longitudeHi self.codeLength = codeLength self.latitudeCenter = min(latitudeLo + (latitudeHi - latitudeLo) / 2, kLatitudeMax) self.longitudeCenter = min(longitudeLo + (longitudeHi - longitudeLo) / 2, kLongitudeMax) } init(_ area: OpenLocationCodeArea) { self.latitudeLo = area.latitudeLo self.longitudeLo = area.longitudeLo self.latitudeHi = area.latitudeHi self.longitudeHi = area.longitudeHi self.codeLength = area.codeLength self.latitudeCenter = area.latitudeCenter self.longitudeCenter = area.longitudeCenter } // Returns lat/lng coordinate array representing the area's center point. @objc func latlng() -> Array<Double>{ return [self.latitudeCenter, self.longitudeCenter] } } #endif
46.25908
83
0.655954
2f00eb05a53f167f836307cffa21de6e0d2d9194
3,334
// // VTextDemoView.swift // VComponentsDemo // // Created by Vakhtang Kontridze on 1/12/21. // import SwiftUI import VComponents // MARK: - V Text Demo View struct VTextDemoView: View { // MARK: Properties static var navBarTitle: String { "Text" } @State private var vTextDemoType: VTextDemoType = .center private let baseTextTitle: String = "Lorem ipsum dolor sit amet" private let baseTextText: String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla dapibus volutpat enim, vitae blandit justo iaculis sit amet. Aenean vitae leo tincidunt, sollicitudin mauris a, mollis massa. Sed posuere, nibh non fermentum ultrices, ipsum nunc luctus arcu, a auctor velit nisl ac nibh. Donec vel arcu condimentum, iaculis quam sed, commodo orci." private let titleColor: Color = ColorBook.primary private let titleFont: Font = .system(size: 16, weight: .semibold) private let textFont: Font = .system(size: 14) // MARK: Body var body: some View { VBaseView(title: Self.navBarTitle, content: { DemoView(component: component, settings: settings) }) } @ViewBuilder private func component() -> some View { switch vTextDemoType { case .center: VText(type: .oneLine, font: titleFont, color: titleColor, title: baseTextTitle) .frame(maxWidth: .infinity, alignment: .center) case .leading: VText(type: .oneLine, font: titleFont, color: titleColor, title: baseTextTitle) .frame(maxWidth: .infinity, alignment: .leading) case .trailing: VText(type: .oneLine, font: titleFont, color: titleColor, title: baseTextTitle) .frame(maxWidth: .infinity, alignment: .trailing) case .multiLineCenter: VText(type: .multiLine(limit: nil, alignment: .center), font: titleFont, color: titleColor, title: baseTextText) case .multiLineLeading: VText(type: .multiLine(limit: nil, alignment: .leading), font: titleFont, color: titleColor, title: baseTextText) case .multiLineTrailing: VText(type: .multiLine(limit: nil, alignment: .trailing), font: titleFont, color: titleColor, title: baseTextText) } } @ViewBuilder private func settings() -> some View { VWheelPicker( selection: $vTextDemoType, headerTitle: "Type", footerTitle: "Not an actual type of the component. Just different configurations listed for demo purposes." ) } } // MARK: - Helpers private enum VTextDemoType: Int, VPickableTitledItem { case center case leading case trailing case multiLineCenter case multiLineLeading case multiLineTrailing var pickerTitle: String { switch self { case .center: return "Center" case .leading: return "Leading" case .trailing: return "Trailing" case .multiLineCenter: return "Multi-Line Center" case .multiLineLeading: return "Multi-Line Leading" case .multiLineTrailing: return "Multi-Line Trailing" } } } // MARK: - Preview struct VTextDemoView_Previews: PreviewProvider { static var previews: some View { VTextDemoView() } }
35.849462
384
0.64877
1df6a0b1eb97f2efc55df2700c22ed0fb1bef972
5,189
// // Copyright (c) 2020 Touch Instinct // // 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 TIUIKitCore import TISwiftUtils /// Base full OTP View for entering the verification code open class OTPSwiftView<View: OTPView>: BaseInitializableControl { private var emptyOTPView: View? { textFieldsCollection.first { $0.codeTextField.text.orEmpty.isEmpty } ?? textFieldsCollection.last } public private(set) var codeStackView = UIStackView() public private(set) var textFieldsCollection: [View] = [] public var onTextEnter: ParameterClosure<String>? public var code: String { get { textFieldsCollection.compactMap { $0.codeTextField.text }.joined() } set { textFieldsCollection.first?.codeTextField.set(inputText: newValue) } } public override var isFirstResponder: Bool { !textFieldsCollection.allSatisfy { !$0.codeTextField.isFirstResponder } } open override func addViews() { super.addViews() addSubview(codeStackView) } open override func configureAppearance() { super.configureAppearance() codeStackView.contentMode = .center codeStackView.distribution = .fillEqually } open func configure(with config: OTPCodeConfig) { textFieldsCollection = createTextFields(numberOfFields: config.codeSymbolsCount) codeStackView.addArrangedSubviews(textFieldsCollection) codeStackView.spacing = config.spacing configure(customSpacing: config.customSpacing, for: codeStackView) bindTextFields(with: config) } @discardableResult open override func becomeFirstResponder() -> Bool { guard let emptyOTPView = emptyOTPView, !emptyOTPView.isFirstResponder else { return false } return emptyOTPView.codeTextField.becomeFirstResponder() } @discardableResult open override func resignFirstResponder() -> Bool { guard let emptyOTPView = emptyOTPView, emptyOTPView.isFirstResponder else { return false } return emptyOTPView.codeTextField.resignFirstResponder() } } // MARK: - Configure textfields private extension OTPSwiftView { func configure(customSpacing: OTPCodeConfig.Spacing?, for stackView: UIStackView) { guard let customSpacing = customSpacing else { return } customSpacing.forEach { viewIndex, spacing in guard viewIndex < stackView.arrangedSubviews.count, viewIndex >= .zero else { return } self.set(spacing: spacing, after: stackView.arrangedSubviews[viewIndex], for: stackView) } } func set(spacing: CGFloat, after view: UIView, for stackView: UIStackView) { stackView.setCustomSpacing(spacing, after: view) } func createTextFields(numberOfFields: Int) -> [View] { var textFieldsCollection: [View] = [] (.zero..<numberOfFields).forEach { _ in let textField = View() textField.codeTextField.previousTextField = textFieldsCollection.last?.codeTextField textFieldsCollection.last?.codeTextField.nextTextField = textField.codeTextField textFieldsCollection.append(textField) } return textFieldsCollection } func bindTextFields(with config: OTPCodeConfig) { let onTextChangedSignal: VoidClosure = { [weak self] in guard let code = self?.code else { return } let correctedCode = code.prefix(config.codeSymbolsCount).string self?.onTextEnter?(correctedCode) } let onTap: VoidClosure = { [weak self] in self?.becomeFirstResponder() } textFieldsCollection.forEach { $0.codeTextField.onTextChangedSignal = onTextChangedSignal $0.onTap = onTap } } }
34.593333
105
0.65504
8f7615a8ba55cd888ff6c3d535f802b73c4018c0
1,421
/** * Copyright IBM Corporation 2018 * * 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 /** The user input. */ public struct InputData: Codable { /** The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. */ public var text: String // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case text = "text" } /** Initialize a `InputData` with member variables. - parameter text: The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. - returns: An initialized `InputData`. */ public init( text: String ) { self.text = text } }
27.862745
119
0.685433
898e9326227a4383f8e68f2aaa8acf94bc5014ca
3,667
import Flutter import UIKit import MLKitTranslate import MLKitLanguageID public class SwiftMlkitTranslatePlugin: NSObject, FlutterPlugin { let locale = Locale.current lazy var allLanguages = TranslateLanguage.allLanguages().sorted { return locale.localizedString(forLanguageCode: $0.rawValue)! < locale.localizedString(forLanguageCode: $1.rawValue)! } public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "mlkit_translate", binaryMessenger: registrar.messenger()) let instance = SwiftMlkitTranslatePlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "translate": let args = call.arguments as? [String: Any] let source = args?["source"] as? String let target = args?["target"] as? String ?? "en" let text = args?["text"] as? String ?? "" if (source == nil) { LanguageIdentification.languageIdentification(options: LanguageIdentificationOptions(confidenceThreshold: 0.0)).identifyLanguage(for: text) { (languageCode, error) in if (error != nil) { self.translateText(result: result, source: "en", target: target, text: text) } else { self.translateText(result: result, source: languageCode ?? "en", target: target, text: text) } } } else { translateText(result: result, source: source!, target: target, text: text) } break; case "downloadModel": if let args = call.arguments as? [String: Any], let model = args["model"] as? String { ModelManager.modelManager().download( TranslateRemoteModel.translateRemoteModel( language: TranslateLanguage.allLanguages().first(where: {$0.rawValue == model}) ?? .english ), conditions: ModelDownloadConditions( allowsCellularAccess: true, allowsBackgroundDownloading: true ) ) } else { result(FlutterError(code: "-1", message: "iOS could not extract " + "flutter arguments in method: (downloadModel)", details: nil)) } result("Success") break; default: result(FlutterMethodNotImplemented); } } private func translateText(result: @escaping FlutterResult, source: String, target: String, text: String) { let translator = Translator.translator(options: TranslatorOptions( sourceLanguage: TranslateLanguage.allLanguages().first(where: {$0.rawValue == source}) ?? .english, targetLanguage: TranslateLanguage.allLanguages().first(where: {$0.rawValue == target}) ?? .english )) translator.downloadModelIfNeeded(with: ModelDownloadConditions( allowsCellularAccess: true, allowsBackgroundDownloading: true )) { error in if (error != nil) { result(text) } else { translator.translate(text) { translatedText, error in guard error == nil, let translatedText = translatedText else { return } result(translatedText) } } } } }
41.670455
186
0.572948
f7c1871e8df125296893e80adc70db39a5f1f8db
6,622
// Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // // InternalSingleValueDecodingContainer.swift // SmokeDynamoDB // import Foundation import DynamoDBModel internal struct InternalSingleValueDecodingContainer { internal let codingPath: [CodingKey] internal let userInfo: [CodingUserInfoKey: Any] internal let attributeValue: DynamoDBModel.AttributeValue internal let attributeNameTransform: ((String) -> String)? init(attributeValue: DynamoDBModel.AttributeValue, codingPath: [CodingKey], userInfo: [CodingUserInfoKey: Any], attributeNameTransform: ((String) -> String)?) { self.attributeValue = attributeValue self.codingPath = codingPath self.userInfo = userInfo self.attributeNameTransform = attributeNameTransform } } extension InternalSingleValueDecodingContainer: SingleValueDecodingContainer { func decodeNil() -> Bool { return attributeValue.NULL ?? false } func decode(_ type: Bool.Type) throws -> Bool { guard let value = attributeValue.BOOL else { throw getTypeMismatchError(expectation: Bool.self) } return value } func decode(_ type: Int.Type) throws -> Int { guard let valueAsString = attributeValue.N, let value = Int(valueAsString) else { throw getTypeMismatchError(expectation: Int.self) } return value } func decode(_ type: Int8.Type) throws -> Int8 { guard let valueAsString = attributeValue.N, let value = Int8(valueAsString) else { throw getTypeMismatchError(expectation: Int8.self) } return value } func decode(_ type: Int16.Type) throws -> Int16 { guard let valueAsString = attributeValue.N, let value = Int16(valueAsString) else { throw getTypeMismatchError(expectation: Int16.self) } return value } func decode(_ type: Int32.Type) throws -> Int32 { guard let valueAsString = attributeValue.N, let value = Int32(valueAsString) else { throw getTypeMismatchError(expectation: Int32.self) } return value } func decode(_ type: Int64.Type) throws -> Int64 { guard let valueAsString = attributeValue.N, let value = Int64(valueAsString) else { throw getTypeMismatchError(expectation: Int64.self) } return value } func decode(_ type: UInt.Type) throws -> UInt { guard let valueAsString = attributeValue.N, let value = UInt(valueAsString) else { throw getTypeMismatchError(expectation: UInt.self) } return value } func decode(_ type: UInt8.Type) throws -> UInt8 { guard let valueAsString = attributeValue.N, let value = UInt8(valueAsString) else { throw getTypeMismatchError(expectation: UInt8.self) } return value } func decode(_ type: UInt16.Type) throws -> UInt16 { guard let valueAsString = attributeValue.N, let value = UInt16(valueAsString) else { throw getTypeMismatchError(expectation: UInt16.self) } return value } func decode(_ type: UInt32.Type) throws -> UInt32 { guard let valueAsString = attributeValue.N, let value = UInt32(valueAsString) else { throw getTypeMismatchError(expectation: UInt32.self) } return value } func decode(_ type: UInt64.Type) throws -> UInt64 { guard let valueAsString = attributeValue.N, let value = UInt64(valueAsString) else { throw getTypeMismatchError(expectation: UInt64.self) } return value } func decode(_ type: Float.Type) throws -> Float { guard let valueAsString = attributeValue.N, let value = Float(valueAsString) else { throw getTypeMismatchError(expectation: Float.self) } return value } func decode(_ type: Double.Type) throws -> Double { guard let valueAsString = attributeValue.N, let value = Double(valueAsString) else { throw getTypeMismatchError(expectation: Double.self) } return value } func decode(_ type: String.Type) throws -> String { guard let value = attributeValue.S else { throw getTypeMismatchError(expectation: String.self) } return value } func decode<T>(_ type: T.Type) throws -> T where T: Decodable { if type == Date.self { let dateAsString = try String(from: self) guard let date = dateAsString.dateFromISO8601 as? T else { throw getTypeMismatchError(expectation: Date.self) } return date } return try T(from: self) } private func getTypeMismatchError(expectation: Any.Type) -> DecodingError { let description = "Expected to decode \(expectation)." let context = DecodingError.Context(codingPath: codingPath, debugDescription: description) return DecodingError.typeMismatch(expectation, context) } } extension InternalSingleValueDecodingContainer: Swift.Decoder { func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey { let container = InternalKeyedDecodingContainer<Key>(decodingContainer: self) return KeyedDecodingContainer<Key>(container) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { let container = InternalUnkeyedDecodingContainer(decodingContainer: self) return container } func singleValueContainer() throws -> SingleValueDecodingContainer { return self } }
32.145631
108
0.622773
8a57e127294c888777ba71afc78542ac782a4f8b
2,250
// // AppDelegate.swift // Hahabbit // // Created by TSAI TSUNG-HAN on 2021/5/12. // import UIKit import Firebase import IQKeyboardManagerSwift import UserNotifications import SwiftTheme @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // setup theme color ThemeManager.setTheme(index: UserManager.shared.themeColorNumber) UITabBar.appearance().theme_tintColor = ThemeColor.color // setup NavigationBar back button let image = UIImage(named: "arrowCircleLeft") UINavigationBar.appearance().backIndicatorImage = image UINavigationBar.appearance().backIndicatorTransitionMaskImage = image UINavigationBar.appearance().theme_tintColor = ThemeColor.color // setup IQKeyboard IQKeyboardManager.shared.enable = true IQKeyboardManager.shared.disabledDistanceHandlingClasses.append(ChatPageViewController.self) // setup Firebase FirebaseApp.configure() // request Notification Authorization UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge, .carPlay]) { _, error in if let err = error { print(err) } } 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.290323
177
0.760444
183a194cda6db152c7e52dbe4ff5f7e51ad122d4
26,507
// // CloudKitManager.swift // CloudKitSyncPOC // // Created by Nick Harris on 12/16/15. // Copyright © 2015 Nick Harris. All rights reserved. // import Foundation import UIKit import CoreData import CloudKit class CloudKitManager { // MARK: Class Properties fileprivate let privateDB: CKDatabase fileprivate let coreDataManager: CoreDataManager fileprivate let operationQueue: OperationQueue // MARK: init init(coreDataManager: CoreDataManager) { self.coreDataManager = coreDataManager self.operationQueue = OperationQueue() self.operationQueue.maxConcurrentOperationCount = 1 privateDB = CKContainer.default().privateCloudDatabase CKContainer.default().accountStatus { [unowned self] (accountStatus, error) in switch accountStatus { case .available: self.initializeCloudKit() default: self.handleCloudKitUnavailable(accountStatus, error: error! as NSError) } } } // MARK: Public Functions func saveChangesToCloudKit(_ insertedObjects: [NSManagedObjectID], modifiedManagedObjectIDs: [NSManagedObjectID], deletedRecordIDs: [CKRecordID]) { // create the operations let createRecordsForNewObjectsOperation = CreateRecordsForNewObjectsOperation(insertedManagedObjectIDs: insertedObjects, coreDataManager: coreDataManager) let fetchModifiedRecordsOperation = FetchRecordsForModifiedObjectsOperation(coreDataManager: coreDataManager, modifiedManagedObjectIDs: modifiedManagedObjectIDs) let modifyRecordsOperation = ModifyRecordsFromManagedObjectsOperation(coreDataManager: coreDataManager, cloudKitManager: self, modifiedManagedObjectIDs: modifiedManagedObjectIDs, deletedRecordIDs: deletedRecordIDs) let clearDeletedCloudKitObjectsOperation = ClearDeletedCloudKitObjectsOperation(coreDataManager: coreDataManager) let transferCreatedRecordsOperation = BlockOperation() { [unowned modifyRecordsOperation, unowned createRecordsForNewObjectsOperation] in modifyRecordsOperation.recordsToSave = createRecordsForNewObjectsOperation.createdRecords } let transferFetchedRecordsOperation = BlockOperation() { [unowned modifyRecordsOperation, unowned fetchModifiedRecordsOperation] in modifyRecordsOperation.fetchedRecordsToModify = fetchModifiedRecordsOperation.fetchedRecords } // setup dependencies transferCreatedRecordsOperation.addDependency(createRecordsForNewObjectsOperation) transferFetchedRecordsOperation.addDependency(fetchModifiedRecordsOperation) modifyRecordsOperation.addDependency(transferCreatedRecordsOperation) modifyRecordsOperation.addDependency(transferFetchedRecordsOperation) clearDeletedCloudKitObjectsOperation.addDependency(modifyRecordsOperation) // add the operations to the queue operationQueue.addOperation(createRecordsForNewObjectsOperation) operationQueue.addOperation(transferCreatedRecordsOperation) operationQueue.addOperation(fetchModifiedRecordsOperation) operationQueue.addOperation(transferFetchedRecordsOperation) operationQueue.addOperation(modifyRecordsOperation) operationQueue.addOperation(clearDeletedCloudKitObjectsOperation) } func performFullSync() { queueFullSyncOperations() } func syncZone(_ zoneName: String, completionBlockOperation: BlockOperation) { if let cloudKitZone = CloudKitZone(rawValue: zoneName) { // suspend the queue so nothing finishes before all our dependencies are setup operationQueue.isSuspended = true // queue up the change operations for a zone let saveChangedRecordsToCoreDataOperation = queueChangeOperationsForZone(cloudKitZone, modifyRecordZonesOperation: nil) // add our completion block to the queue as well to handle background fetches completionBlockOperation.addDependency(saveChangedRecordsToCoreDataOperation) operationQueue.addOperation(completionBlockOperation) // let the queue begin firing again operationQueue.isSuspended = false } } // MARK: CloudKit Unavailable Functions fileprivate func handleCloudKitUnavailable(_ accountStatus: CKAccountStatus, error:NSError?) { cloudKitEnabled = false var errorText = "Synchronization is disabled\n" if let error = error { print("handleCloudKitUnavailable ERROR: \(error)") print("An error occured: \(error.localizedDescription)") errorText += error.localizedDescription } switch accountStatus { case .restricted: errorText += "iCloud is not available due to restrictions" case .noAccount: errorText += "There is no CloudKit account setup.\nYou can setup iCloud in the Settings app." default: break } displayCloudKitNotAvailableError(errorText) } fileprivate func displayCloudKitNotAvailableError(_ errorText: String) { if !suppressCloudKitEnabledError { DispatchQueue.main.async(execute: { let alertController = UIAlertController(title: "iCloud Synchronization Error", message: errorText, preferredStyle: UIAlertControllerStyle.alert) let firstButton = CloudKitPromptButtonType.OK let firstButtonAction = UIAlertAction(title: firstButton.rawValue, style: firstButton.actionStyle(), handler: { (action: UIAlertAction) -> Void in firstButton.performAction() }); alertController.addAction(firstButtonAction) let secondButton = CloudKitPromptButtonType.DontShowAgain let secondButtonAction = UIAlertAction(title: secondButton.rawValue, style: secondButton.actionStyle(), handler: { (action: UIAlertAction) -> Void in secondButton.performAction() }); alertController.addAction(secondButtonAction) if let appDelegate = UIApplication.shared.delegate, let appWindow = appDelegate.window!, // yes the UIWindow really is window?? - http://stackoverflow.com/questions/28901893/why-is-main-window-of-type-double-optional let rootViewController = appWindow.rootViewController { rootViewController.present(alertController, animated: true, completion: nil) } }) } } // MARK: CloudKit Init Functions fileprivate func initializeCloudKit() { print("CloudKit IS available") cloudKitEnabled = true // suspend the operation queue until all operations are created and enqueued operationQueue.isSuspended = true // self.deleteRecordZone() let modifyRecordZonesOperation = queueZoneInitilizationOperations() let modifySubscriptionsOperation = queueSubscriptionInitilizationOperations() // set the dependencies between zones and subscriptions (we need the zones to exist before any subscriptions can be created) modifySubscriptionsOperation.addDependency(modifyRecordZonesOperation) let syncAllZonesOperation = BlockOperation { [unowned self] in self.queueFullSyncOperations() } syncAllZonesOperation.addDependency(modifyRecordZonesOperation) operationQueue.addOperation(syncAllZonesOperation) // all init operations are ready, start the queue operationQueue.isSuspended = false } fileprivate func queueFullSyncOperations() { // 1. Fetch all the changes both locally and from each zone let fetchOfflineChangesFromCoreDataOperation = FetchOfflineChangesFromCoreDataOperation(coreDataManager: coreDataManager, cloudKitManager: self, entityNames: ModelObjectType.allCloudKitModelObjectTypes) let fetchCarZoneChangesOperation = FetchRecordChangesForCloudKitZoneOperation(cloudKitZone: CloudKitZone.CarZone) let fetchTruckZoneChangesOperation = FetchRecordChangesForCloudKitZoneOperation(cloudKitZone: CloudKitZone.TruckZone) let fetchBusZoneChangesOperation = FetchRecordChangesForCloudKitZoneOperation(cloudKitZone: CloudKitZone.BusZone) // 2. Process the changes after transfering let processSyncChangesOperation = ProcessSyncChangesOperation(coreDataManager: coreDataManager) let transferDataToProcessSyncChangesOperation = BlockOperation { [unowned processSyncChangesOperation, unowned fetchOfflineChangesFromCoreDataOperation, unowned fetchCarZoneChangesOperation, unowned fetchTruckZoneChangesOperation, unowned fetchBusZoneChangesOperation] in processSyncChangesOperation.preProcessLocalChangedObjectIDs.append(contentsOf: fetchOfflineChangesFromCoreDataOperation.updatedManagedObjects) processSyncChangesOperation.preProcessLocalDeletedRecordIDs.append(contentsOf: fetchOfflineChangesFromCoreDataOperation.deletedRecordIDs) processSyncChangesOperation.preProcessServerChangedRecords.append(contentsOf: fetchCarZoneChangesOperation.changedRecords) processSyncChangesOperation.preProcessServerChangedRecords.append(contentsOf: fetchTruckZoneChangesOperation.changedRecords) processSyncChangesOperation.preProcessServerChangedRecords.append(contentsOf: fetchBusZoneChangesOperation.changedRecords) processSyncChangesOperation.preProcessServerDeletedRecordIDs.append(contentsOf: fetchCarZoneChangesOperation.deletedRecordIDs) processSyncChangesOperation.preProcessServerDeletedRecordIDs.append(contentsOf: fetchTruckZoneChangesOperation.deletedRecordIDs) processSyncChangesOperation.preProcessServerDeletedRecordIDs.append(contentsOf: fetchBusZoneChangesOperation.deletedRecordIDs) } // 3. Fetch records from the server that we need to change let fetchRecordsForModifiedObjectsOperation = FetchRecordsForModifiedObjectsOperation(coreDataManager: coreDataManager) let transferDataToFetchRecordsOperation = BlockOperation { [unowned fetchRecordsForModifiedObjectsOperation, unowned processSyncChangesOperation] in fetchRecordsForModifiedObjectsOperation.preFetchModifiedRecords = processSyncChangesOperation.postProcessChangesToServer } // 4. Modify records in the cloud let modifyRecordsFromManagedObjectsOperation = ModifyRecordsFromManagedObjectsOperation(coreDataManager: coreDataManager, cloudKitManager: self) let transferDataToModifyRecordsOperation = BlockOperation { [unowned fetchRecordsForModifiedObjectsOperation, unowned modifyRecordsFromManagedObjectsOperation, unowned processSyncChangesOperation] in if let fetchedRecordsDictionary = fetchRecordsForModifiedObjectsOperation.fetchedRecords { modifyRecordsFromManagedObjectsOperation.fetchedRecordsToModify = fetchedRecordsDictionary } modifyRecordsFromManagedObjectsOperation.preModifiedRecords = processSyncChangesOperation.postProcessChangesToServer // also set the recordIDsToDelete from what we processed modifyRecordsFromManagedObjectsOperation.recordIDsToDelete = processSyncChangesOperation.postProcessDeletesToServer } // 5. Modify records locally let saveChangedRecordsToCoreDataOperation = SaveChangedRecordsToCoreDataOperation(coreDataManager: coreDataManager) let transferDataToSaveChangesToCoreDataOperation = BlockOperation { [unowned saveChangedRecordsToCoreDataOperation, unowned processSyncChangesOperation] in saveChangedRecordsToCoreDataOperation.changedRecords = processSyncChangesOperation.postProcessChangesToCoreData saveChangedRecordsToCoreDataOperation.deletedRecordIDs = processSyncChangesOperation.postProcessDeletesToCoreData } // 6. Delete all of the DeletedCloudKitObjects let clearDeletedCloudKitObjectsOperation = ClearDeletedCloudKitObjectsOperation(coreDataManager: coreDataManager) // set dependencies // 1. transfering all the fetched data to process for conflicts transferDataToProcessSyncChangesOperation.addDependency(fetchOfflineChangesFromCoreDataOperation) transferDataToProcessSyncChangesOperation.addDependency(fetchCarZoneChangesOperation) transferDataToProcessSyncChangesOperation.addDependency(fetchTruckZoneChangesOperation) transferDataToProcessSyncChangesOperation.addDependency(fetchBusZoneChangesOperation) // 2. processing the data onces its transferred processSyncChangesOperation.addDependency(transferDataToProcessSyncChangesOperation) // 3. fetching records changed local transferDataToFetchRecordsOperation.addDependency(processSyncChangesOperation) fetchRecordsForModifiedObjectsOperation.addDependency(transferDataToFetchRecordsOperation) // 4. modifying records in CloudKit transferDataToModifyRecordsOperation.addDependency(fetchRecordsForModifiedObjectsOperation) modifyRecordsFromManagedObjectsOperation.addDependency(transferDataToModifyRecordsOperation) // 5. modifying records in CoreData transferDataToSaveChangesToCoreDataOperation.addDependency(processSyncChangesOperation) saveChangedRecordsToCoreDataOperation.addDependency(transferDataToModifyRecordsOperation) // 6. clear the deleteCloudKitObjects clearDeletedCloudKitObjectsOperation.addDependency(saveChangedRecordsToCoreDataOperation) // add operations to the queue operationQueue.addOperation(fetchOfflineChangesFromCoreDataOperation) operationQueue.addOperation(fetchCarZoneChangesOperation) operationQueue.addOperation(fetchTruckZoneChangesOperation) operationQueue.addOperation(fetchBusZoneChangesOperation) operationQueue.addOperation(transferDataToProcessSyncChangesOperation) operationQueue.addOperation(processSyncChangesOperation) operationQueue.addOperation(transferDataToFetchRecordsOperation) operationQueue.addOperation(fetchRecordsForModifiedObjectsOperation) operationQueue.addOperation(transferDataToModifyRecordsOperation) operationQueue.addOperation(modifyRecordsFromManagedObjectsOperation) operationQueue.addOperation(transferDataToSaveChangesToCoreDataOperation) operationQueue.addOperation(saveChangedRecordsToCoreDataOperation) operationQueue.addOperation(clearDeletedCloudKitObjectsOperation) } // MARK: RecordZone Functions fileprivate func queueZoneInitilizationOperations() -> CKModifyRecordZonesOperation { // 1. Fetch all the zones // 2. Process the returned zones and create arrays for zones that need creating and those that need deleting // 3. Modify the zones in cloudkit let fetchAllRecordZonesOperation = FetchAllRecordZonesOperation.fetchAllRecordZonesOperation() let processServerRecordZonesOperation = ProcessServerRecordZonesOperation() let modifyRecordZonesOperation = createModifyRecordZoneOperation(nil, recordZoneIDsToDelete: nil) let transferFetchedZonesOperation = BlockOperation() { [unowned fetchAllRecordZonesOperation, unowned processServerRecordZonesOperation] in if let fetchedRecordZones = fetchAllRecordZonesOperation.fetchedRecordZones { processServerRecordZonesOperation.preProcessRecordZoneIDs = Array(fetchedRecordZones.keys) } } let transferProcessedZonesOperation = BlockOperation() { [unowned modifyRecordZonesOperation, unowned processServerRecordZonesOperation] in modifyRecordZonesOperation.recordZonesToSave = processServerRecordZonesOperation.postProcessRecordZonesToCreate modifyRecordZonesOperation.recordZoneIDsToDelete = processServerRecordZonesOperation.postProcessRecordZoneIDsToDelete } transferFetchedZonesOperation.addDependency(fetchAllRecordZonesOperation) processServerRecordZonesOperation.addDependency(transferFetchedZonesOperation) transferProcessedZonesOperation.addDependency(processServerRecordZonesOperation) modifyRecordZonesOperation.addDependency(transferProcessedZonesOperation) operationQueue.addOperation(fetchAllRecordZonesOperation) operationQueue.addOperation(transferFetchedZonesOperation) operationQueue.addOperation(processServerRecordZonesOperation) operationQueue.addOperation(transferProcessedZonesOperation) operationQueue.addOperation(modifyRecordZonesOperation) return modifyRecordZonesOperation } fileprivate func deleteRecordZone() { let fetchAllRecordZonesOperation = FetchAllRecordZonesOperation.fetchAllRecordZonesOperation() let modifyRecordZonesOperation = createModifyRecordZoneOperation(nil, recordZoneIDsToDelete: nil) let dataTransferOperation = BlockOperation() { [unowned modifyRecordZonesOperation, unowned fetchAllRecordZonesOperation] in if let fetchedRecordZones = fetchAllRecordZonesOperation.fetchedRecordZones { modifyRecordZonesOperation.recordZoneIDsToDelete = Array(fetchedRecordZones.keys) } } dataTransferOperation.addDependency(fetchAllRecordZonesOperation) modifyRecordZonesOperation.addDependency(dataTransferOperation) operationQueue.addOperation(fetchAllRecordZonesOperation) operationQueue.addOperation(dataTransferOperation) operationQueue.addOperation(modifyRecordZonesOperation) } // MARK: Subscription Functions fileprivate func queueSubscriptionInitilizationOperations() -> CKModifySubscriptionsOperation { // 1. Fetch all subscriptions // 2. Process which need to be created and which need to be deleted // 3. Make the adjustments in iCloud let fetchAllSubscriptionsOperation = FetchAllSubscriptionsOperation.fetchAllSubscriptionsOperation() let processServerSubscriptionsOperation = ProcessServerSubscriptionsOperation() let modifySubscriptionsOperation = createModifySubscriptionOperation() let transferFetchedSubscriptionsOperation = BlockOperation() { [unowned processServerSubscriptionsOperation, unowned fetchAllSubscriptionsOperation] in processServerSubscriptionsOperation.preProcessFetchedSubscriptions = fetchAllSubscriptionsOperation.fetchedSubscriptions } let transferProcessedSubscriptionsOperation = BlockOperation() { [unowned modifySubscriptionsOperation, unowned processServerSubscriptionsOperation] in modifySubscriptionsOperation.subscriptionsToSave = processServerSubscriptionsOperation.postProcessSubscriptionsToCreate modifySubscriptionsOperation.subscriptionIDsToDelete = processServerSubscriptionsOperation.postProcessSubscriptionIDsToDelete } transferFetchedSubscriptionsOperation.addDependency(fetchAllSubscriptionsOperation) processServerSubscriptionsOperation.addDependency(transferFetchedSubscriptionsOperation) transferProcessedSubscriptionsOperation.addDependency(processServerSubscriptionsOperation) modifySubscriptionsOperation.addDependency(transferProcessedSubscriptionsOperation) operationQueue.addOperation(fetchAllSubscriptionsOperation) operationQueue.addOperation(transferFetchedSubscriptionsOperation) operationQueue.addOperation(processServerSubscriptionsOperation) operationQueue.addOperation(transferProcessedSubscriptionsOperation) operationQueue.addOperation(modifySubscriptionsOperation) return modifySubscriptionsOperation } // MARK: Sync Records fileprivate func queueChangeOperationsForZone(_ cloudKitZone: CloudKitZone, modifyRecordZonesOperation: CKModifyRecordZonesOperation?) -> SaveChangedRecordsToCoreDataOperation { // there are two operations that need to be chained together for each zone // the first is to fetch record changes // the second is to save those changes to CoreData // we'll also need a block operation to transfer data between them let fetchRecordChangesOperation = FetchRecordChangesForCloudKitZoneOperation(cloudKitZone: cloudKitZone) let saveChangedRecordsToCoreDataOperation = SaveChangedRecordsToCoreDataOperation(coreDataManager: coreDataManager) let dataTransferOperation = BlockOperation() { [unowned saveChangedRecordsToCoreDataOperation, unowned fetchRecordChangesOperation] in print("addChangeOperationsForZone.dataTransferOperation") saveChangedRecordsToCoreDataOperation.changedRecords = fetchRecordChangesOperation.changedRecords saveChangedRecordsToCoreDataOperation.deletedRecordIDs = fetchRecordChangesOperation.deletedRecordIDs } // set the dependencies if let modifyRecordZonesOperation = modifyRecordZonesOperation { fetchRecordChangesOperation.addDependency(modifyRecordZonesOperation) } dataTransferOperation.addDependency(fetchRecordChangesOperation) saveChangedRecordsToCoreDataOperation.addDependency(dataTransferOperation) // add the operations to the queue operationQueue.addOperation(fetchRecordChangesOperation) operationQueue.addOperation(dataTransferOperation) operationQueue.addOperation(saveChangedRecordsToCoreDataOperation) return saveChangedRecordsToCoreDataOperation } // MARK: Create Operation Helper Functions fileprivate func createModifyRecordZoneOperation(_ recordZonesToSave: [CKRecordZone]?, recordZoneIDsToDelete: [CKRecordZoneID]?) -> CKModifyRecordZonesOperation { let modifyRecordZonesOperation = CKModifyRecordZonesOperation(recordZonesToSave: recordZonesToSave, recordZoneIDsToDelete: recordZoneIDsToDelete) modifyRecordZonesOperation.modifyRecordZonesCompletionBlock = { (modifiedRecordZones: [CKRecordZone]?, deletedRecordZoneIDs: [CKRecordZoneID]?, error: NSError?) -> Void in print("--- CKModifyRecordZonesOperation.modifyRecordZonesOperation") if let error = error { print("createModifyRecordZoneOperation ERROR: \(error)") return } if let modifiedRecordZones = modifiedRecordZones { for recordZone in modifiedRecordZones { print("Modified recordZone: \(recordZone)") } } if let deletedRecordZoneIDs = deletedRecordZoneIDs { for zoneID in deletedRecordZoneIDs { print("Deleted zoneID: \(zoneID)") } } } as? ([CKRecordZone]?, [CKRecordZoneID]?, Error?) -> Void return modifyRecordZonesOperation } fileprivate func createModifySubscriptionOperation() -> CKModifySubscriptionsOperation { let modifySubscriptionsOperation = CKModifySubscriptionsOperation() modifySubscriptionsOperation.modifySubscriptionsCompletionBlock = { (modifiedSubscriptions: [CKSubscription]?, deletedSubscriptionIDs: [String]?, error: NSError?) -> Void in print("--- CKModifySubscriptionsOperation.modifySubscriptionsCompletionBlock") if let error = error { print("createModifySubscriptionOperation ERROR: \(error)") return } if let modifiedSubscriptions = modifiedSubscriptions { for subscription in modifiedSubscriptions { print("Modified subscription: \(subscription)") } } if let deletedSubscriptionIDs = deletedSubscriptionIDs { for subscriptionID in deletedSubscriptionIDs { print("Deleted subscriptionID: \(subscriptionID)") } } } as? ([CKSubscription]?, [String]?, Error?) -> Void return modifySubscriptionsOperation } // MARK: NSUserDefault Properties var lastCloudKitSyncTimestamp: Date { get { if let lastCloudKitSyncTimestamp = UserDefaults.standard.object(forKey: CloudKitUserDefaultKeys.LastCloudKitSyncTimestamp.rawValue) as? Date { return lastCloudKitSyncTimestamp } else { return Date.distantPast } } set { UserDefaults.standard.set(newValue, forKey: CloudKitUserDefaultKeys.LastCloudKitSyncTimestamp.rawValue) } } fileprivate var cloudKitEnabled: Bool { get { return UserDefaults.standard.bool(forKey: CloudKitUserDefaultKeys.CloudKitEnabledKey.rawValue) } set { UserDefaults.standard.set(newValue, forKey: CloudKitUserDefaultKeys.CloudKitEnabledKey.rawValue) } } fileprivate var suppressCloudKitEnabledError: Bool { get { return UserDefaults.standard.bool(forKey: CloudKitUserDefaultKeys.SuppressCloudKitErrorKey.rawValue) } } }
51.670565
222
0.72147
fcbc2421f3764d7f3538c37a3bd46799588657af
571
// // FileTests.swift // EP DiagramTests // // Created by David Mann on 6/28/20. // Copyright © 2020 EP Studios. All rights reserved. // import XCTest @testable import EP_Diagram class FileTests: XCTestCase { func testCleanupFilename() { var filename = DiagramIO.cleanupFilename("x:x/y:z") XCTAssertEqual("x_x_y_z", filename) filename = DiagramIO.cleanupFilename("abcde.tmp") XCTAssertEqual("abcde.tmp", filename) filename = DiagramIO.cleanupFilename("abcde\ntmp") XCTAssertEqual("abcde_tmp", filename) } }
23.791667
59
0.674256
33aad226bb55970d401cb28af84cee41128c3bea
1,002
/** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { func constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? { if nums.count == 0 { return nil } if nums.count == 1 { return TreeNode(nums[0]) } let node = TreeNode(nums.max()!) let indexOfMax = nums.firstIndex(of: nums.max()!)! node.left = constructMaximumBinaryTree(Array(nums[..<indexOfMax])) node.right = constructMaximumBinaryTree(Array(nums[(indexOfMax+1)...])) return node } }
33.4
85
0.561876
1a5ba6bf60ac591bd0116474213a96b526aa655b
1,421
// // MessengerUITests.swift // MessengerUITests // // Created by Ayham Al Chouhuf on 4/19/21. // import XCTest class MessengerUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.046512
182
0.65658
8f1cc5552ee779c3c1c473df69908e189642c3c4
999
// // CalendarKit_SwiftTests.swift // CalendarKit-SwiftTests // // Created by Maurice Arikoglu on 29.11.17. // Copyright © 2017 Maurice Arikoglu. All rights reserved. // import XCTest @testable import CalendarKit_Swift class CalendarKit_SwiftTests: 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. } } }
27
111
0.661662
ff87d1e473a6321fd25edaf97def7a30a0c373e7
2,443
// // Talk.swift // PyConJP // // Created by Yutaro Muta on 7/11/16. // Copyright © 2016 PyCon JP. All rights reserved. // import Foundation struct Talk { let id: Int let title: String let description: String let speakers: [String] let startDate: Date let endDate: Date let day: String let startTime: String let endTime: String let category: String let room: Room let language: Language } extension Talk { init?(dictionary: [String: Any]) { guard let id = dictionary["id"] as? Int, let title = dictionary["title"] as? String, let description = dictionary["description"] as? String, let speakers = dictionary["speakers"] as? [String], let day = dictionary["day"] as? String, let startTime = dictionary["start"] as? String, let startDate = Date.date(from: day + " " + startTime), let endTime = dictionary["end"] as? String, let endDate = Date.date(from: day + " " + endTime), let category = dictionary["category"] as? String, let room = Room(dictionary["rooms"] as? String ?? ""), let language = Language(dictionary["language"] as? String ?? "") else { return nil } self.init(id: id, title: title, description: description, speakers: speakers, startDate: startDate, endDate: endDate, day: day, startTime: startTime, endTime: endTime, category: category, room: room, language: language) } init?(_ talkObject: TalkObject) { guard let room = talkObject.room, let language = talkObject.language else { return nil } self.init(id: talkObject.id, title: talkObject.title, description: talkObject.descriptionText, speakers: talkObject.speakers.components(separatedBy: ", "), startDate: talkObject.startDate, endDate: talkObject.endDate, day: talkObject.day, startTime: talkObject.startTime, endTime: talkObject.endTime, category: talkObject.category, room: room, language: language) } }
32.144737
96
0.535817
2fe30c8e4e7a6a87495cdaec50d9538b3dcd6d26
2,221
import Foundation import os.log #if DEBUG && true fileprivate var log = Logger( subsystem: Bundle.main.bundleIdentifier!, category: "SyncTxManager_PendingSettings" ) #else fileprivate var log = Logger(OSLog.disabled) #endif class SyncTxManager_PendingSettings: Equatable, CustomStringConvertible { enum EnableDisable{ case willEnable case willDisable } private weak var parent: SyncTxManager? let paymentSyncing: EnableDisable let delay: TimeInterval let startDate: Date let fireDate: Date init(_ parent: SyncTxManager, enableSyncing delay: TimeInterval) { let now = Date() self.parent = parent self.paymentSyncing = .willEnable self.delay = delay self.startDate = now self.fireDate = now + delay log.trace("init()") startTimer() } init(_ parent: SyncTxManager, disableSyncing delay: TimeInterval) { let now = Date() self.parent = parent self.paymentSyncing = .willDisable self.delay = delay self.startDate = now self.fireDate = now + delay log.trace("init()") startTimer() } deinit { log.trace("deinit()") } private func startTimer() { log.trace("startTimer()") let deadline: DispatchTime = DispatchTime.now() + fireDate.timeIntervalSinceNow DispatchQueue.global(qos: .utility).asyncAfter(deadline: deadline) {[weak self] in self?.approve() } } /// Automatically invoked after the timer expires. /// Can also be called manually to approve before the delay. /// func approve() { log.trace("approve()") if let parent = parent { parent.updateState(pending: self, approved: true) } } func cancel() { log.trace("cancel()") if let parent = parent { parent.updateState(pending: self, approved: false) } } var description: String { let dateStr = fireDate.description(with: Locale.current) switch paymentSyncing { case .willEnable: return "<SyncTxManager_PendingSettings: willEnable @ \(dateStr)>" case .willDisable: return "<SyncTxManager_PendingSettings: willDisable @ \(dateStr)>" } } static func == (lhs: SyncTxManager_PendingSettings, rhs: SyncTxManager_PendingSettings) -> Bool { return (lhs.paymentSyncing == rhs.paymentSyncing) && (lhs.fireDate == rhs.fireDate) } }
22.663265
98
0.710491
0ae9bd7ce179492bbe353a646d6dbe6d6055e43c
3,765
// // AppDelegate.swift // Habits // // Created by Mario Hahn on 13.03.20. // Copyright © 2020 Mario Hahn. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UITableView.appearance().tableFooterView = UIView() // 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. } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Habits") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
44.821429
199
0.667463
bf5ac53fa18c6cbfe8926b7984ac936bc48f6a5c
104
class Solution { func addDigits(num: Int) -> Int { return num - 9 * ((num - 1) / 9 ) } }
20.8
41
0.480769
5b77cff83fcf8acd7feb7cb169d2c2bfd35b7581
294
// // Project5App.swift // Project5 WatchKit Extension // // Created by Paul Hudson on 07/10/2020. // import SwiftUI @main struct Project5App: App { var body: some Scene { WindowGroup { NavigationView { ContentView() } } } }
14.7
41
0.540816
d79f4a14bcc6d93524e3ac93cc33a3ef1076d7ba
7,720
// // CurvedTabBar.swift // CustomTabBar // // Created by Zhi Zhou on 2020/7/14. // Copyright © 2020 Zhi Zhou. All rights reserved. // import UIKit open class CurvedTabBar: UITabBar { private enum ShapeLayerStyle { case mask, fill } private var maskShapeLayer: CALayer? private var fillShapeLayer: CALayer? private let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .systemThickMaterial)) private let centerButton = UIButton(type: .system) private var centerButtonWidthLayoutConstraint: NSLayoutConstraint? private var centerButtonHeightLayoutConstraint: NSLayoutConstraint? open var centerButtonBottomOffset: CGFloat = 5.0 public typealias ActionHandler = (UIButton) -> Void? public var centerActionHandler: ActionHandler? open override func draw(_ rect: CGRect) { setupShapeLayer() } open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let buttonRadius: CGFloat = bounds.height / 2 return point.y > 0 || (point.y >= -buttonRadius && (point.x >= center.x - buttonRadius) && (point.x <= center.x + buttonRadius)) } public override init(frame: CGRect) { super.init(frame: frame) setupInterface() } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() layoutCenterButton() } } extension CurvedTabBar { private func setupInterface() { setupEffectView() setupCenterButton() } private func setupEffectView() { effectView.contentView.layer.masksToBounds = false insertSubview(effectView, at: 0) effectView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ effectView.leftAnchor.constraint(equalTo: self.leftAnchor), effectView.rightAnchor.constraint(equalTo: self.rightAnchor), effectView.topAnchor.constraint(equalTo: self.topAnchor), effectView.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) } private func setupCenterButton() { centerButton.backgroundColor = .systemBlue centerButton.isPointerInteractionEnabled = true centerButton.pointerStyleProvider = { button, proposedEffect, proposedShape -> UIPointerStyle? in var rect = button.bounds.insetBy(dx: 0, dy: 0) rect = button.convert(rect, to: proposedEffect.preview.target.container) return UIPointerStyle(effect: .lift(proposedEffect.preview), shape: .roundedRect(rect, radius: button.bounds.width / 2)) } centerButton.addTarget(self, action: #selector(action(_:)), for: .touchUpInside) addSubview(centerButton) centerButton.translatesAutoresizingMaskIntoConstraints = false centerButtonWidthLayoutConstraint = centerButton.widthAnchor.constraint(equalToConstant: 0) centerButtonHeightLayoutConstraint = centerButton.heightAnchor.constraint(equalToConstant: 0) NSLayoutConstraint.activate([ centerButton.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0), centerButton.centerYAnchor.constraint(equalTo: self.topAnchor, constant: -centerButtonBottomOffset), centerButtonWidthLayoutConstraint!, centerButtonHeightLayoutConstraint! ]) } private func layoutCenterButton() { let centerImage = UIImage(systemName: "plus", withConfiguration: UIImage.SymbolConfiguration(pointSize: (bounds.height - safeAreaInsets.bottom) / 2 - centerButtonBottomOffset, weight: .medium))?.withRenderingMode(.alwaysOriginal).withTintColor(.systemBackground) centerButton.setImage(centerImage, for: .normal) // bounds.height - safeAreaInsets.bottom: 减去底部安全区域,防止按钮显示过大不协调。 let sizeConstant = bounds.height - safeAreaInsets.bottom - centerButtonBottomOffset centerButtonWidthLayoutConstraint?.constant = sizeConstant centerButtonHeightLayoutConstraint?.constant = sizeConstant centerButton.layer.cornerRadius = centerButton.bounds.height / 2 } } extension CurvedTabBar { private func setupShapeLayer() { let maskShapeLayer = CAShapeLayer() maskShapeLayer.path = createPath(style: .mask) if let oldShapeLayer = self.maskShapeLayer { effectView.layer.replaceSublayer(oldShapeLayer, with: maskShapeLayer) } else { effectView.layer.mask = maskShapeLayer } let fillShapeLayer = CAShapeLayer() fillShapeLayer.path = createPath(style: .fill) fillShapeLayer.strokeColor = UIColor.shadowColor.cgColor if let oldShapeLayer = self.fillShapeLayer { effectView.contentView.layer.replaceSublayer(oldShapeLayer, with: fillShapeLayer) } else { effectView.contentView.layer.addSublayer(fillShapeLayer) } self.maskShapeLayer = maskShapeLayer self.fillShapeLayer = fillShapeLayer } private func createPath(style: ShapeLayerStyle) -> CGPath { // bounds.height - safeAreaInsets.bottom: 减去底部安全区域,防止弧度显示过大不协调。 let height: CGFloat = (bounds.height - safeAreaInsets.bottom) / 2 let path = UIBezierPath() let centerWidth = frame.width / 2 let shadowHeight = 1 / UIScreen.main.scale path.move(to: CGPoint(x: 0, y: -shadowHeight)) path.addLine(to: CGPoint(x: centerWidth - height * 2, y: -shadowHeight)) path.addCurve(to: CGPoint(x: centerWidth, y: height), controlPoint1: CGPoint(x: centerWidth - height / 2, y: 0), controlPoint2: CGPoint(x: centerWidth - height, y: height)) path.addCurve(to: CGPoint(x: centerWidth + height * 2, y: -shadowHeight), controlPoint1: CGPoint(x: centerWidth + height, y: height), controlPoint2: CGPoint(x: centerWidth + height / 2, y: 0)) path.addLine(to: CGPoint(x: frame.width, y: -shadowHeight)) switch style { case .mask: path.addLine(to: CGPoint(x: frame.width, y: frame.height)) path.addLine(to: CGPoint(x: 0, y: frame.height)) default: break } path.close() return path.cgPath } } extension CurvedTabBar { @objc private func action(_ button: UIButton) { centerActionHandler?(button) } } fileprivate extension UIImage { /// 根据新的尺寸重绘图片 func resizeImage(withSize newSize: CGSize) -> UIImage? { let format = UIGraphicsImageRendererFormat() format.opaque = false format.scale = 0 let renderer = UIGraphicsImageRenderer(size: newSize, format: format) let newImage = renderer.image { (context) in let rect = CGRect(origin: .zero, size: newSize) draw(in: rect) } return newImage } } fileprivate extension UIColor { /// 分割线颜色 static var shadowColor: UIColor { return UIColor { (traitCollection) -> UIColor in if traitCollection.userInterfaceStyle == .dark { return UIColor(white: 1, alpha: 0.15) } else { return UIColor(white: 0, alpha: 0.3) } } } }
29.465649
270
0.633031
76ec7d20ca24ce862264eaa2977bd51966fab83e
483
// // viewHorizontal.swift // xo // // Created by Sajjad Hashemian on 9/25/15. // Copyright © 2015 Sajjad Hashemian. All rights reserved. // import Cocoa class viewHorizontal: NSView { override func drawRect(dirtyRect: NSRect) { let path = NSBezierPath(); let start = NSPoint(x: 0, y: self.frame.height / 2) let end = NSPoint(x:self.frame.width,y: self.frame.height / 2) path.moveToPoint(start) path.lineToPoint(end) NSColor.blackColor().set() path.stroke() } }
23
64
0.691511
2f039384f2684977907327236b0064ee8b89ff9d
8,752
// // ColorPickerMapView.swift // Alderis // // Created by Adam Demasi on 14/3/20. // Copyright © 2020 HASHBANG Productions. All rights reserved. // import UIKit internal protocol ColorPickerWheelViewDelegate: AnyObject { func colorPickerWheelView(didSelectColor color: Color) } internal class ColorPickerWheelView: UIView { weak var delegate: ColorPickerWheelViewDelegate? var color: Color { didSet { updateColor() } } private var containerView: UIView! private var wheelView: ColorPickerWheelInnerView! private var selectionView: ColorWell! private var selectionViewXConstraint: NSLayoutConstraint! private var selectionViewYConstraint: NSLayoutConstraint! private var selectionViewFingerDownConstraint: NSLayoutConstraint! private var isFingerDown = false private let touchDownFeedbackGenerator = UIImpactFeedbackGenerator(style: .medium) private let touchUpFeedbackGenerator = UIImpactFeedbackGenerator(style: .light) init(color: Color) { self.color = color super.init(frame: .zero) containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false containerView.clipsToBounds = true addSubview(containerView) containerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(gestureRecognizerFired(_:)))) containerView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(gestureRecognizerFired(_:)))) let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(gestureRecognizerFired(_:))) panGestureRecognizer.maximumNumberOfTouches = 1 containerView.addGestureRecognizer(panGestureRecognizer) wheelView = ColorPickerWheelInnerView() wheelView.translatesAutoresizingMaskIntoConstraints = false wheelView.handleLayout = { [weak self] in self?.setNeedsLayout() } containerView.addSubview(wheelView) selectionView = ColorWell() selectionView.translatesAutoresizingMaskIntoConstraints = false selectionView.isDragInteractionEnabled = false selectionView.isDropInteractionEnabled = false #if swift(>=5.3) if #available(iOS 14, *) { selectionView.isContextMenuInteractionEnabled = false } #endif containerView.addSubview(selectionView) selectionViewXConstraint = selectionView.leftAnchor.constraint(equalTo: containerView.leftAnchor) selectionViewYConstraint = selectionView.topAnchor.constraint(equalTo: containerView.topAnchor) // https://www.youtube.com/watch?v=Qs8kDiOwPBA selectionViewFingerDownConstraint = selectionView.widthAnchor.constraint(equalToConstant: 56) let selectionViewNormalConstraint = selectionView.widthAnchor.constraint(equalToConstant: UIFloat(24)) selectionViewNormalConstraint.priority = .defaultHigh // Remove minimum width constraint configured by ColorWell internally let selectionWidthConstraint = selectionView.constraints.first { $0.firstAnchor == selectionView.widthAnchor } selectionWidthConstraint?.isActive = false NSLayoutConstraint.activate([ containerView.centerXAnchor.constraint(equalTo: self.centerXAnchor), containerView.topAnchor.constraint(equalTo: self.topAnchor), containerView.bottomAnchor.constraint(equalTo: self.bottomAnchor), containerView.widthAnchor.constraint(equalTo: containerView.heightAnchor, constant: UIFloat(30)), wheelView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: UIFloat(30)), wheelView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: UIFloat(-30)), wheelView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: UIFloat(15)), wheelView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: UIFloat(-15)), selectionViewXConstraint, selectionViewYConstraint, selectionViewNormalConstraint, selectionView.heightAnchor.constraint(equalTo: selectionView.widthAnchor) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() updateSelectionPoint() } private func updateColor() { wheelView.brightness = color.brightness selectionView.backgroundColor = color.uiColor updateSelectionPoint() } private func updateSelectionPoint() { let colorPoint = pointForColor(color, in: wheelView.frame.size) let point = CGPoint(x: wheelView.frame.origin.x + colorPoint.x - (selectionView.frame.size.width / 2), y: min( frame.size.height - selectionView.frame.size.height - 1, max(1, wheelView.frame.origin.y + colorPoint.y - (selectionView.frame.size.height / 2)) )) selectionViewXConstraint.constant = point.x selectionViewYConstraint.constant = point.y } private func colorAt(position: CGPoint, in size: CGSize) -> Color { let point = CGPoint(x: (size.width / 2) - position.x, y: (size.height / 2) - position.y) let h = 180 + round(atan2(point.y, point.x) * (180 / .pi)) let handleRange = size.width / 2 let handleDistance = min(sqrt(point.x * point.x + point.y * point.y), handleRange) let s = round(100 / handleRange * handleDistance) return Color(hue: h / 360, saturation: s / 100, brightness: color.brightness, alpha: 1) } private func pointForColor(_ color: Color, in size: CGSize) -> CGPoint { let handleRange = size.width / 2 let handleAngle = (color.hue * 360) * (.pi / 180) let handleDistance = color.saturation * handleRange return CGPoint(x: (size.width / 2) + handleDistance * cos(handleAngle), y: (size.height / 2) + handleDistance * sin(handleAngle)) } @objc private func gestureRecognizerFired(_ sender: UIGestureRecognizer) { switch sender.state { case .began, .changed, .ended: var location = sender.location(in: containerView) location.x -= wheelView.frame.origin.x location.y -= wheelView.frame.origin.y color = colorAt(position: location, in: wheelView.frame.size) delegate?.colorPickerWheelView(didSelectColor: color) case .possible, .cancelled, .failed: break @unknown default: break } if sender is UITapGestureRecognizer { return } switch sender.state { case .began, .ended, .cancelled: isFingerDown = sender.state == .began selectionViewFingerDownConstraint.isActive = isFingerDown && !isCatalyst updateSelectionPoint() UIView.animate(withDuration: 0.2, animations: { self.containerView.layoutIfNeeded() self.updateSelectionPoint() }, completion: { _ in self.updateSelectionPoint() }) if sender.state == .began { touchDownFeedbackGenerator.impactOccurred() } else { touchUpFeedbackGenerator.impactOccurred() } case .possible, .changed, .failed: break @unknown default: break } } } private class ColorPickerWheelInnerView: UIView { private var brightnessView: UIView! var brightness: CGFloat { get { 1 - brightnessView.alpha } set { brightnessView.alpha = 1 - newValue } } var handleLayout: (() -> Void)! private var saturationMask: GradientView! override init(frame: CGRect) { super.init(frame: frame) clipsToBounds = true let hueView = GradientView() hueView.translatesAutoresizingMaskIntoConstraints = false hueView.autoresizingMask = [.flexibleWidth, .flexibleHeight] hueView.gradientLayer.type = .conic hueView.gradientLayer.colors = Color.Component.hue.sliderTintColor(for: Color(red: 1, green: 0, blue: 0, alpha: 1)).map(\.uiColor.cgColor) hueView.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5) hueView.gradientLayer.endPoint = CGPoint(x: 0.5, y: 0) hueView.gradientLayer.transform = CATransform3DMakeRotation(0.5 * .pi, 0, 0, 1) addSubview(hueView) let saturationView = UIView() saturationView.translatesAutoresizingMaskIntoConstraints = false saturationView.autoresizingMask = [.flexibleWidth, .flexibleHeight] saturationView.backgroundColor = .white addSubview(saturationView) saturationMask = GradientView() saturationMask.gradientLayer.type = .radial saturationMask.gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor] saturationMask.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5) saturationMask.gradientLayer.endPoint = CGPoint(x: 1, y: 1) saturationView.mask = saturationMask brightnessView = UIView() brightnessView.translatesAutoresizingMaskIntoConstraints = false brightnessView.autoresizingMask = [.flexibleWidth, .flexibleHeight] brightnessView.backgroundColor = .black addSubview(brightnessView) } convenience init() { self.init(frame: .zero) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = frame.size.height / 2 saturationMask.frame = bounds handleLayout() } }
36.016461
140
0.761997
79f48786946ed0e1953fe3f757d888e92ad3c1c5
1,563
// // NSObject+JY.swift // JYFoundation // // Created by Scott Rong on 2017/3/25. // Copyright © 2018年 jayasme All rights reserved. // import Foundation import ObjectiveC extension NSObject { public func jy_getAssociatedObject(key: String) -> Any? { let key: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: key.hashValue) return objc_getAssociatedObject(self, key) } public func jy_setAssociatedObject(key: String, object: Any?) { guard let object = object else { jy_removeAssociationObject(key: key) return } // determin the type of association storage policy var policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_COPY_NONATOMIC if object is NSString || object is NSNumber { policy = .OBJC_ASSOCIATION_COPY_NONATOMIC } else if object is NSObject { policy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC } else { policy = .OBJC_ASSOCIATION_ASSIGN } jy_setAssociatedObject(key: key, object: object, policy: policy) } public func jy_setAssociatedObject(key: String, object: Any, policy: objc_AssociationPolicy) { let key: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: key.hashValue) objc_setAssociatedObject(self, key, object, policy) } public func jy_removeAssociationObject(key: String) { let key: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: key.hashValue) objc_removeAssociatedObjects(key ?? "") } }
32.5625
98
0.667306
ebc993c2151fdcdfbd3886e919aecafbb20a1fdc
305
//: [Previous](@previous) import Foundation var queue = CircularQueue(capacity: 3, defaultValue: -1) //queue.dequeue() queue.enqueue(elem: 4) queue.enqueue(elem: 2) queue.enqueue(elem: 2) queue.enqueue(elem: 2) queue.enqueue(elem: 2) queue.dequeue() queue.dequeue() //queue.dequeue() print("\(queue)")
17.941176
56
0.714754
76bc590ebf9c3637d951647a27fbd7c38dcd8334
2,593
// The local grid computing cluster. public class SporificaVirus { // Function type used as status change callback by the infection burst // process. public typealias Callback = (Grid.Point) -> () var grid: Grid var virus: Virus var listeners: [Grid.Status: Callback] = [:] // Create a computing cluster given a string description of the grid and its // virus generation. Returns nil if parsing the grid failed. public convenience init?(grid s: String, generation: Virus.Generation) { let xs = s.split(separator: "\n").map(String.init) self.init(grid: xs, generation: generation) } // Create a computing cluster given a string description of the grid and its // virus generation. Returns nil if parsing the grid failed. public init?(grid xs: [String], generation: Virus.Generation) { guard let grid = Grid(xs) else { return nil } self.grid = grid self.virus = Virus(heading: .up, position: .origin, generation: generation) } // Register the given callback function to be called when the provided status // change arise. Returns the callback previously setup for the event if any. @discardableResult public func on(_ event: Grid.Status, callback: @escaping Callback) -> Callback? { let old = listeners[event] listeners[event] = callback return old } // Make the virus burst a given number of time in this computing cluster. public func burst(times: Int = 1) { for _ in 0..<times { let current = virus.position // the current node let status = virus.burst(in: grid) // Notify listener if any. if let callback = listeners[status] { callback(current) } } } // Returns a description of the grid with the virus frop the top-left (tl) // point to the bottom-right (br) point included. public func draw(_ tl: Grid.Point, _ br: Grid.Point) -> String { // Helper giving the prefix to display just before the given position. func separator(_ p: Grid.Point) -> String { switch p { case _ where p.x == tl.x: return "" case virus.position: return "[" case virus.position[.right]: return "]" default: return " " } } var description = "" for y in tl.y...br.y { for x in tl.x...br.x { let position = Grid.Point(x: x, y: y) description.append(separator(position)) description.append(grid[position].rawValue) } if y != br.y { // don't finish with a newline. description.append("\n") } } return description } }
35.520548
83
0.643656
4b10b09b17e1919135a417147ba733ca67b90e43
1,209
// // WGColors.swift // TheWordGame // // Created by Daniel McCrystal on 6/13/17. // Copyright © 2017 Lampshade Software. All rights reserved. // import UIKit class WordGameUI { static let yellow = UIColor(red: 255 / 256, green: 208 / 256, blue: 60 / 256, alpha: 1.0) static let red = UIColor(red: 255 / 256, green: 137 / 256, blue: 119 / 256, alpha: 1.0) static let blue = UIColor(red: 181 / 256, green: 213 / 256, blue: 255 / 256, alpha: 1.0) static let green = UIColor(red: 134 / 256, green: 255 / 256, blue: 134 / 256, alpha: 1.0) static let dark = UIColor(red: 34 / 256, green: 40 / 256, blue: 47 / 256, alpha: 1.0) static let lightDark = UIColor(red: 34 * 1.5 / 256, green: 40 * 1.5 / 256, blue: 47 * 1.5 / 256, alpha: 1.0) static func font(size: Int) -> UIFont { return UIFont(name: "GillSans-Light", size: CGFloat(size))! } static func getBanner(view: UIView) -> UIView { let width = view.bounds.width let height = view.bounds.height let bannerView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height * 0.1)) bannerView.backgroundColor = WordGameUI.yellow return bannerView } }
35.558824
109
0.616212
3882ac3c4c5f914790fea3a1697139af57b51c06
8,675
/* file: unary_boolean_expression.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY unary_boolean_expression ABSTRACT SUPERTYPE OF ( ONEOF ( not_expression, odd_function ) ) SUBTYPE OF ( boolean_expression, unary_generic_expression ); END_ENTITY; -- unary_boolean_expression (line:33182 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) generic_expression (no local attributes) SUPER- ENTITY(2) expression (no local attributes) SUPER- ENTITY(3) boolean_expression (no local attributes) SUPER- ENTITY(4) unary_generic_expression ATTR: operand, TYPE: generic_expression -- EXPLICIT -- possibly overriden by ENTITY: linearized_table_function, TYPE: maths_function ENTITY: restriction_function, TYPE: maths_space ENTITY: repackaging_function, TYPE: maths_function ENTITY: not_expression, TYPE: boolean_expression ENTITY: value_function, TYPE: string_expression ENTITY: reindexed_array_function, TYPE: maths_function ENTITY: homogeneous_linear_function, TYPE: maths_function ENTITY: b_spline_function, TYPE: maths_function ENTITY: length_function, TYPE: string_expression ENTITY: partial_derivative_function, TYPE: maths_function ENTITY: odd_function, TYPE: numeric_expression ENTITY: rationalize_function, TYPE: maths_function ENTITY: general_linear_function, TYPE: maths_function ENTITY: unary_numeric_expression, TYPE: numeric_expression ENTITY: definite_integral_function, TYPE: maths_function ENTITY(SELF) unary_boolean_expression (no local attributes) SUB- ENTITY(6) not_expression REDCR: operand, TYPE: boolean_expression -- EXPLICIT -- OVERRIDING ENTITY: unary_generic_expression SUB- ENTITY(7) odd_function REDCR: operand, TYPE: numeric_expression -- EXPLICIT -- OVERRIDING ENTITY: unary_generic_expression */ //MARK: - Partial Entity public final class _unary_boolean_expression : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eUNARY_BOOLEAN_EXPRESSION.self } //ATTRIBUTES // (no local attributes) public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init() { super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 0 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } self.init( ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY unary_boolean_expression ABSTRACT SUPERTYPE OF ( ONEOF ( not_expression, odd_function ) ) SUBTYPE OF ( boolean_expression, unary_generic_expression ); END_ENTITY; -- unary_boolean_expression (line:33182 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eUNARY_BOOLEAN_EXPRESSION : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _unary_boolean_expression.self } public let partialEntity: _unary_boolean_expression //MARK: SUPERTYPES public let super_eGENERIC_EXPRESSION: eGENERIC_EXPRESSION // [1] public let super_eEXPRESSION: eEXPRESSION // [2] public let super_eBOOLEAN_EXPRESSION: eBOOLEAN_EXPRESSION // [3] public let super_eUNARY_GENERIC_EXPRESSION: eUNARY_GENERIC_EXPRESSION // [4] public var super_eUNARY_BOOLEAN_EXPRESSION: eUNARY_BOOLEAN_EXPRESSION { return self } // [5] //MARK: SUBTYPES public var sub_eNOT_EXPRESSION: eNOT_EXPRESSION? { // [6] return self.complexEntity.entityReference(eNOT_EXPRESSION.self) } public var sub_eODD_FUNCTION: eODD_FUNCTION? { // [7] return self.complexEntity.entityReference(eODD_FUNCTION.self) } //MARK: ATTRIBUTES /// __EXPLICIT__ attribute /// - origin: SUPER( ``eUNARY_GENERIC_EXPRESSION`` ) public var OPERAND: eGENERIC_EXPRESSION { get { return SDAI.UNWRAP( super_eUNARY_GENERIC_EXPRESSION.partialEntity._operand ) } set(newValue) { let partial = super_eUNARY_GENERIC_EXPRESSION.partialEntity partial._operand = SDAI.UNWRAP(newValue) } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_unary_boolean_expression.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eGENERIC_EXPRESSION.self) else { return nil } self.super_eGENERIC_EXPRESSION = super1 guard let super2 = complexEntity?.entityReference(eEXPRESSION.self) else { return nil } self.super_eEXPRESSION = super2 guard let super3 = complexEntity?.entityReference(eBOOLEAN_EXPRESSION.self) else { return nil } self.super_eBOOLEAN_EXPRESSION = super3 guard let super4 = complexEntity?.entityReference(eUNARY_GENERIC_EXPRESSION.self) else { return nil } self.super_eUNARY_GENERIC_EXPRESSION = super4 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "UNARY_BOOLEAN_EXPRESSION", type: self, explicitAttributeCount: 0) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eGENERIC_EXPRESSION.self) entityDef.add(supertype: eEXPRESSION.self) entityDef.add(supertype: eBOOLEAN_EXPRESSION.self) entityDef.add(supertype: eUNARY_GENERIC_EXPRESSION.self) entityDef.add(supertype: eUNARY_BOOLEAN_EXPRESSION.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "OPERAND", keyPath: \eUNARY_BOOLEAN_EXPRESSION.OPERAND, kind: .explicit, source: .superEntity, mayYieldEntityReference: true) return entityDef } } }
35.995851
185
0.720807
aca0fac3d8e27d4ea8578c68fe532b83be39c1f0
753
// // Copyright © 2021 Jesús Alfredo Hernández Alarcón. All rights reserved. // import Foundation enum Endpoint { case newStories case topStories case bestStories case item(Int) static let baseUrl = URL(string: "https://hacker-news.firebaseio.com")! func url(_ baseURL: URL) -> URL { switch self { case .newStories: return baseURL.appendingPathComponent("/v0/newstories.json") case .topStories: return baseURL.appendingPathComponent("/v0/topstories.json") case .bestStories: return baseURL.appendingPathComponent("/v0/beststories.json") case let .item(id): return baseURL.appendingPathComponent("/v0/item/\(id).json") } } }
26.892857
75
0.638778
50920df171499df9f8a382f561d673ea84cfd01b
2,308
// // ViewController.swift // TDBadgedCell // // Created by Tim Davies on 07/09/2016. // Copyright © 2016 Tim Davies. All rights reserved. // import UIKit class ViewController: UITableViewController { /// List of example table view cells let demoItems : [[String:String]] = [ ["title" : "This is an example badge", "badge": "1"], ["title" : "This is a second example badge", "badge": "123"], ["title" : "A text badge", "badge": "Warning!"], ["title" : "Another text badge with a really long title!", "badge": "Danger!"], ] override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = editButtonItem } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demoItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier:"BadgedCell") as? TDBadgedCell; if(cell == nil) { cell = TDBadgedCell(style: .default, reuseIdentifier: "BadgedCell"); } cell?.textLabel!.text = demoItems[indexPath.row]["title"] cell?.detailTextLabel?.text = demoItems[indexPath.row]["title"] cell?.badgeString = demoItems[indexPath.row]["badge"]! // Set accessory views for two badges if(indexPath.row == 0) { cell?.accessoryType = .disclosureIndicator } if(indexPath.row == 1) { cell?.badgeColor = .lightGray cell?.badgeTextColor = .black cell?.accessoryType = .checkmark } // Set background colours for two badges if(indexPath.row == 2) { cell?.badgeColor = .orange } else if(indexPath.row == 3) { cell?.badgeColor = .red } // Uncomment this to test with dynamic type. // cell?.badgeTextStyle = .caption1 return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { tableView.deselectRow(at: indexPath, animated: true) } } }
31.616438
109
0.598354
e217561e245ac44892e0736d908db75342c819f5
1,292
// // FileManager.swift // MenoumeSpiti-MovementSMS // // Created by Orestis Papadopoulos on 26/03/2020. // Copyright © 2020 opapadopoulos. All rights reserved. // import Foundation func saveUserDetailsModel(_ model: UserDetailsModel) { guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } try? FileManager().createDirectory(at: documentsDirectoryUrl, withIntermediateDirectories: true) let filePath = documentsDirectoryUrl.appendingPathComponent("userDetails.json") let json = try? JSONEncoder().encode(model) do { try json!.write(to: filePath) } catch { print("Failed to write JSON data: \(error.localizedDescription)") } } func loadUserDetailsModel() -> UserDetailsModel? { guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil } let filePath = documentsDirectoryUrl.appendingPathComponent("userDetails.json") do { let data = try Data(contentsOf: filePath, options: .mappedIfSafe) let jsonResult = try JSONDecoder().decode(UserDetailsModel.self, from: data) return jsonResult } catch { print(error) return nil } }
33.128205
134
0.708978
48461ee172e6f44059bbd013213a0ae60cebfcb0
1,578
// // NewsItemCell.swift // facile // // Created by Renaud Pradenc on 28/08/2019. // import UIKit class NewsItemCell: UITableViewCell { private static var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = .short formatter.dateStyle = .medium return formatter }() @objc var date: Date? = nil { didSet { if let date = date { dateLabel.text = NewsItemCell.dateFormatter.string(from: date) } else { dateLabel.text = "" } } } @objc var title: String? = nil { didSet { titleLabel.text = title } } // TODO: the title should be bold when not read @objc var isRead: Bool = false { didSet { titleLabel.textColor = titleColor(isRead: isRead) titleLabel.font = UIFont.systemFont(ofSize: 15.0, weight: isRead ? .regular : .semibold) } } private func titleColor(isRead: Bool) -> UIColor { if #available(iOS 11, *) { if isRead { return UIColor(named: "news.title.read")! } else { return UIColor(named: "news.title.unread")! } } else { // < iOS 11 if isRead { return UIColor(white: 0.3, alpha: 1.0) } else { return .black } } } @IBOutlet private weak var dateLabel: UILabel! @IBOutlet private weak var titleLabel: UILabel! }
25.047619
100
0.516477
7137cef2cb73b9dea807edc1c594bbc5632ec714
1,304
// // LinuxMain.swift // ThreadlyTests // // The MIT License (MIT) // // Copyright (c) 2017 Nikolai Vazquez // // 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 XCTest @testable import ThreadlyTests XCTMain([ testCase(ThreadlyTests.allTests), ])
38.352941
81
0.745399
aca8b122f6ab75b6a82f4bdef748b2ac3e397c88
695
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import Foundation import SwiftyJSON class StringUnpacker: Unpacker { func unpack(ivalue: IValue, modelSpec: JSON, result: inout [String: Any], packerContext: PackerContext) throws { let unpack = modelSpec["unpack"] guard let key = unpack["key"].string else { throw BaseIValuePackerError.missingKeyParam } guard let answer = ivalue.toString() else { throw BaseIValuePackerError.decodeStringError } result[key] = answer } }
28.958333
116
0.671942
b9ad2dcfcf7efb3e874aac65391e21f61098be6c
2,067
// RUN: %target-swift-frontend -Xllvm -tf-dump-intermediates -Xllvm -tf-dump-graph -O -emit-sil -verify %s | %FileCheck %s import TensorFlow public func testDatasetWithFakeData() { TensorFlow.enableTPU(infeed: true) let x: TensorHandle<Float> = #tfop( "tfc.makeIteratorGetNextWithDatasets", dataSource: "fake", filePath: "dummy_path", batchSize: 1, outputShapes: [TensorShape()]) let y = Tensor<Float>(handle: x) + 1 _hostOp(y.array.scalars[0]) } // CHECK-LABEL: --- TFPartition Accelerator Result: {{.*}}testDatasetWithFakeData{{.*}} // CHECK: bb0: // CHECK: [[GETNEXT:%[0-9]+]] = graph_op "tfc.makeIteratorGetNextWithDatasets{{.*}} : $TensorHandle<Float> // CHECK: [[RESULT:%[0-9]+]] = graph_op "Add"([[GETNEXT]] : $TensorHandle<Float>, {{.*}} : $TensorHandle<Float> // CHECK-NEXT: return [[RESULT]] : $TensorHandle<Float> public func testDatasetWithMNIST() { TensorFlow.enableTPU(infeed: true) let (images1, labels1): (TensorHandle<Float>, TensorHandle<Int32>) = #tfop( "tfc.makeIteratorGetNextWithDatasets", dataSource: "mnist", filePath: "some_path", batchSize: 64, output_shapes: [TensorShape(64,224,224,3), TensorShape(64)]) let images : TensorHandle<Float> = #tfop("Identity", images1) let labels : TensorHandle<Int32> = #tfop("Identity", labels1) // Confirm we can add more nodes to the graph. let imagesMod = Tensor<Float>(handle: images) + 1 let labelsMod = Tensor<Int32>(handle: labels) + 2 _hostOp(imagesMod.array.scalars[0]) _hostOp(labelsMod.array.scalars[0]) } // CHECK-LABEL: --- TFPartition Accelerator Result: {{.*}}testDatasetWithMNIST{{.*}} // CHECK: bb0: // CHECK: (%0, %1) = graph_op "tfc.makeIteratorGetNextWithDatasets{{.*}} : $TensorHandle<Float>, $TensorHandle<Int32> // CHECK: graph_op "Add"( // CHECK: graph_op "Add"( // The operands can appear in arbitrary order here. // CHECK: [[RESULT:%.*]] = tuple ({{.*}} : $TensorHandle<{{.*}}>, {{.*}} : $TensorHandle<{{.*}}>) // CHECK-NEXT: return [[RESULT]] : $(TensorHandle<{{.*}}>, TensorHandle<{{.*}}>)
43.978723
122
0.665215
abc9ab01f58572e7dcf0b77832c48176e752523d
995
// // ContainerTableViewCell.swift // LoadMoreDemo // // Created by Alessandro Marzoli on 03/04/2020. // Copyright © 2020 Alessandro Marzoli. All rights reserved. // import UIKit public final class ContainerTableViewCell<V: UIView>: UITableViewCell { public lazy var view: V = { return V() }() public required init?(coder aDecoder: NSCoder) { fatalError() } public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } private func setup() { view.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(view) NSLayoutConstraint.activate([ view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), view.topAnchor.constraint(equalTo: contentView.topAnchor), view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) ]) } }
26.891892
84
0.732663
ed0c2f2a09dd0f93d28e6a61af2dcaac6bb002a0
12,106
// // StereoViewController.swift // MetalScope // // Created by Jun Tanaka on 2017/01/23. // Copyright © 2017 eje Inc. All rights reserved. // import UIKit import SceneKit open class StereoViewController: UIViewController, SceneLoadable { #if (arch(arm) || arch(arm64)) && os(iOS) public let device: MTLDevice #endif open var scene: SCNScene? { didSet { _stereoView?.scene = scene } } open var stereoParameters: StereoParametersProtocol = StereoParameters() { didSet { _stereoView?.stereoParameters = stereoParameters } } open var stereoView: StereoView { if !isViewLoaded { loadView() } guard let view = _stereoView else { fatalError("Unexpected context to load stereoView") } return view } open var showsCloseButton: Bool = true { didSet { _closeButton?.isHidden = !showsCloseButton } } open var closeButton: UIButton { if _closeButton == nil { loadCloseButton() } guard let button = _closeButton else { fatalError("Unexpected context to load closeButton") } return button } open var closeButtonHandler: ((_ sender: UIButton) -> Void)? open var showsHelpButton: Bool = false { didSet { _helpButton?.isHidden = !showsHelpButton } } open var helpButton: UIButton { if _helpButton == nil { loadHelpButton() } guard let button = _helpButton else { fatalError("Unexpected context to load helpButton") } return button } open var helpButtonHandler: ((_ sender: UIButton) -> Void)? open var introductionView: UIView? { willSet { introductionView?.removeFromSuperview() } didSet { guard isViewLoaded else { return } if let _ = introductionView { showIntroductionView() } else { hideIntroductionView() } } } private weak var _stereoView: StereoView? private weak var _closeButton: UIButton? private weak var _helpButton: UIButton? private weak var introdutionContainerView: UIView? private var introductionViewUpdateTimer: DispatchSourceTimer? #if (arch(arm) || arch(arm64)) && os(iOS) public init(device: MTLDevice) { self.device = device super.init(nibName: nil, bundle: nil) } #else public init() { super.init(nibName: nil, bundle: nil) } #endif public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func loadView() { #if (arch(arm) || arch(arm64)) && os(iOS) let stereoView = StereoView(device: device) #else let stereoView = StereoView() #endif stereoView.backgroundColor = .black stereoView.scene = scene stereoView.stereoParameters = stereoParameters stereoView.translatesAutoresizingMaskIntoConstraints = false stereoView.isPlaying = false _stereoView = stereoView let introductionContainerView = UIView(frame: stereoView.bounds) introductionContainerView.isHidden = true self.introdutionContainerView = introductionContainerView let view = UIView(frame: stereoView.bounds) view.backgroundColor = .black view.addSubview(stereoView) view.addSubview(introductionContainerView) self.view = view NSLayoutConstraint.activate([ stereoView.topAnchor.constraint(equalTo: view.topAnchor), stereoView.bottomAnchor.constraint(equalTo: view.bottomAnchor), stereoView.leadingAnchor.constraint(equalTo: view.leadingAnchor), stereoView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) if showsCloseButton { loadCloseButton() } if showsHelpButton { loadHelpButton() } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() introdutionContainerView!.bounds = view!.bounds introdutionContainerView!.center = CGPoint(x: view!.bounds.midX, y: view!.bounds.midY) introductionView?.frame = introdutionContainerView!.bounds } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if animated { _stereoView?.alpha = 0 } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _stereoView?.isPlaying = true if animated { UIView.animate(withDuration: 0.2) { self._stereoView?.alpha = 1 } } if UIDevice.current.orientation != .unknown { showIntroductionView(animated: animated) startIntroductionViewVisibilityUpdates() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) _stereoView?.isPlaying = false stopIntroductionViewVisibilityUpdates() } open override var prefersStatusBarHidden: Bool { return true } open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscapeRight } private func loadCloseButton() { if !isViewLoaded { loadView() } let icon = UIImage(named: "icon-close", in: Bundle(for: StereoViewController.self), compatibleWith: nil) let closeButton = UIButton(type: .system) closeButton.setImage(icon, for: .normal) closeButton.isHidden = !showsCloseButton closeButton.contentVerticalAlignment = .top closeButton.contentHorizontalAlignment = .left closeButton.contentEdgeInsets = UIEdgeInsets(top: 11, left: 11, bottom: 0, right: 0) closeButton.translatesAutoresizingMaskIntoConstraints = false _closeButton = closeButton view.addSubview(closeButton) NSLayoutConstraint.activate([ closeButton.widthAnchor.constraint(equalToConstant: 88), closeButton.heightAnchor.constraint(equalToConstant: 88), closeButton.topAnchor.constraint(equalTo: view.topAnchor), closeButton.leadingAnchor.constraint(equalTo: view.leadingAnchor) ]) closeButton.addTarget(self, action: #selector(handleTapOnCloseButton(_:)), for: .touchUpInside) } @objc private func handleTapOnCloseButton(_ sender: UIButton) { if let handler = closeButtonHandler { handler(sender) } else if sender.allTargets.count == 1 { presentingViewController?.dismiss(animated: true, completion: nil) } } private func loadHelpButton() { if !isViewLoaded { loadView() } let icon = UIImage(named: "icon-help", in: Bundle(for: StereoViewController.self), compatibleWith: nil) let helpButton = UIButton(type: .system) helpButton.setImage(icon, for: .normal) helpButton.isHidden = !showsHelpButton helpButton.contentVerticalAlignment = .top helpButton.contentHorizontalAlignment = .right helpButton.contentEdgeInsets = UIEdgeInsets(top: 11, left: 0, bottom: 0, right: 11) helpButton.translatesAutoresizingMaskIntoConstraints = false _helpButton = helpButton view.addSubview(helpButton) NSLayoutConstraint.activate([ helpButton.widthAnchor.constraint(equalToConstant: 88), helpButton.heightAnchor.constraint(equalToConstant: 88), helpButton.topAnchor.constraint(equalTo: view.topAnchor), helpButton.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) helpButton.addTarget(self, action: #selector(handleTapOnHelpButton(_:)), for: .touchUpInside) } @objc private func handleTapOnHelpButton(_ sender: UIButton) { if let handler = helpButtonHandler { handler(sender) } else if sender.allTargets.count == 1 { let url = URL(string: "https://support.google.com/cardboard/answer/6383058")! UIApplication.shared.openURL(url) } } private func showIntroductionView(animated: Bool = false) { precondition(isViewLoaded) guard let introductionView = introductionView, let containerView = introdutionContainerView, let stereoView = _stereoView else { return } if introductionView.superview != containerView { introductionView.frame = containerView.bounds introductionView.autoresizingMask = [] containerView.addSubview(introductionView) } if animated { if containerView.isHidden { containerView.isHidden = false containerView.transform = CGAffineTransform(translationX: 0, y: containerView.bounds.height) } UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState], animations: { containerView.transform = .identity stereoView.alpha = 0 }, completion: nil) } else { containerView.isHidden = false containerView.transform = .identity stereoView.alpha = 0 } } private func hideIntroductionView(animated: Bool = false) { precondition(isViewLoaded) guard let containerView = introdutionContainerView, let stereoView = _stereoView else { return } if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.beginFromCurrentState], animations: { containerView.transform = CGAffineTransform(translationX: 0, y: containerView.bounds.height) stereoView.alpha = 1 }, completion: { isFinished in guard isFinished else { return } containerView.isHidden = true containerView.transform = .identity }) } else { containerView.isHidden = true containerView.transform = .identity stereoView.alpha = 1 } } private func startIntroductionViewVisibilityUpdates(withInterval interval: TimeInterval = 3, afterDelay delay: TimeInterval = 3) { precondition(introductionViewUpdateTimer == nil) let timer = DispatchSource.makeTimerSource(queue: .main) timer.scheduleRepeating(deadline: .now() + delay, interval: interval) timer.setEventHandler { [weak self] in guard self?.isViewLoaded == true, let _ = self?.introductionView else { return } switch UIDevice.current.orientation { case .landscapeLeft where self?.introdutionContainerView?.isHidden == false: self?.hideIntroductionView(animated: true) case .landscapeRight where self?.introdutionContainerView?.isHidden == true: self?.showIntroductionView(animated: true) default: break } } timer.resume() introductionViewUpdateTimer = timer } private func stopIntroductionViewVisibilityUpdates() { introductionViewUpdateTimer?.cancel() introductionViewUpdateTimer = nil } } extension StereoViewController: ImageLoadable {} #if (arch(arm) || arch(arm64)) && os(iOS) extension StereoViewController: VideoLoadable {} #endif
32.111406
136
0.614571
3982f28699aa85a63d15718ad469ced6a053a4d4
3,337
// // MovieCollectionViewCell.swift // MoviesApp // // Created by ÜNAL ÖZTÜRK on 5.04.2020. // Copyright © 2020 ÜNAL ÖZTÜRK. All rights reserved. // import UIKit class MovieCollectionViewCell: UICollectionViewCell { static var identifier: String = "movieCell" var posterImage: PosterImageLoader = { var imageView = PosterImageLoader() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleToFill return imageView }() var titleLabel: UILabel = { var label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.numberOfLines = 0 label.textColor = .white label.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) return label }() var starImage: UIImageView = { var imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit imageView.image = FavoriteBarButton.favorited.image return imageView }() override init(frame: CGRect) { super.init(frame: frame) configureUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() resetCell() } private func resetCell() { self.titleLabel.text = "" self.starImage.isHidden = true self.posterImage.image = nil } private func configureUI() { backgroundColor = .gray layer.cornerRadius = 5 layer.masksToBounds = true addSubview(posterImage) NSLayoutConstraint.activate([ posterImage.topAnchor.constraint(equalTo: topAnchor), posterImage.bottomAnchor.constraint(equalTo: bottomAnchor), posterImage.trailingAnchor.constraint(equalTo: trailingAnchor), posterImage.leadingAnchor.constraint(equalTo: leadingAnchor) ]) addSubview(titleLabel) NSLayoutConstraint.activate([ titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor), titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor), titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor), ]) addSubview(starImage) NSLayoutConstraint.activate([ starImage.topAnchor.constraint(equalTo: topAnchor, constant: 5), starImage.trailingAnchor.constraint(equalTo: trailingAnchor,constant: -5), starImage.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 1/5), starImage.widthAnchor.constraint(equalTo: heightAnchor, multiplier: 1/5) ]) } func configureWithMovie(movie: Movie) { titleLabel.text = movie.title movie.favorite ? (starImage.isHidden = false) : (starImage.isHidden = true) //To get poster image guard let posterPath = movie.posterPath, let url = posterImage.tmdbImageUrl(width: frame.size.width, path: posterPath) else { return } posterImage.loadImageWithUrl(url) } }
31.780952
89
0.633203
39583bf88c37cc265d037e7cf997504bcf64c44d
2,175
// // AppDelegate.swift // iShowcaseExample // // Created by Rahul Iyer on 14/10/15. // Copyright © 2015 rahuliyer. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.276596
285
0.754943
fe8136df753d7363babeff0e9504c4dbf65b9348
7,538
// // BusinessesViewController.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit import MBProgressHUD class ResultsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var businesses: [Business]! @IBOutlet weak var resultsTableView: UITableView! var filterSearchSettings = FilterSettings() //views var searchBar: UISearchBar! var spinner: UIActivityIndicatorView! //infinite scrolling var isMoreDataLoading = false override func viewDidLoad() { super.viewDidLoad() resultsTableView.delegate = self resultsTableView.dataSource = self resultsTableView.estimatedRowHeight = 100 resultsTableView.rowHeight = UITableViewAutomaticDimension //add a search bar searchBar = UISearchBar() searchBar.sizeToFit() searchBar.delegate = self navigationItem.titleView = searchBar //add inifite scroll indicator spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) spinner.frame = CGRect(x:0, y: 0, width: self.resultsTableView.frame.width, height: 40) self.resultsTableView.tableFooterView = spinner //perform search at first loaded businesses = [Business]() doSearch() /* Example of Yelp search with more search options specified Business.searchWithTerm("Restaurants", sort: .distance, categories: ["asianfusion", "burgers"], deals: true) { (businesses: [Business]!, error: Error!) -> Void in self.businesses = businesses for business in businesses { print(business.name!) print(business.address!) } } */ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return businesses?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell") as! ResultCell cell.business = businesses[indexPath.section] cell.resultNameLabelView.text = "\(indexPath.section + 1). " + cell.business.name! return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { //when it reaches bottom of tableview if(indexPath.section == self.businesses.count - 1 && resultsTableView.isDragging) { isMoreDataLoading = true spinner.startAnimating() doSearch() } } // MARK: - Perform Search fileprivate func doSearch() { if !isMoreDataLoading {MBProgressHUD.showAdded(to: self.view, animated: true)} let term = filterSearchSettings.searchString ?? "Everything" let sortby = YelpSortMode(rawValue: filterSearchSettings.sortbySelectedIndex) var categories: [String]? let selectedCategories = filterSearchSettings.selectedCategories if selectedCategories.count > 0 { categories = [String] () for (_, value) in selectedCategories { categories?.append(value) } } let deals = filterSearchSettings.isOfferingDeal let distance = filterSearchSettings.radius[filterSearchSettings.distanceSelectedIndex] let offset = isMoreDataLoading ? businesses.count : nil //number of results business returned per API call is default to be 20. It can be changed by passing the limit parameter Business.searchWithTerm(term: term, sort: sortby, categories: categories, deals: deals, distance: distance, offset: offset, completion: { (businesses: [Business]?, error: Error?) -> Void in //update load more data flag if self.isMoreDataLoading { if let businesses = businesses { self.businesses.append(contentsOf: businesses) } self.spinner.stopAnimating() self.resultsTableView.reloadData() } else { MBProgressHUD.hide(for: self.view, animated: true) self.businesses = businesses //self.resultsTableView.setContentOffset(.zero, animated: false) let indexPath = IndexPath(row: 0, section: 0) self.resultsTableView.reloadData() self.resultsTableView.scrollToRow(at: indexPath, at: .top, animated: false) } self.isMoreDataLoading = false } ) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowFilterSettings" { guard let filterNav = segue.destination as? UINavigationController, let filterVC = filterNav.viewControllers.first as? FiltersViewController else { return } filterVC.prepare(filterSetting: filterSearchSettings, filterSettingsHandler: { (filters) in self.filterSearchSettings = filters self.doSearch() }) } else if segue.identifier == "ShowMapView" { guard let mapViewVC = segue.destination as? ResultsMapViewController else { return } mapViewVC.businesses = businesses } } } //search bar extension extension ResultsViewController: UISearchBarDelegate { //on search button clicked func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { filterSearchSettings.searchString = searchBar.text searchBar.setShowsCancelButton(false, animated: true) searchBar.resignFirstResponder() doSearch() } //on search bar text changed // func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { // filterSearchSettings.searchString = searchText // doSearch() // } //show cancel button func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { searchBar.setShowsCancelButton(true, animated: true) return true } //dismiss cancel button func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { searchBar.setShowsCancelButton(false, animated: true) return true } //dismiss input keyboard func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { self.searchBar.showsCancelButton = false searchBar.text = "" searchBar.resignFirstResponder() } }
34.420091
197
0.623375
e489651b170a9b2cf2005b781ae9dcaa561ddc46
1,820
// // Prefix.swift // PrefixPackageDescription // // Created by Borinschi Ivan on 4/23/18. // import Foundation import Files public class PrefixFiles { public init() { } /// Get all swift files in directory /// /// - Parameter folder: Folder /// - Returns: Optional array of Files public func getAllSwiftFiles(folder: Folder) -> [File]? { return getFilesFrom(folder: folder, contain: ".swift") } /// Get files from /// /// - Parameters: /// - folder: Folder /// - name: name to check if file name contain this contain /// - Returns: Optional array of Files public func getFilesFrom(folder: Folder, contain name: String) -> [File]? { return getFilesFrom(folder: folder, contain: PrefixParser.containWord(name)) } /// Get all files from current directory if files names contain pattern /// /// - Parameter pattern: PrefixParserPattern /// - Returns: Optional array of Files public func getFilesFromCurrentFolder(contain pattern: PrefixParserPattern? = nil) -> [File]? { return getFilesFrom(folder: Folder.current, contain: pattern) } /// Get all files from Folder if file names contain pattern /// /// - Parameters: /// - folder: Folder /// - pattern: PrefixParserPattern /// - Returns: Optional array of Files public func getFilesFrom(folder: Folder, contain pattern: PrefixParserPattern? = nil) -> [File]? { var files = [File]() for file in folder.files { if let pattern = pattern { if file.name.contains(pattern) { files.append(file) } } else { files.append(file) } } return files } }
28.4375
102
0.585714
62675ee240d41c3ec8546239b8aa7920005ab8c0
473
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "combine-schedulers", platforms: [ .iOS(.v10), .macOS(.v10_12), .tvOS(.v10), .watchOS(.v3), ], products: [ .library( name: "CombineSchedulers", targets: ["CombineSchedulers"] ) ], targets: [ .target(name: "CombineSchedulers"), .testTarget( name: "CombineSchedulersTests", dependencies: ["CombineSchedulers"] ), ] )
17.518519
41
0.596195
fbe4c91b25779f417e482c33820e830e31b99226
1,407
// // Tests_macOS.swift // Tests macOS // // Created by Vladislav Fitc on 10/04/2021. // import XCTest class Tests_macOS: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.72093
182
0.653163
48041dfdc79f542be393ebacd6e5c8728e31c892
2,053
// // YPFiltersView.swift // photoTaking // // Created by Sacha Durand Saint Omer on 21/10/16. // Copyright © 2016 octopepper. All rights reserved. // import Stevia class YPFiltersView: UIView { let imageView = UIImageView() var collectionView: UICollectionView! var filtersLoader: UIActivityIndicatorView! fileprivate let collectionViewContainer: UIView = UIView() convenience init() { self.init(frame: CGRect.zero) collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout()) filtersLoader = UIActivityIndicatorView(activityIndicatorStyle: .gray) filtersLoader.hidesWhenStopped = true filtersLoader.startAnimating() filtersLoader.color = YPConfig.colors.tintColor sv( imageView, collectionViewContainer.sv( filtersLoader, collectionView ) ) let isIphone4 = UIScreen.main.bounds.height == 480 let sideMargin: CGFloat = isIphone4 ? 20 : 0 |-sideMargin-imageView.top(0)-sideMargin-| |-sideMargin-collectionViewContainer-sideMargin-| collectionViewContainer.bottom(0) imageView.Bottom == collectionViewContainer.Top |collectionView.centerVertically().height(160)| filtersLoader.centerInContainer() imageView.heightEqualsWidth() backgroundColor = UIColor(r: 66, g: 66, b: 66) imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true collectionView.backgroundColor = .clear collectionView.showsHorizontalScrollIndicator = false } func layout() -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 4 layout.sectionInset = UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 18) layout.itemSize = CGSize(width: 100, height: 120) return layout } }
33.112903
93
0.651729
2000655c948abb46753da93b13ecc40c75d13074
3,121
// // KeyTextField.swift // ⌘英かな // // MIT License // Copyright (c) 2016 iMasanari // import Cocoa var activeKeyTextField: KeyTextField? class KeyTextField: NSComboBox { /// Custom delegate with other methods than NSTextFieldDelegate. var shortcut: KeyboardShortcut? = nil var saveAddress: (row: Int, id: String)? = nil var isAllowModifierOnly = true override func becomeFirstResponder() -> Bool { let became = super.becomeFirstResponder(); if (became) { activeKeyTextField = self } return became; } // override func resignFirstResponder() -> Bool { // let resigned = super.resignFirstResponder(); // if (resigned) { // } // return resigned; // } override func textDidEndEditing(_ obj: Notification) { super.textDidEndEditing(obj) switch self.stringValue { case "English": shortcut = KeyboardShortcut(keyCode: 102) break case "Kana": shortcut = KeyboardShortcut(keyCode: 104) break case "⇧Kana": shortcut = KeyboardShortcut(keyCode: 104, flags: CGEventFlags.maskShift) break case "前の入力ソースを選択", "select the previous input source": let symbolichotkeys = UserDefaults.init(suiteName: "com.apple.symbolichotkeys.plist")?.object(forKey: "AppleSymbolicHotKeys") as! NSDictionary let parameters = symbolichotkeys.value(forKeyPath: "60.value.parameters") as! [Int] shortcut = KeyboardShortcut(keyCode: CGKeyCode(parameters[1]), flags: CGEventFlags(rawValue: UInt64(parameters[2]))) break case "入力メニューの次のソースを選択", "select next source in input menu": let symbolichotkeys = UserDefaults.init(suiteName: "com.apple.symbolichotkeys.plist")?.object(forKey: "AppleSymbolicHotKeys") as! NSDictionary let parameters = symbolichotkeys.value(forKeyPath: "61.value.parameters") as! [Int] shortcut = KeyboardShortcut(keyCode: CGKeyCode(parameters[1]), flags: CGEventFlags(rawValue: UInt64(parameters[2]))) break case "Disable": shortcut = KeyboardShortcut(keyCode: CGKeyCode(999)) break default: break } if let shortcut = shortcut { self.stringValue = shortcut.toString() if let saveAddress = saveAddress { if saveAddress.id == "input" { keyMappingList[saveAddress.row].input = shortcut } else { keyMappingList[saveAddress.row].output = shortcut } keyMappingListToShortcutList() } } else { self.stringValue = "" } saveKeyMappings() if activeKeyTextField == self { activeKeyTextField = nil } } func blur() { self.window?.makeFirstResponder(nil) activeKeyTextField = nil } }
33.55914
154
0.57834
01af148f287b99ec0f679c81cacb4ee9da6dcf10
269
// // Tab2Cell.swift // HLMiscExample // // Created by 钟浩良 on 2018/7/20. // Copyright © 2018年 钟浩良. All rights reserved. // import UIKit class Tab2Cell: UICollectionViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var badgeView: UIView! }
16.8125
47
0.67658
1ee74c7156218c1842d24bcf02d383b4d759b691
584
// // KeychainItemStorage.swift // TVToday // // Created by Jeans Ruiz on 6/21/20. // Copyright © 2020 Jeans. All rights reserved. // import Foundation import KeychainSwift @propertyWrapper struct KeychainItemStorage { private let key: String private lazy var keychain = KeychainSwift() init(key: String) { self.key = key } var wrappedValue: String? { mutating get { return keychain.get(key) } set { if let newValue = newValue { keychain.set(newValue, forKey: key) } else { keychain.delete(key) } } } }
16.685714
48
0.630137
c11781a92d481d0c11c6da130ee3a20d5ce3d53f
6,695
// // PickerView.swift // Pods // // Created by Viktor Rutberg on 2016-12-21. // // import Foundation import UIKit protocol PickerViewDelegate: class { func picker(_ sender: PickerView, didSelectIndex index: Int) func picker(_ sender: PickerView, didSlideTo: CGPoint) } final class PickerView: UIView, UIScrollViewDelegate { private let items: [String] private let itemWidth: Int private let itemFont: UIFont private let itemFontColor: UIColor private let sliderVelocityCoefficient: Double private let defaultSelectedIndex: Int private var didSetDefault = false private var silenceIndexUpdates = false var delegate: PickerViewDelegate? private(set) var selectedIndex: Int = 0 init(items: [String], itemWidth: Int, itemFont: UIFont, itemFontColor: UIColor, sliderVelocityCoefficient: Double, defaultSelectedIndex: Int) { self.items = items self.itemWidth = itemWidth self.itemFont = itemFont self.itemFontColor = itemFontColor self.sliderVelocityCoefficient = sliderVelocityCoefficient self.defaultSelectedIndex = defaultSelectedIndex super.init(frame: .zero) addSubview(scrollView) setupScrollView() setupScrollViewContent() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var xContentInset: CGFloat { return (frame.width - CGFloat(itemWidth)) / 2.0 } lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.contentInset = UIEdgeInsets(top: 0, left: self.xContentInset, bottom: 0, right: self.xContentInset) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.isScrollEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.delegate = self return scrollView }() private lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.alignment = .center stackView.distribution = .equalCentering return stackView }() private lazy var singleTapGestureRecognizer: UITapGestureRecognizer = { let gestureRecognizer = UITapGestureRecognizer() gestureRecognizer.numberOfTapsRequired = 1 gestureRecognizer.isEnabled = true gestureRecognizer.cancelsTouchesInView = false return gestureRecognizer }() private func scroll(toIndex index: Int, animated: Bool = true) { let point = convert(indexToPoint: index) scrollView.setContentOffset(point, animated: animated) } public func set(selectedIndex index: Int, animated: Bool = true, silently: Bool = false) { if silently { silenceIndexUpdates = true } scroll(toIndex: index, animated: animated) silenceIndexUpdates = false } private func markItemAsSelected(at index: Int) { guard selectedIndex != index else { return } selectedIndex = index if !silenceIndexUpdates { delegate?.picker(self, didSelectIndex: selectedIndex) } } private func convert(contentOffsetToIndex contentOffset: CGFloat) -> Int { let offsetX = contentOffset + xContentInset var itemIndex = Int(round(offsetX / CGFloat(itemWidth))) if itemIndex > items.count - 1 { itemIndex = items.count - 1 } else if itemIndex < 0 { itemIndex = 0 } return itemIndex } private func convert(indexToPoint index: Int) -> CGPoint { let itemX = CGFloat(itemWidth * index) return CGPoint(x: itemX - xContentInset, y: 0) } override func layoutSubviews() { super.layoutSubviews() scrollView.contentInset = UIEdgeInsets(top: 0, left: self.xContentInset, bottom: 0, right: self.xContentInset) if !didSetDefault { set(selectedIndex: defaultSelectedIndex, animated: false, silently: true) didSetDefault = true } else { set(selectedIndex: selectedIndex, animated: false) } } @objc private func scrollViewWasTapped(_ sender: UITapGestureRecognizer) { let point = sender.location(in: scrollView) // TODO(vrutberg): // * This should probably be merged with convert(contentOffsetToIndex) var itemIndex = Int(floor(point.x / CGFloat(itemWidth))) if itemIndex > items.count - 1 { itemIndex = items.count - 1 } else if itemIndex < 0 { itemIndex = 0 } set(selectedIndex: itemIndex) } private func setupScrollView() { addSubview(scrollView) scrollView.addGestureRecognizer(singleTapGestureRecognizer) singleTapGestureRecognizer.addTarget(self, action: #selector(scrollViewWasTapped(_:))) matchSizeWithConstraints(view1: scrollView, view2: self) } private func setupScrollViewContent() { scrollView.addSubview(stackView) for value in items { let valueLabel = UILabel() valueLabel.translatesAutoresizingMaskIntoConstraints = false valueLabel.text = "\(value)" valueLabel.font = itemFont valueLabel.textColor = itemFontColor valueLabel.textAlignment = .center stackView.addArrangedSubview(valueLabel) NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: scrollView, attribute: .height, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: valueLabel, attribute: .width, relatedBy: .equal, toItem: valueLabel, attribute: .height, multiplier: 1, constant: 0).isActive = true } matchSizeWithConstraints(view1: stackView, view2: scrollView) } internal func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let targetOffset = scrollView.contentOffset.x + velocity.x * CGFloat(sliderVelocityCoefficient) let index = convert(contentOffsetToIndex: targetOffset) targetContentOffset.pointee = convert(indexToPoint: index) } internal func scrollViewDidScroll(_ scrollView: UIScrollView) { let index = convert(contentOffsetToIndex: scrollView.contentOffset.x) delegate?.picker(self, didSlideTo: scrollView.contentOffset) markItemAsSelected(at: index) } }
31.580189
171
0.666916
1646e11533a32c7b5fd16c0a2d99bd742544aaac
3,171
// // UINavigationController.swift // Pods // // Created by away4m on 12/30/16. // // import Foundation public extension UINavigationController { /// SwifterSwift: Pop ViewController with completion handler. /// /// - Parameter completion: optional completion handler (default is nil). public func popViewController(completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) popViewController(animated: true) CATransaction.commit() } // Push ViewController with completion handler. /// /// - Parameters: /// - viewController: viewController to push. /// - Parameter completion: optional completion handler (default is nil). public func pushViewController(viewController: UIViewController, completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) pushViewController(viewController, animated: true) CATransaction.commit() } // Make navigation controller's navigation bar transparent. /// /// - Parameter withTint: tint color (default is .white). public func makeTransparent(withTint: UIColor = .white) { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true navigationBar.tintColor = withTint navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: withTint] } public func completelyTransparentBar() { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true view.backgroundColor = UIColor.clear navigationBar.backgroundColor = UIColor.clear } public func previousViewController() -> UIViewController? { return viewController(at: viewControllers.count - 2) } public func viewController(at index: Int) -> UIViewController? { guard index >= 0 else { return nil } return viewControllers[index] } public func removeViewController(at index: Int) { var _viewControllers = viewControllers _viewControllers.remove(at: index) viewControllers = _viewControllers } public func removeViewController(atTail index: Int) { var _viewControllers = viewControllers _viewControllers.remove(at: _viewControllers.count - index - 1) viewControllers = _viewControllers } public func removeViewControllers(previous number: Int) { var _viewControllers = viewControllers if number < _viewControllers.count { _viewControllers.removeSubrange(_viewControllers.count - number - 1..._viewControllers.count - 2) viewControllers = _viewControllers } } public func removePreviousViewController() { removeViewController(atTail: 1) } }
35.233333
109
0.689688
f7f30d4dee7d5ab11ce9279687ca0f9eb3a89ef0
299
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B{deinit{class d<a{struct B}}class S<T{func a<h{func b<T where h.g=a{
37.375
87
0.735786
d55c5151bc5a8052e4bdf6f79c998d2ca9513902
2,044
import XCTest @testable import Aspen class LogLevelTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testInitNewLevel() { let level = DefaultLogLevel.verbose let name = "Test Level" let label = "TESTLABEL" let newLevel = LogLevel(level: level, name: name, label: label) XCTAssertEqual(newLevel.level, level) XCTAssertEqual(newLevel.name, name) XCTAssertEqual(newLevel.label, label) } func testStaticLogLevels() { let verbose = LogLevel.VERBOSE_LEVEL XCTAssertEqual(verbose.level, DefaultLogLevel.verbose) let info = LogLevel.INFO_LEVEL XCTAssertEqual(info.level, DefaultLogLevel.info) let warning = LogLevel.WARNING_LEVEL XCTAssertEqual(warning.level, DefaultLogLevel.warning) let error = LogLevel.ERROR_LEVEL XCTAssertEqual(error.level, DefaultLogLevel.error) } func testFetchingDefaultLevels() { let verbose = LogLevel.getLevel(.verbose) XCTAssertEqual(verbose, LogLevel.VERBOSE_LEVEL) let info = LogLevel.getLevel(.info) XCTAssertEqual(info, LogLevel.INFO_LEVEL) let warning = LogLevel.getLevel(.warning) XCTAssertEqual(warning, LogLevel.WARNING_LEVEL) let error = LogLevel.getLevel(.error) XCTAssertEqual(error, LogLevel.ERROR_LEVEL) } func testGettingEmojiIdentifiers() { let verbose = LogLevel.VERBOSE_LEVEL XCTAssertEqual(verbose.emojiIdentifier(), "🚧") let info = LogLevel.INFO_LEVEL XCTAssertEqual(info.emojiIdentifier(), "☝️") let warning = LogLevel.WARNING_LEVEL XCTAssertEqual(warning.emojiIdentifier(), "⚠️") let error = LogLevel.ERROR_LEVEL XCTAssertEqual(error.emojiIdentifier(), "🚨") } }
26.894737
71
0.613992
ef86e01c6de7cb59ba0d2e780e7bd45f41d34e74
2,555
// // ChallengeTableViewCell.swift // JourneyPRO // // Copyright © 2017 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import BridgeAppSDK class ChallengeTableViewCell: UITableViewCell { @IBOutlet open var titleLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet open var subtitleLabel: UILabel? @IBOutlet weak var checkmarkImageView: UIImageView? @IBOutlet weak var shadowBorderView: UIView! @IBOutlet weak var whiteBorderView: UIView! override func awakeFromNib() { super.awakeFromNib() checkmarkImageView?.isHidden = true titleLabel?.textColor = UIColor(named: "darkGrayText") subtitleLabel?.textColor = UIColor(named: "black54") contentView.backgroundColor = UIColor.appWhiteTwo shadowBorderView?.backgroundColor = UIColor.appWhiteThree whiteBorderView?.backgroundColor = UIColor.white } }
43.305085
84
0.751859
c1976655f8d2a13f8559fc104fcfdb76b142ca8f
823
public func escapeString(s: String) -> String { var z = "" debugPrint(s, terminator: "", toStream: &z) return z } public func inspect(o: Any) -> String { var z = "" debugPrint(o, terminator: "", toStream: &z) return z } public func p(a: Any...) { for e in a { debugPrint(e) } } // printList is like the "puts" command in Ruby. // printList will check whether the line ends with a new line, and if it does // not, it will append a new line to it. // // Since importing Glibc already imports the "puts" command found in C which // would conflict with this command, we've given it a unique name instead. public func printList(string: String) { // 10 - new line if string.isEmpty || string.utf16.codeUnitAt(string.utf16.count - 1) != 10 { print(string) } else { Stdout.write(string) } }
24.205882
78
0.658566
4627ec01d1765661c37b6bafdebdf1ec25f0452e
605
import Vapor /// Register your application's routes here. public func routes(_ router: Router) throws { // Basic "It works" router.get { req in return "Session service up and running" } // Example of configuring a controller let sessionController = SessionController.shared router.get("api", "session", use: sessionController.all) router.get("api", "session", String.parameter, use: sessionController.trigger) router.post("api", "session", use: sessionController.create) router.delete("api", "session", Session.parameter, use: sessionController.delete) }
35.588235
85
0.702479
e553b05907d494f6fdfab5638d699d84266a707b
1,758
// // JDSubFindFactory.swift // MyFFM // // Created by BaoLuniOS-3 on 2017/2/18. // Copyright © 2017年 BaoLuniOS-3. All rights reserved. // import UIKit enum JDSubFindTyep { case JDSubFindTypeRecommend // 推荐 case JDSubFindTypeCategory // 分类 case JDSubFindTypeRadio // 广播 case JDSubFindTypeRand // 榜单 case JDSubFindTypeAnchor // 主播 case JDSubFindTypeUnkown // 未知 } class JDSubFindFactory { /// 快速构建子控制器 class func subFindVC(identifier : String) -> JDFindBaseController { var con : JDFindBaseController! let type = typeFromTitle(identifier) switch type { case .JDSubFindTypeRecommend: con = JDFindRecommendController() case .JDSubFindTypeCategory: con = JDFindCategoryController() case .JDSubFindTypeRadio: con = JDFindRadioController() case .JDSubFindTypeRand: con = JDFindRandController() case .JDSubFindTypeAnchor: con = JDFindAnchorController() default: con = JDFindBaseController() } return con } /// 获取子控制器的类型 private class func typeFromTitle(_ title : String) -> JDSubFindTyep { switch title { case "推荐": return .JDSubFindTypeRecommend case "分类": return .JDSubFindTypeCategory case "广播": return .JDSubFindTypeRadio case "榜单": return .JDSubFindTypeRand case "主播": return .JDSubFindTypeAnchor default: return .JDSubFindTypeUnkown } } }
24.082192
73
0.551763
eb809e04f5edb644f53e29403ad2b7cd919be50e
5,553
// // ViewController.swift // LocalSearch // // Created by Patrick DeSantis on 9/10/16. // Copyright © 2016 Patrick DeSantis. All rights reserved. // import CoreLocation import MapKit import UIKit class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var segmentedControl: UISegmentedControl! fileprivate let locationManager = CLLocationManager() fileprivate let searchCompleter = MKLocalSearchCompleter() fileprivate var localSearch: MKLocalSearch? fileprivate var mapItems = [MKMapItem]() fileprivate var searchCompletions = [MKLocalSearchCompletion]() override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 60 tableView.rowHeight = UITableViewAutomaticDimension locationManager.delegate = self searchCompleter.delegate = self searchCompleter.filterType = .locationsOnly } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) locationManager.requestWhenInUseAuthorization() } @IBAction func toggleResults(_ sender: AnyObject) { tableView.reloadData() } func search(query: String) { guard let location = locationManager.location else { return } let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1) let region = MKCoordinateRegion(center: location.coordinate, span: span) if searchCompleter.isSearching { searchCompleter.cancel() } searchCompleter.region = region searchCompleter.queryFragment = query let request = MKLocalSearchRequest() request.naturalLanguageQuery = query request.region = region localSearch = MKLocalSearch(request: request) localSearch?.start(completionHandler: localSearchCompletionHandler) } func search(searchCompletion: MKLocalSearchCompletion) { let request = MKLocalSearchRequest(completion: searchCompletion) localSearch = MKLocalSearch(request: request) localSearch?.start(completionHandler: localSearchCompletionHandler) segmentedControl.selectedSegmentIndex = 1 textField.text = request.naturalLanguageQuery } func localSearchCompletionHandler(response: MKLocalSearchResponse?, error: Error?) { guard let response = response, error == nil else { self.mapItems = [] print(error) return } self.mapItems = response.mapItems self.tableView.reloadData() } } extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorizedAlways, .authorizedWhenInUse: manager.requestLocation() default: break } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error) } } extension ViewController: MKLocalSearchCompleterDelegate { func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) { searchCompletions = completer.results tableView.reloadData() } func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) { print(error) } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch segmentedControl.selectedSegmentIndex { case 0: return searchCompletions.count default: return mapItems.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MapItemCell", for: indexPath) as! MapItemTableViewCell switch segmentedControl.selectedSegmentIndex { case 0: let searchCompletion = searchCompletions[indexPath.row] cell.update(searchCompletion: searchCompletion) default: let mapItem = mapItems[indexPath.row] cell.update(mapItem: mapItem) } return cell } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch segmentedControl.selectedSegmentIndex { case 0: let searchCompletion = searchCompletions[indexPath.row] search(searchCompletion: searchCompletion) default: tableView.deselectRow(at: indexPath, animated: true) } } } extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { localSearch?.cancel() let previousText = textField.text as NSString? let text = previousText?.replacingCharacters(in: range, with: string) as String? if let text = text, !text.isEmpty { search(query: text) } else { mapItems = [] searchCompletions = [] } return true } }
30.679558
129
0.681614
0101400bcfa0507fb16e28b6e09c4dbe5c9921e8
1,920
// // Copyright (c) Bytedance Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. // import UIKit public protocol DCRefreshExecuteProtocol: NSObjectProtocol { func refresh() func loadMore() } public protocol DCRefreshControlProtocol: NSObjectProtocol { var isRefreshing: Bool { get } var isLoading: Bool { get } var hasMoreData: Bool { get } func setRefresh(_ isOpen: Bool) func setLoadMore(_ isOpen: Bool) func beginRefreshing() func endRefresh() func endLoadMore() func endWithNoMoreData() } open class DCRefreshContainerModel: DCContainerModel, DCRefreshExecuteProtocol { public weak var refreshHandler: DCRefreshControlProtocol? override public func addSubmodel(_ model: Any) { if let containerModel = model as? DCRefreshContainerModel { containerModel.refreshHandler = self.refreshHandler } super.addSubmodel(model) } public func refreshSubmodelHandler() { for item in modelArray { if let containerModel = item as? DCRefreshContainerModel { containerModel.refreshHandler = self.refreshHandler containerModel.refreshSubmodelHandler() } } } open func refresh() { for item in modelArray { guard let containerModel = item as? DCRefreshContainerModel else { continue } containerModel.refreshHandler = self.refreshHandler containerModel.refresh() } // override } open func loadMore() { for item in modelArray { guard let containerModel = item as? DCRefreshContainerModel else { continue } containerModel.loadMore() } // override } }
27.826087
80
0.633854
50695b0b7ad670ae4c64597fa3278911d29eb531
1,191
// // Tip_CalculatorUITests.swift // Tip CalculatorUITests // // Created by RAUL RIVERO RUBIO on 2/13/20. // Copyright © 2020 RAUL RIVERO RUBIO. All rights reserved. // import XCTest class Tip_CalculatorUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.028571
182
0.695214
e80409d4be5286592bce2bd670838e1f93da3fc3
35,706
// // SKTileLayer.swift // SKTiled // // Created by Michael Fessenden. // // Web: https://github.com/mfessenden // Email: [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import SpriteKit import GameplayKit #if os(iOS) || os(tvOS) import UIKit #else import Cocoa #endif /** ## Overview Subclass of `SKTiledLayerObject`, the tile layer is a container for an array of tiles (sprites). Tiles maintain a link to the map's tileset via their `SKTilesetData` property. ### Properties | Property | Description | |---------------------------|--------------------------------------------------------| | tileCount | Returns a count of valid tiles. | ### Instance Methods ### | Method | Description | |---------------------------|--------------------------------------------------------| | getTiles() | Returns an array of current tiles. | | getTiles(ofType:) | Returns tiles of the given type. | | getTiles(globalID:) | Returns all tiles matching a global id. | | getTilesWithProperty(_:_) | Returns tiles matching the given property & value. | | animatedTiles() | Returns all animated tiles. | | getTileData(globalID:) | Returns all tiles matching a global id. | | tileAt(coord:) | Returns a tile at the given coordinate, if one exists. | ### Usage Accessing a tile at a given coordinate: ```swift let tile = tileLayer.tileAt(2, 6)! ``` Query tiles of a certain type: ```swift let floorTiles = tileLayer.getTiles(ofType: "Floor") ``` */ public class SKTileLayer: SKTiledLayerObject { fileprivate typealias TilesArray = Array2D<SKTile> /// Container for the tile sprites. fileprivate var tiles: TilesArray /// Returns a count of valid tiles. public var tileCount: Int { return self.getTiles().count } /// Tuple of layer render statistics. override internal var renderInfo: RenderInfo { var current = super.renderInfo current.tc = tileCount if let graph = graph { current.gn = graph.nodes?.count ?? nil } return current } override var layerRenderStatistics: LayerRenderStatistics { var current = super.layerRenderStatistics var tc: Int switch updateMode { case .full: tc = self.tileCount case .dynamic: tc = 0 default: tc = 0 } current.tiles = tc return current } /// Debug visualization options. override public var debugDrawOptions: DebugDrawOptions { didSet { guard oldValue != debugDrawOptions else { return } debugNode.draw() let doShowTileBounds = debugDrawOptions.contains(.drawTileBounds) tiles.forEach { $0?.showBounds = doShowTileBounds } } } /// Tile highlight duration override public var highlightDuration: TimeInterval { didSet { tiles.compactMap { $0 }.forEach { $0.highlightDuration = highlightDuration } } } override public var speed: CGFloat { didSet { guard oldValue != speed else { return } self.getTiles().forEach { $0.speed = speed } } } // MARK: - Init /** Initialize with layer name and parent `SKTilemap`. - parameter layerName: `String` layer name. - parameter tilemap: `SKTilemap` parent map. */ override public init(layerName: String, tilemap: SKTilemap) { self.tiles = TilesArray(columns: Int(tilemap.size.width), rows: Int(tilemap.size.height)) super.init(layerName: layerName, tilemap: tilemap) self.layerType = .tile } /** Initialize with parent `SKTilemap` and layer attributes. **Do not use this intializer directly** - parameter tilemap: `SKTilemap` parent map. - parameter attributes: `[String: String]` layer attributes. */ public init?(tilemap: SKTilemap, attributes: [String: String]) { // name, width and height are required guard let layerName = attributes["name"] else { return nil } self.tiles = TilesArray(columns: Int(tilemap.size.width), rows: Int(tilemap.size.height)) super.init(layerName: layerName, tilemap: tilemap, attributes: attributes) self.layerType = .tile } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Tiles /** Returns a tile at the given coordinate, if one exists. - parameter x: `Int` y-coordinate. - parameter y: `Int` x-coordinate. - returns: `SKTile?` tile object, if it exists. */ public func tileAt(_ x: Int, _ y: Int) -> SKTile? { if isValid(x, y) == false { return nil } return tiles[x,y] } /** Returns a tile at the given coordinate, if one exists. - parameter coord: `CGPoint` tile coordinate. - returns: `SKTile?` tile object, if it exists. */ public func tileAt(coord: CGPoint) -> SKTile? { return tileAt(Int(coord.x), Int(coord.y)) } /** Returns a tile at the given screen position, if one exists. - parameter point: `CGPoint` screen point. - parameter offset: `CGPoint` pixel offset. - returns: `SKTile?` tile object, if it exists. */ public func tileAt(point: CGPoint, offset: CGPoint = CGPoint.zero) -> SKTile? { let coord = coordinateForPoint(point) return tileAt(coord: coord) } /** Returns an array of current tiles. - returns: `[SKTile]` array of tiles. */ public func getTiles() -> [SKTile] { return tiles.compactMap { $0 } } /** Returns tiles with a property of the given type. - parameter ofType: `String` type. - returns: `[SKTile]` array of tiles. */ public func getTiles(ofType: String) -> [SKTile] { return tiles.compactMap { $0 }.filter { $0.tileData.type == ofType } } /** Returns tiles matching the given global id. - parameter globalID: `Int` tile global id. - returns: `[SKTile]` array of tiles. */ public func getTiles(globalID: Int) -> [SKTile] { return tiles.compactMap { $0 }.filter { $0.tileData.globalID == globalID } } /** Returns tiles with a property of the given type. - parameter type: `String` type. - returns: `[SKTile]` array of tiles. */ public func getTilesWithProperty(_ named: String, _ value: Any) -> [SKTile] { var result: [SKTile] = [] for tile in tiles where tile != nil { if let pairValue = tile!.tileData.keyValuePair(key: named) { if pairValue.value == String(describing: value) { result.append(tile!) } } } return result } /** Returns all tiles with animation. - returns: `[SKTile]` array of animated tiles. */ public func animatedTiles() -> [SKTile] { return getTiles().filter { $0.tileData.isAnimated == true } } /** Return tile data from a global id. - parameter globalID: `Int` global tile id. - returns: `SKTilesetData?` tile data (for valid id). */ public func getTileData(globalID gid: Int) -> SKTilesetData? { return tilemap.getTileData(globalID: gid) } /** Returns tiles with a property of the given type. - parameter type: `String` type. - returns: `[SKTile]` array of tiles. */ public func getTileData(withProperty named: String) -> [SKTilesetData] { var result: [SKTilesetData] = [] for tile in tiles where tile != nil { if tile!.tileData.hasKey(named) && !result.contains(tile!.tileData) { result.append(tile!.tileData) } } return result } // MARK: - Layer Data /** Add tile data array to the layer and render it. - parameter data: `[UInt32]` tile data. - parameter debug: `Bool` debug mode. - returns: `Bool` data was successfully added. */ @discardableResult public func setLayerData(_ data: [UInt32], debug: Bool = false) -> Bool { if !(data.count == size.pointCount) { log("invalid data size for layer \"\(self.layerName)\": \(data.count), expected: \(size.pointCount)", level: .error) return false } var errorCount: Int = 0 for index in data.indices { let gid = data[index] // skip empty tiles if (gid == 0) { continue } let x: Int = index % Int(self.size.width) let y: Int = index / Int(self.size.width) let coord = CGPoint(x: CGFloat(x), y: CGFloat(y)) // build the tile let tile = self.buildTileAt(coord: coord, id: gid) if (tile == nil) { errorCount += 1 } } if (errorCount != 0) { log("layer \"\(self.layerName)\": \(errorCount) \(errorCount > 1 ? "errors" : "error") loading data.", level: .warning) } return errorCount == 0 } /** Clear the layer of tiles. */ public func clearLayer() { self.tiles.forEach { tile in tile?.removeFromParent() } self.tiles = TilesArray(columns: Int(tilemap.size.width), rows: Int(tilemap.size.height)) } /** Build an empty tile at the given coordinates. Returns an existing tile if one already exists, or nil if the coordinate is invalid. - parameter coord: `CGPoint` tile coordinate - parameter gid: `Int?` tile id. - parameter tileType: `String` optional tile class name. - returns: `SKTile?` tile. */ public func addTileAt(coord: CGPoint, gid: Int? = nil, tileType: String? = nil) -> SKTile? { guard isValid(coord: coord) else { return nil } // remove the current tile _ = removeTileAt(coord: coord) let tileData: SKTilesetData? = (gid != nil) ? getTileData(globalID: gid!) : nil let Tile = (tilemap.delegate != nil) ? tilemap.delegate!.objectForTileType(named: tileType) : SKTile.self let tile = Tile.init() tile.tileSize = tileSize if let tileData = tileData { tile.tileData = tileData tile.texture = tileData.texture tile.tileSize = (tileData.tileset != nil) ? tileData.tileset!.tileSize : self.tileSize } // set the tile overlap amount tile.setTileOverlap(tilemap.tileOverlap) tile.highlightColor = highlightColor // set the layer property tile.layer = self self.tiles[Int(coord.x), Int(coord.y)] = tile // get the position in the layer (plus tileset offset) let tilePosition = pointForCoordinate(coord: coord, offsetX: offset.x, offsetY: offset.y) tile.position = tilePosition addChild(tile) // add to tile cache NotificationCenter.default.post( name: Notification.Name.Layer.TileAdded, object: tile, userInfo: ["layer": self] ) return tile } /** Build an empty tile at the given coordinates with a custom texture. Returns nil is the coordinate is invalid. - parameter coord: `CGPoint` tile coordinate. - parameter texture: `SKTexture?` optional tile texture. - returns: `SKTile?` tile. */ public func addTileAt(coord: CGPoint, texture: SKTexture? = nil, tileType: String? = nil) -> SKTile? { guard isValid(coord: coord) else { return nil } let Tile = (tilemap.delegate != nil) ? tilemap.delegate!.objectForTileType(named: tileType) : SKTile.self let tile = Tile.init() tile.tileSize = tileSize tile.texture = texture // set the tile overlap amount tile.setTileOverlap(tilemap.tileOverlap) tile.highlightColor = highlightColor // set the layer property tile.layer = self self.tiles[Int(coord.x), Int(coord.y)] = tile // get the position in the layer (plus tileset offset) let tilePosition = pointForCoordinate(coord: coord, offsetX: offset.x, offsetY: offset.y) tile.position = tilePosition addChild(tile) return tile } /** Build an empty tile at the given coordinates. Returns an existing tile if one already exists, or nil if the coordinate is invalid. - parameter x: `Int` x-coordinate - parameter y: `Int` y-coordinate - parameter gid: `Int?` tile id. - returns: `SKTile?` tile. */ public func addTileAt(_ x: Int, _ y: Int, gid: Int? = nil) -> SKTile? { let coord = CGPoint(x: CGFloat(x), y: CGFloat(y)) return addTileAt(coord: coord, gid: gid) } /** Build an empty tile at the given coordinates with a custom texture. Returns nil is the coordinate is invalid. - parameter x: `Int` x-coordinate - parameter y: `Int` y-coordinate - parameter texture: `SKTexture?` optional tile texture. - returns: `SKTile?` tile. */ public func addTileAt(_ x: Int, _ y: Int, texture: SKTexture? = nil) -> SKTile? { let coord = CGPoint(x: CGFloat(x), y: CGFloat(y)) return addTileAt(coord: coord, texture: texture) } /** Remove the tile at a given x/y coordinates. - parameter x: `Int` x-coordinate - parameter y: `Int` y-coordinate - returns: `SKTile?` removed tile. */ public func removeTileAt(_ x: Int, _ y: Int) -> SKTile? { let coord = CGPoint(x: CGFloat(x), y: CGFloat(y)) return removeTileAt(coord: coord) } /** Clear all tiles. */ public func clearTiles() { self.tiles.forEach { tile in tile?.removeAnimation() tile?.removeFromParent() } self.tiles = TilesArray(columns: Int(tilemap.size.width), rows: Int(tilemap.size.height)) } /** Remove the tile at a given coordinate. - parameter coord: `CGPoint` tile coordinate. - returns: `SKTile?` removed tile. */ public func removeTileAt(coord: CGPoint) -> SKTile? { let current = tileAt(coord: coord) if let current = current { current.removeFromParent() self.tiles[Int(coord.x), Int(coord.y)] = nil } return current } /** Build a tile at the given coordinate with the given id. Returns nil if the id cannot be resolved. - parameter coord: `CGPoint` x&y coordinate. - parameter id: `UInt32` tile id. - returns: `SKTile?` tile object. */ fileprivate func buildTileAt(coord: CGPoint, id: UInt32) -> SKTile? { // get tile attributes from the current id let tileAttrs = flippedTileFlags(id: id) let globalId = Int(tileAttrs.gid) if let tileData = tilemap.getTileData(globalID: globalId) { // set the tile data flip flags tileData.flipHoriz = tileAttrs.hflip tileData.flipVert = tileAttrs.vflip tileData.flipDiag = tileAttrs.dflip // get tile object from delegate let Tile = (tilemap.delegate != nil) ? tilemap.delegate!.objectForTileType(named: tileData.type) : SKTile.self if let tile = Tile.init(data: tileData) { // set the tile overlap amount tile.setTileOverlap(tilemap.tileOverlap) tile.highlightColor = highlightColor // set the layer property tile.layer = self tile.highlightDuration = highlightDuration // get the position in the layer (plus tileset offset) let tilePosition = pointForCoordinate(coord: coord, offsetX: tileData.tileset.tileOffset.x, offsetY: tileData.tileset.tileOffset.y) // add to the layer //tile.tileSize = CGSize(width: 10, height: 10) addChild(tile) //tile.tileSize = CGSize(width: 130, height: 230) // set orientation & position tile.orientTile() tile.position = tilePosition // add to the tiles array self.tiles[Int(coord.x), Int(coord.y)] = tile // set the tile zPosition to the current y-coordinate //tile.zPosition = coord.y if tile.texture == nil { Logger.default.log("cannot find a texture for id: \(tileAttrs.gid)", level: .warning, symbol: self.logSymbol) } // add to tile cache NotificationCenter.default.post( name: Notification.Name.Layer.TileAdded, object: tile, userInfo: ["layer": self] ) return tile } else { Logger.default.log("invalid tileset data (id: \(id))", level: .warning, symbol: self.logSymbol) } } else { // check for bad gid calls if !gidErrors.contains(tileAttrs.gid) { gidErrors.append(tileAttrs.gid) } } return nil } /** Set a tile at the given coordinate. - parameter x: `Int` x-coordinate - parameter y: `Int` y-coordinate - returns: `SKTile?` tile. */ public func setTile(_ x: Int, _ y: Int, tile: SKTile? = nil) -> SKTile? { self.tiles[x, y] = tile return tile } /** Set a tile at the given coordinate. - parameter coord: `CGPoint` tile coordinate. - returns: `SKTile?` tile. */ public func setTile(at coord: CGPoint, tile: SKTile? = nil) -> SKTile? { self.tiles[Int(coord.x), Int(coord.y)] = tile return tile } // MARK: - Overlap /** Set the tile overlap. Only accepts a value between 0 - 1.0 - parameter overlap: `CGFloat` tile overlap value. */ public func setTileOverlap(_ overlap: CGFloat) { for tile in tiles where tile != nil { tile!.setTileOverlap(overlap) } } // MARK: - Callbacks /** Called when the layer is finished rendering. - parameter duration: `TimeInterval` fade-in duration. */ override public func didFinishRendering(duration: TimeInterval = 0) { super.didFinishRendering(duration: duration) } // MARK: - Shaders /** Set a shader for tiles in this layer. - parameter for: `[SKTile]` tiles to apply shader to. - parameter named: `String` shader file name. - parameter uniforms: `[SKUniform]` array of shader uniforms. */ public func setShader(for sktiles: [SKTile], named: String, uniforms: [SKUniform] = []) { let shader = SKShader(fileNamed: named) shader.uniforms = uniforms for tile in sktiles { tile.shader = shader } } // MARK: - Debugging /** Visualize the layer's boundary shape. */ override public func drawBounds() { tiles.compactMap{ $0 }.forEach { $0.drawBounds() } super.drawBounds() } override public func debugLayer() { super.debugLayer() for tile in getTiles() { log(tile.debugDescription, level: .debug) } } // MARK: - Updating: Tile Layer /** Run animation actions on all tiles layer. */ override public func runAnimationAsActions() { super.runAnimationAsActions() let animatedTiles = getTiles().filter { tile in tile.tileData.isAnimated == true } animatedTiles.forEach { $0.runAnimationAsActions() } } /** Remove tile animations. - parameter restore: `Bool` restore tile/obejct texture. */ override public func removeAnimationActions(restore: Bool = false) { super.removeAnimationActions(restore: restore) let animatedTiles = getTiles().filter { tile in tile.tileData.isAnimated == true } animatedTiles.forEach { $0.removeAnimationActions(restore: restore) } } /** Update the tile layer before each frame is rendered. - parameter currentTime: `TimeInterval` update interval. */ override public func update(_ currentTime: TimeInterval) { super.update(currentTime) guard (self.updateMode != TileUpdateMode.actions) else { return } } } // MARK: - Extensions extension SKTiledLayerObject { // convenience properties public var width: CGFloat { return tilemap.width } public var height: CGFloat { return tilemap.height } public var tileWidth: CGFloat { return tilemap.tileWidth } public var tileHeight: CGFloat { return tilemap.tileHeight } public var sizeHalved: CGSize { return tilemap.sizeHalved } public var tileWidthHalf: CGFloat { return tilemap.tileWidthHalf } public var tileHeightHalf: CGFloat { return tilemap.tileHeightHalf } public var sizeInPoints: CGSize { return tilemap.sizeInPoints } /// Layer transparency. public var opacity: CGFloat { get { return self.alpha } set { self.alpha = newValue } } /// Layer visibility. public var visible: Bool { get { return !self.isHidden } set { self.isHidden = !newValue } } /** Add a node at the given coordinates. By default, the zPositon will be higher than all of the other nodes in the layer. - parameter node: `SKNode` object. - parameter x: `Int` x-coordinate. - parameter y: `Int` y-coordinate. - parameter dx: `CGFloat` offset x-amount. - parameter dy: `CGFloat` offset y-amount. - parameter zpos: `CGFloat?` optional z-position. */ public func addChild(_ node: SKNode, _ x: Int, _ y: Int, dx: CGFloat = 0, dy: CGFloat = 0, zpos: CGFloat? = nil) { let coord = CGPoint(x: CGFloat(x), y: CGFloat(y)) let offset = CGPoint(x: dx, y: dy) addChild(node, coord: coord, offset: offset, zpos: zpos) } /** Returns a point for a given coordinate in the layer, with optional offset values for x/y. - parameter x: `Int` x-coordinate. - parameter y: `Int` y-coordinate. - parameter offsetX: `CGFloat` x-offset value. - parameter offsetY: `CGFloat` y-offset value. - returns: `CGPoint` position in layer. */ public func pointForCoordinate(_ x: Int, _ y: Int, offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> CGPoint { return self.pointForCoordinate(coord: CGPoint(x: CGFloat(x), y: CGFloat(y)), offsetX: offsetX, offsetY: offsetY) } /** Returns a point for a given coordinate in the layer, with optional offset. - parameter coord: `CGPoint` tile coordinate. - parameter offset: `CGPoint` tile offset. - returns: `CGPoint` point in layer. */ public func pointForCoordinate(coord: CGPoint, offset: CGPoint) -> CGPoint { return self.pointForCoordinate(coord: coord, offsetX: offset.x, offsetY: offset.y) } /** Returns a point for a given coordinate in the layer, with optional offset. - parameter coord: `CGPoint` tile coordinate. - parameter offset: `TileOffset` tile offset hint. - returns: `CGPoint` point in layer. */ public func pointForCoordinate(coord: CGPoint, tileOffset: SKTiledLayerObject.TileOffset = .center) -> CGPoint { var offset = CGPoint(x: 0, y: 0) switch tileOffset { case .top: offset = CGPoint(x: 0, y: -tileHeightHalf) case .topLeft: offset = CGPoint(x: -tileWidthHalf, y: -tileHeightHalf) case .topRight: offset = CGPoint(x: tileWidthHalf, y: -tileHeightHalf) case .bottom: offset = CGPoint(x: 0, y: tileHeightHalf) case .bottomLeft: offset = CGPoint(x: -tileWidthHalf, y: tileHeightHalf) case .bottomRight: offset = CGPoint(x: tileWidthHalf, y: tileHeightHalf) case .left: offset = CGPoint(x: -tileWidthHalf, y: 0) case .right: offset = CGPoint(x: tileWidthHalf, y: 0) default: break } return self.pointForCoordinate(coord: coord, offsetX: offset.x, offsetY: offset.y) } /** Returns a tile coordinate for a given vector_int2 coordinate. - parameter vec2: `int2` vector int2 coordinate. - parameter offsetX: `CGFloat` x-offset value. - parameter offsetY: `CGFloat` y-offset value. - returns: `CGPoint` position in layer. */ public func pointForCoordinate(vec2: int2, offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> CGPoint { return self.pointForCoordinate(coord: vec2.cgPoint, offsetX: offsetX, offsetY: offsetY) } /** Returns a tile coordinate for a given point in the layer. - parameter x: `Int` x-position. - parameter y: `Int` y-position. - returns: `CGPoint` position in layer. */ public func coordinateForPoint(_ x: Int, _ y: Int) -> CGPoint { return self.coordinateForPoint(CGPoint(x: CGFloat(x), y: CGFloat(y))) } /** Returns the center point of a layer. */ public var center: CGPoint { return CGPoint(x: (size.width / 2) - (size.width * anchorPoint.x), y: (size.height / 2) - (size.height * anchorPoint.y)) } /** Calculate the distance from the layer's origin */ public func distanceFromOrigin(_ pos: CGPoint) -> CGVector { let dx = (pos.x - center.x) let dy = (pos.y - center.y) return CGVector(dx: dx, dy: dy) } override public var description: String { let isTopLevel = self.parents.count == 1 let indexString = (isTopLevel == true) ? ", index: \(index)" : "" let layerTypeString = (layerType != TiledLayerType.none) ? layerType.stringValue.capitalized : "Background" return "\(layerTypeString) Layer: \"\(self.path)\"\(indexString), zpos: \(Int(self.zPosition))" } override public var debugDescription: String { return "<\(description)>" } /// Returns a value for use in a dropdown menu. public var menuDescription: String { let parentCount = parents.count let isGrouped: Bool = (parentCount > 1) var layerSymbol: String = layerType.symbol let isGroupNode = (layerType == TiledLayerType.group) let hasChildren: Bool = (childLayers.isEmpty == false) if (isGroupNode == true) { layerSymbol = (hasChildren == true) ? "▿" : "▹" } let filler = (isGrouped == true) ? String(repeating: " ", count: parentCount - 1) : "" return "\(filler)\(layerSymbol) \(layerName)" } } extension SKTiledLayerObject { /// String representing the layer name (null if not set). public var layerName: String { return self.name ?? "null" } /// Returns an array of parent layers, beginning with the current. public var parents: [SKNode] { var current = self as SKNode var result: [SKNode] = [current] while current.parent != nil { if (current.parent! as? SKTiledLayerObject != nil) { result.append(current.parent!) } current = current.parent! } return result } /// Returns an array of child layers. public var childLayers: [SKNode] { return self.enumerate() } /** Returns an array of tiles/objects that conform to the `SKTiledGeometry` protocol. - returns: `[SKNode]` array of child objects. */ public func renderableObjects() -> [SKNode] { var result: [SKNode] = [] enumerateChildNodes(withName: "*") { node, _ in if (node as? SKTiledGeometry != nil) { result.append(node) } } return result } /// Indicates the layer is a top-level layer. public var isTopLevel: Bool { return self.parents.count <= 1 } /// Translate the parent hierarchy to a path string public var path: String { let allParents: [SKNode] = self.parents.reversed() if (allParents.count == 1) { return self.layerName } return allParents.reduce("") { result, node in let comma = allParents.firstIndex(of: node)! < allParents.count - 1 ? "/" : "" return result + "\(node.name ?? "nil")" + comma } } /// Returns the actual zPosition as rendered by the scene. internal var actualZPosition: CGFloat { return (isTopLevel == true) ? zPosition : parents.reduce(zPosition, { result, parent in return result + parent.zPosition }) } /// Returns a string array representing the current layer name & index. public var layerStatsDescription: [String] { let digitCount: Int = self.tilemap.lastIndex.digitCount + 1 let parentNodes = self.parents let isGrouped: Bool = (parentNodes.count > 1) let isGroupNode: Bool = (self as? SKGroupLayer != nil) let indexString = (isGrouped == true) ? String(repeating: " ", count: digitCount) : "\(index).".zfill(length: digitCount, pattern: " ") let typeString = self.layerType.stringValue.capitalized.zfill(length: 6, pattern: " ", padLeft: false) let hasChildren: Bool = (childLayers.isEmpty == false) var layerSymbol: String = " " if (isGroupNode == true) { layerSymbol = (hasChildren == true) ? "▿" : "▹" } let filler = (isGrouped == true) ? String(repeating: " ", count: parentNodes.count - 1) : "" let layerPathString = "\(filler)\(layerSymbol) \"\(layerName)\"" let layerVisibilityString: String = (self.isolated == true) ? "(i)" : (self.visible == true) ? "[x]" : "[ ]" // layer position string, filters out child layers with no offset var positionString = self.position.shortDescription if (self.position.x == 0) && (self.position.y == 0) { positionString = "" } let graphStat = (renderInfo.gn != nil) ? "\(renderInfo.gn!)" : "" return [indexString, typeString, layerVisibilityString, layerPathString, positionString, self.sizeInPoints.shortDescription, self.offset.shortDescription, self.anchorPoint.shortDescription, "\(Int(self.zPosition))", self.opacity.roundTo(2), graphStat] } /** Recursively enumerate child nodes. - returns: `[SKNode]` child elements. */ internal func enumerate() -> [SKNode] { var result: [SKNode] = [self] for child in children { if let node = child as? SKTiledLayerObject { result += node.enumerate() } } return result } } extension SKTiledLayerObject.TiledLayerType { /// Returns a string representation of the layer type. internal var stringValue: String { return "\(self)".lowercased() } internal var symbol: String { switch self { case .tile: return "⊞" case .object: return "⧉" default: return "" } } } extension SKTiledLayerObject.TiledLayerType: CustomStringConvertible, CustomDebugStringConvertible { var description: String { switch self { case .none: return "none" case .tile: return "tile" case .object: return "object" case .image: return "image" case .group: return "group" } } var debugDescription: String { return description } } /** Initialize a color with RGB Integer values (0-255). - parameter r: `Int` red component. - parameter g: `Int` green component. - parameter b: `Int` blue component. - returns: `SKColor` color with given values. */ internal func SKColorWithRGB(_ r: Int, g: Int, b: Int) -> SKColor { return SKColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0) } /** Initialize a color with RGBA Integer values (0-255). - parameter r: `Int` red component. - parameter g: `Int` green component. - parameter b: `Int` blue component. - parameter a: `Int` alpha component. - returns: `SKColor` color with given values. */ internal func SKColorWithRGBA(_ r: Int, g: Int, b: Int, a: Int) -> SKColor { return SKColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(a)/255.0) } // MARK: - Deprecated extension SKTiledLayerObject { @available(*, deprecated, renamed: "runAnimationAsActions") /** Initialize SpriteKit animation actions for the layer. */ public func runAnimationAsAction() { self.runAnimationAsActions() } } extension SKTileLayer { /** Returns an array of valid tiles. - returns: `[SKTile]` array of current tiles. */ @available(*, deprecated, message: "use `getTiles()` instead") public func validTiles() -> [SKTile] { return self.getTiles() } }
33.748582
176
0.57671
1824b240f0cc76539732889dede2b1f773176202
2,177
// // AppDelegate.swift // RSScrollMenuView // // Created by WhatsXie on 2017/7/17. // Copyright © 2017年 StevenXie. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.319149
285
0.756546
f4d969589c1132ed7f93de39ee4a977311e31e5d
2,629
import Foundation import XCTest @testable import Relayer final class DispatcherTests: XCTestCase { var sut: Dispatcher! var webSocketSession: WebSocketSessionMock! var networkMonitor: NetworkMonitoringMock! var socketConnectionObserver: SocketConnectionObserverMock! override func setUp() { webSocketSession = WebSocketSessionMock() networkMonitor = NetworkMonitoringMock() socketConnectionObserver = SocketConnectionObserverMock() let url = URL(string: "ws://staging.walletconnect.org")! sut = Dispatcher(url: url, networkMonitor: networkMonitor, socket: webSocketSession, socketConnectionObserver: socketConnectionObserver) } func testDisconnectOnConnectionLoss() { XCTAssertTrue(sut.socket.isConnected) networkMonitor.onUnsatisfied?() XCTAssertFalse(sut.socket.isConnected) } func testConnectsOnConnectionSatisfied() { sut.disconnect(closeCode: .normalClosure) XCTAssertFalse(sut.socket.isConnected) networkMonitor.onSatisfied?() XCTAssertTrue(sut.socket.isConnected) } func testSendWhileConnected() { sut.connect() sut.send("1"){_ in} XCTAssertEqual(webSocketSession.sendCallCount, 1) } func testTextFramesSentAfterReconnectingSocket() { sut.disconnect(closeCode: .normalClosure) sut.send("1"){_ in} sut.send("2"){_ in} XCTAssertEqual(webSocketSession.sendCallCount, 0) sut.connect() socketConnectionObserver.onConnect?() XCTAssertEqual(webSocketSession.sendCallCount, 2) } func testOnMessage() { let expectation = expectation(description: "on message") sut.onMessage = { message in XCTAssertNotNil(message) expectation.fulfill() } webSocketSession.onMessageReceived?("message") waitForExpectations(timeout: 0.001) } func testOnConnect() { let expectation = expectation(description: "on connect") sut.onConnect = { expectation.fulfill() } socketConnectionObserver.onConnect?() waitForExpectations(timeout: 0.001) } func testOnDisconnect() { let expectation = expectation(description: "on disconnect") sut.onDisconnect = { expectation.fulfill() } socketConnectionObserver.onDisconnect?() waitForExpectations(timeout: 0.001) } } class SocketConnectionObserverMock: SocketConnectionObserving { var onConnect: (() -> ())? var onDisconnect: (() -> ())? }
32.060976
144
0.66375
e21770480f0e86ef4485e151cbb1fd7ebabbbaec
1,457
// // PersonQuery.swift // ChikaCore // // Created by Mounir Ybanez on 1/7/18. // Copyright © 2018 Nir. All rights reserved. // public protocol PersonQuery { func getPersons(for personIDs: [ID], completion: @escaping (Result<[Person]>) -> Void) -> Bool } public protocol PersonQueryOperator { func withPersonIDs(_ personIDs: [ID]) -> PersonQueryOperator func withCompletion(_ completion: @escaping (Result<[Person]>) -> Void) ->PersonQueryOperator func getPersons(using query: PersonQuery) -> Bool } public class PersonQueryOperation: PersonQueryOperator { var personIDs: [ID]? var completion: ((Result<[Person]>) -> Void)? public init() { } public func withPersonIDs(_ aPersonIDs: [ID]) -> PersonQueryOperator { personIDs = aPersonIDs return self } public func withCompletion(_ aCompletion: @escaping (Result<[Person]>) -> Void) -> PersonQueryOperator { completion = aCompletion return self } public func getPersons(using query: PersonQuery) -> Bool { defer { personIDs?.removeAll() personIDs = nil completion = nil } guard personIDs != nil else { return false } let callback = completion let ok = query.getPersons(for: personIDs!) { result in callback?(result) } return ok } }
24.694915
108
0.599176
210531953c9243e759a00c03ebc2007dd0f9235d
483
// // Created by Ryan Ackermann on 7/10/15. // Copyright (c) 2015 Ryan Ackermann. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // Override point for customization after application launch. return true } }
24.15
152
0.720497
4b44ce6bd8d13d5a258d175b7b1d834175dcd17d
341
import Foundation import SWXMLHash extension XMLIndexer { func userInfo() throws -> [String: String] { let keysAndValues: [(String, String)] = try self["userInfo"][0].children.map { try ($0.value(ofAttribute: "key"), $0.value(ofAttribute: "value")) } return Dictionary(keysAndValues) { $1 } } }
26.230769
86
0.615836
7a6e962ac66a2cebd36715b863e6604d5fca9d41
4,614
// // YPLibraryView.swift // YPImgePicker // // Created by Sacha Durand Saint Omer on 2015/11/14. // Copyright © 2015 Yummypets. All rights reserved. // import UIKit import Stevia import Photos final class YPLibraryView: UIView { let assetZoomableViewMinimalVisibleHeight: CGFloat = 50 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var assetZoomableView: YPAssetZoomableView! @IBOutlet weak var assetViewContainer: YPAssetViewContainer! @IBOutlet weak var assetViewContainerConstraintTop: NSLayoutConstraint! let maxNumberWarningView = UIView() let maxNumberWarningLabel = UILabel() let progressView = UIProgressView() let line = UIView() override func awakeFromNib() { super.awakeFromNib() sv( line ) layout( assetViewContainer!, |line| ~ 1 ) line.backgroundColor = .clear setupMaxNumberOfItemsView() setupProgressBarView() } /// At the bottom there is a view that is visible when selected a limit of items with multiple selection func setupMaxNumberOfItemsView() { // View Hierarchy sv( maxNumberWarningView.sv( maxNumberWarningLabel ) ) // Layout |maxNumberWarningView|.bottom(0) if #available(iOS 11.0, *) { maxNumberWarningView.Top == safeAreaLayoutGuide.Bottom - 40 maxNumberWarningLabel.centerHorizontally().top(11) } else { maxNumberWarningView.height(40) maxNumberWarningLabel.centerInContainer() } // Style maxNumberWarningView.backgroundColor = UIColor(r: 246, g: 248, b: 248) maxNumberWarningLabel.font = UIFont(name: "Helvetica Neue", size: 14) maxNumberWarningView.isHidden = true } /// When video is processing this bar appears func setupProgressBarView() { sv( progressView ) progressView.height(5) progressView.Top == line.Top progressView.Width == line.Width progressView.progressViewStyle = .bar progressView.trackTintColor = YPConfig.colors.progressBarTrackColor progressView.progressTintColor = YPConfig.colors.progressBarCompletedColor ?? YPConfig.colors.tintColor progressView.isHidden = true progressView.isUserInteractionEnabled = false } } // MARK: - UI Helpers extension YPLibraryView { class func xibView() -> YPLibraryView? { let bundle = Bundle(for: YPPickerVC.self) let nib = UINib(nibName: "YPLibraryView", bundle: bundle) let xibView = nib.instantiate(withOwner: self, options: nil)[0] as? YPLibraryView return xibView } // MARK: - Grid func hideGrid() { assetViewContainer.grid.alpha = 0 } // MARK: - Loader and progress func fadeInLoader() { UIView.animate(withDuration: 0.2) { self.assetViewContainer.spinnerView.alpha = 1 } } func hideLoader() { assetViewContainer.spinnerView.alpha = 0 } func updateProgress(_ progress: Float) { progressView.isHidden = progress > 0.99 || progress == 0 progressView.progress = progress UIView.animate(withDuration: 0.1, animations: progressView.layoutIfNeeded) } // MARK: - Crop Rect func currentCropRect() -> CGRect { guard let cropView = assetZoomableView else { return CGRect.zero } let normalizedX = min(1, cropView.contentOffset.x &/ cropView.contentSize.width) let normalizedY = min(1, cropView.contentOffset.y &/ cropView.contentSize.height) let normalizedWidth = min(1, cropView.frame.width / cropView.contentSize.width) let normalizedHeight = min(1, cropView.frame.height / cropView.contentSize.height) return CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight) } // MARK: - Curtain func refreshImageCurtainAlpha() { let imageCurtainAlpha = abs(assetViewContainerConstraintTop.constant) / (assetViewContainer.frame.height - assetZoomableViewMinimalVisibleHeight) assetViewContainer.curtain.alpha = imageCurtainAlpha } func cellSize() -> CGSize { let size = UIScreen.main.bounds.width/4 * UIScreen.main.scale return CGSize(width: size, height: size) } }
30.966443
111
0.631773
183d62c54ba5ad0db213e4cbc48a64be6ac82ff7
2,777
/// Copyright (c) 2020 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 UIKit class KeyboardFollower: ObservableObject { @Published var keyboardHeight: CGFloat = 0 @Published var isVisible = false init() { NotificationCenter.default.addObserver( self, selector: #selector(keyboardVisibilityChanged), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } // deinit { // NotificationCenter.default.removeObserver( // self, // name: UIResponder.keyboardWillChangeFrameNotification, // object: nil) // } @objc private func keyboardVisibilityChanged(_ notification: Notification) { guard let userInfo = notification.userInfo else { return } guard let keyboardEndFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } isVisible = keyboardEndFrame.minY < UIScreen.main.bounds.height keyboardHeight = isVisible ? keyboardEndFrame.height : 0 } }
44.790323
109
0.75081
de7a7419a5503953a7f5a27b0593bc9e20003c79
2,957
//// //// Created by Mike on 8/15/21. //// final class NavigationLinkDestination { let view: SomeView init<V: View>(_ destination: V) { view = destination } } public struct NavigationLink<Label, Destination>: View where Label: View, Destination: View { // @State var destination: NavigationLinkDestination // let label: Label // // @EnvironmentObject var navigationContext: NavigationContext public init( @ViewBuilder destination: () -> Destination, @ViewBuilder label: () -> Label ) { self.init(destination: destination(), label: label) } public init( isActive: Binding<Swift.Bool>, @ViewBuilder destination: () -> Destination, @ViewBuilder label: () -> Label ) { self.init(destination: destination(), isActive: isActive, label: label) } public init<V>( tag: V, selection: Binding<V?>, @ViewBuilder destination: () -> Destination, @ViewBuilder label: () -> Label ) where V: Hashable { self.init( destination: destination(), tag: tag, selection: selection, label: label) } internal init(destination: Destination, @ViewBuilder label: () -> Label) { // self.label = label() // self.destination = .init(destination) // _destination = State(wrappedValue: NavigationLinkDestination(destination)) // self.label = label() } internal init( destination: Destination, isActive: Binding<Bool>, @ViewBuilder label: () -> Label ) {} internal init<V>( destination: Destination, tag: V, selection: Binding<V?>, @ViewBuilder label: () -> Label ) where V: Hashable {} } extension NavigationLink where Label == Text { @_disfavoredOverload public init<S>(_ title: S, @ViewBuilder destination: () -> Destination) where S : Swift.StringProtocol { self.init(title, destination: destination()) } @_disfavoredOverload public init<S>(_ title: S, isActive: Binding<Swift.Bool>, @ViewBuilder destination: () -> Destination) where S : Swift.StringProtocol { self.init(title, destination: destination(), isActive: isActive) } @_disfavoredOverload public init<S, V>(_ title: S, tag: V, selection: Binding<V?>, @ViewBuilder destination: () -> Destination) where S : Swift.StringProtocol, V : Swift.Hashable { self.init( title, destination: destination(), tag: tag, selection: selection) } internal init<S>(_ title: S, destination: Destination) where S : Swift.StringProtocol {} internal init<S>(_ title: S, destination: Destination, isActive: Binding<Swift.Bool>) where S : Swift.StringProtocol {} internal init<S, V>(_ title: S, destination: Destination, tag: V, selection: Binding<V?>) where S : Swift.StringProtocol, V : Swift.Hashable {} }
31.457447
163
0.6209
03ac23b24d0ff6b934dcd66032d996c2b3ec08a1
927
// // CustomTimePickerTests.swift // CustomTimePickerTests // // Created by recherst on 2021/8/18. // import XCTest @testable import CustomTimePicker class CustomTimePickerTests: 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. } } }
27.264706
111
0.675297
48eeb77af0d7338d3ed9fa5c33d25715df01b107
886
// // UITableView+Styles.swift // SurfPlaybook // // Created by Александр Чаусов on 19.04.2021. // Copyright © 2021 Surf. All rights reserved. // import UIKit extension UITableView { func apply(style: TableViewStyleType) { style.apply(for: self) } } enum TableViewStyleType { case `default` func apply(for view: UITableView) { switch self { case .default: view.backgroundColor = Colors.Main.background view.contentInsetAdjustmentBehavior = .never view.keyboardDismissMode = .onDrag view.separatorStyle = .none // дефолтный отступ снизу до контента, как завещал Гомес view.contentInset = .init(top: 0, left: 0, bottom: 30, right: 0) } } }
23.945946
68
0.541761
8fa0054475d9aefe1cc931d89739e57f5ffda32e
763
import UIKit import XCTest import SwiftyBootpay class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.433333
111
0.606815
c1debf58f8826ca53304d9f8780e45a550102c3e
2,477
// // WeatherForecastTests.swift // OpenWeather // // Created by Dario Banno on 29/05/2017. // Copyright © 2017 AppTown. All rights reserved. // import XCTest @testable import OpenWeather class WeatherForecastTests: XCTestCase { func test_invalid_json_population() { // GIVEN I have an invalid json let jsonObject = ["ciao": "bella"] // WHEN I populate a forecast object from json let forecast = WeatherForecast(json: jsonObject) // THEN I can see object is nil XCTAssertNil(forecast) } func test_valid_json_population() { // GIVEN I have a json object for weather let jsonObject = json(forFile: "forecast.json")! // WHEN I populate a weather object from json let forecast = WeatherForecast(json: jsonObject) // THEN I can see object is not nil XCTAssertNotNil(forecast) // AND I can see all fields are properly populated XCTAssertEqual(forecast?.station.id, 2643743) XCTAssertEqual(forecast?.station.name, "London") XCTAssertEqual(forecast?.station.country, "GB") XCTAssertEqual(forecast?.weatherList.count, 2) XCTAssertEqual(forecast?.weatherList[0].code, 802) XCTAssertEqual(forecast?.weatherList[0].condition, "Clouds") XCTAssertEqual(forecast?.weatherList[0].humidity, 62) XCTAssertEqual(forecast?.weatherList[0].temperature, 293.81) XCTAssertEqual(forecast?.weatherList[0].temperatureMin, 293.81) XCTAssertEqual(forecast?.weatherList[0].temperatureMax, 295.409) XCTAssertEqual(forecast?.weatherList[0].timestamp, 1496070000) XCTAssertEqual(forecast?.weatherList[0].wind.speed, 5.47) XCTAssertEqual(forecast?.weatherList[0].wind.degrees, 241.503) XCTAssertEqual(forecast?.weatherList[1].code, 800) XCTAssertEqual(forecast?.weatherList[1].condition, "Clear") XCTAssertEqual(forecast?.weatherList[1].humidity, 75) XCTAssertEqual(forecast?.weatherList[1].temperature, 286.917) XCTAssertEqual(forecast?.weatherList[1].temperatureMin, 286.917) XCTAssertEqual(forecast?.weatherList[1].temperatureMax, 286.917) XCTAssertEqual(forecast?.weatherList[1].timestamp, 1496124000) XCTAssertEqual(forecast?.weatherList[1].wind.speed, 3.46) XCTAssertEqual(forecast?.weatherList[1].wind.degrees, 257.501) } }
39.31746
72
0.672184
fbd75321cb70a477657ecc3dd20bb3d9527e327d
2,915
// // QueuedDownloadsCell.swift // appdb // // Created by ned on 22/04/2019. // Copyright © 2019 ned. All rights reserved. // import UIKit import Cartography import AlamofireImage class QueuedDownloadsCell: UICollectionViewCell { private var iconSize: CGFloat = (75 ~~ 65) private var margin: CGFloat = (15 ~~ 12) private var name: UILabel! private var icon: UIImageView! private var status: UILabel! func configure(with app: RequestedApp) { name.text = app.name status.text = app.status if app.type != .myAppstore { if let url = URL(string: app.image) { icon.af.setImage(withURL: url, placeholderImage: #imageLiteral(resourceName: "placeholderIcon"), filter: Global.roundedFilter(from: iconSize), imageTransition: .crossDissolve(0.2)) } } else { icon.image = #imageLiteral(resourceName: "blank_icon") } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.setup() } func setup() { theme_backgroundColor = Color.veryVeryLightGray contentView.theme_backgroundColor = Color.veryVeryLightGray contentView.layer.cornerRadius = 6 contentView.layer.borderWidth = 1 / UIScreen.main.scale contentView.layer.theme_borderColor = Color.borderCgColor layer.backgroundColor = UIColor.clear.cgColor // Name name = UILabel() name.theme_textColor = Color.title name.font = .systemFont(ofSize: 18.5 ~~ 16.5) name.numberOfLines = 1 name.makeDynamicFont() // Icon icon = UIImageView() icon.layer.borderWidth = 1 / UIScreen.main.scale icon.layer.theme_borderColor = Color.borderCgColor icon.contentMode = .scaleToFill icon.layer.cornerRadius = Global.cornerRadius(from: iconSize) // Status status = UILabel() status.theme_textColor = Color.darkGray status.font = .systemFont(ofSize: 14 ~~ 13) status.numberOfLines = 2 status.makeDynamicFont() contentView.addSubview(name) contentView.addSubview(icon) contentView.addSubview(status) constrain(name, status, icon) { name, status, icon in icon.width ~== iconSize icon.height ~== icon.width icon.left ~== icon.superview!.left ~+ margin icon.centerY ~== icon.superview!.centerY (name.left ~== icon.right ~+ (15 ~~ 12)) ~ Global.notMaxPriority name.right ~== name.superview!.right ~- margin name.top ~== icon.top ~+ 5 status.left ~== name.left status.top ~== name.bottom ~+ (2 ~~ 0) status.right ~<= status.superview!.right ~- margin } } }
31.010638
158
0.607547
ef746b6f3608ff6b1be58632629669829856e852
14,242
// // MoviesViewController.swift // Flickster // // Created by Priscilla Lok on 2/4/16. // Copyright © 2016 Priscilla Lok. All rights reserved. // import UIKit import AFNetworking import M13ProgressSuite class MoviesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UITabBarDelegate { @IBOutlet weak var backgroundLayerView: UIView! @IBOutlet weak var tabBar: UITabBar! @IBOutlet weak var offlineView: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var searchResults: [NSDictionary]? var useSearchResults: Bool? var movies: [NSDictionary]? var topRatedMovies: [NSDictionary]? var nowPlayingMovies: [NSDictionary]? var refreshControl: UIRefreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() //set color schemes let primaryColor: UIColor = UIColor(red: 0.05, green: 0.14, blue: 0.22, alpha: 1.0) let secondaryColor: UIColor = UIColor(red: 0.42, green: 0.52, blue: 0.62, alpha: 1.0) self.backgroundLayerView.backgroundColor = primaryColor self.tableView.backgroundColor = primaryColor self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None let textSearchField: UITextField = self.searchBar.valueForKey("_searchField") as! UITextField textSearchField.backgroundColor = primaryColor textSearchField.textColor = secondaryColor self.searchBar.barTintColor = secondaryColor UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).tintColor = primaryColor self.tabBar.barTintColor = primaryColor UITabBar.appearance().tintColor = UIColor(red: 0.32, green: 0.42, blue: 0.52, alpha: 1.0) //initialize and set up tableview tableView.dataSource = self tableView.delegate = self self.offlineView.hidden = true makeRequestToAPI() //initialize and set up refresh control refreshControl.addTarget(self, action: "refreshControlAction:", forControlEvents: UIControlEvents.ValueChanged) tableView.insertSubview(refreshControl, atIndex: 0) //initialize and set up search bar self.searchBar.delegate = self useSearchResults = false //initialize and set up tab bar self.tabBar.delegate = self self.tabBar.selectedItem = self.tabBar.items![0] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //# MARK: Obtain movie data methods func makeRequestToAPI() { var nowPlayingRequestDone = false var topRatedRequestDone = false self.navigationController?.showProgress() self.navigationController?.setProgress(0, animated: true) //now_playing API call let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = NSURL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)") let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60.0) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(dataOrNil, response, error) in if error != nil { self.offlineView.hidden = false return } if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary { self.nowPlayingMovies = responseDictionary["results"] as? [NSDictionary] //assign movies based on which tab is selected if (self.tabBar.items?.indexOf(self.tabBar.selectedItem!))! == 0{ self.movies = self.nowPlayingMovies } else { self.movies = self.topRatedMovies } self.searchResults = self.movies self.tableView.reloadData() } self.offlineView.hidden = true } nowPlayingRequestDone = true self.refreshControl.endRefreshing() if nowPlayingRequestDone == true && topRatedRequestDone == true { self.navigationController?.setProgress(1, animated: true) self.navigationController?.setProgress(0, animated: false) self.navigationController?.finishProgress() self.tableView.reloadData() } }) task.resume() //top_rated API call let topRatedUrl = NSURL(string: "https://api.themoviedb.org/3/movie/top_rated?api_key=\(apiKey)") let topRatedRequest = NSURLRequest(URL: topRatedUrl!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60.0) let topRatedSession = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) let topRatedTask : NSURLSessionDataTask = topRatedSession.dataTaskWithRequest(topRatedRequest, completionHandler: {(dataOrNil, response, error) in if error != nil { self.offlineView.hidden = false return } if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary { self.topRatedMovies = responseDictionary["results"] as? [NSDictionary] if (self.tabBar.items?.indexOf(self.tabBar.selectedItem!))! == 0{ self.movies = self.nowPlayingMovies } else { self.movies = self.topRatedMovies } self.searchResults = self.movies self.tableView.reloadData() } self.offlineView.hidden = true } topRatedRequestDone = true self.refreshControl.endRefreshing() if nowPlayingRequestDone == true && topRatedRequestDone == true { self.navigationController?.setProgress(1, animated: true) self.navigationController?.setProgress(0, animated: false) self.navigationController?.finishProgress() self.tableView.reloadData() } }) topRatedTask.resume() } // Makes a network request to get updated data func refreshControlAction(refreshControl: UIRefreshControl) { makeRequestToAPI() self.tableView.reloadData() } //# MARK: Navigation methods override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let vc = segue.destinationViewController as! MovieDetailsViewController let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) let currentMovies: [NSDictionary]? = self.getCurrentMovies() if currentMovies != nil { let movie = currentMovies![(indexPath?.row)!] if let posterPath = movie["poster_path"] as? String { let posterBaseUrl = "http://image.tmdb.org/t/p/w500" let posterUrl = posterBaseUrl + posterPath vc.posterUrl = posterUrl } let title = movie["title"] as? String vc.movieTitle = title let rating = movie["vote_average"] as? Double vc.rating = rating let releaseDate = movie["release_date"] as? String vc.releaseDate = releaseDate let overview = movie["overview"] as? String vc.overview = overview } } //# MARK: TableView Methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.getCurrentMovies().count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MovieCell", forIndexPath: indexPath) as! MovieCell cell.selectionStyle = .Gray var movie :NSDictionary = [:] //determine which array to parse movie from if self.useSearchResults == false { movie = movies![indexPath.row] } else { movie = self.searchResults![indexPath.row] } let title = movie["title"] as! String if let posterPath = movie["poster_path"] as? String { let posterBaseUrl = "http://image.tmdb.org/t/p/w500" let posterUrl = NSURL(string: posterBaseUrl + posterPath) let imageRequest = NSURLRequest(URL: posterUrl!) //set image in cell cell.posterView.setImageWithURLRequest( imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in // imageResponse will be nil if the image is cached if imageResponse != nil { print("Image was NOT cached, fade in image") cell.posterView.alpha = 0.0 cell.posterView.image = image UIView.animateWithDuration(0.3, animations: { () -> Void in cell.posterView.alpha = 1.0 }) } else { print("Image was cached so just update the image") cell.posterView.image = image } }, failure: { (imageRequest, imageResponse, error) -> Void in }) cell.posterView.contentMode = .ScaleAspectFill } else { // No poster image. Can either set to nil (no image) or a default movie poster image // that you include as an asset cell.posterView.image = nil } //set title cell.titleLabel.text = title //set star ratings cell.starRatingView.settings.fillMode = .Half cell.starRatingView.rating = (movie["vote_average"] as? Double)!/2.0 return cell } //# MARK: Tab Bar Methods //tab bar for selection between now_playing and top_rated movies func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { let selectedIndex = tabBar.items?.indexOf(item) if selectedIndex == 0 { self.movies = self.nowPlayingMovies } else { self.movies = self.topRatedMovies } self.tableView.reloadData() } //# MARK: Search Methods func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { self.getSearchResultsForSearchText(searchText) } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { self.useSearchResults = true self.searchBar.showsCancelButton = true self.getSearchResultsForSearchText(searchBar.text!) } //function to either get search results or entire list of movies func getCurrentMovies() -> [NSDictionary] { if self.useSearchResults == true { if self.searchResults != nil { return self.searchResults! } else { return [] } } else { if self.movies != nil{ return self.movies! } else { return [] } } } func getSearchResultsForSearchText(searchText: String) { //clear search results self.searchResults?.removeAll() if searchText.characters.count == 0 { //no search text, default to all movies for movie in self.movies! { self.searchResults?.append(movie) } } else { for movie in self.getMoviesForSearchText(searchText) { self.searchResults?.append(movie) } } self.tableView.reloadData() } func getMoviesForSearchText(text: String) -> [NSDictionary] { let predicate: NSPredicate = NSPredicate(format: "title contains[c] %@", text) let results: [NSDictionary] = (self.movies! as NSArray).filteredArrayUsingPredicate(predicate) as! [NSDictionary] return results } func searchBarCancelButtonClicked(searchBar: UISearchBar) { self.useSearchResults = false self.searchBar.text = "" self.searchBar.endEditing(true) self.searchBar.showsCancelButton = false self.tableView.reloadData() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { self.useSearchResults = true self.view.endEditing(true) self.searchBar.showsCancelButton = false self.tableView.reloadData() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
39.126374
146
0.585943
fcf0cfd8c67a1133281fd694a214e35427166466
2,083
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime import Dispatch // For sleep #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #endif @available(SwiftStdlib 5.5, *) enum TL { @TaskLocal static var number: Int = 0 @TaskLocal static var other: Int = 0 } @available(SwiftStdlib 5.5, *) @discardableResult func printTaskLocal<V>( _ key: TaskLocal<V>, _ expected: V? = nil, file: String = #file, line: UInt = #line ) -> V? { let value = key.get() print("\(key) (\(value)) at \(file):\(line)") if let expected = expected { assert("\(expected)" == "\(value)", "Expected [\(expected)] but found: \(value), at \(file):\(line)") } return expected } // ==== ------------------------------------------------------------------------ @available(SwiftStdlib 5.5, *) func copyTo_sync_noWait() { print(#function) TL.$number.withValue(1111) { TL.$number.withValue(2222) { TL.$other.withValue(9999) { Task { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222) printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999) TL.$number.withValue(3333) { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (3333) printTaskLocal(TL.$other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999) } } } } } sleep(1) } @available(SwiftStdlib 5.5, *) func copyTo_sync_noValues() { Task { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) } sleep(1) } /// Similar to tests in `async_task_locals_copy_to_async_ but without any task involved at the top level. @available(SwiftStdlib 5.5, *) @main struct Main { static func main() { copyTo_sync_noWait() copyTo_sync_noValues() } }
24.797619
130
0.62458
5b5b8d5a2f0f7c36261c98538c2bc9bd51485366
15,520
/* Copyright 2019 FUJITSU CLOUD TECHNOLOGIES LIMITED 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 XCTest @testable import NCMB /// NCMBFieldTypeConverter のテストクラスです。 final class NCMBFieldTypeConverterTests: NCMBTestCase { func test_convertToFieldValue_NCMBIncrementOperator() { var object : [String : Any] = [:] object["__op"] = "Increment" object["amount"] = 42 let incrementOperator = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((incrementOperator! as! NCMBIncrementOperator).amount as! Int, 42) } func test_convertToFieldValue_NCMBAddOperator() { var object : [String : Any] = [:] object["__op"] = "Add" object["objects"] = ["takanokun"] let addOperator = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((addOperator! as! NCMBAddOperator).elements.count, 1) XCTAssertEqual((addOperator! as! NCMBAddOperator).elements[0] as! String, "takanokun") } func test_convertToFieldValue_NCMBAddUniqueOperator() { var object : [String : Any] = [:] object["__op"] = "AddUnique" object["objects"] = ["takanokun"] let addUniqueOperator = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((addUniqueOperator! as! NCMBAddUniqueOperator).elements.count, 1) XCTAssertEqual((addUniqueOperator! as! NCMBAddUniqueOperator).elements[0] as! String, "takanokun") } func test_convertToFieldValue_NCMBRemoveOperator() { var object : [String : Any] = [:] object["__op"] = "Remove" object["objects"] = ["takanokun"] let removeOperator = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((removeOperator! as! NCMBRemoveOperator).elements.count, 1) XCTAssertEqual((removeOperator! as! NCMBRemoveOperator).elements[0] as! String, "takanokun") } func test_convertToFieldValue_NCMBAddRelationOperator() { var object : [String : Any] = [:] object["__op"] = "AddRelation" object["className"] = "TestClass" var pointerJson : [String : Any] = [:] pointerJson["__type"] = "Pointer" pointerJson["className"] = "TestClass" pointerJson["objectId"] = "hogeHOGE12345678" object["objects"] = [pointerJson] let addRelationOperator = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((addRelationOperator! as! NCMBAddRelationOperator).elements.count, 1) XCTAssertEqual((addRelationOperator! as! NCMBAddRelationOperator).elements[0] , NCMBPointer(className: "TestClass", objectId: "hogeHOGE12345678")) } func test_convertToFieldValue_NCMBRemoveRelationOperator() { var object : [String : Any] = [:] object["__op"] = "RemoveRelation" object["className"] = "TestClass" var pointerJson : [String : Any] = [:] pointerJson["__type"] = "Pointer" pointerJson["className"] = "TestClass" pointerJson["objectId"] = "hogeHOGE12345678" object["objects"] = [pointerJson] let removeRelationOperator = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((removeRelationOperator! as! NCMBRemoveRelationOperator).elements.count, 1) XCTAssertEqual((removeRelationOperator! as! NCMBRemoveRelationOperator).elements[0] , NCMBPointer(className: "TestClass", objectId: "hogeHOGE12345678")) } func test_convertToFieldValue_Date() { var object : [String : Any] = [:] object["__type"] = "Date" object["iso"] = "1986-02-04T12:34:56.789Z" let date = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual(date! as! Date, Date(timeIntervalSince1970: 507904496.789)) } func test_convertToFieldValue_NCMBPointer() { var object : [String : Any] = [:] object["__type"] = "Pointer" object["className"] = "TestClass" object["objectId"] = "abcde12345" let pointer = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((pointer! as! NCMBPointer).className, "TestClass") XCTAssertEqual((pointer! as! NCMBPointer).objectId, "abcde12345") } func test_convertToFieldValue_NCMBRelation() { var object : [String : Any] = [:] object["__type"] = "Relation" object["className"] = "TestClass" let relation = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((relation! as! NCMBRelation).className, "TestClass") } func test_convertToFieldValue_NCMBGeoPoint() { var object : [String : Any] = [:] object["__type"] = "GeoPoint" object["latitude"] = Double(35.6666269) object["longitude"] = Double(139.765607) let geoPoint = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertEqual((geoPoint! as! NCMBGeoPoint).latitude, Double(35.6666269)) XCTAssertEqual((geoPoint! as! NCMBGeoPoint).longitude, Double(139.765607)) } // func test_convertToFieldValue_NCMBObjectField() { // TBD // } func test_convertToFieldValue_Int() { let object : Int = 42 let int = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertNil(int) } func test_convertToFieldValue_String() { let object : String = "takanokun" let string = NCMBFieldTypeConverter.convertToFieldValue(object: object) XCTAssertNil(string) } func test_converToObject_NCMBIncrementOperator() { let incrementOperator = NCMBIncrementOperator(amount: 42) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: incrementOperator) XCTAssertEqual(object!["__op"]! as! String, "Increment") XCTAssertEqual(object!["amount"]! as! Int, 42) } func test_converToObject_NCMBAddOperator() { let addOperator = NCMBAddOperator(elements: ["takanokun", "takano_san"]) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: addOperator) XCTAssertEqual(object!["__op"]! as! String, "Add") XCTAssertEqual((object!["objects"]! as! Array<String>).count, 2) XCTAssertEqual((object!["objects"]! as! Array<String>)[0], "takanokun") XCTAssertEqual((object!["objects"]! as! Array<String>)[1], "takano_san") } func test_converToObject_NCMBAddUniqueOperator() { let addUniqueOperator = NCMBAddUniqueOperator(elements: ["takanokun", "takano_san"]) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: addUniqueOperator) XCTAssertEqual(object!["__op"]! as! String, "AddUnique") XCTAssertEqual((object!["objects"]! as! Array<String>).count, 2) XCTAssertEqual((object!["objects"]! as! Array<String>)[0], "takanokun") XCTAssertEqual((object!["objects"]! as! Array<String>)[1], "takano_san") } func test_converToObject_NCMBRemoveOperator() { let removeOperator = NCMBRemoveOperator(elements: ["takanokun", "takano_san"]) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: removeOperator) XCTAssertEqual(object!["__op"]! as! String, "Remove") XCTAssertEqual((object!["objects"]! as! Array<String>).count, 2) XCTAssertEqual((object!["objects"]! as! Array<String>)[0], "takanokun") XCTAssertEqual((object!["objects"]! as! Array<String>)[1], "takano_san") } func test_converToObject_NCMBAddRelationOperator() { let JsontoObject1 = NCMBPointer(className: "TestClass", objectId: "hogeHOGE12345678") let JsontoObject2 = NCMBPointer(className: "TestClass", objectId: "hogeHOGE90123456") let addRelationOperator = NCMBAddRelationOperator(elements: [JsontoObject1,JsontoObject2]) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: addRelationOperator) XCTAssertEqual(object!["__op"]! as! String, "AddRelation") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>).count, 2) XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0].count, 3) XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0]["__type"] as! String, "Pointer") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0]["className"] as! String, "TestClass") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0]["objectId"] as! String, "hogeHOGE12345678") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1].count, 3) XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1]["__type"] as! String, "Pointer") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1]["className"] as! String, "TestClass") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1]["objectId"] as! String, "hogeHOGE90123456") } func test_converToObject_NCMBRemoveRelationOperator() { let JsontoObject1 = NCMBPointer(className: "TestClass", objectId: "hogeHOGE12345678") let JsontoObject2 = NCMBPointer(className: "TestClass", objectId: "hogeHOGE90123456") let removeRelationOperator = NCMBRemoveRelationOperator(elements: [JsontoObject1,JsontoObject2]) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: removeRelationOperator) XCTAssertEqual(object!["__op"]! as! String, "RemoveRelation") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>).count, 2) XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0].count, 3) XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0]["__type"] as! String, "Pointer") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0]["className"] as! String, "TestClass") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[0]["objectId"] as! String, "hogeHOGE12345678") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1].count, 3) XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1]["__type"] as! String, "Pointer") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1]["className"] as! String, "TestClass") XCTAssertEqual((object!["objects"]! as! Array<Dictionary<String,Any>>)[1]["objectId"] as! String, "hogeHOGE90123456") } func test_converToObject_Date() { let date = Date(timeIntervalSince1970: 507904496.789) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: date) XCTAssertEqual(object!["__type"]! as! String, "Date") XCTAssertEqual(object!["iso"]! as! String, "1986-02-04T12:34:56.789Z") } func test_converToObject_NCMBPointer() { let pointer = NCMBPointer(className: "TestClass", objectId: "abcde12345") let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: pointer) XCTAssertEqual(object!["__type"]! as! String, "Pointer") XCTAssertEqual(object!["className"]! as! String, "TestClass") XCTAssertEqual(object!["objectId"]! as! String, "abcde12345") } func test_converToObject_NCMBRelation() { let relation = NCMBRelation(className: "TestClass") let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: relation) XCTAssertEqual(object!["__type"]! as! String, "Relation") XCTAssertEqual(object!["className"]! as! String, "TestClass") } func test_converToObject_NCMBGeoPoint() { let geoPoint = NCMBGeoPoint(latitude: 35.6666269, longitude: 139.765607) let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: geoPoint) XCTAssertEqual(object!["__type"]! as! String, "GeoPoint") XCTAssertEqual(object!["latitude"]! as! Double, Double(35.6666269)) XCTAssertEqual(object!["longitude"]! as! Double, Double(139.765607)) } // func test_converToObject_NCMBObjectField() { // TBD // } func test_converToObject_Int() { let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: 42) XCTAssertNil(object) } func test_converToObject_String() { let object : [String : Any]? = NCMBFieldTypeConverter.converToObject(value: "takanokun") XCTAssertNil(object) } static var allTests = [ ("test_convertToFieldValue_NCMBIncrementOperator", test_convertToFieldValue_NCMBIncrementOperator), ("test_convertToFieldValue_NCMBAddOperator", test_convertToFieldValue_NCMBAddOperator), ("test_convertToFieldValue_NCMBAddUniqueOperator", test_convertToFieldValue_NCMBAddUniqueOperator), ("test_convertToFieldValue_NCMBRemoveOperator", test_convertToFieldValue_NCMBRemoveOperator), ("test_convertToFieldValue_NCMBAddRelationOperator", test_convertToFieldValue_NCMBAddRelationOperator), ("test_convertToFieldValue_NCMBRemoveRelationOperator", test_convertToFieldValue_NCMBRemoveRelationOperator), ("test_convertToFieldValue_Date", test_convertToFieldValue_Date), ("test_convertToFieldValue_NCMBPointer", test_convertToFieldValue_NCMBPointer), ("test_convertToFieldValue_NCMBRelation", test_convertToFieldValue_NCMBRelation), ("test_convertToFieldValue_NCMBGeoPoint", test_convertToFieldValue_NCMBGeoPoint), // ("test_convertToFieldValue_NCMBObjectField", test_convertToFieldValue_NCMBObjectField), ("test_convertToFieldValue_Int", test_convertToFieldValue_Int), ("test_convertToFieldValue_String", test_convertToFieldValue_String), ("test_converToObject_NCMBIncrementOperator", test_converToObject_NCMBIncrementOperator), ("test_converToObject_NCMBAddOperator", test_converToObject_NCMBAddOperator), ("test_converToObject_NCMBAddUniqueOperator", test_converToObject_NCMBAddUniqueOperator), ("test_converToObject_NCMBRemoveOperator", test_converToObject_NCMBRemoveOperator), ("test_converToObject_NCMBAddRelationOperator", test_converToObject_NCMBAddRelationOperator), ("test_converToObject_NCMBRemoveRelationOperator", test_converToObject_NCMBRemoveRelationOperator), ("test_converToObject_Date", test_converToObject_Date), ("test_converToObject_NCMBPointer", test_converToObject_NCMBPointer), ("test_converToObject_NCMBRelation", test_converToObject_NCMBRelation), ("test_converToObject_NCMBGeoPoint", test_converToObject_NCMBGeoPoint), // ("test_converToObject_NCMBObjectField", test_converToObject_NCMBObjectField), ("test_converToObject_Int", test_converToObject_Int), ("test_converToObject_String", test_converToObject_String), ] }
53.888889
160
0.699356
48ee7a8c1c0a9e2f9a03c412b84c91412007dfe8
2,301
// // Extensions.swift // TCalculator // // Created by Dominic Beger on 24.08.16. // Copyright © 2016 Dominic Beger. All rights reserved. // import Foundation extension String { // At least Swift has extension properties. But the fact that it's necessary to create a custom property for a String-length is indeed creepy. var length: Int { return characters.count } subscript (i: Int) -> Character { return self[self.startIndex.advancedBy(i)] } subscript (i: Int) -> String { return String(self[i]) } subscript (r: Range<Int>) -> String { let start = startIndex.advancedBy(r.startIndex) let end = start.advancedBy(r.endIndex - r.startIndex) return self[Range(start ..< end)] } func isLetter() -> Bool { guard self.length == 1 else { return false } let letters = NSCharacterSet.letterCharacterSet() let range = self.rangeOfCharacterFromSet(letters) return range?.count > 0 } func isDigit() -> Bool { guard self.length == 1 else { return false } let digits = NSCharacterSet.decimalDigitCharacterSet() let range = self.rangeOfCharacterFromSet(digits) return range?.count > 0 } func isMathematicOperator() -> Bool { guard self.length == 1 else { return false } return "+-*/%^!".containsString(self) } func isBracket() -> Bool { guard self.length == 1 else { return false } return "()".containsString(self) } func replace(index: Int, _ newChar: Character) -> String { var chars = Array(self.characters) chars[index] = newChar let modifiedString = String(chars) return modifiedString } } extension Dictionary { func containsKey(key: Key) -> Bool { return self[key] != nil } } extension TCToken { func isOpeningBracket() -> Bool { return self.type == TCTokenType.Bracket && (self as! TCGenericToken<String>).value == "("; } func isClosingBracket() -> Bool { return self.type == TCTokenType.Bracket && (self as! TCGenericToken<String>).value == ")"; } }
26.448276
146
0.578879
e2578f84c5778e0079ecb6fe7bcf35a960696d99
3,903
// RUN: %target-run-simple-swift // REQUIRES: executable_test // An end-to-end test that we can differentiate property accesses, with custom // VJPs for the properties specified in various ways. import StdlibUnittest var E2EDifferentiablePropertyTests = TestSuite("E2EDifferentiableProperty") struct TangentSpace : VectorProtocol { let x, y: Float } extension TangentSpace : Differentiable { typealias TangentVector = TangentSpace } struct Space { /// `x` is a computed property with a custom vjp. var x: Float { @differentiable(vjp: vjpX) get { storedX } set { storedX = newValue } } func vjpX() -> (Float, (Float) -> TangentSpace) { return (x, { v in TangentSpace(x: v, y: 0) } ) } private var storedX: Float @differentiable var y: Float init(x: Float, y: Float) { self.storedX = x self.y = y } } extension Space : Differentiable { typealias TangentVector = TangentSpace mutating func move(along direction: TangentSpace) { x.move(along: direction.x) y.move(along: direction.y) } } E2EDifferentiablePropertyTests.test("computed property") { let actualGrad = gradient(at: Space(x: 0, y: 0)) { (point: Space) -> Float in return 2 * point.x } let expectedGrad = TangentSpace(x: 2, y: 0) expectEqual(expectedGrad, actualGrad) } E2EDifferentiablePropertyTests.test("stored property") { let actualGrad = gradient(at: Space(x: 0, y: 0)) { (point: Space) -> Float in return 3 * point.y } let expectedGrad = TangentSpace(x: 0, y: 3) expectEqual(expectedGrad, actualGrad) } struct GenericMemberWrapper<T : Differentiable> : Differentiable { // Stored property. @differentiable var x: T func vjpX() -> (T, (T.TangentVector) -> GenericMemberWrapper.TangentVector) { return (x, { TangentVector(x: $0) }) } } E2EDifferentiablePropertyTests.test("generic stored property") { let actualGrad = gradient(at: GenericMemberWrapper<Float>(x: 1)) { point in return 2 * point.x } let expectedGrad = GenericMemberWrapper<Float>.TangentVector(x: 2) expectEqual(expectedGrad, actualGrad) } struct ProductSpaceSelfTangent : VectorProtocol { let x, y: Float } extension ProductSpaceSelfTangent : Differentiable { typealias TangentVector = ProductSpaceSelfTangent } E2EDifferentiablePropertyTests.test("fieldwise product space, self tangent") { let actualGrad = gradient(at: ProductSpaceSelfTangent(x: 0, y: 0)) { (point: ProductSpaceSelfTangent) -> Float in return 5 * point.y } let expectedGrad = ProductSpaceSelfTangent(x: 0, y: 5) expectEqual(expectedGrad, actualGrad) } struct ProductSpaceOtherTangentTangentSpace : VectorProtocol { let x, y: Float } extension ProductSpaceOtherTangentTangentSpace : Differentiable { typealias TangentVector = ProductSpaceOtherTangentTangentSpace } struct ProductSpaceOtherTangent { var x, y: Float } extension ProductSpaceOtherTangent : Differentiable { typealias TangentVector = ProductSpaceOtherTangentTangentSpace mutating func move(along direction: ProductSpaceOtherTangentTangentSpace) { x.move(along: direction.x) y.move(along: direction.y) } } E2EDifferentiablePropertyTests.test("fieldwise product space, other tangent") { let actualGrad = gradient(at: ProductSpaceOtherTangent(x: 0, y: 0)) { (point: ProductSpaceOtherTangent) -> Float in return 7 * point.y } let expectedGrad = ProductSpaceOtherTangentTangentSpace(x: 0, y: 7) expectEqual(expectedGrad, actualGrad) } E2EDifferentiablePropertyTests.test("computed property") { struct TF_544 : Differentiable { var value: Float @differentiable var computed: Float { get { value } set { value = newValue } } } let actualGrad = gradient(at: TF_544(value: 2.4)) { x in return x.computed * x.computed } let expectedGrad = TF_544.TangentVector(value: 4.8) expectEqual(expectedGrad, actualGrad) } runAllTests()
26.917241
117
0.723034
269b4ef374f6f0ccf7e8777fed98eef9cd9ee1dc
1,028
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten import Foundation // === xdr source ============================================================ // enum ManageContractRequestResultCode // { // // codes considered as "success" for the operation // SUCCESS = 0, // // // codes considered as "failure" for the operation // MALFORMED = -1, // NOT_FOUND = -2, // not found contract request, when try to remove // TOO_MANY_CONTRACTS = -3, // NOT_ALLOWED_TO_REMOVE = -4, // only contract creator can remove contract // DETAILS_TOO_LONG = -5, // CONTRACT_CREATE_TASKS_NOT_FOUND = -6 // key-value not set // }; // =========================================================================== public enum ManageContractRequestResultCode: Int32, XDREnum { case success = 0 case malformed = -1 case notFound = -2 case tooManyContracts = -3 case notAllowedToRemove = -4 case detailsTooLong = -5 case contractCreateTasksNotFound = -6 }
32.125
80
0.582685
ed2d29b29751650d3edf8bdbb6517c54b4f6450b
8,417
// // CoreGraphics+Z.swift // ZKit // // Created by Kaz Yoshikawa on 12/12/16. // Copyright © 2016 Electricwoods LLC. All rights reserved. // import Foundation import CoreGraphics import QuartzCore import simd infix operator • infix operator × extension CGRect { public init(size: CGSize) { self.init(origin: .zero, size: size) } public var cgPath: CGPath { return CGPath(rect: self, transform: nil) } public func cgPath(cornerRadius: CGFloat) -> CGPath { // +7-------------6+ // 0 5 // | | // 1 4 // +2-------------3+ let cornerRadius = min(size.width * 0.5, size.height * 0.5, cornerRadius) let path = CGMutablePath() path.move(to: minXmidY + CGPoint(x: 0, y: cornerRadius)) // (0) path.addLine(to: minXmaxY - CGPoint(x: 0, y: cornerRadius)) // (1) path.addQuadCurve(to: minXmaxY + CGPoint(x: cornerRadius, y: 0), control: minXmaxY) // (2) path.addLine(to: maxXmaxY - CGPoint(x: cornerRadius, y: 0)) // (3) path.addQuadCurve(to: maxXmaxY - CGPoint(x: 0, y: cornerRadius), control: maxXmaxY) // (4) path.addLine(to: maxXminY + CGPoint(x: 0, y: cornerRadius)) // (5) path.addQuadCurve(to: maxXminY - CGPoint(x: cornerRadius, y: 0), control: maxXminY) // (6) path.addLine(to: minXminY + CGPoint(x: cornerRadius, y: 0)) // (7) path.addQuadCurve(to: minXminY + CGPoint(x: 0, y: cornerRadius), control: minXminY) // (0) path.closeSubpath() return path } public var minXminY: CGPoint { return CGPoint(x: minX, y: minY) } public var midXminY: CGPoint { return CGPoint(x: midX, y: minY) } public var maxXminY: CGPoint { return CGPoint(x: maxX, y: minY) } public var minXmidY: CGPoint { return CGPoint(x: minX, y: midY) } public var midXmidY: CGPoint { return CGPoint(x: midX, y: midY) } public var maxXmidY: CGPoint { return CGPoint(x: maxX, y: midY) } public var minXmaxY: CGPoint { return CGPoint(x: minX, y: maxY) } public var midXmaxY: CGPoint { return CGPoint(x: midX, y: maxY) } public var maxXmaxY: CGPoint { return CGPoint(x: maxX, y: maxY) } public func aspectFill(_ size: CGSize) -> CGRect { let result: CGRect let margin: CGFloat let horizontalRatioToFit = size.width / size.width let verticalRatioToFit = size.height / size.height let imageHeightWhenItFitsHorizontally = horizontalRatioToFit * size.height let imageWidthWhenItFitsVertically = verticalRatioToFit * size.width if (imageHeightWhenItFitsHorizontally > size.height) { margin = (imageHeightWhenItFitsHorizontally - size.height) * 0.5 result = CGRect(x: minX, y: minY - margin, width: size.width * horizontalRatioToFit, height: size.height * horizontalRatioToFit) } else { margin = (imageWidthWhenItFitsVertically - size.width) * 0.5 result = CGRect(x: minX - margin, y: minY, width: size.width * verticalRatioToFit, height: size.height * verticalRatioToFit) } return result } public func aspectFit(_ size: CGSize) -> CGRect { let widthRatio = self.size.width / size.width let heightRatio = self.size.height / size.height let ratio = min(widthRatio, heightRatio) let width = size.width * ratio let height = size.height * ratio let xmargin = (self.size.width - width) / 2.0 let ymargin = (self.size.height - height) / 2.0 return CGRect(x: minX + xmargin, y: minY + ymargin, width: width, height: height) } public func transform(to rect: CGRect) -> CGAffineTransform { var t = CGAffineTransform.identity t = t.translatedBy(x: -self.minX, y: -self.minY) t = t.translatedBy(x: rect.minX, y: rect.minY) t = t.scaledBy(x: 1 / self.width, y: 1 / self.height) t = t.scaledBy(x: rect.width, y: rect.height) return t } static public func + (lhs: CGRect, rhs: CGPoint) -> CGRect { return CGRect(origin: lhs.origin + rhs, size: lhs.size) } static public func - (lhs: CGRect, rhs: CGPoint) -> CGRect { return CGRect(origin: lhs.origin - rhs, size: lhs.size) } static public func + (lhs: CGRect, rhs: CGSize) -> CGRect { return CGRect(origin: lhs.origin, size: lhs.size + rhs) } static public func - (lhs: CGRect, rhs: CGSize) -> CGRect { return CGRect(origin: lhs.origin, size: lhs.size - rhs) } } extension CGSize { public func aspectFit(_ size: CGSize) -> CGSize { let widthRatio = self.width / size.width let heightRatio = self.height / size.height let ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio let width = size.width * ratio let height = size.height * ratio return CGSize(width: width, height: height) } static public func - (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height) } static public func + (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height) } static public func * (lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width * rhs, height: lhs.height * rhs) } static public func / (lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width / rhs, height: lhs.height / rhs) } static public func * (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width * rhs.width , height: lhs.height * rhs.height) } static public func / (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width / rhs.width , height: lhs.height / rhs.height) } } extension CGAffineTransform { static public func * (lhs: CGAffineTransform, rhs: CGAffineTransform) -> CGAffineTransform { return lhs.concatenating(rhs) } } extension float4x4 { public init(affineTransform: CGAffineTransform) { let t = CATransform3DMakeAffineTransform(affineTransform) self.init( SIMD4<Float>(Float(t.m11), Float(t.m12), Float(t.m13), Float(t.m14)), SIMD4<Float>(Float(t.m21), Float(t.m22), Float(t.m23), Float(t.m24)), SIMD4<Float>(Float(t.m31), Float(t.m32), Float(t.m33), Float(t.m34)), SIMD4<Float>(Float(t.m41), Float(t.m42), Float(t.m43), Float(t.m44))) } } // MARK: - public protocol FloatCovertible { var floatValue: Float { get } } extension CGFloat: FloatCovertible { public var floatValue: Float { return Float(self) } } extension Int: FloatCovertible { public var floatValue: Float { return Float(self) } } extension Float: FloatCovertible { public var floatValue: Float { return self } } // MARK: - public protocol CGFloatCovertible { var cgFloatValue: CGFloat { get } } extension CGFloat: CGFloatCovertible { public var cgFloatValue: CGFloat { return self } } extension Int: CGFloatCovertible { public var cgFloatValue: CGFloat { return CGFloat(self) } } extension Float: CGFloatCovertible { public var cgFloatValue: CGFloat { return CGFloat(self) } } // MARK: - extension CGPoint { static public func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } static public func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } static public func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint { return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs) } static public func / (lhs: CGPoint, rhs: CGFloat) -> CGPoint { return CGPoint(x: lhs.x / rhs, y: lhs.y / rhs) } static public func • (lhs: CGPoint, rhs: CGPoint) -> CGFloat { // dot product return lhs.x * rhs.x + lhs.y * rhs.y } static public func × (lhs: CGPoint, rhs: CGPoint) -> CGFloat { // cross product return lhs.x * rhs.y - lhs.y * rhs.x } public var length²: CGFloat { return (x * x) + (y * y) } public var length: CGFloat { return sqrt(self.length²) } public var normalized: CGPoint { return self / length } static public func length²(_ lhs: CGPoint, _ rhs: CGPoint) -> CGFloat { return pow(rhs.x - lhs.x, 2.0) + pow(rhs.y - lhs.y, 2.0) } static public func length(_ lhs: CGPoint, _ rhs: CGPoint) -> CGFloat { return sqrt(length²(lhs, rhs)) } } extension CGPoint { public init<X: CGFloatCovertible, Y: CGFloatCovertible>(_ x: X, _ y: Y) { self.init(x: x.cgFloatValue, y: y.cgFloatValue) } } extension CGSize { public init<W: CGFloatCovertible, H: CGFloatCovertible>(_ width: W, _ height: H) { self.init(width: width.cgFloatValue, height: height.cgFloatValue) } } extension CGRect { public init<X: CGFloatCovertible, Y: CGFloatCovertible, W: CGFloatCovertible, H: CGFloatCovertible>(_ x: X, _ y: Y, _ width: W, _ height: H) { self.init(origin: CGPoint(x, y), size: CGSize(width, height)) } }
29.953737
143
0.679221
0a4f73a9b5d59584390dfcd500615674b7d71094
3,188
// // SessionAgent.swift // NuguAgents // // Created by MinChul Lee on 2020/05/28. // Copyright (c) 2019 SK Telecom Co., Ltd. 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 import NuguCore public final class SessionAgent: SessionAgentProtocol { // CapabilityAgentable public var capabilityAgentProperty: CapabilityAgentProperty = CapabilityAgentProperty(category: .session, version: "1.0") // private private let directiveSequencer: DirectiveSequenceable private let contextManager: ContextManageable private let sessionManager: SessionManageable // Handleable Directive private lazy var handleableDirectiveInfos = [ DirectiveHandleInfo(namespace: capabilityAgentProperty.name, name: "Set", blockingPolicy: BlockingPolicy(medium: .none, isBlocking: false), directiveHandler: handleSet) ] public init( contextManager: ContextManageable, directiveSequencer: DirectiveSequenceable, sessionManager: SessionManageable ) { self.contextManager = contextManager self.directiveSequencer = directiveSequencer self.sessionManager = sessionManager contextManager.add(delegate: self) directiveSequencer.add(directiveHandleInfos: handleableDirectiveInfos.asDictionary) } deinit { directiveSequencer.remove(directiveHandleInfos: handleableDirectiveInfos.asDictionary) } } // MARK: - ContextInfoDelegate extension SessionAgent: ContextInfoDelegate { public func contextInfoRequestContext(completion: (ContextInfo?) -> Void) { let payload: [String: AnyHashable?] = [ "version": capabilityAgentProperty.version, "list": sessionManager.activeSessions.map { ["sessionId": $0.sessionId, "playServiceId": $0.playServiceId] } ] completion( ContextInfo(contextType: .capability, name: capabilityAgentProperty.name, payload: payload.compactMapValues { $0 }) ) } } // MARK: - Private(Directive) private extension SessionAgent { func handleSet() -> HandleDirective { return { [weak self] directive, completion in guard let item = try? JSONDecoder().decode(SessionAgentItem.self, from: directive.payload) else { completion(.failed("Invalid payload")) return } defer { completion(.finished) } let session = Session(sessionId: item.sessionId, dialogRequestId: directive.header.dialogRequestId, playServiceId: item.playServiceId) self?.sessionManager.set(session: session) } } }
36.227273
176
0.69793
67f2f4a27cfd9699ad7cff2f6c55f033890aaa91
2,366
// // ParameterAdjustmentView.swift // Core Image Explorer // // Created by Warren Moore on 1/10/15. // Copyright (c) 2015 objc.io. All rights reserved. // import UIKit let kSliderMarginX: CGFloat = 20 let kSliderMarginY: CGFloat = 8 let kSliderHeight: CGFloat = 48 protocol ParameterAdjustmentDelegate { func parameterValueDidChange(_ param: ScalarFilterParameter) } class ParameterAdjustmentView: UIView { var parameters: [ScalarFilterParameter]! var sliderViews = [LabeledSliderView]() func setAdjustmentDelegate(_ delegate: ParameterAdjustmentDelegate) { for sliderView in sliderViews { sliderView.delegate = delegate } } init(frame: CGRect, parameters: [ScalarFilterParameter]) { super.init(frame: frame) self.parameters = parameters addSubviews() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addSubviews() { var yOffset: CGFloat = kSliderMarginY for param in parameters { let frame = CGRect(x: 0, y: yOffset, width: UIScreen.main.bounds.width, height: kSliderHeight) let sliderView = LabeledSliderView(frame: frame, parameter: param) sliderView.translatesAutoresizingMaskIntoConstraints = false addSubview(sliderView) sliderViews.append(sliderView) addConstraint(NSLayoutConstraint(item: sliderView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: kSliderMarginX)) addConstraint(NSLayoutConstraint(item: sliderView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: yOffset)) addConstraint(NSLayoutConstraint(item: sliderView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -kSliderMarginX * 2)) addConstraint(NSLayoutConstraint(item: sliderView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: kSliderHeight)) yOffset += (kSliderHeight + kSliderMarginY) } } }
34.794118
124
0.639053
b971c05b8c3624fa7673ff3e1797d4b69c97d18b
1,793
// // Created by Daniel Heredia on 2/27/18. // Copyright © 2018 Daniel Heredia. All rights reserved. // // The heavy pill import Foundation let bottlesNumber = 20 let secretHeavyBottle = 19 /// Get the total weight of a collection of pills /// of different bottles. For the purposes of this problem /// the code inside this method must be considered a blackbox. /// /// - Parameter bottlePills: Amounts of pills for every bottle, every item is the amount of pills from the bottle with that index /// - Returns: The total weight or nil if the number of brought items is different from `bottlesNumber` func weight(bottlePills: [Int]) -> Double? { if bottlePills.count != bottlesNumber { return nil } let lightWeight = 1.0 let heavyWeight = 1.1 var totalWeight = 0.0 for i in 0..<bottlePills.count { let pillsNumber = bottlePills[i] let pillWeight = i == secretHeavyBottle ? heavyWeight : lightWeight totalWeight += Double(pillsNumber) * pillWeight } // The small fraction is added because sometimes // float numbers result of an addition can't be // represented accurately. // Example // .2 + .1 = 0.30000000000000004 return totalWeight + 0.00000001 } /// Find the bottle with heaviest pills /// /// - Returns: The index of the bottle with heaviest pills func findHeavierBottle() -> Int { var bottlePills = [Int]() for i in 1...bottlesNumber { bottlePills.append(i) } let realWeight = weight(bottlePills: bottlePills)! let idealWeight = Double(bottlesNumber * (bottlesNumber + 1) / 2) let remainder = realWeight - idealWeight return Int(remainder * 10) - 1 } let heavierBottle = findHeavierBottle() print("Index of the bottle with heaviest pills: \(heavierBottle)")
32.017857
129
0.689347
46fb86dba1a7cf382f1928eacf883ceadfa42a43
2,648
// // ConstellationController.swift // App // // Created by 晋先森 on 2018/8/5. // import Foundation import Vapor import FluentPostgreSQL import SwiftSoup import Fluent class ConstellationController: RouteCollection { var startUrl = "https://www.meiguoshenpo.com/baiyang/" var type = "xingzuo" private var constells: [ConstellationContainer]? private var types: [ConstellationType]? func boot(router: Router) throws { router.group("sp") { (group) in group.get("xingzuo", use: getListHandler) } } } extension ConstellationController { //*[@id="PAGE_LEFT"] private func getListHandler(_ req: Request) throws -> Future<Response> { return try getHTMLResponse(req, url: startUrl).flatMap(to: Response.self, { (html) in let soup = try SwiftSoup.parse(html) // 白羊 金牛 双子 巨蟹 ... let allXingzuo = try soup.select("div[class='astro_box']").select("a") self.constells = try allXingzuo.map({ (xingzuo) in let link = try xingzuo.attr("href") let key = try xingzuo.attr("title") let abbr = try xingzuo.attr("class") let name = try xingzuo.text() return ConstellationContainer(name: name, link: link, key: key, abbr: abbr) }) // 白羊座 运势 百科 爱情 事业 性格 排行 故事 名人 let eleTypes = try soup.select("div[class='index_left']").select("li").select("a") self.types = try eleTypes.map { element -> ConstellationType in let link = try element.attr("href") let key = try element.attr("title") let name = try element.text() return ConstellationType(name: name, link: link, key: key) } struct Result: Content { var targetUrl: String var constells: [ConstellationContainer]? var types: [ConstellationType]? } let data = Result(targetUrl: self.startUrl,constells: self.constells, types: self.types) return try ResponseJSON<Result>(data: data).encode(for: req) }) } } fileprivate struct ConstellationContainer: Content { var name: String? var link: String? var key: String? var abbr: String? } fileprivate struct ConstellationType: Content { var name: String? var link: String? var key: String? }
24.981132
100
0.547205
62eb078d9cd2dacd11f50ba0d035b622f2cef60f
1,823
// // ProfileSummary.swift // SwiftUI-07(Profile) // // Created by pgq on 2020/3/17. // Copyright © 2020 pq. All rights reserved. // import SwiftUI struct ProfileSummary: View { var profile: Profile static let goalFormat: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .none return formatter }() var body: some View { List { Text(profile.username) .bold() .font(.title) Text("Notifications: \(self.profile.prefersNotifications ? "On": "Off" )") Text("Seasonal Photos: \(self.profile.seasonalPhoto.rawValue)") Text("Goal Date: \(self.profile.goalDate, formatter: Self.goalFormat)") VStack(alignment: .leading) { Text("Completed Badges") .font(.headline) ScrollView { HStack { HikeBadge(name: "First Hike") HikeBadge(name: "First Hike") .hueRotation(Angle(degrees: 90)) HikeBadge(name: "First Hike") .hueRotation(Angle(degrees: 45)) } } .frame(height: 140) } VStack(alignment: .leading) { Text("Recnt Hikes") .font(.headline) HikeView(hike: hikeData[0]) } } } } struct ProfileSummary_Previews: PreviewProvider { static var previews: some View { ProfileSummary(profile: Profile.default) } }
27.621212
86
0.459682