blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
7a228c4c0845f9c33fcc1db8054e048fb3085d28
Swift
lamberdd/wordGames
/Cities/Screens/BuyFullVersion/ViewModel/PurchaseViewModel.swift
UTF-8
3,912
2.515625
3
[]
no_license
// // BuyFullVersionPresenter.swift // Cities // // Created by Владислав Казмирчук on 28.05.2020. // Copyright © 2020 Влад Казмирчук. All rights reserved. // import Foundation import RxSwift import RxCocoa class PurchaseViewModel { private let iapManager: IAPManager private let promoService: PromocodeService private let bag = DisposeBag() let purchaseClick = PublishRelay<Void>() let purchaseButtonLoader = BehaviorRelay<Bool>(value: true) let purchaseButtonTitle = BehaviorRelay<String>(value: "") let restoreClick = PublishRelay<Void>() let checkPromo = PublishRelay<String>() let alertText = PublishRelay<String>() let loading = BehaviorRelay<Bool>(value: false) let error = BehaviorRelay<Bool>(value: false) let purchased = BehaviorRelay<Bool>(value: false) deinit { print("Purchase ViewModel deinited") } init(iapManager: IAPManager = IAPManager(), promoService: PromocodeService = PromocodeService()) { self.iapManager = iapManager self.promoService = promoService if AppSettings.global.isFullVersion { setSuccessState() } else { purchaseButtonLoader.accept(true) iapManager.getPriceForFullVersion { [weak self] (price) in guard let price = price else { self?.error.accept(true) return } let translateText = translate("get_for") self?.purchaseButtonTitle.accept("\(translateText) \(price)") self?.purchaseButtonLoader.accept(false) } } purchaseClick.subscribe { [weak self] (_) in self?.buy() }.disposed(by: bag) restoreClick.subscribe { [weak self] (_) in self?.restore() }.disposed(by: bag) checkPromo.subscribe(onNext: { [weak self] (promoText) in self?.checkPromo(promoText) }).disposed(by: bag) } private func checkPromo(_ promo: String) { if promo.count < 3 { alertText.accept(translate("invalidCode")) return } loading.accept(true) promoService.checkCode(code: promo) { (status) in DispatchQueue.main.async { self.loading.accept(false) switch status { case .success: self.successPurchase() default: self.alertText.accept(translate(status.rawValue)) } } } } private func buy() { loading.accept(true) iapManager.buyFull { [weak self] (status) in print("Buy status: \(status)") switch status { case .success: self?.successPurchase() case .error: self?.alertText.accept(translate("purchase_error")) case .paymentProblem: self?.alertText.accept(translate("cannot_purchase")) default: break; } self?.loading.accept(false) } } private func restore() { loading.accept(true) iapManager.restore { [weak self] (status) in print("Restore status: \(status)") switch status { case .success: self?.successPurchase() case .error: self?.alertText.accept(translate("purchase_error")) case .noPurchases: self?.alertText.accept(translate("no_restore_purchases")) default: break; } self?.loading.accept(false) } } private func successPurchase() { AppSettings.global.isFullVersion = true setSuccessState() } private func setSuccessState() { purchased.accept(true) } }
true
f202ec4336f0c69da398daf3291685faa7b53ed7
Swift
ThePowerOfSwift/japanese-lds-quad-ios
/JapaneseLDSQuad/HighlightChangeDelegate.swift
UTF-8
1,111
2.5625
3
[]
no_license
// // HighlightChangeDelegate.swift // JapaneseLDSQuad // // Created by Nozomi Okada on 2/25/20. // Copyright © 2020 nozokada. All rights reserved. // import UIKit protocol HighlightChangeDelegate { func removeHighlight(id: String) } extension HighlightChangeDelegate where Self: UIViewController { func addNoteViewController() { guard let viewController = storyboard?.instantiateViewController(withIdentifier: Constants.StoryBoardID.notes) as? NoteViewController else { return } addChild(viewController) view.addSubview(viewController.view) viewController.didMove(toParent: self) viewController.delegate = self let height = view.frame.height let width = view.frame.width viewController.view.frame = CGRect(x: 0, y: view.frame.maxY, width: width, height: height) } } extension UIViewController { func getNoteViewController() -> NoteViewController? { let noteViewControllers = children.filter { $0 is NoteViewController } as! [NoteViewController] return noteViewControllers.first } }
true
516c80e1e5d83f7004772dac1cdf83ceb3054eee
Swift
L-Sypniewski/Swift-5.1-Overview-with-examples
/Swift5.1.playground/Pages/Universal Self.xcplaygroundpage/Contents.swift
UTF-8
252
3.609375
4
[]
no_license
//: [Previous](@previous) import Foundation class Cat { class var sound: String { "meow"} func talk() { print(Self.sound) } } class Lion: Cat { override class var sound: String { "roar"} } Cat().talk() Lion().talk()
true
bbe906a654cd2f1089630fd675abb334f775a4d1
Swift
shaktiprakash099/stretchyTableheaderview
/Photos-DucTran/CommentsTableViewCell.swift
UTF-8
753
2.640625
3
[]
no_license
// // CommentsTableViewCell.swift // Photos-DucTran // // Created by GLB-312-PC on 05/06/18. // Copyright © 2018 Developers Academy. All rights reserved. // import UIKit class CommentsTableViewCell: UITableViewCell { @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var commentTextLabel : UILabel! var comment : Comment?{ didSet{ if let comment = comment { userNameLabel.text = comment.user.toString() userNameLabel.textColor = comment.user.toColor() commentTextLabel.text = comment.text } else{ userNameLabel.text = nil commentTextLabel.text = nil } } } }
true
b1083c5f9a782b8ddc64666429da9d68860d7ad0
Swift
BiGapps-IOS/DWExt
/DWExt/DWExt/UIButton+UsefulExtensions.swift
UTF-8
1,440
3.0625
3
[ "MIT" ]
permissive
// // UIButton+UsefulExtensions.swift // UsefulExtensions // // Created by Denis Windover on 31/05/2020. // Copyright © 2020 BigApps. All rights reserved. // import UIKit extension UIButton { @IBInspectable public var numOfLines: Int{ set { self.titleLabel?.numberOfLines = newValue self.titleLabel?.textAlignment = .center self.titleLabel?.adjustsFontSizeToFitWidth = true } get { self.titleLabel?.numberOfLines ?? 0 } } } extension UIButton{ @IBInspectable public var isAdjustFontToSizeWidth: Bool{ set { self.titleLabel?.adjustsFontSizeToFitWidth = newValue } get { return self.titleLabel?.adjustsFontSizeToFitWidth ?? false } } @IBInspectable public var imageColor:UIColor{ set{ self.setImageColor(color: newValue) } get{ return self.tintColor } } public func setImageColor(color: UIColor) { let templateImage = self.imageView?.image?.withRenderingMode(.alwaysTemplate) self.imageView?.image = templateImage self.imageView?.tintColor = color } public func monkeyButton(){ self.isUserInteractionEnabled = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.isUserInteractionEnabled = true } } }
true
50a00c54e2f90eaffcf8d0ae36e75f66f0974293
Swift
nidegen/unsplash-photopicker-ios
/UnsplashPhotoPicker/UnsplashPhotoPicker/Classes/Utils/URL+Extensions.swift
UTF-8
866
2.796875
3
[ "MIT" ]
permissive
// // URL+Extensions.swift // Unsplash // // Created by Olivier Collet on 2017-10-23. // Copyright © 2017 Unsplash. All rights reserved. // import Foundation extension URL { func appending(queryItems: [URLQueryItem]) -> URL { guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true) else { return self } var queryDictionary = [String: String]() if let queryItems = components.queryItems { for item in queryItems { queryDictionary[item.name] = item.value } } for item in queryItems { queryDictionary[item.name] = item.value } var newComponents = components newComponents.queryItems = queryDictionary.map({ URLQueryItem(name: $0.key, value: $0.value) }) return newComponents.url ?? self } }
true
536b643be6e3d7d059c9e90f6b5c7b7c7bd10864
Swift
kjwamlex/Quickr
/Quickr/CustomSegue.swift
UTF-8
1,198
2.609375
3
[]
no_license
// // CustomSegue.swift // Custom Segue Swift 2 2015 // // Created by PJ Vea on 8/4/15. // Copyright © 2015 Vea Software. All rights reserved. // import UIKit class CustomSegue: UIStoryboardSegue { override func perform() { let sourceVC = self.source let destinationVC = self.destination sourceVC.view.addSubview(destinationVC.view) destinationVC.view.transform = CGAffineTransform(scaleX: 0.0005, y: 0.0005) UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions(), animations: { () -> Void in destinationVC.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) { (finished) -> Void in destinationVC.view.removeFromSuperview() let time = DispatchTime.now() + Double(Int64(0.001 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { sourceVC.present(destinationVC, animated: false, completion: nil) } } } }
true
4c034781af07925f0f0113e548d25526ca9ffc9b
Swift
zacharytamas/swift-fun-facts
/FunFacts/ViewController.swift
UTF-8
858
2.640625
3
[]
no_license
// // ViewController.swift // FunFacts // // Created by Zachary Jones on 6/14/17. // Copyright © 2017 Zachary Jones. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var funFactLabel: UILabel! @IBOutlet weak var showButton: UIButton! var factProvider = FactProvider() override func viewDidLoad() { super.viewDidLoad() funFactLabel.text = factProvider.randomFact() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showFact() { funFactLabel.text = factProvider.randomFact() let newColor = BackgroundColorProvider.randomColor() view.backgroundColor = newColor showButton.tintColor = newColor } }
true
80c695d29f1b56ca6c0b207a250d674e2b4c0d24
Swift
bugKrusha/Camille
/Sources/SlackBotKit/Camillink/Camillink+Tracking.swift
UTF-8
4,102
2.6875
3
[]
no_license
import ChameleonKit import Foundation extension SlackBot.Camillink { static func tryTrackLink(_ config: Config, _ storage: Storage, _ bot: SlackBot, _ message: Message) throws { // Check for a web link, make sure it's not Mail.app, etc let links = message.links() .filter({ $0.url.absoluteString.hasPrefix("http") }) .map({ $0.url }) .compactMap({ self.removeGarbageQueryParameters(url: $0) }) .removeDuplicates() guard !links.isEmpty else { return } for link in links { switch try? storage.get(Record.self, forKey: link.absoluteString, from: Keys.namespace) { case let record?: if isRecordExpired(config, record) { try storage.remove(forKey: link.absoluteString, from: Keys.namespace) } else if !shouldSilence(link, config, message, record) { let response: MarkdownString = "\(.wave) That \("link", link) is also being discussed in \("this message", record.permalink) in \(record.channelID)" try bot.perform(.respond(to: message, .threaded, with: response)) } case nil: // new link guard !shouldSilenceForAllowListedDomain(link) else { return } let permalink = try bot.perform(.permalink(for: message)) let record = Record(date: config.dateFactory(), channelID: permalink.channel, permalink: permalink.permalink) try storage.set(forKey: link.absoluteString, from: Keys.namespace, value: record) } } } private static func isRecordExpired(_ config: Config, _ record: Record) -> Bool { guard let dayLimit = config.recencyLimitInDays else { return false } guard let daysSince = config.calendar.dateComponents([.day], from: record.date, to: config.dateFactory()).day else { return true } return dayLimit < daysSince } private static func shouldSilence(_ link: URL, _ config: Config, _ message: Message, _ record: Record) -> Bool { return shouldSilenceForAllowListedDomain(link) || shouldSilenceForCrossLink(config, message, record) || shouldSilenceForSameChannel(config, message, record) } private static func shouldSilenceForCrossLink(_ config: Config, _ message: Message, _ record: Record) -> Bool { guard config.silentCrossLink else { return false } return message.channels().contains(record.channelID) } private static func shouldSilenceForAllowListedDomain(_ link: URL) -> Bool { let allowListedHosts = [ "apple.com", "developer.apple.com", "iosdevelopers.slack.com", "iosfolks.com", "mlb.tv" ] guard let components = URLComponents(url: link, resolvingAgainstBaseURL: false) else { return false } return allowListedHosts.contains(where: { $0 == components.host }) } private static func shouldSilenceForSameChannel(_ config: Config, _ message: Message, _ record: Record) -> Bool { guard config.silentSameChannel else { return false } return message.channel == record.channelID } private static func removeGarbageQueryParameters(url: URL) -> URL? { let denyListedQueryParameters = [ "utm", "utm_source", "utm_media", "utm_campaign", "utm_medium", "utm_term", "utm_content", "t", "s", ] guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil } urlComponents.queryItems?.removeAll(where: { queryItem in denyListedQueryParameters.contains(where: { $0 == queryItem.name }) }) if let queryItems = urlComponents.queryItems, queryItems.isEmpty { // An empty queryItems array will retain a trailing ? but nilling it out removes that urlComponents.queryItems = nil } return urlComponents.url } }
true
0f3aafe13866ac294342e857bf2b345af63f623d
Swift
Appsaurus/UIKitTheme
/Sources/UIKitTheme/Source/AppStyleGuide/SubAppStyleGuides/TableViewCellStyleGuide.swift
UTF-8
1,208
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // TableViewCellStyleGuide.swift // AppsaurusUIKit // // Created by Brian Strobach on 3/10/18. // import UIKit open class TableViewCellStyleDefaults: SubAppStyleGuideDefaults { open lazy var viewStyle: ViewStyle = ViewStyle() open lazy var selectedBackgroundColor: UIColor? = nil open lazy var selectionStyle: UITableViewCell.SelectionStyle = .none } open class TableViewCellStyleGuide: SubAppStyleGuide, DefaultSettingsManaged { public typealias Defaults = TableViewCellStyleDefaults open lazy var defaults: Defaults = Defaults(appStyleGuide: appStyleGuide) open lazy var defaultStyle: TableViewCellStyle = TableViewCellStyle(viewStyle: defaults.viewStyle, selectedBackgroundColor: defaults.selectedBackgroundColor, selectionStyle: defaults.selectionStyle) open override func applyAppearanceProxySettings() { UITableViewCell.appearance().apply(tableViewCellStyle: self.defaultStyle) } } // MARK: Convenience Extensions // Make it easy to access functions from current style guide inside method signatures at call site. extension TableViewCellStyle { public static var defaultStyle: TableViewCellStyle { return App.style.tableViewCell.defaultStyle } }
true
ce86addb244e0d4e39433ca69ec6d4815c7f5656
Swift
Galaxylaughing/capstone-ios
/LibAwesome/CurrentReadCountBadge.swift
UTF-8
980
2.890625
3
[]
no_license
// // CurrentReadCountBadge.swift // LibAwesome // // Created by Sabrina on 1/16/20. // Copyright © 2020 SabrinaLowney. All rights reserved. // import SwiftUI struct CurrentReadCountBadge: View { @EnvironmentObject var env: Env var body: some View { VStack { Text(String(self.env.currentReadsCount)) .font(.caption) .padding(3) .foregroundColor(Color.white) .padding(.horizontal, 2) .background( Capsule() .fill(Color.blue) ) } } } struct CurrentReadCountBadge_Previews: PreviewProvider { static func makeEnv() -> Env { let previewEnv = Env() previewEnv.currentReadsCount = 1 return previewEnv } static var env = makeEnv() static var previews: some View { CurrentReadCountBadge() .environmentObject(self.env) } }
true
8f13d31eb07358c6862a52f69bb4f60f226326e3
Swift
Nexters/proutine-iOS
/mytine/Resources/UIView+Extensions.swift
UTF-8
1,942
2.953125
3
[]
no_license
// // UIView+Extensions.swift // mytine // // Created by 황수빈 on 2020/07/15. // Copyright © 2020 황수빈. All rights reserved. // import Foundation import UIKit extension UIView { func viewRounded(cornerRadius: CGFloat?) { if let cornerRadius = cornerRadius { self.layer.cornerRadius = cornerRadius } else { self.layer.cornerRadius = self.layer.frame.height / 2 } self.layer.masksToBounds = true } func viewRoundedCustom(cornerRadius: Double, borderColor: UIColor, firstCorner: UIRectCorner, secondCorner: UIRectCorner) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [firstCorner, secondCorner], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)) let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds maskLayer.path = path.cgPath self.layer.mask = maskLayer let borderShape = CAShapeLayer() borderShape.frame = self.layer.bounds borderShape.path = path.cgPath borderShape.strokeColor = borderColor.cgColor borderShape.fillColor = nil borderShape.lineWidth = 0.5 self.layer.addSublayer(borderShape) } func viewBorder(borderColor: UIColor, borderWidth: CGFloat?) { self.layer.borderColor = borderColor.cgColor if let borderWidth = borderWidth { self.layer.borderWidth = borderWidth } else { self.layer.borderWidth = 1.0 } } func dropShadow(color: UIColor, offSet: CGSize, opacity: Float, radius: CGFloat) { let containerView = UIView() self.layer.shadowColor = color.cgColor self.layer.shadowOffset = offSet self.layer.shadowOpacity = opacity self.layer.shadowRadius = radius self.layer.masksToBounds = false addSubview(containerView) } }
true
dbd26698a7b074887dd247b2807fb4f830905d50
Swift
JManke91/RxActivityIndicatorSampleProject
/RxActivityIndicator/ViewController.swift
UTF-8
3,188
2.65625
3
[]
no_license
// // ViewController.swift // RxActivityIndicator // // Created by Julian Manke on 30.07.19. // Copyright © 2019 Julian Manke. All rights reserved. // import UIKit import RxCocoa import RxSwift class ViewController: UIViewController { @IBOutlet weak var makeSuccessRequestButton: UIButton! @IBOutlet weak var makeErrorRequestButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! let repository = MockRepository() let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() activityIndicator.isHidden = true styleButtons() repository.newImplementationLoadingState() .drive(onNext: { loadingState in switch loadingState { case .loading: self.activityIndicator.isHidden = false self.activityIndicator.startAnimating() case .success: self.activityIndicator.isHidden = true self.activityIndicator.stopAnimating() self.showToast(message: "Successful request", toastColor: .green) case .error: self.activityIndicator.isHidden = true self.activityIndicator.stopAnimating() self.showToast(message: "An error occured!", toastColor: .red) default: break } }) .disposed(by: disposeBag) } private func styleButtons() { makeSuccessRequestButton.layer.cornerRadius = 5 makeSuccessRequestButton.layer.borderWidth = 1 makeSuccessRequestButton.layer.borderColor = UIColor.black.cgColor makeErrorRequestButton.layer.cornerRadius = 5 makeErrorRequestButton.layer.borderWidth = 1 makeErrorRequestButton.layer.borderColor = UIColor.black.cgColor } @IBAction func errorButtonPressed() { repository.observeProperty(for: ExpectedRequestResult.error).subscribe(onNext: { (property) in }, onError: { error in }) .disposed(by: disposeBag) } @IBAction func successButtonPressed() { repository.observeProperty(for: ExpectedRequestResult.success) .subscribe() .disposed(by: disposeBag) } func showToast(message : String, toastColor: UIColor) { let width: CGFloat = 200 let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - width / 2, y: self.view.frame.size.height-100, width: width, height: 35)) toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6) toastLabel.textColor = UIColor.black toastLabel.textAlignment = .center; toastLabel.text = message toastLabel.alpha = 1.0 toastLabel.layer.cornerRadius = 10; toastLabel.clipsToBounds = true toastLabel.backgroundColor = toastColor self.view.addSubview(toastLabel) UIView.animate(withDuration: 2.0, delay: 0.1, options: .curveEaseOut, animations: { toastLabel.alpha = 0.0 }, completion: {(isCompleted) in toastLabel.removeFromSuperview() }) } }
true
08f7a23c668937d74bc4edde2d82f41f1dbda39c
Swift
usman-tahir/rubyeuler
/sicp_2_23.swift
UTF-8
298
3.1875
3
[]
no_license
#!/usr/bin/env swift // sicp exercise 2.23 func forEach(proc: (Int) -> (), n: [Int], i: Int = 0) -> [Int] { if i == n.count { return [] } else { proc(n[i]) return forEach(proc, n, i: i+1) } } func display(x: Int) { println(x) } let list = [57, 321, 88] forEach(display,list)
true
77138f1f3489b7893fe7086b4b4a152ec264574d
Swift
acoustic-content-samples/sample-traveler-ios-app
/AcousticContentSampleApp/Controllers/Search /SearchResultController.swift
UTF-8
5,635
2.59375
3
[ "Apache-2.0" ]
permissive
// // Copyright 2020 Acoustic, L.P. // 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 /// View controller to show search results class SearchResultController: UITableViewController { var dataSource = SearchDataSource() private var items = [SearchResultModel]() var textToSearch: String? override func viewDidLoad() { super.viewDidLoad() refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(handleRefresh(_:)), for: UIControl.Event.valueChanged) } @objc func handleRefresh(_ refreshControl: UIRefreshControl) { guard let text = textToSearch else { refreshControl.endRefreshing() return } loadData(text: text) { [weak self] in self?.updateContent() refreshControl.endRefreshing() } } func cleanAllData() { dataSource.clearDataModels() items.removeAll() } func loadData(text: String, completion: (()->())?) { cleanAllData() dataSource.getData(searchText: text) { [weak self] (result) in DispatchQueue.main.async { guard let result = result else { return } self?.items.append(contentsOf: result) completion?() } } } func search(_ text: String) { textToSearch = text loadData(text: text) { [weak self] in self?.updateContent() } } private func updateContent() { tableView.reloadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? // Cell configuration if indexPath.row < items.count { let model = items[indexPath.row] switch model { case .article(let articleModel): cell = tableView.dequeueReusableCell(withIdentifier: "ArticleCell", for: indexPath) (cell as? ArticleCell)?.configure(model: articleModel) case .gallery(let galleryModel): cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell", for: indexPath) (cell as? ImageCell)?.configure(model: galleryModel) } } return cell ?? UITableViewCell() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Logic to show Gallery Details if let cell = tableView.cellForRow(at: indexPath) as? ImageCell { guard let model = cell.model as? GalleryImageModel, let detailsController = storyboard?.instantiateViewController(withIdentifier: "GalleryDetailsViewController") as? GalleryDetailsViewController else { return } detailsController.configure(model: model) present(detailsController, animated: true, completion: nil) } // Logic to show Article controller else if let cell = tableView.cellForRow(at: indexPath) as? ArticleCell { guard let model = cell.model, let detailsController = storyboard?.instantiateViewController(withIdentifier: "ArticleViewController") as? ArticleViewController else { return } detailsController.configure(model: model, backTitle: "Back") self.navigationController?.pushViewController(detailsController, animated: true) } } // Data pagging logic override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == items.count - 1, dataSource.canGetNextPage() { // Loads next page data and updates table view dataSource.getNextPage { [weak self] (_) in DispatchQueue.main.async { guard let dataSource = self?.dataSource else { return } let startRow = indexPath.row + 1 let indexes = (startRow..<dataSource.dataModel.count).map({ return IndexPath(row: $0, section: 0) }) self?.tableView.beginUpdates() self?.items = dataSource.dataModel self?.tableView.insertRows(at: indexes, with: .fade) self?.tableView.endUpdates() } } } } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } }
true
54d80c9f3ead854ff763e41a981abf3d91ca6829
Swift
reyandrey/sandbox_ios
/SandboxApp/SandboxApp/UI/WebView/WebViewController.swift
UTF-8
3,963
2.546875
3
[ "MIT" ]
permissive
// // WebViewController.swift // GUDom // // Created by Andrey Fokin on 19.06.2020. // Copyright © 2020 First Line Software. All rights reserved. // import UIKit import WebKit import PanModal class WebViewController: ViewController { var url: URL! var completionHanler: (()->())? = nil private lazy var cookies: [String: String] = { return [:] }() private lazy var webView: WKWebView = { var webView = WKWebView() webView.navigationDelegate = self webView.isMultipleTouchEnabled = false webView.translatesAutoresizingMaskIntoConstraints = false return webView }() convenience init(url: URL) { self.init() self.url = url } override func setup() { super.setup() view.backgroundColor = .white let doneItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneDidTap(_:))) doneItem.tintColor = .darkText navigationItem.setRightBarButton(doneItem, animated: false) view.addSubview(webView) } override func loadView() { super.loadView() setCookies() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) load(url) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() webView.frame = view.bounds.inset(by: UIEdgeInsets(top: view.safeAreaInsets.top, left: 0, bottom: 0, right: 0)) } override func setActivityIndication(_ active: Bool, animated: Bool = true) { super.setActivityIndication(active, animated: animated) UIView.animate(withDuration: active ? 0 : 0.33) { self.webView.alpha = active ? 0 : 1 self.title = active ? "Загрузка..." : self.webView.title } } } // MARK: WKNavigationDelegate extension WebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { setActivityIndication(false) } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { setActivityIndication(true) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { setActivityIndication(false) presentAlert(withTitle: "Ошибка", message: error.localizedDescription) { self.dismiss(animated: true, completion: nil) } } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { setActivityIndication(false) presentAlert(withTitle: "Ошибка", message: error.localizedDescription) { self.dismiss(animated: true, completion: nil) } } } // MARK: Private private extension WebViewController { func setCookies() { let httpCookies = cookies.compactMap { HTTPCookie(properties: [ .domain: url.host ?? "", .path: "/", .name: $0.key, .value: $0.value, .secure: "TRUE" ]) } HTTPCookieStorage.shared.setCookies(httpCookies, for: self.url, mainDocumentURL: nil) } func load(_ url: URL) { let request = URLRequest(url: url) HTTPCookieStorage.shared.cookies?.forEach({ (cookie) in webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie) }) webView.load(request) } @objc func doneDidTap(_ sender: Any) { dismiss(animated: true, completion: completionHanler) } } // MARK: Static extension WebViewController { class func open(url: URL, from presenter: UIViewController, presentPanModal: Bool = true, completionHandler: (()->())? = nil) { let webVC = WebViewController() webVC.url = url webVC.completionHanler = completionHandler let modalNC = NavigationController() modalNC.setViewControllers([webVC], animated: false) if presentPanModal { presenter.presentPanModal(modalNC) } else { modalNC.modalPresentationStyle = .overFullScreen presenter.present(modalNC, animated: true, completion: nil) } } }
true
13e1ca4b516350f02179b77fddafc0b81cea3cbb
Swift
rayray199085/SCCarHelper
/SCCarHelper/SCCarHelper/Classes/Tools/Network/SCNetworkManager+extension.swift
UTF-8
1,399
2.640625
3
[ "Apache-2.0" ]
permissive
// // SCNetworkManager+extension.swift // SCCarHelper // // Created by Stephen Cao on 27/6/19. // Copyright © 2019 Stephencao Cao. All rights reserved. // import Foundation import Alamofire extension SCNetworkManager{ func getCarData(completion:@escaping (_ data: Data?,_ isSuccess: Bool)->()){ let urlString = "https://app-car.carsalesnetwork.com.au/stock/car/test/v1/listing" let params = ["username":"test","password":"2h7H53eXsQupXvkz"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (data, res, isSuccess, statusCode, error) in completion(data, isSuccess) } } func getCarDetailsData(detailsUrlString: String, completion:@escaping (_ data: Data?,_ isSuccess: Bool)->()){ let urlString = "https://app-car.carsalesnetwork.com.au\(detailsUrlString)" let params = ["username":"test","password":"2h7H53eXsQupXvkz"] request(urlString: urlString, method: HTTPMethod.get, params: params) { (data, res, isSuccess, _, _) in completion(data, isSuccess) } } } extension SCNetworkManager{ func getCarImage(imageUrlString: String, completion:@escaping (_ image: UIImage?)->()){ guard let url = URL(string: imageUrlString) else{ completion(nil) return } UIImage.downloadImage(url: url) { (image) in completion(image) } } }
true
5d91175f60afe010fc28be8b2db3ac5e232c619f
Swift
BarryDuggan/RealmWrapper
/Example/Sources/Extension/UIViewController-Extension.swift
UTF-8
536
2.921875
3
[ "MIT" ]
permissive
import UIKit extension UIViewController { func alert(title: String? = nil, message: String? = nil, preferredStyle: UIAlertController.Style = .alert, actions: [UIAlertAction]?, completion: (() -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle) if let actions = actions { actions.forEach({ (action) in alert.addAction(action) }) } present(alert, animated: true, completion: completion) } }
true
2fb1cceaa39b3807178c61516d9fdebad3660165
Swift
Katherin-Chuco/MecaWashIOS
/iMecaWash/Network/MecaWashApi.swift
UTF-8
4,404
2.546875
3
[]
no_license
import Foundation import Alamofire import os class MecaWashApi { static let baseUrlString = "http://64.202.186.215/APIMekaWash" static let loginProviderUrlString = "\(baseUrlString)/wamekawash/v1/loginprovider" static let loginCustomerUrlString = "\(baseUrlString)/wamekawash/v1/logincustomer" static func getLocals(id: Int) -> String { return "\(baseUrlString)/wamekawash/v4/providers/\(id)/locals" } static func getServices(id: Int) -> String { return "\(baseUrlString)/wamekawash/v5/locals/\(id)/services" } static private func get<T: Decodable>( from urlString: String, headers: HTTPHeaders, responseType: T.Type, responseHandler: @escaping ((T) -> Void), errorHandler: @escaping((Error) -> Void)) { guard let url = URL(string: urlString) else { let message = "Error on URL" os_log("%@", message) return } AF.request(url, headers: headers).validate().responseJSON( completionHandler: { response in switch response.result { case .success( _): do { let decoder = JSONDecoder() if let data = response.data { let dataResponse = try decoder.decode(responseType, from: data) responseHandler(dataResponse) } } catch { errorHandler(error) } case .failure(let error): errorHandler(error) } }) } static private func post<T: Decodable>( from urlString: String, parameters: [String : String], responseType: T.Type, responseHandler: @escaping ((T) -> Void), errorHandler: @escaping((Error) -> Void)) { guard let url = URL(string: urlString) else { let message = "Error on URL" os_log("%@", message) return } AF.request(url, method: .post, parameters: parameters).validate().responseJSON( completionHandler: { response in switch response.result { case .success( _): do { let decoder = JSONDecoder() if let data = response.data { let dataResponse = try decoder.decode(responseType, from: data) responseHandler(dataResponse) } } catch { errorHandler(error) } case .failure(let error): errorHandler(error) } }) } static func loginClient(username: String, password: String, responseHandler: @escaping ((PostClientResponse) -> Void), errorHandler: @escaping ((Error) -> Void)) { let parameters = ["Username" : username, "Password" : password] self.post(from: loginCustomerUrlString, parameters: parameters, responseType: PostClientResponse.self, responseHandler: responseHandler, errorHandler: errorHandler) } static func localsRequest(key: String, url: String, responseHandler: @escaping ((GetLocalsResponse) -> Void), errorHandler: @escaping ((Error) -> Void)) { let headers: HTTPHeaders = [ "Authorization": key, ] self.get(from: url, headers: headers, responseType: GetLocalsResponse.self, responseHandler: responseHandler, errorHandler: errorHandler) } static func servicesRequest(key: String, url: String, responseHandler: @escaping ((GetServicesResponse) -> Void), errorHandler: @escaping ((Error) -> Void)) { let headers: HTTPHeaders = [ "Authorization": key, ] self.get(from: url, headers: headers, responseType: GetServicesResponse.self, responseHandler: responseHandler, errorHandler: errorHandler) } }
true
c60cab33aec4a388cf9f560873832c97c4050639
Swift
TelerikAcademy/Mobile-Applications-for-iOS
/demos/HttpDemos/HttpDemos/BookDetailsViewController.swift
UTF-8
2,031
2.6875
3
[]
no_license
// // BookDetailsViewController.swift // HttpDemos // // Created by Doncho Minkov on 3/22/17. // Copyright © 2017 Doncho Minkov. All rights reserved. // import UIKit class BookDetailsViewController: UIViewController, HttpRequesterDelegate { @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var labelDescription: UILabel! var bookId: String? var book: Book? var url: String { get{ let appDelegate = UIApplication.shared.delegate as! AppDelegate return "\(appDelegate.baseUrl)/books" } } var http: HttpRequester? { get{ let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.http } } override func viewDidLoad() { super.viewDidLoad() self.loadBookDetails() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadBookDetails(){ self.http?.delegate = self let url = "\(self.url)/\(self.bookId!)" self.showLoadingScreen() self.http?.get(fromUrl: url) } func didReceiveData(data: Any) { let dict = data as! Dictionary<String, Any> self.book = Book(withDict: dict) self.updateUI() } func updateUI() { DispatchQueue.main.async { self.labelTitle.text = self.book?.title self.labelDescription.text = self.book?.bookDescription self.hideLoadingScreen() } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
2ce19642c3bdcc8d8d61f53c9ced654e1a581532
Swift
virgilius-santos/VSCommonSwiftLibrary
/Finances/Finances/Components/TabView.swift
UTF-8
1,508
2.625
3
[]
no_license
import SwiftUI private let screen = NSScreen.main?.visibleFrame ?? .zero struct TabView: View { @StateObject var viewModel: ContentViewModel = .init() var buttons: [TabButton] = [] var body: some View { HStack { VStack { TabButton( image: "message", title: "All Chats", selectedTab: $viewModel.selectedTab ) TabButton( image: "person", title: "Personal", selectedTab: $viewModel.selectedTab ) TabButton( image: "bubble.middle.bottom", title: "Bots", selectedTab: $viewModel.selectedTab ) TabButton( image: "slider.horizontal.3", title: "Edit", selectedTab: $viewModel.selectedTab ) Spacer() } .padding() .padding(.top) .background(BlurView()) Spacer() } .frame(width: screen.width / 1.2, height: screen.height - 60) } } struct TabView_Previews: PreviewProvider { static var previews: some View { TabView() } } final class ContentViewModel: ObservableObject { @Published var selectedTab = "All Chats" }
true
469f1b483e7f3769ff38276737f83d56ee863e17
Swift
ilyahal/ToDo-iOS
/ToDo/Classes/Presentation/Common/View/Custom View/ModalView.swift
UTF-8
1,513
2.828125
3
[]
no_license
// // ModalView.swift // ToDo // // Created by Илья Халяпин on 09.01.2018. // Copyright © 2018 Илья Халяпин. All rights reserved. // import UIKit @IBDesignable final class ModalView: UIView { // MARK: - Инициализация public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initPhase2() } public override init(frame: CGRect) { super.init(frame: frame) initPhase2() } /// Инициализация объекта private func initPhase2() { self.cornerRadius = 5 } } // MARK: - Публичные свойства extension ModalView { /// Радиус скругления @IBInspectable var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue } } } // MARK: - UIView extension ModalView { override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() runtimeSetup() } override func awakeFromNib() { super.awakeFromNib() runtimeSetup() } } // MARK: - Приватные методы private extension ModalView { /// Настройка при выполнении func runtimeSetup() { self.superview?.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0.2274509804, alpha: 0.3967893836) } }
true
cc02953cf0a16513e90cc4b986653d12970447ef
Swift
thaihauit/MVVM-Demo
/MVVM-Moya/App/Model/Token.swift
UTF-8
812
3.109375
3
[]
no_license
// // User.swift // VIPER // // Created by Ha Nguyen Thai on 9/25/19. // Copyright © 2019 Ace. All rights reserved. // import Foundation struct Token { var token: String var expires_at: String } extension Token: Decodable { enum DataKey: String, CodingKey { case data } enum TokenCodingKey: String, CodingKey { case token = "access_token" case expires_at = "expires_at" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DataKey.self) let detailContainer = try container.nestedContainer(keyedBy: TokenCodingKey.self, forKey: .data) token = try detailContainer.decode(String.self, forKey: .token) expires_at = try detailContainer.decode(String.self, forKey: .expires_at) } }
true
f0aba840a8a4b8d7370364817cf8b152860dd101
Swift
gene8189/instagram
/instagram/CaptionViewController.swift
UTF-8
1,033
2.671875
3
[]
no_license
// // CaptionViewController.swift // instagram // // Created by Tan Yee Gene on 09/09/2016. // Copyright © 2016 Tan Yee Gene. All rights reserved. // import UIKit protocol CaptionDelegate { func captionDelegate(controller: CaptionViewController, didFinishEditImage caption: String) } class CaptionViewController: UIViewController { @IBOutlet var captionText: UITextView! var delegate: CaptionDelegate? @IBOutlet var imageView: UIImageView! var selectedImage: UIImage! override func viewDidLoad() { super.viewDidLoad() self.imageView.image = selectedImage } @IBAction func onBackButtonPressed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func onShareButtonPressed(sender: AnyObject) { if let captionDelegate = self.delegate{ captionDelegate.captionDelegate(self, didFinishEditImage:self.captionText.text) } self.dismissViewControllerAnimated(true, completion: nil) } }
true
ecc54c00bcfb1595ffbb571b4b96f898bf37ce43
Swift
ohlulu/UserInterface
/UserInterfaceDemo/RearrangeViewController.swift
UTF-8
1,993
2.765625
3
[]
no_license
// // RearrangeViewController.swift // UserInterface // // Created by Christian Otkjær on 02/08/16. // Copyright © 2016 Christian Otkjær. All rights reserved. // import UIKit import UserInterface class RearrangeViewController: UIViewController { @IBOutlet weak var rearrangableView: RearrangableView! { didSet { rearrangableView.delegate = self } } } // MARK: - <#comment#> extension RearrangeViewController : RearrangableViewDelegate { func rearrangingShouldBeginForView(_ view: UIView) -> Bool { guard let superview = view.superview else { return false } superview.bringSubview(toFront: view) // view.layer.shadowColor = UIColor.blackColor().CGColor // view.layer.shadowOffset = CGSize(width: 5, height: 5) // view.layer.shadowRadius = 7 // view.layer.shadowOpacity = 0.4 return true } func rearrangingWillEndForView(_ view: UIView, withProposedCenter center: CGPoint) -> CGPoint? { guard let superview = view.superview else { return nil } var frame = view.frame frame.center = center if frame.maxX > superview.bounds.maxX { frame.origin.x -= frame.maxX - superview.bounds.maxX } if frame.minX < superview.bounds.minX { frame.origin.x += superview.bounds.minX - frame.minX } if frame.maxY > superview.bounds.maxY { frame.origin.y -= frame.maxY - superview.bounds.maxY } if frame.minY < superview.bounds.minY { frame.origin.y += superview.bounds.minY - frame.minY } return frame.center } func rearrangingDidEndForView(_ view: UIView) { // view.layer.shadowColor = UIColor.clearColor().CGColor // view.layer.shadowOffset = CGSizeZero // view.layer.shadowRadius = 0 // view.layer.shadowOpacity = 0 } }
true
19304c0dca5d5dd5bb0db9d3d26b7fe02a3e05b2
Swift
molamolastudio/biolifetracker-iOS
/BioLifeTracker/BioLifeTracker/NotificationService.swift
UTF-8
2,536
3.03125
3
[]
no_license
// // NotificationService.swift // BioLifeTracker // // Created by Andhieka Putra on 18/4/15. // Copyright (c) 2015 Mola Mola Studios. All rights reserved. // import Foundation /// This class provides notification service during observation taking. /// It will call notification for a specified time interval. class NotificationService { // Constants let timeInterval = Double(1440*60) // 24 hours * 60 minutes per hour let minToSec = 60 let alertMsg = "Time to take an observation!" let actionStr = "Go" let titleStr = "BioLifeTracker" let maxCounter = 128 /// Implementation of Singleton Pattern class var sharedInstance: NotificationService { struct Singleton { static let instance = NotificationService() } return Singleton.instance } /// Initiates a NotificationService instance init() { let notificationTypes: UIUserNotificationType = .Alert | .Badge | .Sound let settings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) } /// Schedules notification for the next 24 hours. func sessionHasStarted(session: Session) { if session.interval == nil { return } UIApplication.sharedApplication().cancelAllLocalNotifications() let sessionExpiryTime = NSDate().dateByAddingTimeInterval( NSTimeInterval(timeInterval) ) var notificationTime: NSDate var counter = 1 do { notificationTime = NSDate().dateByAddingTimeInterval( NSTimeInterval(counter * session.interval! * minToSec) ) let notification = UILocalNotification() notification.fireDate = notificationTime notification.timeZone = NSTimeZone.defaultTimeZone() notification.alertBody = alertMsg notification.alertAction = actionStr notification.alertTitle = titleStr notification.soundName = UILocalNotificationDefaultSoundName notification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) counter++ } while counter <= maxCounter && sessionExpiryTime.timeIntervalSinceDate(notificationTime) > 0 } /// Cancels all notifications. func sessionHasEnded() { UIApplication.sharedApplication().cancelAllLocalNotifications() } }
true
8060fd1b06b5b83d06dcb22a7979f0d5c788f793
Swift
oscarvictoria/Pursuit-Core-iOS-Introduction-to-Unit-Testing-Lab
/UnitTestingLab/UnitTestingLab/JokeFile.swift
UTF-8
744
2.796875
3
[]
no_license
// // JokeFile.swift // UnitTestingLab // // Created by Oscar Victoria Gonzalez on 12/2/19. // Copyright © 2019 Oscar Victoria Gonzalez . All rights reserved. // import Foundation struct Jokes: Codable { let setup: String let punchline: String } extension Jokes { static func getJokes() -> [Jokes] { var joke = [Jokes]() guard let fileURL = Bundle.main.url(forResource: "joke-api", withExtension: "json") else { fatalError("could not locate json file") } do { let data = try Data(contentsOf: fileURL) let jokesData = try JSONDecoder().decode([Jokes].self, from: data) joke = jokesData } catch { print("failed to load contents") } return joke } }
true
4ff3339562ec982d6536bda00e78253d47e4ae40
Swift
San-Di/HotelBookingAsgn
/HotelBooking/cells/swifts/OuterCollectionViewCell.swift
UTF-8
1,829
2.578125
3
[]
no_license
// // OuterCollectionViewCell.swift // HotelBooking // // Created by Sandi on 9/6/19. // Copyright © 2019 Sandi. All rights reserved. // import UIKit class OuterCollectionViewCell: UICollectionViewCell { @IBOutlet weak var innerCollectionView: UICollectionView! var mHotelList: [HotelVOS] = HotelVOS.getHotelList() let width: CGFloat = 0 let height: CGFloat = 280 let spacing: CGFloat = 48 override func awakeFromNib() { super.awakeFromNib() innerCollectionView.delegate = self innerCollectionView.dataSource = self innerCollectionView.register(UINib(nibName: String(describing: InnerCollectionViewCell.self), bundle: nil), forCellWithReuseIdentifier: String(describing: InnerCollectionViewCell.self)) let innerCollectionViewLayout = innerCollectionView.collectionViewLayout as! UICollectionViewFlowLayout innerCollectionViewLayout.itemSize = CGSize(width: (innerCollectionView.frame.width - spacing) / 1.5 , height: height) } } extension OuterCollectionViewCell: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return mHotelList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: InnerCollectionViewCell.self), for: indexPath) as! InnerCollectionViewCell item.mHotel = mHotelList[indexPath.row] return item } func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } } extension OuterCollectionViewCell: UICollectionViewDelegate{ }
true
af914b7ffb77f1262616668286901841a20b7ba2
Swift
farazhaider88/HackerRank-Swift
/LeftRotationArray.playground/Contents.swift
UTF-8
597
3.75
4
[]
no_license
/* https://www.hackerrank.com/challenges/array-left-rotation/problem */ func shiftLeftArray(numberToShift: Int, shiftPlaces: Int,ar: [Int]) -> String { var localArray = ar let count = shiftPlaces for i in 1...count{ print("i value \(i)") let letter = localArray.removeFirst() print(letter) localArray.append(letter) } let stringArray = localArray.map { String($0) } let string = stringArray.joined(separator: " ") return string } var input = shiftLeftArray(numberToShift: 5, shiftPlaces: 4, ar: [1,2,3,4,5]) print(input)
true
75beb3074144f398ffc6f338706e0556d48faf0a
Swift
EoinOhAnnagain/SummerPracticum-iOS
/DBA/Model/StopTimes.swift
UTF-8
441
2.734375
3
[]
no_license
// // StopTimes.swift // DBA // // Created by Eoin Ó'hAnnagáin on 12/08/2021. // import Foundation struct StopTimes { // Structure to create an object for busses approaching a stop let remainingTime: String let route: String let arrivalTime: String } //MARK: - JSON Decoding struct stopTimesJSON: Codable { // Structure to decode the received stop times JSON let countdown: Int let route_number: String }
true
c8b8e855d35b439c66cc65b7bf9d262f78e81574
Swift
ksubjeck/cs147
/vTag/ExploreMenuWithPopup.swift
UTF-8
3,654
2.671875
3
[]
no_license
// // ExploreMenuWithPopup.swift // vTag // // Created by Cole DePasquale on 12/4/17. // Copyright © 2017 VTag. All rights reserved. // import UIKit class ExploreMenuWithPopup: UIViewController, UITextFieldDelegate { @IBOutlet weak var tagTitle: UITextField! @IBOutlet weak var leftButton: UIButton! @IBOutlet weak var rightButton: UIButton! //private instance variables var newTag = false; var currTag: Tag? override func viewDidLoad() { super.viewDidLoad() self.tagTitle.delegate = self; } override func viewWillAppear(_ animated: Bool) { if(newTag){ leftButton.setTitle("More Info", for: .normal); leftButton.frame.size.width = 110; rightButton.setTitle("Set Tag", for: .normal); rightButton.frame.size.width = 110; rightButton.frame.origin = CGPoint(x: 120, y: 257) } else { tagTitle.text = currTag?.name; tagTitle.isUserInteractionEnabled = false; } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true); } @IBAction func pressedX(_ sender: Any) { dismiss(animated: true, completion: nil); } func textFieldShouldReturn(_ textField: UITextField) -> Bool { tagTitle.resignFirstResponder(); return true; } /** * More Info to edit * Tag info to see more about it */ @IBAction func leftButtonPress(_ sender: Any) { } /** * Pressed set tag or marked as completed */ @IBAction func rightButtonPress(_ sender: Any) { if let navigation = presentingViewController as? UINavigationController { if let presenter = navigation.viewControllers.first as? ViewController{ if(newTag){ // Creating a new Tag! //Sets proper date info let formatter = DateFormatter(); formatter.dateFormat = "MM-dd-yyy, HH:mm:ss"; let yourDate = formatter.string(from: Date()); tagTitle.isUserInteractionEnabled = true; let tag = Tag(name: tagTitle.text!, photo: #imageLiteral(resourceName: "VTag Logo"), dateDue: yourDate) presenter.placeObject(tag: tag!); } else { //Deleting Tag! tagTitle.isUserInteractionEnabled = false; presenter.deletingObject(); } } } dismiss(animated: true, completion: nil); } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch(segue.identifier ?? "") { case "More Info": guard let destinationViewController = segue.destination as? ExploreViewController else { fatalError("Unexpected destination: \(segue.destination)") } if(newTag){ destinationViewController.newTag = true; let tag = Tag(name: tagTitle.text!, photo: #imageLiteral(resourceName: "VTag Logo"), dateDue: "") destinationViewController.tag = tag } else { destinationViewController.newTag = false; destinationViewController.tag = currTag; } default: print("Wrong Segue") } } }
true
204863251fecf766ecac59e5c93c9dd5c58e8dfa
Swift
jgestal/Reversi
/Shared/Game/Board.swift
UTF-8
6,493
3.21875
3
[ "MIT" ]
permissive
// // Board.swift // Reversi // // Created by Juan Gestal Romani on 25/11/2018. // Copyright © 2018 Juan Gestal Romani. All rights reserved. // import GameplayKit class Board: NSObject { var currentPlayer = Player.allPlayers[0] static let size = 8 static let moves = [Move(row: -1, col: -1), Move(row: 0, col: -1), Move(row: 1, col: -1), Move(row: -1, col: 0), Move(row: 1, col: 0), Move(row: -1, col: 1), Move(row: 0, col: 1), Move(row: 1, col: 1)] var rows = [[StoneColor]]() // Restriction 1: // The movement is in the board bounds private func isInBounds(row: Int, col: Int) -> Bool { return !(row < 0 || col < 0 || row >= Board.size || col >= Board.size) } // Restriction 2: // The movement has not been made already private func moveHasBeenMadeAlready(row: Int, col: Int) -> Bool { return rows[row][col] != .empty } // Restriction 3: // The movement is legal: capture enemy stones private func isLegal(row: Int, col: Int) -> Bool { for move in Board.moves { var passedOpponent = false var currentRow = row var currentCol = col for _ in 0..<Board.size { currentRow += move.row currentCol += move.col // Check if new possition is in bounds guard isInBounds(row: currentRow, col: currentCol) else { break } let stone = rows[currentRow][currentCol] if stone == currentPlayer.opponent.stoneColor { passedOpponent = true } else if stone == currentPlayer.stoneColor && passedOpponent { return true } else { break } } } return false } // Check the restrictions: // 1. In Bounds // 2. Has Been Made // 3. Legal func canMoveIn(row: Int, col: Int) -> Bool { return isInBounds(row: row, col: col) && !moveHasBeenMadeAlready(row: row, col: col) && isLegal(row: row, col: col) } func makeMove(currentPlayer: Player, row: Int, col: Int) -> [Move] { var didCapture = [Move]() rows[row][col] = currentPlayer.stoneColor didCapture.append(Move(row: row, col: col)) for move in Board.moves { var mightCapture = [Move]() var currentRow = row var currentCol = col for _ in 0..<Board.size { currentRow += move.row currentCol += move.col if !isInBounds(row: currentRow, col: currentCol) { continue } let stone = rows[currentRow][currentCol] if stone == currentPlayer.opponent.stoneColor { mightCapture.append(Move(row: currentRow, col: currentCol)) } else if stone == currentPlayer.stoneColor { didCapture.append(contentsOf: mightCapture) mightCapture.forEach { rows[$0.row][$0.col] = currentPlayer.stoneColor } break } else { break } } } return didCapture } func getScores() -> (black: Int, white: Int) { var black = 0 var white = 0 rows.forEach { $0.forEach { black += $0 == .black ? 1 : 0 white += $0 == .white ? 1 : 0 } } return (black,white) } func showMoveMarks() -> [Move] { var moves = [Move]() for row in 0..<Board.size { for col in 0..<Board.size { let stone = rows[row][col] if stone == .blackMark || stone == .whiteMark { moves.append(Move(row: row, col: col)) } } } return moves } func getAvailableMoves() -> [Move] { var availableMoves = [Move]() for row in 0..<Board.size { for col in 0..<Board.size { if canMoveIn(row: row, col: col) { availableMoves.append(Move(row: row, col: col)) } } } return availableMoves } func copy(with zone: NSZone? = nil) -> Any { let copy = Board() copy.setGameModel(self) return copy } } extension Board: GKGameModel { var players: [GKGameModelPlayer]? { return Player.allPlayers } var activePlayer: GKGameModelPlayer? { return currentPlayer } func setGameModel(_ gameModel: GKGameModel) { let board = gameModel as! Board currentPlayer = board.currentPlayer rows = board.rows } func isWin(for player: GKGameModelPlayer) -> Bool { let playerObject = player as! Player let scores = getScores() let totalStones = scores.black + scores.white let playerStones = playerObject.stoneColor == .black ? scores.black : scores.white let opponentStones = playerObject.stoneColor == .black ? scores.white : scores.black // TODO: Check also if no movements for rival and IA is winning? return totalStones == 64 && playerStones > opponentStones } func gameModelUpdates(for player: GKGameModelPlayer) -> [GKGameModelUpdate]? { guard let player = player as? Player, !(isWin(for: player) || isWin(for: player.opponent)) else { return nil } return getAvailableMoves() } func apply(_ gameModelUpdate: GKGameModelUpdate) { let move = gameModelUpdate as! Move _ = makeMove(currentPlayer: currentPlayer, row: move.row, col: move.col) currentPlayer = currentPlayer.opponent } }
true
3d935ee67f6c5d7b986e61e2c58b4ab79dfbe322
Swift
shashanoid/ShopifyiOSChallenge
/ShopifyCollections/ShopifyCollections/ProductCell.swift
UTF-8
3,213
2.84375
3
[]
no_license
// Shopify Collections // // Created by Shashwat Singh // Copyright © 2019 Shashwat Singh. All rights reserved. // import UIKit class ProductCell: UICollectionViewCell { // Casting product data into subviews var product: Product? { didSet { productTitle.text = product!.title productVendor.text = product!.vendor guard let productImageUrl = URL(string: ((product?.productImageURL)!)) else {return} URLSession.shared.dataTask(with: productImageUrl) { (data, _, error) in if let error = error { print("Failed to product image: ", error) return } guard let imageData = data else { return } let image = UIImage(data: imageData) DispatchQueue.main.async { self.productImage.image = image } }.resume() } } let productImage: UIImageView = { let productImage = UIImageView() productImage.backgroundColor = .white productImage.translatesAutoresizingMaskIntoConstraints = false return productImage }() let productTitle: UILabel = { let productTitle = UILabel() productTitle.translatesAutoresizingMaskIntoConstraints = false productTitle.numberOfLines = 0 productTitle.font = UIFont.systemFont(ofSize: 18) return productTitle }() let productVendor: UILabel = { let productVendor = UILabel() productVendor.translatesAutoresizingMaskIntoConstraints = false productVendor.numberOfLines = 0 productVendor.font = UIFont.systemFont(ofSize: 14) return productVendor }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(red:0.87, green:0.89, blue:0.91, alpha:1.0) addSubview(productImage) productImage.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true productImage.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true productImage.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true productImage.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -80).isActive = true addSubview(productTitle) productTitle.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 5).isActive = true productTitle.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -5).isActive = true productTitle.topAnchor.constraint(equalTo: productImage.bottomAnchor, constant: 5).isActive = true addSubview(productVendor) productVendor.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 5).isActive = true productVendor.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -5).isActive = true productVendor.topAnchor.constraint(equalTo: productTitle.bottomAnchor, constant: 5).isActive = true self.layer.cornerRadius = 10 self.layer.borderColor = UIColor.gray.cgColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
f4655ccf8ffc7762a79fc9f8ffa52caeb7014071
Swift
mikemiksch/Coding-Challenges
/HackerRank/Cracking the Coding Interview/Sorting: Bubble Sort.swift
UTF-8
4,084
3.96875
4
[]
no_license
//Consider the following version of Bubble Sort: // // for (int i = 0; i < n; i++) { // // Track number of elements swapped during a single array traversal // int numberOfSwaps = 0; // // for (int j = 0; j < n - 1; j++) { // // Swap adjacent elements if they are in decreasing order // if (a[j] > a[j + 1]) { // swap(a[j], a[j + 1]); // numberOfSwaps++; // } // } // // // If no elements were swapped during a traversal, array is sorted // if (numberOfSwaps == 0) { // break; // } //} // //Task //Given an n-element array, A = a0,a1,...,a-1, of distinct elements, sort array A in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three lines: // //Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place. //First Element: firstElement, where firstElement is the first element in the sorted array. //Last Element: lastElement, where lastElement is the last element in the sorted array. // //Hint: To complete this challenge, you must add a variable that keeps a running tally of all swaps that occur during execution. // //Input Format // //The first line contains an integer, n, denoting the number of elements in array A. //The second line contains n space-separated integers describing the respective values of a0,a1,...,an-1. // //Constraints // // * 2 <= n <= 600 // * 1 <= ai <= 2 x 10^6, viE[0, n-10 // //Output Format // //You must print the following three lines of output: // //Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place. //First Element: firstElement, where firstElement is the first element in the sorted array. //Last Element: lastElement, where lastElement is the last element in the sorted array. // //Sample Input 0 // //3 //1 2 3 // //Sample Output 0 // //Array is sorted in 0 swaps. //First Element: 1 //Last Element: 3 // //Explanation 0 //The array is already sorted, so 0 swaps take place and we print the necessary three lines of output shown above. // //Sample Input 1 // //3 //3 2 1 // //Sample Output 1 // //Array is sorted in 3 swaps. //First Element: 1 //Last Element: 3 // //Explanation 1 //The array is not sorted, and its initial values are: {3,2,1}. The following 3 swaps take place: // // 1. {3,2,1} -> {2,3,1} // 2. {2,3,1} -> {2,1,3} // 3. {2,1,3} -> {1,2,3} // //At this point the array is sorted and we print the necessary three lines of output shown above. import Foundation // Oh hey, they provided the readLine code for a change... // read the integer n let n = Int(readLine()!)! // read the array let arr = readLine()!.components(separatedBy: " ").map{ Int($0)! } // This is an odd challenge. 90% of the code is given to you in the outset, and the solution it wants is horribly inefficient for actually sorting anything, but it is what it is. // We have a function we pass our array into as an argument. func bubbleSort(array: [Int]) { // Create a mutable copy of our argument var mutatingArray = array // Store the maximum index number in the "n" variable let n = mutatingArray.count - 1 // Instantiate our count var swapCount = 0 // A for loop that cycles through the indices of our array for i in 0..<mutatingArray.count { // For each value in the array, we're going to traverse the array to compare it against all other values. for j in 0..<n { // If our value is greater than the next value, it becomes the next value and the count increases by one if mutatingArray[j] > mutatingArray[j + 1] { swap(&mutatingArray[j], &mutatingArray[j + 1]) swapCount += 1 } } } // Print out our answers print("Array is sorted in \(swapCount) swaps.") print("First Element: \(mutatingArray.first!)") print("Last Element: \(mutatingArray.last!)") } // Call our function bubbleSort(array: arr)
true
88983a516314c2880c0de8e3088a85b686d575c7
Swift
duthli/cookneverdie
/cooknerverdie/BaseViewController.swift
UTF-8
2,935
2.578125
3
[]
no_license
// // BaseViewController.swift // cooknerverdie // // Created by do duy hung on 10/18/16. // Copyright © 2016 do duy hung. All rights reserved. // import Foundation //import NVActivityIndicatorView import UIKit internal class BaseViewController : UIViewController { internal override func viewDidLoad() { super.viewDidLoad() } internal override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } internal func setTitleView(title: String) { self.navigationItem.title = title } public func alertView(title : String ,message : String,titleAction : String, completionHandle : (() -> Void)?){ let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: titleAction, style: .default, handler: nil) alertVC.addAction(action) self.present(alertVC, animated: true, completion: nil) completionHandle?() } // func activeActivityIndicator() // { // startAnimating(CGSize(width: 50,height: 50), message: "", type: .BallSpinFadeLoader, color: UIColor.whiteColor(), padding: 1.0, displayTimeThreshold: 1, minimumDisplayTime: 1) // } // func deActiveIndicator() { // stopAnimating() // } internal func isHiddenNavigation(hide: Bool) { navigationController?.navigationBar.isHidden = hide } internal func isTransparent(trans: Bool) { if (trans == true) { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.view.backgroundColor = UIColor.clear } } internal func addbackground(imgName:String) { let img_background = UIImageView(image: UIImage(named: imgName)) self.view.addSubview(img_background) //constraints img_background.translatesAutoresizingMaskIntoConstraints = false let leading = NSLayoutConstraint(item: img_background, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0) let trailing = NSLayoutConstraint(item: img_background, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0) let top = NSLayoutConstraint(item: img_background, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 0) let bottom = NSLayoutConstraint(item: img_background, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0) NSLayoutConstraint.activate([leading,trailing,top,bottom]) } }
true
96351e1a22e18ecb1e48e1931f959b43b02a9b2d
Swift
jestspoko/Reveal
/Reveal/Classes/RevealLabel.swift
UTF-8
4,707
3.078125
3
[ "MIT" ]
permissive
// // RevealLabel.swift // MaskedLabel // // Created by Lukasz Czechowicz on 26.10.2016. // Copyright © 2016 Lukasz Czechowicz. All rights reserved. // import UIKit /// holds UILabel and creates animations public class RevealLabel:Equatable { /// label's reference private var label:UILabel /// animation speed private var speed:Double /// animation's delay private var delay:Double /// function describing a timing curve private var timingFunction:CAMediaTimingFunction /// animation's direction private var direction:Reveal.RevealDirection /// destination mask frame private var destinationRect:CGRect /// layer with B&W gradient used as mask var gradientLayer:CAGradientLayer /** Initializes new label holder - Parameters: - label: UILabel reference - speed: animation speed - delay: animation delay - timingFunction: function describing timing curve - direction: animation direction */ init(_ label:UILabel, speed:Double, delay:Double, timingFunction:CAMediaTimingFunction, direction:Reveal.RevealDirection) { self.label = label self.speed = speed self.delay = delay self.timingFunction = timingFunction self.direction = direction destinationRect = label.bounds gradientLayer = CAGradientLayer() // creates and tweaks destination frame and mask layer depends of animation direction switch direction { case .fromLeft: destinationRect.origin.x = destinationRect.origin.x - destinationRect.size.width - 20 gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) gradientLayer.frame = CGRect(x: destinationRect.origin.x, y: destinationRect.origin.y, width: destinationRect.size.width + 20, height: destinationRect.size.height) case .fromRight: destinationRect.origin.x = destinationRect.origin.x + destinationRect.size.width + 20 gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.frame = CGRect(x: destinationRect.origin.x-20, y: destinationRect.origin.y, width: destinationRect.size.width + 20, height: destinationRect.size.height) } gradientLayer.colors = [UIColor.black.cgColor,UIColor.clear.cgColor] gradientLayer.locations = [0.9, 1.0] label.layer.mask = gradientLayer } /// holds UILabel content public var text:String? { set { self.label.text = newValue } get { return self.label.text } } public static func ==(l: RevealLabel, r: RevealLabel) -> Bool { return l.label == r.label } /** Creates and perfomrs reveal animation on mask - Parameters: - complete: handler fires when animation in complete */ func reaval(complete:((_ revealLabel:RevealLabel)->())? = nil) { CATransaction.begin() CATransaction.setCompletionBlock { if let cpl = complete { cpl(self) } } let animation = CABasicAnimation(keyPath: "bounds") animation.duration = speed animation.fromValue = NSValue(cgRect: label.bounds) animation.toValue = NSValue(cgRect: destinationRect) animation.fillMode = "forwards" animation.beginTime = CACurrentMediaTime() + delay animation.isRemovedOnCompletion = false animation.timingFunction = timingFunction label.layer.add(animation, forKey:"reveal") CATransaction.commit() } /** Creates and perfomrs hide animation on mask - Parameters: - complete: handler fires when animation in complete */ func hide(complete:((_ revealLabel:RevealLabel)->())? = nil) { CATransaction.begin() CATransaction.setCompletionBlock { if let cpl = complete { cpl(self) } } let animation = CABasicAnimation(keyPath: "bounds") animation.duration = speed animation.toValue = NSValue(cgRect: label.bounds) animation.fromValue = NSValue(cgRect: destinationRect) animation.fillMode = "forwards" animation.beginTime = CACurrentMediaTime() + delay animation.isRemovedOnCompletion = false animation.timingFunction = timingFunction label.layer.add(animation, forKey:"hide") CATransaction.commit() } }
true
bc6bb95997d35c92809e58846e3435096c81fa99
Swift
afarooqui98/roomr
/Roomr/Roomr/Matches/FriendViewController.swift
UTF-8
3,814
2.5625
3
[]
no_license
// // FriendViewController.swift // Roomr // // Created by Sophia on 12/5/19. // Copyright © 2019 Ahmed Farooqui. All rights reserved. // import UIKit import Firebase import FirebaseStorage class FriendViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{ var storage: Storage! var ref: DatabaseReference! var peopleQuery: [People] = [] var friendCollectionViewFlowLayout: UICollectionViewFlowLayout! @IBOutlet weak var friendCollection: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.friendCollection.dataSource = self self.friendCollection.delegate = self self.storage = Storage.storage() self.ref = Database.database().reference() self.fetchData(ref) self.setupCollectionViewItemSize() // Do any additional setup after loading the view. } private func setupCollectionViewItemSize() { if friendCollectionViewFlowLayout == nil { let numberOfItemsPerRow: CGFloat = 2 let lineSpacing: CGFloat = 2 let interItemSpacing: CGFloat = 1 let width = (self.friendCollection.frame.width - (numberOfItemsPerRow - 1) * interItemSpacing) / numberOfItemsPerRow let height = width // cell display setting friendCollectionViewFlowLayout = UICollectionViewFlowLayout() friendCollectionViewFlowLayout.itemSize = CGSize(width: width, height: height) friendCollectionViewFlowLayout.sectionInset = UIEdgeInsets.zero friendCollectionViewFlowLayout.scrollDirection = .vertical friendCollectionViewFlowLayout.minimumLineSpacing = lineSpacing friendCollectionViewFlowLayout.minimumInteritemSpacing = interItemSpacing self.friendCollection.setCollectionViewLayout(friendCollectionViewFlowLayout, animated: true) } } func fetchData (_ ref: DatabaseReference?) -> Void { self.peopleQuery = [] guard let userID = Auth.auth().currentUser?.uid else {return} var allPeople: [People] = [] ref?.child("user").child(userID).child("friends").observe(DataEventType.value, with: { (snapshot) in guard let snapshot = snapshot.children.allObjects as? [DataSnapshot] else { return } for person in snapshot { let key = person.key let name = person.childSnapshot(forPath: "name").value as? String let downloadURL = person.childSnapshot(forPath: "imageURL").value as? String let people = People(image: #imageLiteral(resourceName: "example"), name: name ?? "nil", date: Date(), url: downloadURL ?? "gs://roomr-ecee8.appspot.com/mOgPHxdnz7N9aQ5fOrlFS2sDoD92/image7.png", key:key) allPeople.append(people) } DispatchQueue.main.async { self.peopleQuery = allPeople self.friendCollection.reloadData() } }){(error) in print(error.localizedDescription) } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.peopleQuery.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let person = peopleQuery[indexPath.row] let cell = friendCollection.dequeueReusableCell(withReuseIdentifier: "Friend", for: indexPath as IndexPath) as! FriendCell cell.person = person return cell } }
true
93c18bc98841aa133f91d55907be2b418e085ed7
Swift
ricky97itly/vigilesMobile
/vigilesMobile/ReportsClassesStructsModel/ReportsStruct.swift
UTF-8
1,505
3.15625
3
[]
no_license
// // ReportsStruct.swift // vigilesMobile // // Created by vigiles_admin on 08/03/2019. // Copyright © 2019 Vigiles. All rights reserved. // import Foundation class Data: Codable { var success: Reports static var report: Data? } // Struct copia il suo valore quando viene assegnato a qualcos'altro. Class no // Codable permette ai dati di essere serializzati per diversi tipi di rappresentazione dati -> comprende encodable e decodable e rende immediato il loro utilizzo (una riga fa tutto praticamente) // Encodable: permette la codifica di una rappresentazione interna, un nostro oggetto, in una rappresentazione esterna come può essere un JSON // Decodable: permette di decodificare una rappresentazione esterna, come un JSON, in una rappresentazione interna (da JSON alla class/struct conforme a questo protocollo) struct Reports: Codable { static var report: AnyObject? let id: Int? let user_id = MyUserData.user?.success.id as Int? let code_id: Int? let zone_id = 1 let title: String? let address: String? let street_number: Int? let latitude: Double? let longitude: Double? let description: String? let media: String? let tags: String? } // Gestiamo i dati facendo riferimento alla struct precedente. In questo caso usiamo una classe per evitare rallentamenti gestendo ora la quantità di dati presente nel json class ReportsData: Codable { var data: [Reports]? init(data: [Reports]) { self.data = data } }
true
8fe28ca6bb935eb900558bd445565213c3c21317
Swift
SaiVedagiri/TeleMedML
/TeleMedML/TeleMedML/LoginVC.swift
UTF-8
1,729
2.609375
3
[]
no_license
// // LoginVC.swift // TeleMedML // // Created by Arya Tschand on 5/23/20. // Copyright © 2020 aryatschand. All rights reserved. // import UIKit import Parse class LoginVC: UIViewController { @IBOutlet weak var Username: UITextField! @IBOutlet weak var Password: UITextField! var name = "" @IBAction func EnterClick(_ sender: Any) { /* if Username.text == "doctor" { self.performSegue(withIdentifier: "doctorlogin", sender: self) } else { self.performSegue(withIdentifier: "patientlogin", sender: self) } */ PFUser.logInWithUsername(inBackground: Username.text!, password: Password.text!) {(user, error) in if user != nil { if user!["status"] as? String == Optional("Patient") { self.performSegue(withIdentifier: "patientlogin", sender: self) } else { self.performSegue(withIdentifier: "doctorlogin", sender: self) } } else { //no user doesnt exist } } } override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() // Do any additional setup after loading the view. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { name = Username.text! if segue.identifier == "doctorlogin" { let DoctorWelcomeVC = segue.destination as! DoctorWelcomeVC DoctorWelcomeVC.name = name } else if segue.identifier == "patientlogin" { let PatientWelcomeVC = segue.destination as! PatientWelcomeVC PatientWelcomeVC.name = name } } }
true
ac9767bd0edf2bc4986ed52e4710e3e70d5714ab
Swift
ljuben97/RecipeFinder
/RecipeFinder/API/Parsing.swift
UTF-8
1,033
2.890625
3
[]
no_license
// // Parsing.swift // RecipeFinder // // Created by Ljuben Angelkoski on 17.7.21. // import Foundation import Combine func decode<T: Decodable>(_ data: Data) -> AnyPublisher<T, ErrorResponse> { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 do { _ = try decoder.decode(T.self, from: data) } catch { print(String(describing: error)) } return Just(data) .decode(type: T.self, decoder: decoder) .mapError { error in .parsing(description: error.localizedDescription) } .eraseToAnyPublisher() } func decodeArray<T: Decodable>(_ data: Data) -> AnyPublisher<[T], ErrorResponse> { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 do { _ = try decoder.decode([T].self, from: data) } catch { print(String(describing: error)) } return Just(data) .decode(type: [T].self, decoder: decoder) .mapError { error in .parsing(description: error.localizedDescription) } .eraseToAnyPublisher() }
true
8a0d0d7bba774137faa2ba5091447f77bab607ba
Swift
AtmanChen/MoviesSwiftUILearning
/MovieSwiftUILearning/views/components/moviesHome/models/MoviesMenuListPageListener.swift
UTF-8
432
2.609375
3
[]
no_license
// import Foundation final class MoviesMenuPageListener: MoviesPagesListener { var menu: MoviesMenu { didSet { currentPage = 1 } } override func loadPage() { store.dispatch(action: MoviesActions.FetchMoviesMenuList(list: menu, page: currentPage)) } init(menu: MoviesMenu, loadOnInit: Bool? = true) { self.menu = menu super.init() if loadOnInit == true { loadPage() } } }
true
6418068d24e4e1a13bf3e4498c641d99841a8471
Swift
wzboy049/ZDownLoad
/ZDownLoad/ZDownLoadManager/DCircleProgress.swift
UTF-8
2,626
2.75
3
[ "MIT" ]
permissive
// // DCircleProgress.swift // ZBXMobile // // Created by wzboy on 17/4/18. // Copyright © 2017年 zbx. All rights reserved. // import UIKit open class DCircleProgress: UIView { open var lineWidth : CGFloat = 10.0 open var circleFontSize : CGFloat = 13 open var circleColor : UIColor = UIColor.orange open var progressValue : CGFloat = 0{ didSet{ cLabel.text = "\(Int(progressValue * 100))%" setNeedsDisplay() } } open var progressText : String? { didSet{ if progressText != nil { cLabel.text = progressText setNeedsDisplay() } } } open var progress : Progress?{ didSet{ if progress != nil { progressValue = CGFloat(progress!.completedUnitCount)/CGFloat(progress!.totalUnitCount) } } } fileprivate var cLabel = UILabel() override public init(frame:CGRect){ super.init(frame: frame) backgroundColor = UIColor.clear } open func setupcLabel(){ addSubview(cLabel) cLabel.font = UIFont.boldSystemFont(ofSize: circleFontSize) cLabel.textColor = circleColor cLabel.textAlignment = .center cLabel.fill_dd(referView: self) } convenience public init(fontSize:CGFloat, lineWidth:CGFloat = 10,color:UIColor = UIColor.orange){ self.init() circleFontSize = fontSize == 0 ? self.circleFontSize : fontSize self.lineWidth = lineWidth self.circleColor = color setupcLabel() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func draw(_ rect: CGRect) { //路径 let path = UIBezierPath() //线宽 path.lineWidth = lineWidth //颜色 circleColor.set() //拐角 path.lineCapStyle = CGLineCap.round path.lineJoinStyle = CGLineJoin.round //半径 let radius = ( CGFloat.minimum(rect.size.width, rect.size.height) - lineWidth) * 0.5 //画弧(参数:中心、半径、起始角度(3点钟方向为0)、结束角度、是否顺时针) path.addArc(withCenter: CGPoint(x:rect.size.width * 0.5, y: rect.size.height * 0.5), radius: radius, startAngle: CGFloat.pi * 1.5, endAngle: CGFloat.pi * 1.5 + CGFloat.pi * 2 * progressValue, clockwise: true) //描边 path.stroke() } }
true
2db35e3dff33a4e42dc22e4295b051b5e64344b8
Swift
kongbaguni/dailyattendancemanagement
/dailyattendancemanagement/Extensions/SwiftUI/Color+Extensions.swift
UTF-8
1,888
3.515625
4
[]
no_license
// // Color+Extensions.swift // AnyReview // // Created by Changyul Seo on 2020/06/16. // Copyright © 2020 Changyul Seo. All rights reserved. // import SwiftUI #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif extension Color { static var backgroundColor:Color { Color("backgroundColor") } static var strongTextColor:Color { Color("strongTextColor") } /** RGBA 값을 얻어옵니다.*/ var components: (red: CGFloat, green: CGFloat, blue: CGFloat, opacity: CGFloat) { #if canImport(UIKit) typealias NativeColor = UIColor #elseif canImport(AppKit) typealias NativeColor = NSColor #endif var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var o: CGFloat = 0 guard NativeColor(self).getRed(&r, green: &g, blue: &b, alpha: &o) else { // You can handle the failure here as you want return (0, 0, 0, 0) } return (r, g, b, o) } /** rgba 값을 비교하여 차이가 가장 큰 값을 리턴합니다. 두가지 색이 비슷한 색인지 알기 위함.*/ func compare(color:Color)->CGFloat { let a = components let b = color.components let red = abs(a.red - b.red) let green = abs(a.green - b.green) let blue = abs(a.blue - b.blue) let opacity = abs(a.opacity - b.opacity) let arr = [red,green,blue,opacity] let new = arr.sorted() return new.last! } var complementaryColor : Color { let red = Double(1.0 - components.red) let green = Double(1.0 - components.green) let blue = Double(1.0 - components.blue) return .init(.sRGB, red: red, green: green, blue: blue, opacity: Double(components.opacity)) } }
true
de8d493abd06aaaf84ff220d31edd54b4383cff4
Swift
AgoraIO/API-Examples
/iOS/APIExample-Audio/APIExample-Audio/Common/UITypeAlias.swift
UTF-8
20,766
2.9375
3
[ "MIT" ]
permissive
// // UITypeAlias.swift // APIExample // // Created by CavanSu on 2020/5/26. // Copyright © 2020 Agora Corp. All rights reserved. // #if os(iOS) import UIKit #else import Cocoa #endif typealias Color = UIColor typealias MainFont = Font.HelveticaNeue extension String { var localized: String { NSLocalizedString(self, comment: "") } } enum Font { enum HelveticaNeue: String { case ultraLightItalic = "UltraLightItalic" case medium = "Medium" case mediumItalic = "MediumItalic" case ultraLight = "UltraLight" case italic = "Italic" case light = "Light" case thinItalic = "ThinItalic" case lightItalic = "LightItalic" case bold = "Bold" case thin = "Thin" case condensedBlack = "CondensedBlack" case condensedBold = "CondensedBold" case boldItalic = "BoldItalic" func with(size: CGFloat) -> UIFont { return UIFont(name: "HelveticaNeue-\(rawValue)", size: size)! } } } extension UIColor { /// Get color rgba components in order. func rgba() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { let components = self.cgColor.components let numberOfComponents = self.cgColor.numberOfComponents switch numberOfComponents { case 4: return (components![0], components![1], components![2], components![3]) case 2: return (components![0], components![0], components![0], components![1]) default: // FIXME: Fallback to black return (0, 0, 0, 1) } } /// Check the black or white contrast on given color. func blackOrWhiteContrastingColor() -> Color { let rgbaT = rgba() let value = 1 - ((0.299 * rgbaT.r) + (0.587 * rgbaT.g) + (0.114 * rgbaT.b)); return value < 0.5 ? Color.black : Color.white } } enum AssetsColor : String { case videoBackground case videoPlaceholder case textShadow } extension UIColor { static func appColor(_ name: AssetsColor) -> UIColor? { return UIColor(named: name.rawValue) } } extension UIView { /// Adds constraints to this `UIView` instances `superview` object to make sure this always has the same size as the superview. /// Please note that this has no effect if its `superview` is `nil` – add this `UIView` instance as a subview before calling this. func bindFrameToSuperviewBounds() { guard let superview = self.superview else { print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.") return } self.translatesAutoresizingMaskIntoConstraints = false self.topAnchor.constraint(equalTo: superview.topAnchor, constant: 0).isActive = true self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: 0).isActive = true self.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: 0).isActive = true self.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: 0).isActive = true } } //MARK: - Color #if os(iOS) typealias AGColor = UIColor #else typealias AGColor = NSColor #endif extension AGColor { convenience init(hex: Int, alpha: CGFloat = 1) { func transform(_ input: Int, offset: Int = 0) -> CGFloat { let value = (input >> offset) & 0xff return CGFloat(value) / 255 } self.init(red: transform(hex, offset: 16), green: transform(hex, offset: 8), blue: transform(hex), alpha: alpha) } func rgbValue() -> (red: CGFloat, green: CGFloat, blue: CGFloat) { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: nil) return (red * 255, green * 255, blue * 255) } convenience init(hex: String, alpha: CGFloat = 1) { var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { let range = cString.index(after: cString.startIndex) ..< cString.endIndex cString = String(cString[range]) } if (cString.hasPrefix("0X")) { let range = cString.index(cString.startIndex, offsetBy: 2) ..< cString.endIndex cString = String(cString[range]) } if (cString.count != 6) { self.init() return } let scanner = Scanner(string: cString) var hexValue: UInt64 = 0 scanner.scanHexInt64(&hexValue) self.init(hex: Int(hexValue), alpha: alpha) } static func randomColor() -> AGColor { let randomHex = Int(arc4random_uniform(0xCCCCCC) + 0x555555) return AGColor(hex: randomHex) } } //MARK: - Font #if os(iOS) typealias AGFont = UIFont #else typealias AGFont = NSFont #endif //MARK: - Image #if os(iOS) typealias AGImage = UIImage #else typealias AGImage = NSImage #endif // MARK: - Label #if os(iOS) typealias AGLabel = UILabel #else typealias AGLabel = NSTextField #endif extension AGLabel { var formattedFloatValue: Float { get { #if os(iOS) if let text = text, let value = Double(text) { return Float(value) } else { return 0 } #else return floatValue #endif } set { #if os(iOS) text = NSString(format: "%.1f", newValue) as String #else stringValue = NSString(format: "%.1f", newValue) as String #endif } } var formattedCGFloatValue: CGFloat { get { #if os(iOS) if let text = text, let value = Double(text) { return CGFloat(value) } else { return 0 } #else return CGFloat(floatValue) #endif } set { #if os(iOS) text = NSString(format: "%.1f", newValue) as String #else stringValue = NSString(format: "%.1f", newValue) as String #endif } } var formattedIntValue: Int { get { #if os(iOS) if let text = text, let value = Int(text) { return value } else { return 0 } #else return integerValue #endif } set { #if os(iOS) text = "\(newValue)" #else stringValue = "\(newValue)" #endif } } #if os(macOS) var text: String? { get { return stringValue } set { if let newValue = newValue { stringValue = newValue } } } #endif } //MARK: - TextField #if os(iOS) typealias AGTextField = UITextField #else typealias AGTextField = NSTextField #endif extension AGTextField { #if os(iOS) var integerValue: Int { get { if let text = text, let value = Int(text) { return value } else { return 0 } } set { text = "\(newValue)" } } var formattedIntValue: Int { get { return integerValue } set { integerValue = newValue } } var cgFloatValue: CGFloat { get { if let text = text, let value = Double(text) { return CGFloat(value) } else { return 0 } } set { text = "\(newValue)" } } var formattedCGFloatValue: CGFloat { get { return CGFloat(cgFloatValue) } set { cgFloatValue = newValue } } var formattedFloatValue: Float { get { if let text = text, let value = Double(text) { return Float(value) } else { return 0 } } set { text = NSString(format: "%.1f", newValue) as String } } var stringValue: String { get { return text! } set { text = newValue } } #endif var placeholderAGString: String? { get { #if os(iOS) return placeholder #else return placeholderString #endif } set { #if os(iOS) placeholder = newValue #else placeholderString = placeholderAGString #endif } } } //MARK: - Indicator #if os(iOS) typealias AGIndicator = UIActivityIndicatorView #else typealias AGIndicator = NSProgressIndicator #endif extension AGIndicator { func startAnimation() { #if os(iOS) self.startAnimating() #else self.startAnimation(nil) #endif } func stopAnimation() { #if os(iOS) self.stopAnimating() #else self.stopAnimation(nil) #endif } } //MARK: - View #if os(iOS) typealias AGView = UIView #else typealias AGView = NSView #endif extension AGView { var cornerRadius: CGFloat? { get { #if os(iOS) return layer.cornerRadius #else return layer?.cornerRadius #endif } set { guard let newValue = newValue else { return } #if os(iOS) layer.cornerRadius = newValue #else wantsLayer = true layer?.cornerRadius = newValue #endif } } var masksToBounds: Bool? { get { #if os(iOS) return layer.masksToBounds #else return layer?.masksToBounds #endif } set { guard let newValue = newValue else { return } #if os(iOS) layer.masksToBounds = newValue #else wantsLayer = true layer?.masksToBounds = newValue #endif } } var borderWidth: CGFloat { get { #if os(iOS) return layer.borderWidth #else guard let borderWidth = layer?.borderWidth else { return 0 } return borderWidth #endif } set { #if os(iOS) layer.borderWidth = newValue #else wantsLayer = true layer?.borderWidth = newValue #endif } } var borderColor: CGColor { get { #if os(iOS) guard let borderColor = layer.borderColor else { return AGColor.clear.cgColor } return borderColor #else guard let borderColor = layer?.borderColor else { return AGColor.clear.cgColor } return borderColor #endif } set { #if os(iOS) layer.borderColor = newValue #else wantsLayer = true layer?.borderColor = newValue #endif } } #if os(macOS) var backgroundColor: AGColor? { get { if let cgColor = layer?.backgroundColor { return AGColor(cgColor: cgColor) } else { return nil } } set { if let newValue = newValue { wantsLayer = true layer?.backgroundColor = newValue.cgColor } } } var center: CGPoint { get { return CGPoint(x: self.frame.width / 2, y: self.frame.height / 2) } set { self.frame.origin = CGPoint(x: newValue.x - self.frame.width / 2, y: newValue.y - self.frame.height / 2) } } #endif } #if os(iOS) typealias AGVisualEffectView = UIVisualEffectView #else typealias AGVisualEffectView = NSVisualEffectView #endif //MARK: - ImageView #if os(iOS) typealias AGImageView = UIImageView #else typealias AGImageView = NSImageView #endif //MARK: - TableView #if os(iOS) typealias AGTableView = UITableView #else typealias AGTableView = NSTableView #endif //MARK: - TableViewCell #if os(iOS) typealias AGTableViewCell = UITableViewCell #else typealias AGTableViewCell = NSTableCellView #endif //MARK: - CollectionView #if os(iOS) typealias AGCollectionView = UICollectionView #else typealias AGCollectionView = NSCollectionView #endif #if os(iOS) typealias AGCollectionViewFlowLayout = UICollectionViewFlowLayout #else typealias AGCollectionViewFlowLayout = NSCollectionViewFlowLayout #endif //MARK: - CollectionViewCell #if os(iOS) typealias AGCollectionViewCell = UICollectionViewCell #else typealias AGCollectionViewCell = NSCollectionViewItem #endif extension AGCollectionViewCell { #if os(OSX) var contentView: AGView { get { return view } set { view = newValue } } #endif } //MARK: - Button #if os(iOS) typealias AGButton = UIButton #else typealias AGButton = NSButton #endif extension AGButton { #if os(iOS) var image: AGImage? { get { return image(for: .normal) } set { setImage(newValue, for: .normal) } } var highlightImage: AGImage? { get { return image(for: .highlighted) } set { setImage(newValue, for: .highlighted) } } var title: String? { get { return title(for: .normal) } set { setTitle(newValue, for: .normal) } } #else var textColor: AGColor { get { return AGColor.black } set { let pstyle = NSMutableParagraphStyle() pstyle.alignment = .left attributedTitle = NSAttributedString(string: title, attributes: [ NSAttributedString.Key.foregroundColor : newValue, NSAttributedString.Key.paragraphStyle : pstyle ]) } } #endif func switchImage(toImage: AGImage) { #if os(iOS) UIView.animate(withDuration: 0.15, animations: { self.isEnabled = false self.alpha = 0.3 }) { (_) in self.image = toImage self.alpha = 1.0 self.isEnabled = true } #else NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.3 self.isEnabled = false self.animator().alphaValue = 0.3 }) { self.image = toImage self.alphaValue = 1.0 self.isEnabled = true } #endif } } //MARK: - Switch #if os(iOS) typealias AGSwitch = UISwitch #else typealias AGSwitch = NSButton #endif #if os(macOS) extension AGSwitch { var isOn: Bool { get { return state != .off } set { state = newValue ? .on : .off } } } #endif //MARK: - WebView #if os(iOS) typealias AGWebView = UIWebView #else import WebKit typealias AGWebView = WebView #endif #if os(macOS) extension AGWebView { func loadRequest(_ request: URLRequest) { self.mainFrame.load(request) } } #endif //MARK: - Slider #if os(iOS) typealias AGSlider = UISlider #else typealias AGSlider = NSSlider #endif extension AGSlider { #if os(iOS) var floatValue: Float { get { return value } set { setValue(newValue, animated: false) } } var cgFloatValue: CGFloat { get { return CGFloat(value) } set { setValue(Float(newValue), animated: false) } } var integerValue: Int { get { return Int(value) } set { setValue(Float(newValue), animated: false) } } var doubleValue: Double { get { return Double(value) } set { setValue(Float(newValue), animated: false) } } #else var minimumValue: Float { get { return Float(minValue) } set { minValue = Double(newValue) } } var maximumValue: Float { get { return Float(maxValue) } set { maxValue = Double(newValue) } } #endif } //MARK: - SegmentedControl #if os(iOS) typealias AGPopSheetButton = UIButton #else typealias AGPopSheetButton = NSPopUpButton #endif //MARK: - SegmentedControl #if os(iOS) typealias AGSegmentedControl = UISegmentedControl #else typealias AGSegmentedControl = NSPopUpButton #endif #if os(macOS) extension AGSegmentedControl { var selectedSegmentIndex: Int { get { return indexOfSelectedItem } set { selectItem(at: newValue) } } } #endif //MARK: - StoryboardSegue #if os(iOS) typealias AGStoryboardSegue = UIStoryboardSegue #else typealias AGStoryboardSegue = NSStoryboardSegue #endif extension AGStoryboardSegue { var identifierString: String? { get { #if os(iOS) return identifier #else return identifier #endif } } #if os(iOS) var destinationController: AGViewController? { get { return destination } } #endif } //MARK: - Storyboard #if os(iOS) typealias AGStoryboard = UIStoryboard #else typealias AGStoryboard = NSStoryboard #endif //MARK: - ViewController #if os(iOS) typealias AGViewController = UIViewController #else typealias AGViewController = NSViewController #endif extension AGViewController { #if os(OSX) var title: String? { get { return self.view.window?.title } set { guard let title = newValue else { return } self.view.window?.title = title } } #endif func performAGSegue(withIdentifier identifier: String, sender: Any?) { #if os(iOS) performSegue(withIdentifier: identifier, sender: sender) #else performSegue(withIdentifier: identifier, sender: sender) #endif } func dismissVC(_ vc: AGViewController, animated: Bool) { #if os(iOS) vc.dismiss(animated: animated, completion: nil) #else dismiss(nil) #endif } } //MARK: - TableViewController #if os(iOS) typealias AGTableViewController = UITableViewController #else typealias AGTableViewController = NSViewController #endif #if os(iOS) typealias AGBezierPath = UIBezierPath #else typealias AGBezierPath = NSBezierPath #endif extension AGBezierPath { #if os(OSX) func addLine(to point: CGPoint) { var points = [point] self.appendPoints(&points, count: 1) } func addArc(withCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) { self.appendArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise) } #endif } #if os(iOS) typealias AGControl = UIControl #else typealias AGControl = NSControl #endif #if os(OSX) extension String { func buttonWhiteAttributedTitleString() -> NSAttributedString { return buttonAttributedTitleStringWithColor(AGColor.white) } func buttonBlueAttributedTitleString() -> NSAttributedString { return buttonAttributedTitleStringWithColor(AGColor(hex: 0x00a0e9)) } fileprivate func buttonAttributedTitleStringWithColor(_ color: AGColor) -> NSAttributedString { let attributes = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: NSFont.systemFont(ofSize: 13)] let attributedString = NSMutableAttributedString(string: self) let range = NSMakeRange(0, attributedString.length) attributedString.addAttributes(attributes, range: range) attributedString.setAlignment(.center, range: range) attributedString.fixAttributes(in: range) return attributedString } } #endif #if os(iOS) typealias AGApplication = UIApplication #else typealias AGApplication = NSApplication #endif
true
5a33538ab3de057cf22a66ebfe28c12cd2c3a30a
Swift
charlesguo/casacalc
/casacalc/Calculation.swift
UTF-8
3,878
2.90625
3
[]
no_license
// // Calculation.swift // casacalc // // Created by Charles on 22/7/16. // Copyright © 2016 Charles. All rights reserved. // import UIKit class Calculation: NSObject, NSCoding { // MARK: Properties var propertyAddress: String var purchasePrice: Double var nationality: Int var numProperty: Int var basicStampDuty: Double var additionalStampDuty: Double var totalPrice: Double var photo: UIImage? // MARK: Archiving Paths static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("calculations") // MARK: Types struct PropertyKey { static let propertyAddressKey = "propertyAddress" static let purchasePriceKey = "purchasePrice" static let nationalityKey = "nationality" static let numPropertyKey = "numProperty" static let basicStampDutyKey = "basicStampDuty" static let additionalStampDutyKey = "additionalStampDuty" static let totalPriceKey = "totalPrice" static let photoKey = "photo" } // MARK: Initialization init?(propertyAddress: String, purchasePrice: Double, nationality: Int, numProperty: Int, basicStampDuty: Double, additionalStampDuty: Double, totalPrice: Double, photo: UIImage?) { // Initialize stored properties self.propertyAddress = propertyAddress self.purchasePrice = purchasePrice self.nationality = nationality self.numProperty = numProperty self.basicStampDuty = basicStampDuty self.additionalStampDuty = additionalStampDuty self.totalPrice = totalPrice self.photo = photo super.init() // Initialization should fail if there is no address/ purchase price or if the values cannot be computed if propertyAddress.isEmpty || purchasePrice <= 0 || nationality < 0 || numProperty < 0 || basicStampDuty <= 0 || additionalStampDuty < 0 || totalPrice <= 0 { return nil } } // MARK: NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(propertyAddress, forKey: PropertyKey.propertyAddressKey) aCoder.encodeDouble(purchasePrice, forKey: PropertyKey.purchasePriceKey) aCoder.encodeInteger(nationality, forKey: PropertyKey.nationalityKey) aCoder.encodeInteger(numProperty, forKey: PropertyKey.numPropertyKey) aCoder.encodeDouble(basicStampDuty, forKey: PropertyKey.basicStampDutyKey) aCoder.encodeDouble(additionalStampDuty, forKey: PropertyKey.additionalStampDutyKey) aCoder.encodeDouble(totalPrice, forKey: PropertyKey.totalPriceKey) aCoder.encodeObject(photo, forKey: PropertyKey.photoKey) } required convenience init?(coder aDecoder: NSCoder) { let propertyAddress = aDecoder.decodeObjectForKey(PropertyKey.propertyAddressKey) as! String let purchasePrice = aDecoder.decodeDoubleForKey(PropertyKey.purchasePriceKey) let nationality = aDecoder.decodeIntegerForKey(PropertyKey.nationalityKey) let numProperty = aDecoder.decodeIntegerForKey(PropertyKey.numPropertyKey) let basicStampDuty = aDecoder.decodeDoubleForKey(PropertyKey.basicStampDutyKey) let additionalStampDuty = aDecoder.decodeDoubleForKey(PropertyKey.additionalStampDutyKey) let totalPrice = aDecoder.decodeDoubleForKey(PropertyKey.totalPriceKey) let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as? UIImage self.init(propertyAddress: propertyAddress, purchasePrice: purchasePrice, nationality: nationality, numProperty: numProperty, basicStampDuty: basicStampDuty, additionalStampDuty: additionalStampDuty, totalPrice: totalPrice, photo: photo) } }
true
bf59efef4851b823698693f5d526865401e3783a
Swift
ihuettel/100Days
/Roshambo/RoshamboUITests/RoshamboUITests.swift
UTF-8
3,566
2.890625
3
[]
no_license
// // RoshamboUITests.swift // RoshamboUITests // // Created by ihuettel on 1/13/21. // import XCTest class RoshamboUITests: 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 testAllMoves() throws { let app = XCUIApplication() app.launch() for move in ["Rock", "Paper", "Scissors"] { app.buttons[move].tap() app.alerts.buttons["Continue"].tap() } } func testPerfectGame() throws { let app = XCUIApplication() app.launch() for _ in 0 ..< 10 { let shouldWinText = app.staticTexts["shouldWin"].label let opponentsMove = app.staticTexts["opponentsMove"].label var correctMove: String { if shouldWinText == "You must win." { switch opponentsMove { case "Rock": return "Paper" case "Paper": return "Scissors" case "Scissors": return "Rock" default: return "Dynamite" } } else { switch opponentsMove { case "Rock": return "Scissors" case "Paper": return "Rock" case "Scissors": return "Paper" default: return "Dynamite" } } } XCTAssertNotEqual(opponentsMove, "Dynamite", "Your opponent wound up with Dynamite, somehow.") XCTAssertNotEqual(correctMove, "Dynamite", "You wound up with Dynamite, somehow.") app.buttons[correctMove].tap() let alert: XCUIElement = app.alerts["Correct!"] XCTAssertTrue(alert.exists, "Wrong answer in an otherwise perfect game.") app.alerts.buttons["Continue"].tap() } //let scoreText = app.staticTexts["scoreText"].label //XCTAssertEqual(scoreText, "Correct Answers: 10 | Total Answers: 10", "Didn't end 10/10.") // // This code won't work until I implement a "Restart Game" button instead of automatically resetting it // I could also change the way the game functions to make it work, but that's not what I want. // I hope to revisit this at some point, but this was my first foray into testing, and I feel // that I've learned quite a bit already. #staticTextNotTextView // } 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() } } } }
true
0ed212880ee404d6fa77343daee3f28b6c4ae596
Swift
AlexLezin/GB_Swift
/HomeWork/4|_LezinAlex.playground/Contents.swift
UTF-8
5,634
3.59375
4
[]
no_license
//1. Описать класс Car c общими свойствами автомобилей и пустым методом действия по аналогии с прошлым заданием. //2. Описать пару его наследников trunkCar и sportСar. Подумать, какими отличительными свойствами обладают эти автомобили. Описать в каждом наследнике специфичные для него свойства. //3. Взять из прошлого урока enum с действиями над автомобилем. Подумать, какие особенные действия имеет trunkCar, а какие – sportCar. Добавить эти действия в перечисление. //4. В каждом подклассе переопределить метод действия с автомобилем в соответствии с его классом. //5. Создать несколько объектов каждого класса. Применить к ним различные действия. //6. Вывести значения свойств экземпляров в консоль. enum Action { case startEngine, stopEngine, loadCargo, unloadCargo, startTurbine, stopTurbine } class Car { var brand: String var year: Int var ignition: Bool = false { didSet { if ignition { print("Ignition of your \(brand) is on") } else { print("Ignition of your \(brand) is off") } } } var windows: Bool = false { didSet { if windows { print("Windows of your " + brand + " are open") } else { print("Windows of your " + brand + " are closed") } } } func applyAction(_ act:Action) { switch act { case .startEngine: if ignition == false { ignition = true } case .stopEngine: if ignition == true { ignition = false } default: print("Wrong action!") } } init(brand: String, year: Int) { self.brand = brand self.year = year } } class trunkCar: Car { let capacity: Double var cargo: Double = 0 var avaliableCapacity: Double { get { return capacity - cargo } } var cargoUnit: Double { get { return 0.1 * capacity } } func carrentCapacityIs() { print("Current avaliable capacity is \(avaliableCapacity)") } override func applyAction(_ act: Action) { switch act { case .loadCargo: if avaliableCapacity <= capacity && avaliableCapacity > 0 { cargo += cargoUnit carrentCapacityIs() } else { print("Cannot load any more. The trunk is full!") } case .unloadCargo: if cargo > 0 { cargo -= cargoUnit carrentCapacityIs() } else { print("There is nothing to unload. The trunk is empty!") } default: super.applyAction(act) } } init(brand: String, year: Int, capacity: Double) { self.capacity = capacity super.init(brand: brand, year: year) } } class sportCar: Car { override var ignition: Bool { didSet { if !ignition { tourbineMode = false } } } let maxSpeed: Double var tourbineMode: Bool = false var fuelConsumption: Double { get { if tourbineMode { return 0.5 * maxSpeed } else { return 0.1 * maxSpeed } } } override func applyAction(_ act: Action) { switch act { case .startTurbine: if !tourbineMode && ignition { tourbineMode = true print("WROOOOOM! Now your \(brand) fuel consumption is \(fuelConsumption) l/100km") } else if !ignition { print("Start the engine of your \(brand) first, you racer!") } else { print("The tourbine is already working!") } case .stopTurbine: if !ignition { print("You know the engine of your \(brand) is not working, right?") } else if ignition && tourbineMode { tourbineMode = false print("SCREEEEEECH! Now your \(brand) fuel consumption is \(fuelConsumption) l/100km") } else { print("If you want to stop the tourbine we strongly recommend you to start it first!") } default: super.applyAction(act) } } init(brand: String, year: Int, maxSpeed: Double) { self.maxSpeed = maxSpeed super.init(brand: brand, year: year) } } let bmw1 = sportCar(brand: "BMW", year: 2018, maxSpeed: 50.0) bmw1.applyAction(Action.startEngine) bmw1.applyAction(Action.startTurbine) bmw1.applyAction(Action.stopEngine) bmw1.applyAction(Action.startEngine) bmw1.applyAction(Action.stopTurbine) bmw1.applyAction(Action.startTurbine) bmw1.applyAction(Action.stopTurbine) let izh1 = trunkCar(brand: "IZH", year: 1990, capacity: 50.0) izh1.applyAction(.startEngine) for _ in 1...12 { izh1.applyAction(.loadCargo) } for _ in 1...12 { izh1.applyAction(.unloadCargo) }
true
9ba162911aa47fd70d5e1ebdfb5cd22457fae745
Swift
lesslucifer/linkcare_ios_doctor
/DoctorApp/DoctorApp/API/PrescriptionAPI.swift
UTF-8
1,155
2.671875
3
[]
no_license
// // PrescriptionAPI.swift // DoctorApp // // Created by Salm on 5/5/16. // Copyright © 2016 Salm. All rights reserved. // import UIKit import ObjectMapper class PrescriptionAPI { class func submitPrescription(prescription: Prescription, result: APIHandler.Result?) { let mapper = Mapper<Prescription>() let body = APIData(mapper.toJSON(prescription)) API.api1.baseAPI(.POST, path: "/prescriptions", body: body, success: APIHandler.toSuccess(result), failure: APIHandler.toFailure(result)) } class func getPrescriptions(prescriptions: [Int], success: APIGenericHandler<Int>.Arr, failure: APIHandler.Failure?) { if (prescriptions.isEmpty) { success(arr: []) return } let query = prescriptions.map({String($0)}).joinWithSeparator(",") let succHandler: APIHandler.Success = { (data: APIData) in success(arr: data.safeArray({$0.intValue})) } API.api1.baseAPI(.GET, path: "/prescriptions/\(query)", body: nil, success: succHandler, failure: failure) } }
true
88e08a1e41758453a5e2047b4456373f4c6bda82
Swift
shirts/Cat-Jokes-iOS
/CatJokes/CatJokes/ViewController.swift
UTF-8
4,981
3.015625
3
[ "MIT" ]
permissive
// // ViewController.swift // CatJokes // // Created by Kevin on 5/1/16. // Copyright © 2016 Kevin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var answerLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() setCatJoke() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func setCatJoke() { let joke = getCatJoke() questionLabel.text = joke["question"] answerLabel.layer.opacity = 0 self.answerLabel.text = joke["answer"] UIView.animateWithDuration(3, delay: 2, options: [], animations: { self.answerLabel.layer.opacity = 1 }) { (finished) in } } func getCatJoke() -> [String:String] { let index: Int = Int(arc4random_uniform(UInt32(catJokes.count))) return catJokes[index] } let catJokes = [ [ "question": "Can a cat play patty-cake?", "answer": "Pawsibly!" ], [ "question": "Why was the cat so small?", "answer": "Because it only drank condensed milk!" ], [ "question": "Why is the cat so grouchy?", "answer": "Because he's in a bad mewd." ], [ "question": "What happened when the cat swallowed a coin?", "answer": "There was some money in the kitty!" ], [ "question": "Why do you always find the cat in the last place you look?", "answer": "Because you stop looking after you find it." ], [ "question": "Why do people love cats?", "answer": "Because they are purrrrr-fect!" ], [ "question": "Why do cats chase birds?", "answer": "For a lark!" ], [ "question": "Why did the litter of communist kittens become capitalists?", "answer": "Because they finally opened their eyes." ], [ "question": "Why did the judge dismiss the entire jury made up of cats?", "answer": "Because each of them was guilty of purrjury." ], [ "question": "Why did the cat sleep under the car?", "answer": "Because she wanted to wake up oily!" ], [ "question": "Why did the cat run from the tree?", "answer": "Because it was afraid of the bark!" ], [ "question": "Why did the cat put the letter 'M' into the fridge?", "answer": "Because it turns 'ice' into 'mice'!" ], [ "question": "Because she wanted to be a first-aid kit!", "answer": "Why did the cat join the Red Cross?" ], [ "question": "Why did the cat frown when she passed the hen house?", "answer": "Because she heard fowl language!" ], [ "question": "Why did the cat cross the road?", "answer": "It was the chicken's day off!" ], [ "question": "Why did a person with an unspayed female cat have to go to court?", "answer": "For kitty littering." ], [ "question": "Why are cats such good singers?", "answer": "Because they're very mewsical." ], [ "question": "Why are cats better than babies?", "answer": "Because you only have to change a litter box once a day." ], [ "question": "Why are cats longer in the evening than they are in the morning?", "answer": "Because they're let out in the evening and taken in in the morning!" ], [ "question": "Who was the most powerful cat in China?", "answer": "Chairman Miaow!" ], [ "question": "Who helped Cinderella's cat go to the ball?", "answer": "Her furry godmother!" ], [ "question": "Which side of a cat has more hair?", "answer": "The outside, of course!" ], [ "question": "Which is the cats' all-time favorite song?", "answer": "Three Blind Mice." ], [ "question": "Where is one place that your cat can sit, but you can't?", "answer": "Your lap." ], [ "question": "Where does a cat go when it loses its tail?", "answer": "The retail store." ], [ "question": "What's the unluckiest kind of cat to have?", "answer": "A catastrophe!" ], [ "question": "What's a cat's favorite dessert?", "answer": "Chocolate mouse!" ], ] }
true
a0603c4d4477dc56de06021e1cd629ec792f46a1
Swift
Nelmeris/Una-iOS
/Una-Mobile/App/Models/LessonTaskSubstring.swift
UTF-8
1,315
3.1875
3
[]
no_license
// // LessonTaskSubstring.swift // Una-Mobile // // Created by Артем Куфаев on 30/05/2019. // Copyright © 2019 Artem Kufaev. All rights reserved. // import Foundation enum LessonTaskTypes: String, Hashable { case input case find } struct LessonTaskAnswer: Hashable { let value: String let isCorrect: Bool } struct LessonTaskSubstring: Equatable, Hashable { let value: String var changedValue: String let position: Int let type: LessonTaskTypes let answers: [LessonTaskAnswer] init(value: String, position: Int, type: LessonTaskTypes, answers: [LessonTaskAnswer]) { self.value = value self.changedValue = value self.position = position self.type = type self.answers = answers } func uniqueValue() -> NSAttributedString.Key { return NSAttributedString.Key("\(value)-\(position)") } func isCorrectAnswer(value: String) -> Bool { for answer in answers { if (answer.value.lowercased() == value.lowercased() && answer.isCorrect) { return true } } return false } static func == (lhs: LessonTaskSubstring, rhs: LessonTaskSubstring) -> Bool { return lhs.value == rhs.value && lhs.position == rhs.position } }
true
a9377bda193da225504cf0186ed2fb9af3158c19
Swift
168-7cm/feedly-ios
/feedly/Source/TabBar/TabBarController.swift
UTF-8
2,295
2.625
3
[]
no_license
// // TabBarController.swift // feedly // // Created by kou yamamoto on 2021/09/06. // import UIKit final class TabBarController: UITabBarController { override func viewDidLoad() { let viewControllers = [feedlyViewControllerInstansiate(), firestoreViewControllerINstansiate()] self.setViewControllers(viewControllers, animated: true) self.setupTabbarController(viewControllers: viewControllers) } private func feedlyViewControllerInstansiate() -> UINavigationController { let viewController = FeedlyViewController.configureWith() let navigationController = UINavigationController(rootViewController: viewController) return navigationController } private func firestoreViewControllerINstansiate() -> UINavigationController { let viewController = ShopViewController.configuredWith() let navigationController = UINavigationController(rootViewController: viewController) return navigationController } private func setupTabbarController(viewControllers: [UIViewController]) { viewControllers.enumerated().forEach { (index, viewController) in switch index { case 0: setupTabbarController(viewController: viewController, selectedImage: R.image.eiSettings()!, unSelectedImage: R.image.eiSettings()!, title: "記事") case 1: setupTabbarController(viewController: viewController, selectedImage: R.image.eiSettings()!, unSelectedImage: R.image.eiSettings()!, title: "店") default: setupTabbarController(viewController: viewController, selectedImage: R.image.eiSettings()!, unSelectedImage: R.image.eiSettings()!, title: "最新情報") } } } // タブバーのアイコンサイズを設定 private func setupTabbarController(viewController: UIViewController,selectedImage: UIImage, unSelectedImage: UIImage, title: String) { viewController.tabBarItem.selectedImage = selectedImage.resize(size: .init(width: 22, height: 22))?.withRenderingMode(.alwaysOriginal) viewController.tabBarItem.image = unSelectedImage.resize(size: .init(width: 22, height: 22))?.withRenderingMode(.alwaysOriginal) viewController.tabBarItem.title = title } }
true
15443dedb0b76c8aecec08883d4233c1f414a696
Swift
Artem-Obabkov/ShoppingFinal
/Shopping/MainCollectionViewScreen/View/Cell/CollectionCell.swift
UTF-8
1,470
2.765625
3
[]
no_license
// // CollectionViewCell.swift // Shopping // // Created by pro2017 on 03/04/2021. // import UIKit // PROTOCOL TO CHANGE isFavourite IN REAL TIME protocol CollectionCellDelegate { func cardAction(cell: CollectionCell, card: MainList, indexPath: IndexPath) } class CollectionCell: UICollectionViewCell { @IBOutlet weak var button: UIButton! @IBOutlet weak var textLabel: UILabel! var card: MainList? var indexPath: IndexPath? // PASS DATA BY USING DELEGATE var delegate: CollectionCellDelegate? //let highlightedColor: UIColor = UIColor(named: "RedColorFrom")! func setupAmountOfRowsInTF() { if screenWidth >= 414 { textLabel.numberOfLines = 4 } else { textLabel.numberOfLines = 3 } } @IBAction func buttonAction(_ sender: UIButton) { if let card = card, let indexPath = indexPath { try? realm.write { card.isFavourite.toggle() } if card.isFavourite { UIView.animate(withDuration: 0.15) { self.alpha = 0 print(card.isFavourite) } } else { UIView.animate(withDuration: 0.15) { self.alpha = 1 } } self.delegate?.cardAction(cell: self, card: card, indexPath: indexPath) } } }
true
44b5aa9c8e38db07409b6ec8474cdbfd9fcf7c5d
Swift
benspratling4/SwiftAWSSignatureV4
/Sources/SwiftAWSSignatureV4/Data+Extensions.swift
UTF-8
236
2.640625
3
[]
no_license
// // File.swift // // // Created by Ben Spratling on 5/24/23. // import Foundation extension Data { func hexBytes(uppercase:Bool = false)->String { map() { String(format: (uppercase) ? "%02X" : "%02x", $0) }.reduce("", +) } }
true
c5f82668c7c0e6525dc3244510a9bce79a3348e0
Swift
Xecca/LeetCodeProblems
/268.Missing_Number.swift
UTF-8
1,823
4.09375
4
[]
no_license
// Solved by Xecca //268. Missing Number //Сomplexity: Easy //https://leetcode.com/problems/missing-number/ //---------------------------------------------------- //Runtime: 156 ms, faster than 34.57% of Swift online submissions for Missing Number. //Memory Usage: 14.5 MB, less than 26.34% of Swift online submissions for Missing Number.. //---------------------------------------------------- //Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. // //Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? //Constraints: // //n == nums.length //1 <= n <= 104 //0 <= nums[i] <= n //All the numbers of nums are unique. //---------------------------------------------------- func missingNumber(_ nums: [Int]) -> Int { var dictNums = [Int: Int]() let n = nums.count for num in nums { dictNums.updateValue(1, forKey: num) } var i = 0 while i < n { if dictNums[i] != 1 { return i } i += 1 } return n } //Example 1: // //Input: //let nums = [3,0,1] //Output: 2 //Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. //Example 2: // //Input: //let nums = [0,1] //Output: 2 //Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. //Example 3: // //Input: let nums = [9,6,4,2,3,5,7,0,1] //Output: 8 //Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. missingNumber(nums)
true
bc3c76ea26c93fbf79aac7f23854f31b922324a8
Swift
Benny-iPhone/ios_aug_2017
/2017.9.24/ProtocolorProject/ProtocolorProject/LabelViewController.swift
UTF-8
2,092
3
3
[]
no_license
// // LabelViewController.swift // ProtocolorProject // // Created by hackeru on 24/09/2017. // Copyright © 2017 hackeru. All rights reserved. // import UIKit class LabelViewController: UIViewController , ColorPickerViewControllerDelegate{ enum Mode : String{ case backgroundColor = "background" case textColor = "text" } var mode : Mode? @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func colorPickerViewControllerDidCancel(_ controller: ColorPickerViewController) { } func colorPickerViewController(_ controller: ColorPickerViewController, didSelectColor color: UIColor?) { guard let mode = mode else { return } switch mode { case .backgroundColor: label.backgroundColor = color case .textColor: label.textColor = color } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if let nextVC = segue.destination as? ColorPickerViewController, let raw = segue.identifier, let mode = Mode(rawValue: raw){ nextVC.delegate = self self.mode = mode switch mode { case .backgroundColor: nextVC.baseColor = label.backgroundColor ?? .white case .textColor: nextVC.baseColor = label.textColor } } } }
true
d17167eef226ad11dac9ff17efc3617cfd0a0d1f
Swift
fredrikCarlsson1/boardgame
/game/Design/UIButtonExtension.swift
UTF-8
1,667
2.640625
3
[]
no_license
// // UIButtonExtension.swift // game // // Created by Fredrik Carlsson on 2018-01-09. // Copyright © 2018 Fredrik Carlsson. All rights reserved. // import Foundation import UIKit extension UIButton { func pulsate(){ let pulse = CASpringAnimation(keyPath: "transform.scale") pulse.duration = 0.1 pulse.fromValue = 0.95 pulse.toValue = 1 pulse.autoreverses = true pulse.repeatCount = 1 pulse.initialVelocity = 0.5 pulse.damping = 1.0 layer.add(pulse, forKey: nil) } func pulsateSelected(){ let pulse = CASpringAnimation(keyPath: "transform.scale") pulse.duration = 0.5 pulse.fromValue = 0.75 pulse.toValue = 1.3 pulse.autoreverses = true pulse.repeatCount = 1 pulse.initialVelocity = 0.5 pulse.damping = 1.0 layer.add(pulse, forKey: nil) } func pulsateTeam(){ let pulse = CASpringAnimation(keyPath: "transform.scale") pulse.duration = 2 pulse.fromValue = 0.98 pulse.toValue = 1 pulse.autoreverses = true pulse.repeatCount = 4 pulse.initialVelocity = 0.5 pulse.damping = 1.0 layer.add(pulse, forKey: nil) } func pulsateSlow(){ let pulse = CASpringAnimation(keyPath: "transform.scale") pulse.duration = 5 pulse.fromValue = 0.97 pulse.toValue = 1 pulse.autoreverses = true pulse.repeatCount = 10 pulse.initialVelocity = 1 pulse.damping = 0.2 layer.add(pulse, forKey: nil) } }
true
de835997b916aefb3167e5a20ebcbdc8387c646a
Swift
MC1-Negroni-Orsacchiotto/RevengeBear-Negroni
/Negroni/GameOverScene.swift
UTF-8
1,074
2.59375
3
[]
no_license
import SpriteKit class GameOverScene : SKScene { var gameScene:SKScene? var playButton:SKSpriteNode? var backgroundMusic:SKAudioNode? override func didMove(to view: SKView) { playButton = self.childNode(withName: "restartButton") as? SKSpriteNode if let musicURL = Bundle.main.url(forResource: "gameOver", withExtension: "m4a") { backgroundMusic = SKAudioNode(url: musicURL) addChild(backgroundMusic!) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let pos = touch.location(in: self) let node = self.atPoint(pos) if node == playButton { let transition = SKTransition.fade(withDuration: 1) gameScene = SKScene(fileNamed: "GameScene") gameScene?.scaleMode = .aspectFit self.view?.presentScene(gameScene!, transition: transition) } } } }
true
d6e2d614fd3b97d8080dc1eac3ec920b2cee84cd
Swift
sktntn8/bullsEye
/bullsEye/ViewController.swift
UTF-8
3,423
2.84375
3
[]
no_license
// // ViewController.swift // bullsEye // // Created by Mohamed on 4/8/17. // Copyright © 2017 geekFactory. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scoureLabel: UILabel! @IBOutlet weak var roundLabel: UILabel! @IBOutlet weak var backgrounImageView: UIImageView! @IBOutlet weak var targetLable: UILabel! var currentValue = 0 var targetValue = 0 var scoure = 0 var roundValue = 1 override func viewDidLoad() { super.viewDidLoad() startNewRound() setSliderThumbs() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showAlert(_ sender: UIButton) { displayResult() } @IBOutlet weak var slider: UISlider! @IBAction func sliderMoved(_ sender: UISlider) { currentValue = lroundf(sender.value) } @IBAction func startOver(_ sender: UIButton) { scoure = 0 roundValue = 1 scoureLabel.text = "\(scoure)" roundLabel.text = "\(roundValue)" } } extension ViewController{ func startNewRound() { targetValue = 1 + Int(arc4random_uniform(100)) currentValue = 50 targetLable.text = "\(targetValue)" slider.value = Float(currentValue) } func displayResult() { let (incresedScore , userMessage) = calculateTheDefference(target: targetValue, currentValue: currentValue ) scoure = scoure + incresedScore roundValue += 1 scoureLabel.text = "\(scoure)" roundLabel.text = "\(roundValue)" let alert = UIAlertController(title: userMessage, message: "You scoures \(scoure) points" + "\n Your value is \(currentValue)" + "\n your target is \(targetValue)", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: {(action:UIAlertAction!) in self.startNewRound() }) alert.addAction(action) present(alert, animated: true, completion: nil) } func calculateTheDefference( target: Int , currentValue : Int) -> (Int , String){ let defferenceRsult = abs(target - currentValue) switch defferenceRsult { case 0 : return(100,"perfect!") case 1..<5 : return(50,"You almost had it!!") case 5..<10 : return(10,"Pretty good!") default: return(0,"Not even close.") } } func setSliderThumbs(){ let edgInstens = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) slider.setThumbImage(UIImage(named : "SliderThumb-Highlighted"), for: .highlighted) slider.setThumbImage(UIImage(named: "SliderThumb-Normal"), for: .normal) slider.setMinimumTrackImage(UIImage(named: "SliderTrackLeft")? .resizableImage(withCapInsets: edgInstens ), for: .normal) slider.setMaximumTrackImage(UIImage(named: "SliderTrackRight")? .resizableImage(withCapInsets: edgInstens ), for: .normal) } }
true
2d49ed2da1e637b45c5a72854b9b8a6194a53804
Swift
kbfromindia/Digital-Clock
/DClock/DClock/TwoDots.swift
UTF-8
1,618
2.59375
3
[]
no_license
// // TwoDots.swift // DClock // // Created by Sirak Zeray on 1/23/18. // Copyright © 2018 Sirak Zeray. All rights reserved. // import UIKit class TwoDots: UIView { @IBOutlet var TwoDotsXib: UIView! @IBOutlet weak var topView: UIView! @IBOutlet weak var bottonView: UIView! @IBOutlet weak var bottomDot: UIView! @IBOutlet weak var topDot: UIView! func disMissDots() { topDot.isHidden = true bottomDot.isHidden = true } func dotsVisable () { topDot.isHidden = false bottomDot.isHidden = false } func colorOfDots (){ let dataColor = UserDefaults.standard.value(forKey: "colorSet") let colorUI = NSKeyedUnarchiver.unarchiveObject(with: dataColor as! Data) as? UIColor topDot.backgroundColor = colorUI bottomDot.backgroundColor = colorUI } override init(frame: CGRect) { super.init(frame: frame) self.prepare() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.prepare() } func prepare() { Bundle.main.loadNibNamed("TwoDots", owner: self, options: nil) self.TwoDotsXib.frame = self.bounds self.addSubview(self.TwoDotsXib) } override func layoutSubviews() { super .layoutSubviews() makecircle() } func makecircle(){ topDot.layer.cornerRadius = topDot.frame.size.height/2 bottomDot.layer.cornerRadius = bottomDot.frame.size.height/2 } }
true
3cab882bab75e91fc8089bd20bc1d32ab15fdbe7
Swift
p-morris/LightingKit
/LightingKit/Responsibility Chains/ServiceBuilderChain.swift
UTF-8
2,356
3.4375
3
[ "MIT" ]
permissive
// // ServiceBuilderChain.swift // LightingKit // // Created by Peter Morris on 04/12/2018. // Copyright © 2018 Pete Morris. All rights reserved. // import Foundation import HomeKit /// Used to assign services to a `Light` object. protocol ServiceHandler { /** Assigns a service to `light`, based on `characteristic`. If no service is assigned, the request is passed on to `sucessor` - Parameters: - light: The `Light` object to assign a service to. - characteristic: The characteristic that controls the service. - successor: A `ServiceHandler` to pass the request to, in the event that the service is not assigned. */ func assignService(to light: Light, with characteristic: HomeKitCharacteristicProtocol?, successor: ServiceHandler?) } /// Used to assign a `Power` service to a `Light` class PowerServiceHandler: ServiceHandler { func assignService(to light: Light, with characteristic: HomeKitCharacteristicProtocol?, successor: ServiceHandler?) { guard let power = Power(homeKitCharacteristic: characteristic) else { successor?.assignService(to: light, with: characteristic, successor: nil) return } light.power = power } } /// Used to assign a `Brightness` service to a `Light` class BrightnessServiceHandler: ServiceHandler { func assignService(to light: Light, with characteristic: HomeKitCharacteristicProtocol?, successor: ServiceHandler?) { guard let brightness = Brightness(homeKitCharacteristic: characteristic) else { successor?.assignService(to: light, with: characteristic, successor: nil) return } light.brightness = brightness } } /// Used to assign services to `Light` protocol HomeKitServiceBuilder { /// The `ServiceHandler` objects to use to assign services var handlers: [ServiceHandler] { get } /** Assigns services to a `Light` based on an array of `HomeKitCharacteristicProtocol` objects. - Parameters: - light: The `Light` object to assign services to. - characteristics: The characteristics that controls the services that should be assigned. */ func assignServices(to light: Light, with characteristics: [HomeKitCharacteristicProtocol]?) }
true
2af40ba7ee640fdc44332131ce970d523f97fe88
Swift
YTiOSer/YTCollectionView
/YTCollectionView/YTCollectionView/YTCollectionView/CollectionView/protocol/YTCollectionViewSectionItemProtocol.swift
UTF-8
1,747
2.609375
3
[]
no_license
// // YTCollectionViewSectionItemProtocol.swift // YTCustomCollectionViewSwift // // Created by yt on 2021/6/22. // // sectionItem协议(UI和组装cell) import UIKit protocol YTCollectionViewSectionItemProtocol { /// section的内边距 var yt_sectionInset: UIEdgeInsets {get set} /// section的列之间的 水平方向上间距 var yt_horizontalSpacing: Int {get set} /// 同列之间间距 垂直方向上间距 var yt_verticalSpacing: Int {get set} /// section var yt_section: Int {get set} /// section的BgColor var yt_sectionBgColor: UIColor {get set} /// section的BgColorInseets var yt_sectionBgColorInset: UIEdgeInsets {get set} /// cell集合 var yt_cellItems: YTCellModelData? {get set} typealias callBackClosure = (_ indexPath: IndexPath, _ frame: CGRect) -> Void func prepareLayoutWith(collectionView: UICollectionView, topSpace: CGFloat, section: Int, attributesClosure: callBackClosure, decorationAttributeClosure: callBackClosure) func decorationView(layoutAttributes: YTCollectionViewLayoutAttributesSwift) mutating func setUp() } extension YTCollectionViewSectionItemProtocol { func prepareLayoutWith(collectionView: UICollectionView, topSpace: CGFloat, section: Int, attributesClosure: callBackClosure, decorationAttributeClosure: callBackClosure) {} func decorationView(layoutAttributes: YTCollectionViewLayoutAttributesSwift) {} func setUp() {} }
true
4691376325cbf57be76bb4cb06796e8f3b0174e6
Swift
CodeBlo/Muse
/Muse/Sources/Controllers/iTunesHelper.swift
UTF-8
9,239
2.640625
3
[]
no_license
// // iTunesHelper.swift // Muse // // Created by Marco Albera on 28/01/17. // Copyright © 2017 Edge Apps. All rights reserved. // import ScriptingBridge import iTunesLibrary // Protocol for iTunes application queries @objc fileprivate protocol iTunesApplication { // Track properties @objc optional var currentTrack: iTunesTrackProtocol { get } // Playback properties @objc optional var playerPosition: Double { get } @objc optional var playerState: iTunesEPlS { get } @objc optional var soundVolume: Int { get } @objc optional var songRepeat: iTunesERpt { get } @objc optional var shuffleEnabled: Bool { get } // Playback control functions @objc optional func playOnce(_ once: Bool) @objc optional func pause() @objc optional func playpause() @objc optional func nextTrack() @objc optional func previousTrack() @objc optional func openLocation(_ url: NSURL) // Playback properties - setters @objc optional func setPlayerPosition(_ position: Double) @objc optional func setSoundVolume (_ volume: Int) @objc optional func setSongRepeat (_ songRepeat: iTunesERpt) @objc optional func setShuffleEnabled(_ shuffleEnabled: Bool) } // Protocol for iTunes track object @objc fileprivate protocol iTunesTrackProtocol { // Track properties @objc optional var persistentID: String { get } @objc optional var location: String { get } @objc optional var name: String { get } @objc optional var artist: String { get } @objc optional var album: String { get } @objc optional var duration: Double { get } @objc optional var time: String { get } @objc optional var artworks: [iTunesArtworkProtocol] { get } @objc optional var loved: Bool { get } // Track properties - setters @objc optional func setLoved(_ loved: Bool) } // Protocol for iTunes artwork object // Every track provides an array of artworks @objc fileprivate protocol iTunesArtworkProtocol { @objc optional var data: NSImage { get } @objc optional var description: String { get } } // The iTunes library fileprivate let library = try? ITLibrary(apiVersion: "1.0") // All songs in the library fileprivate var librarySongs: [ITLibMediaItem]? { return library?.allMediaItems.filter { $0.mediaKind == .kindSong } } extension SBObject: iTunesArtworkProtocol { } // Protocols will be implemented and populated through here extension SBApplication: iTunesApplication { } class iTunesHelper: PlayerHelper, LikablePlayerHelper, InternalPlayerHelper, LikableInternalPlayerHelper, SearchablePlayerHelper, PlayablePlayerHelper, PlaylistablePlayerHelper { // SIngleton constructor static let shared = iTunesHelper() // The SBApplication object bound to the helper class private let application: iTunesApplication? = SBApplication.init(bundleIdentifier: BundleIdentifier) // MARK: Player features let doesSendPlayPauseNotification = true // MARK: Song data var song: Song { guard let currentTrack = application?.currentTrack else { return Song() } return Song(address: currentTrack.persistentID!, name: currentTrack.name!, artist: currentTrack.artist!, album: currentTrack.album!, duration: trackDuration) } // MARK: Playback controls func internalPlay() { application?.playOnce?(false) } func internalPause() { application?.pause?() } func internalTogglePlayPause() { application?.playpause?() } func internalNextTrack() { application?.nextTrack?() } func internalPreviousTrack() { application?.previousTrack?() } // MARK: Playback status var playerState: PlayerState { // Return current playback status ( R/O ) switch application?.playerState { case iTunesEPlSPlaying?: return .playing case iTunesEPlSPaused?: return .paused case iTunesEPlSStopped?: return .stopped default: // By default return stopped status return .stopped } } var playbackPosition: Double { set { // Set the position on the player application?.setPlayerPosition?(newValue) } get { // Return current playback position return application?.playerPosition ?? 0 } } var trackDuration: Double { // Return current track duration return Double(MMSSString: application?.currentTrack?.time ?? "") ?? 0 } func internalScrub(to doubleValue: Double?, touching: Bool) { if !touching, let value = doubleValue { playbackPosition = value * trackDuration } } // MARK: Playback options var volume: Int { set { // Set the volume on the player application?.setSoundVolume?(newValue) } get { // Get current volume return application?.soundVolume ?? 0 } } var internalRepeating: Bool { set { let repeating: iTunesERpt = newValue ? iTunesERptAll : iTunesERptOff // Toggle repeating on the player application?.setSongRepeat!(repeating) } get { guard let repeating = application?.songRepeat else { return false } // Return current repeating status return repeating == iTunesERptOne || repeating == iTunesERptAll } } var internalShuffling: Bool { set { // Toggle shuffling on the player application?.setShuffleEnabled?(newValue) } get { // Return current shuffling status return application?.shuffleEnabled ?? false } } // MARK: Artwork func artwork() -> Any? { // Returns the first available artwork return application?.currentTrack?.artworks?[0].data } // MARK: Starring func internalSetLiked(_ liked: Bool, completionHandler: @escaping (Bool) -> ()) { // Stars the current track application?.currentTrack?.setLoved?(liked) // Calls the handler completionHandler(liked) } var internalLiked: Bool { return application?.currentTrack?.loved ?? false } // MARK: Searching func search(title: String, completionHandler: @escaping (([Song]) -> Void)) { guard let songs = librarySongs else { return } // Search for matching tracks and asynchronously dispatch them // TODO: also evaluate match for artist and album name DispatchQueue.main.async { completionHandler(songs .filter { $0.title.lowercased().contains(title.lowercased()) } .map { $0.song }) } } // MARK: Playing func play(_ address: String) { // Build an AppleScript query to play our track // because ScriptingBridge binding for opening a file seems broken let query = "tell application \"iTunes\"\n play POSIX file \"\(address)\" \nend tell" NSAppleScript(source: query)?.executeAndReturnError(nil) } // MARK: Playlists func playlists(completionHandler: @escaping (([Playlist]) -> Void)) { guard let playlists = library?.allPlaylists else { return } // Build playlists by mapping the initializer // TODO: extend ITLib to create a converter with more properties DispatchQueue.main.async { completionHandler( playlists .filter { !$0.isMaster && $0.distinguishedKind == .kindNone } .map { $0.playlist } ) } } /** - parameter playlist: the iTunes name of the playlist */ func play(playlist: String) { // Build an AppleScript query to play our playlist let query = "tell application \"iTunes\"\n play user playlist named \"\(playlist)\" \nend tell" NSAppleScript(source: query)?.executeAndReturnError(nil) } // MARK: Application identifier static let BundleIdentifier = "com.apple.iTunes" // MARK: Notification ID static let rawTrackChangedNotification = BundleIdentifier + ".playerInfo" } extension ITLibMediaItem { // TODO: constrain protocl to mediaKindSong items var song: Song { return Song(address: self.location?.path ?? "", // TODO: check for remote tracks name: self.title, artist: self.artist?.name ?? "", album: self.album.title ?? "", duration: Double(self.totalTime)) } } extension ITLibPlaylist { var playlist: Playlist { return Playlist(id: self.persistentID.stringValue, name: self.name, count: self.items.count) } }
true
46704024aee2df1659ed71dd7518d02618accf36
Swift
chromatic-seashell/weibo
/新浪微博/新浪微博/classes/home/GDWTableViewCell.swift
UTF-8
3,393
2.796875
3
[ "Apache-2.0" ]
permissive
// // GDWTableViewCell.swift // 新浪微博 // // Created by apple on 15/11/16. // Copyright © 2015年 apple. All rights reserved. // import UIKit import SDWebImage // Swift中的枚举比OC强大很多, 可以赋值任意类型的数据, 以及可以定义方法 enum GDWTableViewIdentifier : String{ //原创 case OriginalCellIdentifier = "originalCell" //转发 case ForWardCellIdentifier = "forWardCell" static func identifierWithViewModel(viewModel:GDWStatusViewModel) -> String { return (viewModel.status.retweeted_status != nil) ? self.ForWardCellIdentifier.rawValue : self.OriginalCellIdentifier.rawValue } } class GDWTableViewCell: UITableViewCell { /// 用户头像 @IBOutlet weak var iconImageView: UIImageView! /// 会员图标 @IBOutlet weak var vipImageView: UIImageView! /// 昵称 @IBOutlet weak var nameLabel: UILabel! /// 正文 @IBOutlet weak var contentLabel: UILabel! /// 正文宽度约束 @IBOutlet weak var contentLabelWidthCons: NSLayoutConstraint! /// 来源 @IBOutlet weak var sourceLabel: UILabel! /// 时间 @IBOutlet weak var timeLabel: UILabel! /// 认证图标 @IBOutlet weak var verifiedImageView: UIImageView! /// 配图容器 @IBOutlet weak var pictureCollectionView: GDWCollectionView! /// 底部视图 @IBOutlet weak var footerView: UIView! /// 转发正文 @IBOutlet weak var forwardLabel: UILabel! /// 转发正文宽度约束 @IBOutlet weak var forwardLabelWidthCons: NSLayoutConstraint! /// 模型对象 var viewModel: GDWStatusViewModel?{ didSet{ // 1.设置头像 iconImageView.sd_setImageWithURL(viewModel?.avatarURL) // 2.认证图标 //verifiedImageView.image = viewModel?.verifiedImage // 3.昵称 nameLabel.text = viewModel?.status.user?.screen_name ?? "" //print(nameLabel.text) // 4.会员图标 vipImageView.image = viewModel?.mbrankImage // 5.时间 timeLabel.text = viewModel?.createdText ?? "" // 6.来源 sourceLabel.text = viewModel?.sourceText ?? "" // 5.正文 contentLabel.text = viewModel?.status.text ?? "" // 6.转发正文 if let temp = viewModel?.status.retweeted_status?.text { forwardLabelWidthCons.constant = UIScreen.mainScreen().bounds.size.width - 20 forwardLabel.text = temp } // 6.4给collectionView赋值 pictureCollectionView.viewModel = viewModel } } override func awakeFromNib() { super.awakeFromNib() //设置正文的宽度约束 contentLabelWidthCons.constant = UIScreen.mainScreen().bounds.size.width-20 } // MARK: - 外部控制方法 /// 计算当前行的高度 func caculateRowHeight(viewModel: GDWStatusViewModel) -> CGFloat { // 1.将数据赋值给当前cell self.viewModel = viewModel // 2.更新UI layoutIfNeeded() // 3.返回行高 return CGRectGetMaxY(footerView.frame) } }
true
7e4ee8f08ed4a99fa9422f17b5aa0a64c8f05053
Swift
ReidPritchard/launchctl_gui
/SearchBar.swift
UTF-8
679
2.875
3
[]
no_license
// // SearchBar.swift // launchctl_gui // // I DID NOT MAKE THIS SEARCH BAR // I GOT IT FROM https://mobileinvader.com/search-bar-in-swiftui/ // Just changed some little things for macOS vs iOS import SwiftUI struct SearchBar : View { @Binding var searchText: String var body: some View { HStack { TextField("Search", text: $searchText) { NSApplication.shared.windows.first { $0.isKeyWindow }?.endEditing(for: true) } .padding(.leading, 10) Button(action: { self.searchText = "" }) { Text("Clear") } }.padding(.horizontal) } }
true
53eb8d26073c3e04fde8b73824f12ec52ffa2022
Swift
EvangelinaKlyukay/DateHandler
/DateHandler/Model/Photos/ImageManager.swift
UTF-8
1,250
2.84375
3
[]
no_license
// // ImageManager.swift // DateHandler // // Created by Евангелина Клюкай on 24.04.2020. // Copyright © 2020 Евангелина Клюкай. All rights reserved. // import Foundation protocol ImageManagerDelegate: class { func photosUpdated(sender: ImageManager) } class ImageManager { weak var delegate: ImageManagerDelegate? private let network: NetworkManager init(network: NetworkManager) { self.network = network } func loadImages(album: UserAlbum!) { if album.id == nil { print("UserAlbum.id is nil") return } let albumId = album.id! self.network.request(path: "/albums/\(albumId)/photos", parameters: [:], onSuccess: { (response) in if response.count == 0 { return } var images: [UserImage] = [] response.forEach { let image: UserImage = UserImage(data: $0) images.append(image) } album.set(images: images) self.delegate?.photosUpdated(sender: self) }, onFail: { (error) in print(error.localizedDescription) }) } }
true
80037fe2e51879f54bda95f887a8da7575d00902
Swift
yosuke1985/Swift-Firestore-Guide
/FirestoreCodableSamples/Screens/MappingColorsScreen.swift
UTF-8
4,363
3.0625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // MappingColorsSCreen.swift // FirestoreCodableSamples // // Created by Peter Friese on 19.03.21. // import SwiftUI import Firebase import FirebaseFirestoreSwift class MappingColorsViewModel: ObservableObject { @Published var colorEntries = [ColorEntry]() @Published var newColor = ColorEntry.empty @Published var errorMessage: String? private var db = Firestore.firestore() private var listenerRegistration: ListenerRegistration? public func unsubscribe() { if listenerRegistration != nil { listenerRegistration?.remove() listenerRegistration = nil } } func subscribe() { if listenerRegistration == nil { listenerRegistration = db.collection("colors") .addSnapshotListener { [weak self] (querySnapshot, error) in guard let documents = querySnapshot?.documents else { self?.errorMessage = "No documents in 'colors' collection" return } self?.colorEntries = documents.compactMap { queryDocumentSnapshot in let result = Result { try queryDocumentSnapshot.data(as: ColorEntry.self) } switch result { case .success(let colorEntry): if let colorEntry = colorEntry { // A ColorEntry value was successfully initialized from the DocumentSnapshot. self?.errorMessage = nil return colorEntry } else { // A nil value was successfully initialized from the DocumentSnapshot, // or the DocumentSnapshot was nil. self?.errorMessage = "Document doesn't exist." return nil } case .failure(let error): // A Book value could not be initialized from the DocumentSnapshot. switch error { case DecodingError.typeMismatch(_, let context): self?.errorMessage = "\(error.localizedDescription): \(context.debugDescription)" case DecodingError.valueNotFound(_, let context): self?.errorMessage = "\(error.localizedDescription): \(context.debugDescription)" case DecodingError.keyNotFound(_, let context): self?.errorMessage = "\(error.localizedDescription): \(context.debugDescription)" case DecodingError.dataCorrupted(let key): self?.errorMessage = "\(error.localizedDescription): \(key)" default: self?.errorMessage = "Error decoding document: \(error.localizedDescription)" } return nil } } } } } func addColorEntry() { let collectionRef = db.collection("colors") do { let newDocReference = try collectionRef.addDocument(from: newColor) print("ColorEntry stored with new document reference: \(newDocReference)") } catch { print(error) } } } struct MappingColorsScreen: View { @StateObject var viewModel = MappingColorsViewModel() var body: some View { SampleScreen("Mapping Colors", introduction: "Mapping colors is easy once we conform Color to Codable.") { Form { Section(header: Text("Colors")) { List(viewModel.colorEntries) { colorEntry in Text("\(colorEntry.name) (\(colorEntry.color.toHex ?? ""))") .listRowBackground(colorEntry.color) .foregroundColor(colorEntry.color.accessibleFontColor) .padding(.horizontal, 4) .padding(.vertical, 2) .background(colorEntry.color) .cornerRadius(3.0) } } Section { ColorPicker(selection: $viewModel.newColor.color) { Label("First, pick color", systemImage: "paintpalette") } Button(action: viewModel.addColorEntry ) { Label("Then add it", systemImage: "plus") } } } } .onAppear() { viewModel.subscribe() } .onDisappear() { viewModel.unsubscribe() } } } struct MappingColorsScreen_Previews: PreviewProvider { static var previews: some View { Group { NavigationView { MappingColorsScreen() } NavigationView { MappingColorsScreen() } .preferredColorScheme(.dark) } } }
true
5d6829bf5e289b2b9b8ca7b0908c4faf6496d1a9
Swift
dkeise/Course_System_Manager_App
/Course System Manager/Teacher/Model/TeacherMenager.swift
UTF-8
1,150
2.9375
3
[]
no_license
// // TeacherMenager.swift // Course System Manager // // Created by Robson James Junior on 24/11/19. // Copyright © 2019 DilzanaKeise. All rights reserved. // import Foundation class TeacherManager { //Singleton Professor Gerenciador que controla os requerimentos referente ao objeto primitivo private static var privateShared: TeacherManager? private(set) var teacher: Teacher? class var shared: TeacherManager { guard let uwShared = privateShared else { privateShared = TeacherManager() return privateShared! } return uwShared } @objc class func destroy() { privateShared = nil } private init() { teacher = nil } public func getTeacher(email: String, password: String) { //solicitação da API rest RestUtils.getTeacher(email: email, password: password, completionHandler: { (teacher) in self.teacher = nil guard teacher != nil else { return } self.teacher = teacher NotificationCenter.default.post(name: .teacherChaged, object: self.teacher) }) } }
true
951a59ed2bba02983e63342921179c41b3cec2dd
Swift
CMPE137-HiFicus/Lab2
/Card.swift
UTF-8
826
3.03125
3
[]
no_license
// // Card.swift // set game // // Created by KhamTran on 9/9/19. // Copyright © 2019 KhamTran. All rights reserved. // import Foundation struct Card { let cardColor:cardColor let cardSymbol:cardSymbol let cardNumber:cardNumber let cardShade:cardShade } enum cardColor{ case red case green case blue static let allValues = [red, green, blue] } enum cardSymbol{ case triangle case circle case square static let allValue = [triangle,circle,square] } enum cardNumber{ case one case two case three static let allValues = [one,two,three] } enum cardShade { case solid case striped case open static let allValues = [solid,striped,open] }
true
04ccfd6d1713ee4c0e1c2f007f5cae3eedfd9e70
Swift
yourin/Motion
/Motion/ColorImageView.swift
UTF-8
5,903
2.71875
3
[]
no_license
// // ColorImageView.swift // Motion // // Created by youringtone on 2016/04/05. // Copyright © 2016年 youringtone. All rights reserved. // import UIKit class ColorImageView { var tag:Int = 0 var name = "" var baseView:UIView! var up:UIImageView! = UIImageView() var down:UIImageView! = UIImageView() var left:UIImageView! = UIImageView() var right:UIImageView! = UIImageView() var stop:UIImageView! = UIImageView() // var upButton:UIButton! = UIButton() // var downButton:UIButton! = UIButton() // var stopButton:UIButton! = UIButton() // var leftButton:UIButton! = UIButton() // var rightButton:UIButton! = UIButton() // init(){ self.baseView = UIView(frame:CGRect(origin: CGPointZero, size: CGSize(width: 160, height: 240))) self.baseView.userInteractionEnabled = true let square = CGRect(origin: CGPointZero, size: CGSize(width: 70, height: 75)) let longSquare = CGRect(origin: CGPointZero, size: CGSize(width: 40, height: 240)) self.up = UIImageView(frame:square) // self.upButton = UIButton(frame: square) // self.upButton.center = self.up.center // self.upButton.addTarget(self, action: Selector("actionButton:"), forControlEvents: UIControlEvents.TouchUpInside) self.stop = UIImageView(frame:square) // self.stopButton = UIButton(frame: square) self.down = UIImageView(frame:square) // self.downButton = UIButton(frame: square) self.left = UIImageView(frame: longSquare) // self.leftButton = UIButton(frame: longSquare) self.right = UIImageView(frame: longSquare) // self.rightButton = UIButton(frame: longSquare) self.up.center = CGPoint(x:80 , y: 37.5) self.stop.center = self.baseView.center self.down.center = CGPoint(x:80 , y: 202.5) self.left.center = CGPoint(x: 20, y: 120) self.right.center = CGPoint(x: 140, y: 120) self.up.backgroundColor = UIColor.greenColor() self.stop.backgroundColor = UIColor.grayColor() self.down.backgroundColor = UIColor.yellowColor() self.left.backgroundColor = UIColor.redColor() self.right.backgroundColor = UIColor.blueColor() self.baseView.addSubview(self.up) // self.up.addSubview(upButton) self.baseView.addSubview(self.down) self.baseView.addSubview(self.stop) self.baseView.addSubview(self.left) self.baseView.addSubview(self.right) } init(upColor:UIColor,downColor:UIColor,stopColor:UIColor,leftColor:UIColor,rightColor:UIColor){ self.baseView = UIView(frame:CGRect(origin: CGPointZero, size: CGSize(width: 160, height: 240))) self.baseView.userInteractionEnabled = true let square = CGRect(origin: CGPointZero, size: CGSize(width: 70, height: 75)) let longSquare = CGRect(origin: CGPointZero, size: CGSize(width: 40, height: 240)) self.up = UIImageView(frame:square) self.stop = UIImageView(frame:square) self.down = UIImageView(frame:square) self.left = UIImageView(frame:longSquare) self.right = UIImageView(frame:longSquare) self.up.center = CGPoint(x:80 , y: 37.5) self.stop.center = self.baseView.center self.down.center = CGPoint(x:80 , y: 202.5) self.left.center = CGPoint(x: 20, y: 120) self.right.center = CGPoint(x: 140, y: 120) self.up.backgroundColor = upColor// UIColor.greenColor() self.stop.backgroundColor = stopColor // UIColor.grayColor() self.down.backgroundColor = downColor // UIColor.yellowColor() self.left.backgroundColor = leftColor// UIColor.redColor() self.right.backgroundColor = rightColor// UIColor.blueColor() self.baseView.addSubview(self.up) self.baseView.addSubview(self.down) self.baseView.addSubview(self.stop) self.baseView.addSubview(self.left) self.baseView.addSubview(self.right) } init(color:UIColor){ self.baseView = UIView(frame:CGRect(origin: CGPointZero, size: CGSize(width: 80, height: 120))) self.baseView.userInteractionEnabled = true let square = CGRect(origin: CGPointZero, size: CGSize(width: 36, height: 36)) let longSquare = CGRect(origin: CGPointZero, size: CGSize(width: 20, height: 120)) self.up = UIImageView(frame:square) self.stop = UIImageView(frame:square) self.down = UIImageView(frame:square) self.left = UIImageView(frame:longSquare) self.right = UIImageView(frame:longSquare) self.up.center = CGPoint(x: 40 , y: 18) self.stop.center = self.baseView.center self.down.center = CGPoint(x: 40 , y: 120 - 18) self.left.center = CGPoint(x: 10, y: 60) self.right.center = CGPoint(x: 70, y: 60) self.up.backgroundColor = color// UIColor.greenColor() self.stop.backgroundColor = color // UIColor.grayColor() self.down.backgroundColor = color // UIColor.yellowColor() self.left.backgroundColor = color// UIColor.redColor() self.right.backgroundColor = color// UIColor.blueColor() self.baseView.addSubview(self.up) self.baseView.addSubview(self.down) self.baseView.addSubview(self.stop) self.baseView.addSubview(self.left) self.baseView.addSubview(self.right) } func actionButton(){ print(#function) } }
true
55f3a7cc56ffc761dae6bfd9c55f0e671ac114bc
Swift
Crismal/Udemy_Tarea6
/UdemyWebScrapping/Model/Article.swift
UTF-8
491
2.71875
3
[]
no_license
// // article.swift // UdemyWebScrapping // // Created by Cristian Misael Almendro Lazarte on 9/23/18. // Copyright © 2018 Cristian Misael Almendro Lazarte. All rights reserved. // import Foundation class Article { var title: String; var preview: String; var imageUrl: String; var postUrl: String; init(title: String, preview: String, imageUrl: String, postUrl: String) { self.title = title; self.preview = preview; self.imageUrl = imageUrl; self.postUrl = postUrl; } }
true
ef231cb2260135dc9012cb20f1292802a6aef07d
Swift
LexDeBash/HeadsAndHends
/HeadsAndHends/LoginPasswordTVC.swift
UTF-8
1,131
2.53125
3
[]
no_license
// // LoginPasswordTVC.swift // HeadsAndHends // // Created by Alexey Efimov on 13.07.17. // Copyright © 2017 LDB. All rights reserved. // import UIKit class LoginPasswordTVC: UITableViewController { let dataExamle = DataExample() @IBOutlet weak var loginTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() } // MARK: Работа с клавиатурой // Скрытие клавиатуры по клавише "Готово" на текстовой клавиатуре func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK: DataExample @IBAction func autorizationLogin(_ sender: UITextField) { if sender.text?.isEmpty == false { dataExamle.setLogin(sender.text!) } } @IBAction func autorizationPassword(_ sender: UITextField) { if sender.text?.isEmpty == false { dataExamle.setPassword(sender.text!) } } }
true
277f7a9af9a81c52a79dec06f72fd0e7048b7dd4
Swift
llarrynguyen/CoinApp
/CoinApp/Services/Networking/Usage/Models/Scheme.swift
UTF-8
451
3.40625
3
[]
no_license
// // Scheme.swift // CoinApp // // Created by Larry Nguyen on 7/25/21. // import Foundation public enum Scheme { case http case https case custom(scheme: String) } extension Scheme { public var stringValue: String { switch self { case .http: return "http" case .https: return "https" case .custom(let scheme): return scheme } } }
true
9d4abc07e6dad5f0c64ecd0b0851fc8d95bc29fb
Swift
Le1779/learn-ios
/Learn IOS/VIew Controllers/Bluetooth/LearnBLEScanViewController.swift
UTF-8
4,431
2.5625
3
[]
no_license
// // LearnBLEScanViewController.swift // Learn IOS // // Created by Kevin Le on 2020/1/18. // Copyright © 2020 Kevin Le. All rights reserved. // import UIKit import CoreBluetooth class LearnBLEScanViewController: UIViewController { @IBOutlet weak var scanTableView: UITableView! //藍牙管理物件 var manager: CBCentralManager! var discoveredPeripherals: [DiscoveredPeripheral] = [] class DiscoveredPeripheral{ var peripheral: CBPeripheral var rssi: NSNumber init(peripheral: CBPeripheral, rssi: NSNumber) { self.peripheral = peripheral self.rssi = rssi } } override func viewDidLoad() { super.viewDidLoad() manager = CBCentralManager.init(delegate: self, queue: DispatchQueue.main) } @IBAction func startScan(_ sender: Any) { print("Start Scan") let options = [CBCentralManagerScanOptionAllowDuplicatesKey: true] manager.scanForPeripherals(withServices: nil, options: options) } } // MARK: - TableViewController extension LearnBLEScanViewController :UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return discoveredPeripherals.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BleScanTableViewCell let peripheral = discoveredPeripherals[indexPath.row] if peripheral.peripheral.name != nil{ cell.nameLabel.text = String.init(format: "Device Name: %@", (peripheral.peripheral.name)!) } else{ cell.nameLabel.text = "No Name" } cell.addressLabel.text = peripheral.peripheral.identifier.uuidString cell.distanceLabel.text = peripheral.rssi.stringValue return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(String.init(format: "Select device Name: %@", (discoveredPeripherals[indexPath.row].peripheral.name)!)) } } // MARK: - CBCentralManager extension LearnBLEScanViewController :CBCentralManagerDelegate{ /**監聽CentralManager的狀態*/ func centralManagerDidUpdateState(_ central: CBCentralManager){ switch central.state { case .unknown: print("CBCentralManagerStateUnknown") case .resetting: print("CBCentralManagerStateResetting") case .unsupported: print("CBCentralManagerStateUnsupported") case .unauthorized: print("CBCentralManagerStateUnauthorized") case .poweredOff: print("CBCentralManagerStatePoweredOff") case .poweredOn: print("CBCentralManagerStatePoweredOn") @unknown default: print("CBCentralManagerStateUnknown") } } /**掃描到裝置*/ func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){ var isExisted = false var existedPeripheral: DiscoveredPeripheral! for obtainedPeriphal in discoveredPeripherals { if (obtainedPeriphal.peripheral.identifier == peripheral.identifier){ isExisted = true existedPeripheral = obtainedPeriphal } } if !isExisted{ discoveredPeripherals.append(DiscoveredPeripheral(peripheral: peripheral, rssi: RSSI)) } else{ existedPeripheral.rssi = RSSI } sortDiscoveredPeripherals() self.scanTableView.reloadData() //sign reload } func sortDiscoveredPeripherals(){ for i in 0..<discoveredPeripherals.count { for j in 0..<discoveredPeripherals.count - i - 1{ if(discoveredPeripherals[j].rssi.intValue < discoveredPeripherals[j + 1].rssi.intValue){ let temp = discoveredPeripherals[j] discoveredPeripherals[j] = discoveredPeripherals[j + 1] discoveredPeripherals[j + 1] = temp } } } } }
true
0f44dc8484dbdeca35e5b95f1241be3d63d5e6c3
Swift
maahi22/MNA
/MNA/ConnectionHelper/MNAConnectionHelper.swift
UTF-8
15,892
2.796875
3
[]
no_license
// // MNAConnectionHelper.swift // MNA // // Created by Apple on 29/12/17. // Copyright © 2017 KTeck. All rights reserved. // import UIKit class MNAConnectionHelper: NSObject { class func GetParam(_ params: NSDictionary) -> NSString{ var passparam : NSString! do { let jsonData = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) // here "jsonData" is the dictionary encoded in JSON data let theJSONText = NSString(data: jsonData, encoding: String.Encoding.ascii.rawValue) passparam = theJSONText! } catch let error as NSError { print("getParam() \(error)") passparam = "" } return passparam } //https://stackoverflow.com/questions/41745328/completion-handlers-in-swift-3-0 class func GetDataFromJson(url: String, paramString: [String : Any], completion: @escaping (_ success: NSDictionary , _ Status :Bool) -> Void) { print("GetDataFromJson \(url) Param \(paramString)") //@escaping...If a closure is passed as an argument to a function and it is invoked after the function returns, the closure is @escaping. var request = URLRequest(url: URL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" if(paramString != nil){ request.httpBody = self.GetParam(paramString as NSDictionary).data(using: String.Encoding.utf8.rawValue) } let task = URLSession.shared.dataTask(with: request) { Data, response, error in guard let _: Data = Data, let _: URLResponse = response, error == nil else { let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completion(dict as NSDictionary ,false) return } if error != nil{ return } do { let result = try JSONSerialization.jsonObject(with: Data!, options: []) as? [String:AnyObject] print("Result",result!) } catch { print("Error -> \(error)") } let responseStrInISOLatin = String(data: Data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) guard let modifiedDataInUTF8Format = responseStrInISOLatin?.data(using: String.Encoding.utf8) else { print("could not convert data to UTF-8 format") let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completion(dict as NSDictionary ,false) return } do { let responseJSONDict = try JSONSerialization.jsonObject(with: modifiedDataInUTF8Format) completion(responseJSONDict as! NSDictionary ,true) // print(responseJSONDict) } catch { print(error) let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completion(dict as NSDictionary ,false) } } task.resume() } class func GetDataFromJson(url: String, completion: @escaping (_ success: NSDictionary , _ Status :Bool) -> Void) { print("GetDataFromJson \(url)") var request = URLRequest(url: URL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request) { Data, response, error in guard let _: Data = Data, let _: URLResponse = response, error == nil else { let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completion(dict as NSDictionary ,false) return } let responseStrInISOLatin = String(data: Data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) guard let modifiedDataInUTF8Format = responseStrInISOLatin?.data(using: String.Encoding.utf8) else { print("could not convert data to UTF-8 format") let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completion(dict as NSDictionary ,false) return } do { let responseJSONDict = try JSONSerialization.jsonObject(with: modifiedDataInUTF8Format) completion(responseJSONDict as! NSDictionary ,true) //print(responseJSONDict) } catch { print(error) let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completion(dict as NSDictionary ,false) } } task.resume() } class func urlToImageConverter (_ imageUrl:String ,completionHandler :@escaping ( _ image :UIImage , _ Status:Bool) -> Void ){ URLSession.shared.dataTask(with: NSURL(string: imageUrl)! as URL, completionHandler: { (data, response, error) -> Void in if error != nil { print(error) completionHandler (UIImage() , false) return } let image = UIImage(data: data!) if image == nil { completionHandler (UIImage() , false) return } completionHandler (image! , true) }).resume() } class func CallAgetApiWithoutParameter (_ urlString:String ,completionHandler :@escaping ( _ success: NSDictionary , _ Status :Bool) -> Void ){ var request = URLRequest(url: URL(string: urlString)!) request.httpMethod = "GET" let session = URLSession.shared session.dataTask(with: request) {Data, response, error in guard let _: Data = Data, let _: URLResponse = response, error == nil else { let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completionHandler(dict as NSDictionary ,false) return } let responseStrInISOLatin = String(data: Data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) guard let modifiedDataInUTF8Format = responseStrInISOLatin?.data(using: String.Encoding.utf8) else { print("could not convert data to UTF-8 format") let dict :[String : AnyObject] = ["alert":"Failed" as AnyObject] completionHandler(dict as NSDictionary ,false) return } do { let responseJSONDict = try JSONSerialization.jsonObject(with: modifiedDataInUTF8Format) completionHandler(responseJSONDict as! NSDictionary ,true) //print(responseJSONDict) } catch { print(error) } }.resume() } //MNA NOtification class func GetRequestFromJson(url: String, completion: @escaping (_ success: NSArray , _ Status :Bool) -> Void) { print("GetDataFromJson \(url)") var request = URLRequest(url: URL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request) { Data, response, error in guard let _: Data = Data, let _: URLResponse = response, error == nil else { let dict : [Any] = [] completion(dict as NSArray ,false) return } let responseStrInISOLatin = String(data: Data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) guard let modifiedDataInUTF8Format = responseStrInISOLatin?.data(using: String.Encoding.utf8) else { print("could not convert data to UTF-8 format") let dict : [Any] = [] completion(dict as NSArray ,false) return } do { let responseJSONDict = try JSONSerialization.jsonObject(with: modifiedDataInUTF8Format) completion(responseJSONDict as! NSArray ,true) //print(responseJSONDict) } catch { print(error) let dict : [Any] = [] completion(dict as NSArray ,false) } } task.resume() } //Call Login class func LoginCalled(url: String, paramString: [String : Any], completion: @escaping ( _ Status :Bool) -> Void) { var request = URLRequest(url: URL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" if(paramString != nil){ request.httpBody = self.GetParam(paramString as NSDictionary).data(using: String.Encoding.utf8.rawValue) } let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let _: Data = data, let _: URLResponse = response, error == nil else { completion(false) return } if let data = data { if let stringData = String(data: data, encoding: String.Encoding.utf8) { print(stringData) //JSONSerialization if stringData == "true" { completion(true) }else{ completion(false) } } } } task.resume() } //Password change class func ChangePasswordCalled(url: String, paramString: [String : Any], completion: @escaping ( _ Message:String , _ Status:Bool) -> Void) { var request = URLRequest(url: URL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" if(paramString != nil){ request.httpBody = self.GetParam(paramString as NSDictionary).data(using: String.Encoding.utf8.rawValue) } let task = URLSession.shared.dataTask(with: request) { Data, response, error in guard let _: Data = Data, let _: URLResponse = response, error == nil else { completion("",false) return } if let data = Data { if let stringData = String(data: data, encoding: String.Encoding.utf8) { print(stringData) //JSONSerialization if stringData == "true" { completion("",true) }else{ completion("",false) } } } } task.resume() } //Call Save AnnotationOn server class func SaveAnnotationWithParam(url: String, paramString: [String : Any], completion: @escaping ( _ Status :Bool) -> Void) { var request = URLRequest(url: URL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" if(paramString != nil){ request.httpBody = self.GetParam(paramString as NSDictionary).data(using: String.Encoding.utf8.rawValue) } let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let _: Data = data, let _: URLResponse = response, error == nil else { completion(false) return } if let data = data { if let stringData = String(data: data, encoding: String.Encoding.utf8) { // print(stringData) if stringData == "Success" { completion(true) }else{ completion(false) } } } } task.resume() } //Call delete AnnotationOn server class func DeleteAnnotationWithParam(url: String, paramString: [String : Any], completion: @escaping ( _ Status :Bool) -> Void) { var request = URLRequest(url: URL(string: url)!) request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" if(paramString != nil){ request.httpBody = self.GetParam(paramString as NSDictionary).data(using: String.Encoding.utf8.rawValue) } let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let _: Data = data, let _: URLResponse = response, error == nil else { completion(false) return } if let data = data { if let stringData = String(data: data, encoding: String.Encoding.utf8) { // print(stringData) if stringData == "Success" { completion(true) }else{ completion(false) } } } } task.resume() } //Download file class func DownloadFiles(url: URL, to localUrl: URL,NewspaperId:Int, completion: @escaping (_ Status :Bool) -> ()) { //fetch annotation list from server CommonHelper.fetchServerAnnotation(NewspaperId) { (status) in print("fetchServerAnnotation \(status)") } let sessionConfig = URLSessionConfiguration.default let session = URLSession(configuration: sessionConfig) let request = URLRequest(url:url) let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in if let tempLocalUrl = tempLocalUrl, error == nil { // Success if let statusCode = (response as? HTTPURLResponse)?.statusCode { print("Success: \(statusCode)") } do { try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl) completion(true) } catch (let writeError) { print("error writing file \(localUrl) : \(writeError)") completion(false) } } else { print("Failure: %@", error?.localizedDescription); completion(false) } } task.resume() } }
true
5b68a630dbb9bed199d03a9a7bd571194306d7bc
Swift
rolisanchez/10_days_of_statistics
/Day1_2.playground/Contents.swift
UTF-8
1,840
3.5
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit import Foundation //let arrayNumber = Int("9")! //let arrayElementsString = "3 7 8 5 12 14 21 13 18" let arrayNumber = Int("6")! let arrayElementsString = "6 12 8 10 20 16" let arrayFrequenciesString = "5 4 3 2 1 5" //let arrayNumber = Int(readLine()!)! //let arrayElementsString = readLine()! //let arrayFrequenciesString = readLine()! //let arrayElements = arrayElementsString.components(separatedBy: " ").map({Int($0)!}) //let arrayFrequencies = arrayFrequenciesString.components(separatedBy: " ").map({Int($0)!}) let arrayElements = [6, 12, 8, 10, 20, 16] let arrayFrequencies = [5, 4, 3, 2, 1, 5] var dataset : [Int] = [] for index in 0..<arrayNumber { for i in 0..<arrayFrequencies[index] { dataset.append(arrayElements[index]) } } dataset.sort() // If it's odd, grab the middle element. For ex in size 9 grab the element 4 9/2 // If it's even grab the 2 middle elements. For ex in size 10 grab 4 + 5 / 2 var q1 = Int() var q2 = Int() var q3 = Int() if dataset.count % 2 == 0 { let L = dataset[0..<(dataset.count/2)] let U = dataset[(dataset.count/2)..<dataset.count].map({$0}) q2 = (dataset[(dataset.count/2)-1] + dataset[dataset.count/2])/2 if L.count % 2 == 0 { q1 = (L[(L.count/2)-1] + L[L.count/2])/2 q3 = (U[(U.count/2)-1] + U[U.count/2])/2 } else { q1 = L[(L.count/2)] q3 = U[(U.count/2)] } } else { let L = dataset[0..<(dataset.count/2)] let U = dataset[(dataset.count/2)+1..<dataset.count].map({$0}) q2 = dataset[(dataset.count/2)] if L.count % 2 == 0 { q1 = (L[(L.count/2)-1] + L[L.count/2])/2 q3 = (U[(U.count/2)-1] + U[U.count/2])/2 } else { q1 = L[(L.count/2)] q3 = U[(U.count/2)] } } print(Double(q3-q1))
true
5d9c7f512ba9903f2bf45c9efa422969569df2b8
Swift
wwCondor/Atum
/Atum/Atum/Model/Rover.swift
UTF-8
1,381
2.765625
3
[]
no_license
// // Rover.swift // Atum // // Created by Wouter Willebrands on 30/12/2019. // Copyright © 2019 Studio Willebrands. All rights reserved. // import Foundation enum Rover { case curiosity var name: String { switch self { case .curiosity: return "Curiosity" } } } enum RoverCamera { case fhaz case rhaz case mast case chemcam case mahli case mardi case navcam // Used for cameraSelectionButton var fullName: String { switch self { case .fhaz: return "Front Hazard Avoidance Camera" case .rhaz: return "Rear Hazard Avoidance Camera" case .mast: return "Mast Camera" case .chemcam: return "Chemistry and Camera Complex" case .mahli: return "Mars Hand Lens Imager" case .mardi: return "Mars Decent Imager" case .navcam: return "Navigation Camera" } } // Used for Postcard metadata var abbreviation: String { switch self { case .fhaz: return "FHAZ" case .rhaz: return "RHAZ" case .mast: return "MAST" case .chemcam: return "CHEMCAM" case .mahli: return "MAHLI" case .mardi: return "MARDI" case .navcam: return "NAVCAM" } } }
true
7b1625d1927bd02fd07b21806011df0427256496
Swift
PimDieks/GoHere-onboarding-prototype
/GoHere Onboarding/GoHere Onboarding/ViewController.swift
UTF-8
2,171
2.640625
3
[]
no_license
// // ViewController.swift // GoHere Onboarding // // Created by Pim Dieks on 17/05/2019. // Copyright © 2019 Pim Dieks. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! func updateTextView() { let text = textView.text ?? "" let policyPath = "https://www.gohere.app/assets/pdf/privacy-policy.html" let termsPath = "https://www.gohere.app/assets/pdf/terms-of-use.html" let policyRange = NSAttributedString.rangeForSubstring(string: text, target: "Privacy Policy") let termsRange = NSAttributedString.rangeForSubstring(string: text, target: "Terms of Service") let policyLink = NSAttributedString.Link(path: policyPath, range: policyRange) let termsLink = NSAttributedString.Link(path: termsPath, range: termsRange) let attributedString = NSAttributedString.makeHyperlink(for: text, links: [policyLink, termsLink]) let font = textView.font let align = textView.textAlignment textView.attributedText = attributedString textView.font = font textView.textAlignment = align } @IBAction func resetButton(_ sender: Any) { UIApplication.shared.open(URL(string: "http://www.gohere.app/")! as URL, options: [:], completionHandler: nil) } @IBAction func continueButton(_ sender: Any) { let storyboard = UIStoryboard(name: "App", bundle: nil) let mainVC = storyboard.instantiateViewController(withIdentifier: "mainVC") as! ViewController self.present(mainVC, animated: true, completion: { UserDefaults.standard.set(true, forKey: "hasLaunched") }) } @IBAction func skipButton(_ sender: Any) { let storyboard = UIStoryboard(name: "App", bundle: nil) let mainVC = storyboard.instantiateViewController(withIdentifier: "mainVC") as! ViewController self.present(mainVC, animated: true, completion: { UserDefaults.standard.set(true, forKey: "hasLaunched") }) } }
true
673c5ec85af6199653c8ab8757747cf954202bd5
Swift
Sjain020188/currency-converter
/currency-conveter/ViewController.swift
UTF-8
5,091
2.703125
3
[]
no_license
// // ViewController.swift // currency-conveter // // Created by Shruti Jain on 2020/01/24. // Copyright © 2020 Shruti Jain. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate, CurrencyManagerDelegate, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var TableView: UITableView! @IBOutlet weak var TopView: UIView! @IBOutlet weak var MiddleView: UIView! @IBOutlet weak var TargetCurrencyInput: UITextField! @IBOutlet weak var FromCurrencyInput: UITextField! @IBOutlet weak var EnteredAmount: UITextField! @IBOutlet weak var ConvertedAmount: UILabel! var TargetCurrencyPicker: UIPickerView! = UIPickerView() var FromCurrencyPicker: UIPickerView! = UIPickerView() var fromCurrencySelected = "JPY" var targetCurrencySelected = "AUD" @IBAction func ConvertButton(_ sender: Any) { if(EnteredAmount.text != ""){ currency.fetchCurrency(targetCurrencySymbol: targetCurrencySelected, fromCurrencySymbol: fromCurrencySelected) } else { EnteredAmount.placeholder = "Please enter some amount" } flip(); } var currency = CurrencyManager(); override func viewDidLoad() { super.viewDidLoad() TargetCurrencyInput.delegate = self; TargetCurrencyPicker.dataSource = self; TargetCurrencyPicker.delegate = self; TargetCurrencyPicker.tag = 2; FromCurrencyPicker.dataSource = self; FromCurrencyPicker.delegate = self; FromCurrencyPicker.tag = 1; currency.delegate = self; TargetCurrencyInput.inputView = TargetCurrencyPicker; FromCurrencyInput.inputView = FromCurrencyPicker; TableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "ReusableCell") TableView.dataSource = self; } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1; } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ return currency.currencyArray.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return currency.currencyArray[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if(pickerView.tag == 1){ FromCurrencyInput.text = currency.currencyArray[row]; fromCurrencySelected = currency.currencyArray[row]; } if(pickerView.tag == 2){ TargetCurrencyInput.text = currency.currencyArray[row]; targetCurrencySelected = currency.currencyArray[row]; currency.fetchCurrency(targetCurrencySymbol: currency.currencyArray[row], fromCurrencySymbol: fromCurrencySelected) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.endEditing(true); return true; } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { if(textField.text != ""){ return true }else{ textField.placeholder = "please enter some amount"; return false; } } func textFieldDidEndEditing(_ textField: UITextField) { } func didUpdateAmount(_ currencyManager: CurrencyManager,currency: CurrencyData){ DispatchQueue.main.async{ for (_,value) in currency.rates{ let amount = Float(self.EnteredAmount.text!) self.ConvertedAmount.text = "\(String(self.EnteredAmount.text!)) \(self.fromCurrencySelected) = \(String(value * amount!)) \(self.targetCurrencySelected)" } } } @objc func flip() { let xPositionTop = TopView.frame.origin.x let yPositionTop = TopView.frame.origin.y let widthTop = TopView.frame.size.width let heightTop = TopView.frame.size.height let xPositionMiddle = MiddleView.frame.origin.x let yPositionMiddle = MiddleView.frame.origin.y let widthMiddle = TopView.frame.size.width let heightMiddle = TopView.frame.size.height UIView.animate(withDuration: 1.0, animations: { self.TopView.frame = CGRect(x: xPositionMiddle, y: yPositionMiddle, width: widthTop, height: heightTop) self.MiddleView.frame = CGRect(x: xPositionTop, y: yPositionTop, width: widthMiddle, height: heightMiddle) }) } } extension ViewController: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = TableView.dequeueReusableCell(withIdentifier: "ReusableCell", for: indexPath) as! TableViewCell; return cell; } }
true
93fce0ccde7e86edfcd1c4dac9c2db8f5052a18a
Swift
AndresR173/ShopApp
/ShopApp/Services/ProductsService.swift
UTF-8
3,594
3.109375
3
[ "MIT" ]
permissive
// // ProductService.swift // ShopApp // // Created by Andres Felipe Rojas R. on 27/03/21. // import Foundation import Combine protocol ProductsService { func searchProducts(for key: String, offset: String, limit: String) -> AnyPublisher<SearchResponse<Product>, Error> func getCategories() -> AnyPublisher<[ProductCategory], Error> func searchProductsByCategory(_ category: String, offset: String, limit: String) -> AnyPublisher<SearchResponse<Product>, Error> } final class ProductServiceClient: ProductsService { // MARK: - Properties private let apiClient = APIClient() // MARK: - Methods /** Retrieves product catalog for a keyword - parameters: - key: Ke word, this can be more than one word - offset: Initial position (Use this parameter to the se beginning of the page) - limit: The total of elements per page */ func searchProducts(for key: String, offset: String, limit: String) -> AnyPublisher<SearchResponse<Product>, Error> { var urlComponents = Constants.Api.getBaseURLComponents() urlComponents.path = Constants.Api.Paths.products let queryString = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) urlComponents.queryItems = [ URLQueryItem(name: "q", value: queryString), URLQueryItem(name: "offset", value: offset), URLQueryItem(name: "limit", value: limit) ] guard let url = urlComponents.url else { return Fail(error: NetworkError.badRequest).eraseToAnyPublisher() } var request = URLRequest(url: url) request.httpMethod = "GET" return apiClient.run(request) .map(\.value) .eraseToAnyPublisher() } func getCategories() -> AnyPublisher<[ProductCategory], Error> { var urlComponents = Constants.Api.getBaseURLComponents() urlComponents.path = Constants.Api.Paths.categories guard let url = urlComponents.url else { return Fail(error: NetworkError.badRequest).eraseToAnyPublisher() } var request = URLRequest(url: url) request.httpMethod = "GET" return apiClient.run(request) .map(\.value) .eraseToAnyPublisher() } /** Retrieves product catalog by category - parameters: - category: Category ID - offset: Initial position (Use this parameter to the se beginning of the page) - limit: The total of elements per page */ func searchProductsByCategory(_ category: String, offset: String, limit: String) -> AnyPublisher<SearchResponse<Product>, Error> { var urlComponents = Constants.Api.getBaseURLComponents() urlComponents.path = Constants.Api.Paths.products urlComponents.queryItems = [ URLQueryItem(name: "category", value: category), URLQueryItem(name: "offset", value: offset), URLQueryItem(name: "limit", value: limit) ] guard let url = urlComponents.url else { return Fail(error: NetworkError.badRequest).eraseToAnyPublisher() } var request = URLRequest(url: url) request.httpMethod = "GET" return apiClient.run(request) .map(\.value) .eraseToAnyPublisher() } }
true
b9cab41dd094c3590e05f46a79ecd431357c867d
Swift
davidzhangxp/ios_first_baby
/first-baby/Views/HomeViewController.swift
UTF-8
4,388
2.640625
3
[]
no_license
// // HomeViewController.swift // first-baby // // Created by Max Wen on 3/10/21. // import UIKit import FirebaseAuth class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { private let tableView:UITableView = { let view = UITableView() view.register(ProductsTableViewCell.self, forCellReuseIdentifier: ProductsTableViewCell.identifier) return view }() private let searchBarButton :UIButton = { let button = UIButton() button.setTitle("Search", for: .normal) button.setTitleColor(.darkGray, for: .normal) button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) button.backgroundColor = .systemGray6 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.lightGray.cgColor return button }() var productArray:[Product] = [] var productSection = [String]() var productDictionary = [String:[Product]]() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title="Menu" tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() // Do any additional setup after loading the view. loadProducts() searchBarButton.addTarget(self, action: #selector(searchProduct), for: .touchUpInside) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.addSubview(tableView) view.addSubview(searchBarButton) searchBarButton.frame = CGRect(x: 0, y: 0, width: view.width, height: 32) tableView.frame = CGRect(x: 0, y: searchBarButton.bottom + 2, width: view.width, height: view.height - 34) } func numberOfSections(in tableView: UITableView) -> Int { return self.productSection.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return productSection[section].uppercased() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let key = self.productSection[section].uppercased() if let products = productDictionary[key]{ return products.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ProductsTableViewCell.identifier,for: indexPath) as! ProductsTableViewCell let key = self.productSection[indexPath.section].uppercased() if let products = self.productDictionary[key]{ cell.configure(with: products[indexPath.row]) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let key = self.productSection[indexPath.section].uppercased() if let products = self.productDictionary[key]{ showProductView(product: products[indexPath.row]) } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } private func loadProducts(){ FirestoreClass().downloadProductsFromFirestore { (allProducts) in self.productArray = allProducts for product in self.productArray{ let key = product.category.uppercased() if self.productDictionary[key] != nil{ self.productDictionary[key]!.append(product) }else{ self.productDictionary[key] = [product] } self.productSection = [String](self.productDictionary.keys).sorted() } self.tableView.reloadData() } } private func showProductView(product:Product){ let vc = ProductViewController() vc.product = product navigationController?.pushViewController(vc, animated: true) } @objc private func searchProduct(){ let vc = SearchProductViewController() let nav = UINavigationController(rootViewController: vc) vc.products = productArray nav.modalPresentationStyle = .fullScreen present(nav, animated: true, completion: nil) } }
true
46dad3402ee7bf663283be8dcc4bd8d4e4d33281
Swift
mludowise/Swift-Bootcamp_Project2_Carousel
/Carousel/SignInViewController.swift
UTF-8
3,766
2.53125
3
[]
no_license
// // SignInViewController.swift // Carousel // // Created by Mel Ludowise on 10/14/14. // Copyright (c) 2014 Mel Ludowise. All rights reserved. // import UIKit // Default email & password internal var userEmail = "mel@melludowise.com" internal var userPassword = "password" class SignInViewController: MoveWithKeyboardViewController, UITextFieldDelegate, UIAlertViewDelegate { @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var inputsView: UIView! @IBOutlet weak var buttonsView: UIView! @IBOutlet weak var helpText: UITextView! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! var emailAlertView : UIAlertView? var passwordAlertView : UIAlertView? override func viewDidLoad() { super.viewDidLoad() // To detect return key emailTextField.delegate = self passwordTextField.delegate = self // Don't readjust the help text automaticallyAdjustsScrollViewInsets = false setupKeyboardMovement(inputsView, buttonsView: buttonsView, helpText: helpText, navigationBar: navigationBar) } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if (alertView == emailAlertView) { emailTextField.becomeFirstResponder() } else if (alertView == passwordAlertView) { passwordTextField.becomeFirstResponder() } } func checkPassword() { if (emailTextField.text == "") { emailAlertView = UIAlertView(title: kEmailRequiredTtl, message: kEmailRequiredMsg, delegate: self, cancelButtonTitle: kOkButtonTxt) emailAlertView!.show() return } if (passwordTextField.text == "") { passwordAlertView = UIAlertView(title: kPassRequiredTtl, message: kPassRequiredMsg, delegate: self, cancelButtonTitle: kOkButtonTxt) passwordAlertView!.show() return } var alertView = UIAlertView(title: kSigningInTtl, message: nil, delegate: self, cancelButtonTitle: nil) alertView.show() delay(2, { () -> () in alertView.dismissWithClickedButtonIndex(0, animated: true) if (self.emailTextField.text == userEmail && self.passwordTextField.text == userPassword) { var imageFeedViewController = self.storyboard?.instantiateViewControllerWithIdentifier(kImageFeedNavigationControllerID) as UINavigationController self.presentViewController(imageFeedViewController, animated: true, completion: nil) } else { alertView = UIAlertView(title: kSignInFailTtl, message: kSignInFailMsg, delegate: self, cancelButtonTitle: kOkButtonTxt) alertView.show() } }) } func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField == emailTextField) { passwordTextField.becomeFirstResponder() } else { // passwordTextField checkPassword() dismissKeyboard() } return true } @IBAction func onTapGesture(sender: AnyObject) { dismissKeyboard() } @IBAction func onSwipeGesture(sender: AnyObject) { dismissKeyboard() } @IBAction func onSignInButton(sender: AnyObject) { checkPassword() } @IBAction func onBackButton(sender: AnyObject) { navigationController?.popViewControllerAnimated(true) var introViewController = navigationController?.viewControllers[0] as IntroViewController // Make sure view is scrolled to the bottom introViewController.scrollToBottom() } }
true
7e2292fb48ef342b2a6766ffab3e5c93f27db64b
Swift
daltonclaybrook/loading-views
/LoadingViews/CircleSegmentView.swift
UTF-8
5,331
2.609375
3
[]
no_license
// // CircleSegmentView.swift // LoadingViews // // Created by Dalton Claybrook on 2/12/17. // Copyright © 2017 Claybrook Software. All rights reserved. // import UIKit class CircleSegmentView: UIView { enum MaskStyle { case outward, inward } var isAnimating = false var lineWidthRange: ClosedRange<CGFloat> = (20...60) var segmentLengthRange: ClosedRange<CGFloat> = (0.05...0.1) { didSet { configureLayout() } } var rotationDuration: CFTimeInterval = 7.5 { didSet { configureLayout() } } var maskStyle = MaskStyle.outward { didSet { configureLayout() } } private var shapeLayers = [CAShapeLayer]() override var bounds: CGRect { didSet { configureLayout() } } override var intrinsicContentSize: CGSize { let size: CGFloat = 100 return CGSize(width: size, height: size) } override init(frame: CGRect) { super.init(frame: frame) clipsToBounds = false } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) clipsToBounds = false } override func didMoveToSuperview() { super.didMoveToSuperview() configureLayout() } //MARK: Public func startAnimating() { guard !isAnimating else { return } isAnimating = true createAllAnimations() } func stopAnimating() { isAnimating = false shapeLayers.forEach { $0.removeAllAnimations() } } //MARK: Private private func configureLayout() { createShapeLayersIfNecessary() let path = UIBezierPath(ovalIn: bounds) shapeLayers.forEach { $0.path = path.cgPath } layer.mask = maskStyle == .outward ? createOutwardMask() : createInwardMask() createRotateAnimation() } private func createOutwardMask() -> CALayer { let path = UIBezierPath(rect: CGRect(x: -10000, y: -10000, width: 20000, height: 20000)) path.append(UIBezierPath(ovalIn: bounds)) path.usesEvenOddFillRule = true let maskLayer = CAShapeLayer() maskLayer.fillColor = UIColor.green.cgColor maskLayer.strokeColor = nil maskLayer.path = path.cgPath maskLayer.fillRule = kCAFillRuleEvenOdd return maskLayer } private func createInwardMask() -> CALayer { let path = UIBezierPath(ovalIn: bounds) let maskLayer = CAShapeLayer() maskLayer.fillColor = UIColor.green.cgColor maskLayer.strokeColor = nil maskLayer.path = path.cgPath return maskLayer } private func createAllAnimations() { shapeLayers.forEach { self.createAnimation(for: $0, fromValue: $0.lineWidth) } } private func createAnimation(for shapeLayer: CAShapeLayer, fromValue: CGFloat) { let toValue = randomLineWidth() CATransaction.begin() CATransaction.setCompletionBlock { [weak self, weak shapeLayer] in guard let strongSelf = self, let shapeLayer = shapeLayer, strongSelf.isAnimating else { return } strongSelf.createAnimation(for: shapeLayer, fromValue: toValue) } let animation = CABasicAnimation(keyPath: "lineWidth") animation.fromValue = fromValue animation.toValue = toValue animation.duration = CFTimeInterval(arc4random_uniform(1000) + 500) / 1000.0 // 0.5 - 1.5 shapeLayer.lineWidth = toValue shapeLayer.add(animation, forKey: nil) CATransaction.commit() } private func createRotateAnimation() { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0.0 animation.toValue = CGFloat.pi * 2.0 animation.duration = rotationDuration animation.repeatCount = .greatestFiniteMagnitude layer.removeAnimation(forKey: "rotation") layer.add(animation, forKey: "rotation") } private func createShapeLayersIfNecessary() { guard shapeLayers.count == 0 else { return } var lengthRemaining: CGFloat = 1.0 while lengthRemaining > 0.0 { var length = randomSegmentLength() length = min(length, lengthRemaining) let epsilon: CGFloat = 0.005 let shape = CAShapeLayer() shape.strokeStart = 1.0 - lengthRemaining + epsilon shape.strokeEnd = shape.strokeStart + length - epsilon shape.fillColor = nil shape.strokeColor = UIColor.black.cgColor shape.lineWidth = randomLineWidth() shape.lineCap = kCALineCapButt layer.addSublayer(shape) shapeLayers.append(shape) lengthRemaining -= length } } private func randomLineWidth() -> CGFloat { return CGFloat(arc4random_uniform(UInt32(lineWidthRange.upperBound-lineWidthRange.lowerBound))) + lineWidthRange.lowerBound } private func randomSegmentLength() -> CGFloat { let largeUpper = UInt32(segmentLengthRange.upperBound * 1000) let largeLower = UInt32(segmentLengthRange.lowerBound * 1000) let largeLength = arc4random_uniform(largeUpper-largeLower) + largeLower return CGFloat(largeLength) / 1000.0 } }
true
8960a880459bdef303a8e8ea4350ef4f401c57f4
Swift
flywo/SwiftKnowledgePoint
/30特性.playground/Contents.swift
UTF-8
573
2.84375
3
[]
no_license
//: Playground - noun: a place where people can play import UIKit //声明特性:只能用于声明 /* available:表名特定版本可用 unavailable:特定版本无效 introduced:从哪一版本开始引入声明 deprecated:哪一版本开始弃用 obsoleted:哪一版本废弃,不能使用 message:提供文本信息,当使用被弃用或废弃声明时,编译器会抛出警告或错误 renamed:提供文本信息,表示被重命名的声明和新的名字,使用旧的名字时,会报出新的名字 renamed和unavailable可以组合使用 */
true
538b90984e27fe6e80f526a3019960b7188f6faa
Swift
AlleniCode/Zesame
/Carthage/Checkouts/JSONRPCKit/Tests/JSONRPCKitTests/BatchFactoryTests.swift
UTF-8
7,680
2.609375
3
[ "MIT" ]
permissive
// // BatchFactoryTests.swift // JSONRPCKit // // Created by ishkawa on 2016/07/29. // Copyright © 2016年 Shinichiro Oba. All rights reserved. // import XCTest import JSONRPCKit import Dispatch private struct TestRequest: Request { typealias Response = Int var method: String var parameters: Encodable? init(method: String, parameters: Encodable?) { self.method = method self.parameters = parameters } } class BatchFactoryTests: XCTestCase { var batchFactory: BatchFactory! override func setUp() { super.setUp() batchFactory = BatchFactory() } func test1() { let request = TestRequest(method: "method", parameters: ["key": "value"]) let batch = batchFactory.create(request) XCTAssertEqual(batch.batchElement.id?.value as? Int, 1) } func testEncode1() { let request = TestRequest(method: "method", parameters: ["key": "value"]) let request2 = TestRequest(method: "method2", parameters: ["key2": "value2"]) let batch = batchFactory.create(request, request2) let encoder = JSONEncoder() guard let data = try? encoder.encode(batch) else { XCTFail() return } let jsonString = String(data: data, encoding: .utf8) XCTAssertTrue(jsonString?.contains("\"id\":1") ?? false) XCTAssertTrue(jsonString?.contains("\"jsonrpc\":\"2.0\"") ?? false) XCTAssertTrue(jsonString?.contains("\"method\":\"method\"") ?? false) XCTAssertTrue(jsonString?.contains("\"params\":{\"key\":\"value\"}") ?? false) XCTAssertTrue(jsonString?.contains("\"id\":2") ?? false) XCTAssertTrue(jsonString?.contains("\"method\":\"method2\"") ?? false) XCTAssertTrue(jsonString?.contains("\"params\":{\"key2\":\"value2\"}") ?? false) } func testEncode2() { let request = TestRequest(method: "method", parameters: ["key": "value"]) let batch = batchFactory.create(request) let encoder = JSONEncoder() guard let data = try? encoder.encode(batch) else { XCTFail() return } let jsonString = String(data: data, encoding: .utf8) XCTAssertTrue(jsonString?.contains("\"id\":1") ?? false) XCTAssertTrue(jsonString?.contains("\"jsonrpc\":\"2.0\"") ?? false) XCTAssertTrue(jsonString?.contains("\"method\":\"method\"") ?? false) XCTAssertTrue(jsonString?.contains("\"params\":{\"key\":\"value\"}") ?? false) } func test2() { let request1 = TestRequest(method: "method1", parameters: ["key1": "value1"]) let request2 = TestRequest(method: "method2", parameters: ["key2": "value2"]) let batch = batchFactory.create(request1, request2) XCTAssertEqual(batch.batchElement1.id?.value as? Int, 1) XCTAssertEqual(batch.batchElement2.id?.value as? Int, 2) } func test3() { let request1 = TestRequest(method: "method1", parameters: ["key1": "value1"]) let request2 = TestRequest(method: "method2", parameters: ["key2": "value2"]) let request3 = TestRequest(method: "method3", parameters: ["key3": "value3"]) let batch = batchFactory.create(request1, request2, request3) XCTAssertEqual(batch.batchElement1.id?.value as? Int, 1) XCTAssertEqual(batch.batchElement2.id?.value as? Int, 2) XCTAssertEqual(batch.batchElement3.id?.value as? Int, 3) } func test4() { let request1 = TestRequest(method: "method1", parameters: ["key1": "value1"]) let request2 = TestRequest(method: "method2", parameters: ["key2": "value2"]) let request3 = TestRequest(method: "method3", parameters: ["key3": "value3"]) let request4 = TestRequest(method: "method4", parameters: ["key4": "value4"]) let batch = batchFactory.create(request1, request2, request3, request4) XCTAssertEqual(batch.batchElement1.id?.value as? Int, 1) XCTAssertEqual(batch.batchElement2.id?.value as? Int, 2) XCTAssertEqual(batch.batchElement3.id?.value as? Int, 3) XCTAssertEqual(batch.batchElement4.id?.value as? Int, 4) } func test5() { let request1 = TestRequest(method: "method1", parameters: ["key1": "value1"]) let request2 = TestRequest(method: "method2", parameters: ["key2": "value2"]) let request3 = TestRequest(method: "method3", parameters: ["key3": "value3"]) let request4 = TestRequest(method: "method4", parameters: ["key4": "value4"]) let request5 = TestRequest(method: "method5", parameters: ["key5": "value5"]) let batch = batchFactory.create(request1, request2, request3, request4, request5) XCTAssertEqual(batch.batchElement1.id?.value as? Int, 1) XCTAssertEqual(batch.batchElement2.id?.value as? Int, 2) XCTAssertEqual(batch.batchElement3.id?.value as? Int, 3) XCTAssertEqual(batch.batchElement4.id?.value as? Int, 4) XCTAssertEqual(batch.batchElement5.id?.value as? Int, 5) } func test5Response() { let request1 = TestRequest(method: "method1", parameters: ["key1": "value1"]) let request2 = TestRequest(method: "method2", parameters: ["key2": "value2"]) let request3 = TestRequest(method: "method3", parameters: ["key3": "value3"]) let request4 = TestRequest(method: "method4", parameters: ["key4": "value4"]) let request5 = TestRequest(method: "method5", parameters: ["key5": "value5"]) let batch = batchFactory.create(request1, request2, request3, request4, request5) XCTAssertEqual(batch.batchElement1.id?.value as? Int, 1) XCTAssertEqual(batch.batchElement2.id?.value as? Int, 2) XCTAssertEqual(batch.batchElement3.id?.value as? Int, 3) XCTAssertEqual(batch.batchElement4.id?.value as? Int, 4) XCTAssertEqual(batch.batchElement5.id?.value as? Int, 5) let responseArray = """ [ { "id": 2, "jsonrpc": "2.0", "result": 2, }, { "id": 3, "jsonrpc": "2.0", "result": 3, }, { "id": 1, "jsonrpc": "2.0", "result": 1, }, { "id": 5, "jsonrpc": "2.0", "result": 5, }, { "id": 4, "jsonrpc": "2.0", "result": 4, } ] """ let responses = try? batch.responses(from: responseArray.data(using: .utf8)!) XCTAssertEqual(responses?.0, 1) XCTAssertEqual(responses?.1, 2) XCTAssertEqual(responses?.2, 3) XCTAssertEqual(responses?.3, 4) XCTAssertEqual(responses?.4, 5) } func testThreadSafety() { let operationQueue = OperationQueue() for _ in 1..<10000 { operationQueue.addOperation { let request = TestRequest(method: "method", parameters: nil) _ = self.batchFactory.create(request) } } operationQueue.waitUntilAllOperationsAreFinished() let nextId = batchFactory.idGenerator.next().value as? Int XCTAssertEqual(nextId, 10000) } static var allTests = [ ("test1", test1), ("testEncode1", testEncode1), ("testEncode2", testEncode2), ("test2", test2), ("test3", test3), ("test4", test4), ("test5", test5), ("test5Response", test5Response), ("testThreadSafety", testThreadSafety), ] }
true
3260443581997b48752746837c508aac372691ae
Swift
usman-tahir/rubyeuler
/assign_y.swift
UTF-8
323
3.9375
4
[]
no_license
// http://programmingpraxis.com/2015/07/03/assign-y/ // assign a to y if x == 0 // assign b to y if x == 1 func assignY(x: Int, a: Int, b: Int) -> Int { let options:[Int] = [a,b] let y = options[x] return y } let exampleOne = assignY(1,12,6) let exampleTwo = assignY(0,12,6) println(exampleOne) println(exampleTwo)
true
019d81282b81eb4745b33ebcf9fd00597252ba0e
Swift
Jman012/jlsftp
/Sources/jlsftp/Packets/Replies/NameReplyPacket.swift
UTF-8
1,149
2.8125
3
[]
no_license
import Foundation /** Returns the requested file or folder name(s). - Tag: NameReplyPacket - Since: sftp v3 */ public struct NameReplyPacket: BasePacket, Equatable { public struct Name: Equatable { /** The relative or absolute name of a file or folder within the requested directory, depending on the request. - Since: sftp v3 */ public let filename: String /** An undefined string representation of the file or folder, for display purposes. - Since: sftp v3 - Note: This should not be attempted to be parsed. The recommended format of this string is: ``` -rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer 1234567890 123 12345678 12345678 12345678 123456789012 ``` */ public let longName: String /** The file attributes of the file or folder. - Since: sftp v3 */ public let fileAttributes: FileAttributes } /** Request identifier. - Since: sftp v3 */ public let id: PacketId /** The list of requested names. - Since: sftp v3 */ public let names: [Name] public init(id: PacketId, names: [Name]) { self.id = id self.names = names } }
true
0df4df405128539b1f3632265a7c309accb4d78e
Swift
siphty/ADSB-Radar-iOS
/Siphty Extensions/String/Scanner+.swift
UTF-8
695
3.015625
3
[]
no_license
// // Scanner+.swift // EmailParser // // Created by ERNESTO on 25/09/2016. // Copyright © 2016 Hai Nguyen. All rights reserved. // import Foundation extension Scanner { func scanUpToCharactersFrom(_ set: CharacterSet) -> String? { var result: NSString? // 1. return scanUpToCharacters(from: set, into: &result) ? (result as? String) : nil // 2. } func scanUpTo(_ string: String) -> String? { var result: NSString? return self.scanUpTo(string, into: &result) ? (result as? String) : nil } func scanDouble() -> Double? { var double: Double = 0 return scanDouble(&double) ? double : nil } }
true
7c3bff2e11f2a78997e354be59aa221a010b6eaa
Swift
jsq89/Actividad2---Velocimetro
/Velocimetro.playground/Contents.swift
UTF-8
1,887
4
4
[]
no_license
// Actividad 2 - Velocimetro import UIKit // ------------------------ Bloque Enumeración Velocidades -------------------------// enum Velocidades : Int { case Apagado = 0, VelocidadBaja = 20, VelocidadMedia = 50, VelocidadAlta = 120 init (velocidadInicial : Velocidades){ self = velocidadInicial } } // ------------------------------- Bloque Clase Auto -------------------------------// class Auto { var velocidad : Velocidades init() { self.velocidad = Velocidades(velocidadInicial: Velocidades.Apagado) } func cambioDeVelocidad() -> (actual : Int, velocidadEnCadena : String){ let velocidadActual : Int = self.velocidad.rawValue let velocidadActualEnCadena : String switch (self.velocidad.hashValue){ case 0: velocidadActualEnCadena = "Apagado" self.velocidad = Velocidades.VelocidadBaja case 1: velocidadActualEnCadena = "Velocidad baja" self.velocidad = Velocidades.VelocidadMedia case 2: velocidadActualEnCadena = "Velocidad media" self.velocidad = Velocidades.VelocidadAlta case 3: velocidadActualEnCadena = "Velocidad alta" self.velocidad = Velocidades.VelocidadMedia default: // En caso de error pondremos apagado el velocimetro velocidadActualEnCadena = "Apagado" self.velocidad = Velocidades.Apagado } return (velocidadActual, velocidadActualEnCadena) } } // ---------------------------------- Bloque Pruebas ----------------------------------// var auto : Auto = Auto() var velocidadActual : Int var velocidadActualEnCadena : String for i in 1...20 { (velocidadActual,velocidadActualEnCadena)=auto.cambioDeVelocidad() print("\(velocidadActual) , \(velocidadActualEnCadena)") }
true
13c48ed42c448d07f94c762bcdff2688412dbad8
Swift
stabuev/callgov
/ios/CallGov/models/PaperModel.swift
UTF-8
947
2.5625
3
[]
no_license
// // PaperModel.swift // CallGov // // Created by Zaur Kasaev on 28/07/2019. // Copyright © 2019 callgov. All rights reserved. // import Foundation class PaperModel { var id : Int64 var title : String var content : String var name : String var public1 : String var state : String var address : String var dtreg : String var dtlast : String var signatures : String var userSign : String init(id:Int64,title:String,content:String, name:String, public1:String, state:String, address:String, dtreg:String, dtlast:String, signatures : String, userSign : String) { self.id = id self.title = title self.content = content self.name = name self.public1 = public1 self.state = state self.address = address self.dtreg = dtreg self.dtlast = dtlast self.signatures = signatures self.userSign = userSign } }
true
eab4f92f3cd20b6a742fa1438b6af0a367b76b80
Swift
ssjtin/MemeMachine
/MemeMachine/Extension/UIImageView_Extension.swift
UTF-8
828
2.578125
3
[]
no_license
// // UIImageView_Extension.swift // MemeMachine // // Created by Hoang Luong on 5/4/19. // Copyright © 2019 Hoang Luong. All rights reserved. // import UIKit extension UIImageView { func getImageFromVisibleContext() -> UIImage { // UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.main.scale) // self.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: self.bounds.size), afterScreenUpdates: true) // let image = UIGraphicsGetImageFromCurrentImageContext() // UIGraphicsEndImageContext() // // return image let renderer = UIGraphicsImageRenderer(size: self.bounds.size) let image = renderer.image { ctx in self.drawHierarchy(in: self.bounds, afterScreenUpdates: true) } return image } }
true
b240f0118fc46ab3fd30750da8c93dafffbc56e0
Swift
MrAntu/Swift-UI-Kit
/Demos/Chainable/Demo/ChainableDemo/DemoVCs/TextFieldVC.swift
UTF-8
2,017
3.125
3
[ "MIT" ]
permissive
// // TextFieldVC.swift // ChainableDemo // // Created by weiwei.li on 2019/1/10. // Copyright © 2019 dd01.leo. All rights reserved. // import UIKit class TextFieldVC: UIViewController { @IBOutlet weak var input1: UITextField! @IBOutlet weak var input2: UITextField! override func viewDidLoad() { super.viewDidLoad() // input1 不需要设置代理 //支持最大长度限制 // 支持所有代理协议回调 // 支持输入抖动动画 //通过系统方法设置代理,只走协议方法 //不会走链式block回调 input1.placeholder("我是input1") .addShouldBegindEditingBlock { (field) -> (Bool) in return true } .addShouldChangeCharactersInRangeBlock { (field, range, text) -> (Bool) in print("input1: \(text)") return true } .maxLength(5) .shake(true) //通过系统方法设置代理,只走协议方法 //不会走链式block回调 input2.placeholder("我是input2") .addShouldBegindEditingBlock({ (input) -> (Bool) in print("不会调用") return false }) .addShouldChangeCharactersInRangeBlock { (input, range, text) -> (Bool) in print("input2:不会调用调我:\(text)") return true } .delegate = self } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } deinit { print(self) } } extension TextFieldVC: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField.isEqual(input2) { print("input2:调代理方法: \(string)") return true } return false } }
true
25fe94f1ead01144ddcdbbb94161e3e71c8f36ec
Swift
zip520123/Sample-TDD-iOS-app
/Movies/ViewController.swift
UTF-8
2,433
2.640625
3
[]
no_license
// // ViewController.swift // Movies // // Created by zip520123 on 2019/9/12. // Copyright © 2019 zip520123. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let tableView = UITableView() let moviesListPresenter = { () -> MoviesListPresenter in let listModel = MoviesListModel(networkLayer: Network()) let presenter = MoviesListPresenter(moviesListModel: listModel) return presenter }() override func viewDidLoad() { super.viewDidLoad() setupTableView() setupBinding() moviesListPresenter.fetchMovies() } func setupTableView() { view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1).isActive = true tableView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1).isActive = true tableView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true tableView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self) } func setupBinding() { moviesListPresenter.didFetchMovies = { [weak self] in DispatchQueue.main.async { self?.tableView.reloadData() } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return moviesListPresenter.moviesCount() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeue(UITableViewCell.self, indexPath: indexPath) let cell = UITableViewCell(style: .subtitle, reuseIdentifier: String(describing: UITableViewCell.self)) cell.textLabel?.text = moviesListPresenter.movieName(index: indexPath.row) cell.detailTextLabel?.text = moviesListPresenter.moviesRatting(index: indexPath.row) return cell } } extension UITableView { func register<T : UITableViewCell>(_ :T.Type) { let id = String(describing: T.self) register(T.self, forCellReuseIdentifier: id) } func dequeue<T: UITableViewCell>(_ : T.Type, indexPath: IndexPath) -> T { let id = String(describing: T.self) guard let cell = dequeueReusableCell(withIdentifier: id, for: indexPath) as? T else { return T.init() } return cell } }
true
a00f2c52cb42c7be6022908049ffcfb61b2866fd
Swift
ArcticBsq/ModernAutoLayout
/Chapter 8/Lessons/Stack and Layout Priorities in Code/Stack and Layout Priorities in Code/ViewController.swift
UTF-8
4,870
2.921875
3
[]
no_license
// // ViewController.swift // Stack and Layout Priorities in Code // // Created by Илья Москалев on 28.05.2021. // import UIKit class ViewController: UIViewController { // private enum ViewMetrics { // static let margin: CGFloat = 20.0 // static let nameFontSize: CGFloat = 18.0 // static let bioFontSize: CGFloat = 17.0 // } // // // private let nameLabel: UILabel = { // let label = UILabel() // label.font = UIFont.boldSystemFont(ofSize: ViewMetrics.nameFontSize) // label.numberOfLines = 0 // label.setContentHuggingPriority(.defaultLow + 1, for: .vertical) // return label // }() // // // private let profileImageView: UIImageView = { // let imageView = UIImageView() // imageView.contentMode = .top // imageView.setContentHuggingPriority(.defaultLow + 1, for: .horizontal) // return imageView // }() // // private let bioLabel: UILabel = { // let label = UILabel() // label.font = UIFont.systemFont(ofSize: ViewMetrics.bioFontSize) // label.numberOfLines = 0 // return label // }() // // private lazy var labelStackView: UIStackView = { // let stackView = UIStackView(arrangedSubviews: [nameLabel, bioLabel]) // stackView.axis = .vertical // stackView.spacing = UIStackView.spacingUseSystem // return stackView // }() // // private lazy var profileStackView: UIStackView = { // let stackView = UIStackView(arrangedSubviews: [profileImageView, labelStackView]) // stackView.translatesAutoresizingMaskIntoConstraints = false // stackView.spacing = UIStackView.spacingUseSystem // return stackView // }() // // override func viewDidLoad() { // super.viewDidLoad() // // Do any additional setup after loading the view. // setupView() // } // // func setupView() { // view.directionalLayoutMargins = NSDirectionalEdgeInsets(top: ViewMetrics.margin, leading: ViewMetrics.margin, bottom: ViewMetrics.margin, trailing: ViewMetrics.margin) // view.addSubview(profileStackView) // // let margin = view.layoutMarginsGuide // // NSLayoutConstraint.activate([ // profileStackView.leadingAnchor.constraint(equalTo: margin.leadingAnchor), // profileStackView.topAnchor.constraint(equalTo: margin.topAnchor), // profileStackView.trailingAnchor.constraint(equalTo: margin.trailingAnchor) // ]) // } private enum ViewMetrics { static let margin: CGFloat = 20.0 static let nameFontSize: CGFloat = 18.0 static let bioFontSize: CGFloat = 17.0 } private let nameLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: ViewMetrics.nameFontSize) label.numberOfLines = 0 label.text = "Sue Appleseed" label.setContentHuggingPriority(.defaultLow + 1, for: .vertical) return label }() private let bioLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: ViewMetrics.bioFontSize) label.text = "Deep sea diver. Donut maker. Tea drinker." label.numberOfLines = 0 return label }() private let profileImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .top imageView.image = UIImage(named: "profile") imageView.setContentHuggingPriority(.defaultLow + 1, for: .horizontal) return imageView }() private lazy var labelStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [nameLabel, bioLabel]) stackView.axis = .vertical stackView.spacing = UIStackView.spacingUseSystem return stackView }() private lazy var profileStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [profileImageView, labelStackView]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.spacing = UIStackView.spacingUseSystem return stackView }() override func viewDidLoad() { super.viewDidLoad() setupView() configureView() } private func setupView() { view.directionalLayoutMargins = NSDirectionalEdgeInsets(top: ViewMetrics.margin, leading: ViewMetrics.margin, bottom: ViewMetrics.margin, trailing: ViewMetrics.margin) view.addSubview(profileStackView) let margin = view.layoutMarginsGuide NSLayoutConstraint.activate([ profileStackView.leadingAnchor.constraint(equalTo: margin.leadingAnchor), profileStackView.topAnchor.constraint(equalTo: margin.topAnchor), profileStackView.trailingAnchor.constraint(equalTo: margin.trailingAnchor) ]) } private func configureView() { } }
true
5d2f20bf21a68421ee246fcf49229a4e639bbb9b
Swift
guillermomuntaner/GLCodeReview
/GLCodeReview/Classes/MergeRequests/GitLabAPI+MergeRequest.swift
UTF-8
4,896
2.515625
3
[ "MIT" ]
permissive
// // GitLabAPI+MergeRequest.swift // GLCodeReview // // Created by Guillermo Muntaner Perelló on 27/09/2018. // import Foundation extension GitLabAPI { // MARK: - Merge requests public static func getMergeRequests( state: MergeRequest.State? = nil, sort: Sort = .descending, orderBy: OrderBy = .updatedAt) -> Endpoint<[MergeRequest]> { return Endpoint<[MergeRequest]>( path: "api/v4/merge_requests?sort=\(sort.rawValue)&order_by=\(orderBy.rawValue)") } public static func getMergeRequests( inProjectWithId projectId: Int, state: MergeRequest.State? = nil, sort: Sort = .descending, orderBy: OrderBy = .updatedAt) -> Endpoint<[MergeRequest]> { return Endpoint<[MergeRequest]>( path: "api/v4/projects/\(projectId)/merge_requests?sort=\(sort.rawValue)&order_by=\(orderBy.rawValue)") } /// Shows information about a single merge request. /// /// - Note: /// The changes_count value in the response is a string, not an integer. This is because when an MR has too many changes to display and store, it will be capped at 1,000. In that case, the API will return the string "1000+" for the changes count. /// /// [Wiki docs](https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr) /// /// - Parameters: /// - projectId: The ID of the project owned by the authenticated user. /// - mergeRequestIid: The internal ID of the merge request /// - render_html: (optional) - If true response includes rendered HTML for title and description /// - Returns: The detailed merge request. public static func getSingleMergeRequest( inProjectWithId projectId: Int, mergeRequestIid: Int, render_html: Bool?) -> Endpoint<[MergeRequestDetails]> { return Endpoint<[MergeRequestDetails]>( path: "api/v4/projects/\(projectId)/merge_requests\(mergeRequestIid)") } // MARK: - Changes /// Shows information about the merge request including its files and changes. /// /// [Wiki docs](https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr-changes) /// /// - Parameters: /// - projectId: The ID of the project owned by the authenticated user. /// - mergeRequestIid: The internal ID of the merge request /// - Returns: The merge request information with a list of changes. public static func getMergeRequestChanges( inProjectWithId projectId: Int, mergeRequestIid: Int) -> Endpoint<MergeRequestChanges> { return Endpoint<MergeRequestChanges>( path: "api/v4//projects/\(projectId)/merge_requests/\(mergeRequestIid)/changes") } // MARK: - Versions /// Get a list of merge request diff versions. /// /// [Wiki docs](https://docs.gitlab.com/ee/api/merge_requests.html#get-mr-diff-versions) /// /// - Parameters: /// - projectId: The ID of the project owned by the authenticated user. /// - mergeRequestIid: The internal ID of the merge request. /// - Returns: The configured endpoint instance. public static func getMergeRequestVersions( inProjectWithId projectId: Int, mergeRequestIid: Int) -> Endpoint<[Version]> { return Endpoint<[Version]>( path: "api/v4/projects/\(projectId)/merge_requests/\(mergeRequestIid)/versions") } /// Get a single MR diff version. /// /// [Wiki docs](https://docs.gitlab.com/ee/api/merge_requests.html#get-a-single-mr-diff-version) /// /// - Parameters: /// - projectId: The ID of the project owned by the authenticated user. /// - mergeRequestIid: The internal ID of the merge request. /// - versionId: The ID of the merge request diff version. /// - Returns: The configured endpoint instance. public static func getMergeRequestVersion( inProjectWithId projectId: Int, mergeRequestIid: Int, versionId: Int) -> Endpoint<VersionDetails> { return Endpoint<VersionDetails>( path: "api/v4//projects/\(projectId)/merge_requests/\(mergeRequestIid)/versions/\(versionId)") } // MARK: - Commits /// Get a list of merge request commits. /// /// [Wiki docs](https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr-commits) /// /// - Parameters: /// - projectId: The ID of the project owned by the authenticated user. /// - mergeRequestIid: The internal ID of the merge request. /// - Returns: The configured endpoint instance. public static func getMergeRequestCommits( inProjectWithId projectId: Int, mergeRequestIid: Int) -> Endpoint<[Commit]> { return Endpoint<[Commit]>( path: "api/v4//projects/\(projectId)/merge_requests/\(mergeRequestIid)/commits") } }
true
c36581f9fe425877f9f776463a92ca72f8b743d8
Swift
KenEucker/jackpine-biketag-ios
/src/BikeTag/Models/ApiKey.swift
UTF-8
1,532
2.890625
3
[]
no_license
import Foundation private var currentApiKey: ApiKey? class ApiKey { let clientId: String let secret: String let userId: Int class func getCurrentApiKey() -> ApiKey? { return currentApiKey } required init(attributes: [String: Any]) { clientId = attributes["client_id"] as! String secret = attributes["secret"] as! String userId = attributes["user_id"] as! Int } class func setCurrentApiKey(apiKeyAttributes: [String: Any]) { currentApiKey = ApiKey(attributes: apiKeyAttributes) UserDefaults.setApiKey(apiKeyAttributes: apiKeyAttributes) } class func ensureApiKey(successCallback: @escaping () -> Void, errorCallback: @escaping (Error) -> Void) { if getCurrentApiKey() != nil { return successCallback() } let sucessWithApiKey = { (apiKeyAttributes: [String: Any]) -> Void in ApiKey.setCurrentApiKey(apiKeyAttributes: apiKeyAttributes) successCallback() } if let apiKeyAttributes = UserDefaults.apiKey() { Logger.info("Found existing API Key") sucessWithApiKey(apiKeyAttributes) } else { Logger.info("Creating new API Key") let handleFailure = { (error: Error) -> Void in Logger.error("Error setting API Key: \(error)") errorCallback(error) } ApiKeysService().createApiKey(callback: sucessWithApiKey, errorCallback: handleFailure) } } }
true
eed056ac35f0ca52c780647ca89b7c2716152729
Swift
jayjac/OnTheMap
/OnTheMap/src/LocationListViewController.swift
UTF-8
1,825
2.625
3
[]
no_license
// // LocationListViewController.swift // OnTheMap // // Created by Jean-Yves Jacaria on 26/09/2017. // Copyright © 2017 Jean-Yves Jacaria. All rights reserved. // import UIKit class LocationListViewController: UIViewController { @IBOutlet weak var listTableView: UITableView! let cellReuseIdentifier = "LocationListCell" override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(studentLocationsWereLoaded), name: .studentLocationsWereLoaded, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func studentLocationsWereLoaded() { listTableView.reloadData() } } extension LocationListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return StudentLocationAnnotation.annotationsArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as? LocationListCell else { fatalError("Could not dequeue the correct cell for the LocationList view") } let studentInformation = StudentLocationAnnotation.annotationsArray[indexPath.row].studentInformation cell.setup(with: studentInformation) return cell } } extension LocationListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let studentInfo = StudentLocationAnnotation.annotationsArray[indexPath.row].studentInformation studentInfo.openMediaURL() } }
true
d93fbdcdab0684c05401fbf8533eb6d8ee24bb70
Swift
hleise/sBlue
/sBlue/GesturesTableViewController.swift
UTF-8
8,245
2.6875
3
[]
no_license
// // GesturesTableViewController.swift // sBlue // // Created by Hunter Leise on 8/4/16. // Copyright © 2016 Vivo Applications. All rights reserved. // import UIKit class GesturesTableViewController: UITableViewController { @IBAction func unwindToGestures(segue: UIStoryboardSegue) {} override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows switch section { case 0: return customGestures.count + 1 case 1: return defaultGestures.count default: print("Table View section was \(section), it should be 0 or 1") return -1 } } private struct Storyboard { static let NewGestureCellIdentifier = "New Gesture" static let MyGestureCellIdentifier = "My Gesture" static let DefaultGestureCellIdentifier = "Default Gesture" } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: if indexPath.row == 0 { let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.NewGestureCellIdentifier, forIndexPath: indexPath) return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.MyGestureCellIdentifier, forIndexPath: indexPath) if let myGestureCell = cell as? MyGestureTableViewCell { let data = customGestures[indexPath.row - 1] myGestureCell.myGestureLabel.text = data[1] } return cell } case 1: let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.DefaultGestureCellIdentifier, forIndexPath: indexPath) if let defaultGestureCell = cell as? DefaultGestureTableViewCell { let data = defaultGestures[indexPath.row] defaultGestureCell.defaultGestureLabel?.text = data[1] } return cell default: let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.NewGestureCellIdentifier, forIndexPath: indexPath) print("indexPath.section was \(indexPath.section), it should be 0 or 1") return cell } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "My Gestures" case 1: return "Default Gestures" default: print("Section number is \(section), but should be 0 or 1") return nil } } // Returns if you can swipe left on a given cell override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if (indexPath.section == 0) && (indexPath.row != 0) { return true } else { return false } } // Determines what to do when the user swipes left on a cell and selects delete override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { customGestures.removeAtIndex(indexPath.row - 1) tableView.reloadData() } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { precondition(segue.identifier == "toAddGesture" || segue.identifier == "toEditGesture", "Unknown Segue Identifier") if (segue.identifier == "toAddGesture") { let destination = segue.destinationViewController as! AddEditGestureTableViewController destination.gestureTableViewControllerType = "Add Gesture" } else { if let destination = segue.destinationViewController as? AddEditGestureTableViewController { destination.gestureTableViewControllerType = "Edit Gesture" if let indexPath = self.tableView.indexPathForSelectedRow { destination.gestureID = indexPath.row - 1 as Int destination.gestureName = customGestures[indexPath.row - 1][1] } } } } /* class oldgesturesTableViewController: UITableViewController { @IBOutlet weak var gesturesNavigation: UIButton! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return super.numberOfSectionsInTableView(tableView) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return super.tableView(tableView, numberOfRowsInSection: section) } @IBAction func gesturesDropdownClicked(sender: UIButton) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) alert.addAction(UIAlertAction( title: "My Gestures", style: .Default) { (action: UIAlertAction) -> Void in } ) alert.addAction(UIAlertAction( title: "Default Gestures", style: .Default) { (action: UIAlertAction) -> Void in } ) alert.addAction(UIAlertAction( title: "Cancel", style: .Cancel) { (action: UIAlertAction) -> Void in } ) alert.modalPresentationStyle = .Popover let ppc = alert.popoverPresentationController ppc?.sourceView = gesturesNavigation presentViewController(alert, animated: true, completion: nil) } */ }
true
6e3c1eb10eff8ef3c4ef01a47a56421f9b66921b
Swift
IgorChernyshov/TapRunner
/TapRunner/Road.swift
UTF-8
1,005
2.984375
3
[]
no_license
// // Road.swift // TapRunner // // Created by Igor Chernyshov on 01.08.2021. // import SpriteKit final class Road: SKSpriteNode { // MARK: - Properties private static var isLeftToRight: Bool = false // MARK: - Initialization convenience init() { self.init(color: .green, size: CGSize(width: 1536, height: 10)) configure() toggleLeftToRight() } // MARK: - Configuration private func configure() { position = CGPoint(x: 512, y: -125) zRotation = CGFloat.random(in: 0.05...0.20) * (Road.isLeftToRight ? -1 : 1) name = "road" physicsBody = SKPhysicsBody(rectangleOf: size) physicsBody?.isDynamic = false } private func toggleLeftToRight() { let isToggleRequired = Bool.random() if isToggleRequired { Road.isLeftToRight.toggle() } } // MARK: - Game Logic func activate(gameSpeed: Double) { let moveUp = SKAction.moveTo(y: 893, duration: gameSpeed) let delete = SKAction.run { [weak self] in self?.removeFromParent() } run(SKAction.sequence([moveUp, delete])) } }
true
9dbcf9d7897c08bb042bac463b9bcb4083ef339c
Swift
apoorva2111/MECA_Prakhar
/MECA/Utility/Extension/UIColor.swift
UTF-8
2,616
3.046875
3
[]
no_license
import UIKit extension UIColor { class func getCustomRedColor() -> UIColor{ return UIColor(red: 0.9882352941, green: 0, blue: 0, alpha: 1) } class func getCustomBlueColor() -> UIColor{ return UIColor(red: 0.1490196078, green: 0.2784313725, blue: 0.5529411765, alpha: 1) } class func getCustomLightBlueColor() -> UIColor{ return UIColor(red: 0.2392156863, green: 0.4823529412, blue: 0.831372549, alpha: 1) } class func getCustomOrangeColor() -> UIColor{ return UIColor(red: 0.9803921569, green: 0.6235294118, blue: 0.2039215686, alpha: 1) } class func getCustomDarkOrangeColor() -> UIColor{ return UIColor(red: 0.9650015235, green: 0.4383477867, blue: 0.2127818763, alpha: 1) } class func colorFromHex(rgbValue:UInt32, alpha:Double = 1.0)->UIColor{ let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha)) } class func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } } extension UIColor { convenience init(hexString: String) { let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt64() Scanner(string: hex).scanHexInt64(&int) let a, r, g, b: UInt64 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (255, 0, 0, 0) } self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } }
true
9bad267cb1f2fd56d00f8a5231c13dfa0e84dd7c
Swift
derekvallar/Mindful
/Mindful/CreateReminderView.swift
UTF-8
1,511
2.65625
3
[]
no_license
// // NewReminderView.swift // Mindful // // Created by Derek Vitaliano Vallar on 10/16/17. // Copyright © 2017 Derek Vallar. All rights reserved. // import UIKit class CreateReminderView: UIView { private let borderLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) // self.backgroundColor = UIColor.darkGray let reminderView = UIView() // reminderView.backgroundColor = UIColor.blue self.addSubview(reminderView) let margins = self.layoutMarginsGuide NSLayoutConstraint.setupAndActivate(constraints: [ reminderView.leadingAnchor.constraint(equalTo: margins.leadingAnchor), reminderView.trailingAnchor.constraint(equalTo: margins.trailingAnchor), reminderView.heightAnchor.constraint(equalToConstant: 65.0), reminderView.centerYAnchor.constraint(equalTo: margins.centerYAnchor)]) print("Bounds:", reminderView.bounds) layoutIfNeeded() print("Bounds2:", reminderView.bounds) let path = UIBezierPath(roundedRect: reminderView.bounds, cornerRadius: 10.0) borderLayer.path = path.cgPath borderLayer.lineWidth = 4.0 borderLayer.lineDashPattern = [10,10] borderLayer.strokeColor = UIColor.white.cgColor borderLayer.fillColor = nil reminderView.layer.addSublayer(borderLayer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true