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
7decac4fbc0eb1bbf212578255adaa12c89dc614
Swift
jaeyoon-lee2/ICS4U-Unit1-05-Swift
/DiceGame.swift
UTF-8
1,143
3.765625
4
[]
no_license
/* This program generate random number between 1 to 6, get user number, check these two numbers are correct. author Jay Lee version 1.0 since 2020-04-27 */ enum InvalidInputError : Error { case invalidInput } print("Choose the range (1 to ?): ", terminator: "") do { guard let range = Int(readLine()!) else{ throw InvalidInputError.invalidInput } // let rangeNumber = Int(range) let randomNumber = Int.random(in: 1...range) while (true) { // String Input print("Guess the number between 1 to \(range): ", terminator: "") do { guard let userNumber = Int(readLine()!) else{ throw InvalidInputError.invalidInput } // Check range if (userNumber >= 1 && userNumber <= range) { //Check number is right if (userNumber == randomNumber) { break } else { print("Wrong number!") } } else { print("Out of range!") } } catch { print("Invalid input!") } print("Try again!") } // Final output print("Correct! The number is \(randomNumber)!") } catch { print("Invalid input!") } print("\nDone.")
true
5449a0a7a209be947f4b3c60bb6f8508e276e819
Swift
pqhuy87it/Swift-Stackoverflow
/UserDefault+KVO.swift
UTF-8
4,471
3.125
3
[]
no_license
struct UDKeyValueObservedChange<Value> { typealias Kind = NSKeyValueChange let kind: Kind let newValue: Value? let oldValue: Value? let indexes: IndexSet? let isPrior:Bool } class UDKeyValueObservation: NSObject { // 循環参照を避けるために監視オブジェクトは弱参照 weak var object: NSObject? // 値変更時に実行するクロージャ(初期化時のクロージャ) let callback: (NSObject, UDKeyValueObservedChange<Any>) -> Void // 監視するUserDefaultsのキー let defaultName: String // 本家では KeyPath → String 変換が行われる fileprivate init(object: NSObject, defaultName: String, callback: @escaping (NSObject, UDKeyValueObservedChange<Any>) -> Void) { self.object = object self.defaultName = defaultName self.callback = callback } // 値の変更はまずここに通知される // 本家では, 黒魔術(method_exchangeImplementations)で独自関数と入れ替えてる override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let ourObject = self.object, let change = change, object as? NSObject == ourObject, keyPath == defaultName else { return } // [NSKeyValueChangeKey: Any] => UDKeyValueObservedChange let rawKind = change[.kindKey] as! UInt let kind = NSKeyValueChange(rawValue: rawKind)! let notification = UDKeyValueObservedChange(kind: kind, newValue: change[.newKey], oldValue: change[.oldKey], indexes: change[.indexesKey] as! IndexSet?, isPrior: change[.notificationIsPriorKey] as? Bool ?? false) // クロージャを実行 callback(ourObject, notification) } // 監視を開始 // イニシャライザで行わないのは, options に .initial が含まれていた場合, 自身の初期化前に通知されてしまうため(だと思われる). fileprivate func start(_ options: NSKeyValueObservingOptions) { object?.addObserver(self, forKeyPath: defaultName, options: options, context: nil) } // 監視を解除. // deinit 時に自動で呼ばれると言いつつそれぞれ解除処理してる. func invalidate() { object?.removeObserver(self, forKeyPath: defaultName, context: nil) object = nil } deinit { object?.removeObserver(self, forKeyPath: defaultName, context: nil) } } typealias UDChangeHandler<O, V> = (O, UDKeyValueObservedChange<V>) -> Void // KeyPathの方は _KeyValueCodingAndObserving プロトコルが定義されている protocol UDKeyValueCodingAndObserving {} extension UDKeyValueCodingAndObserving { func observe<Value>(_ type: Value.Type, forKey defaultName: String, options: NSKeyValueObservingOptions = [], changeHandler: @escaping UDChangeHandler<Self, Value>) -> UDKeyValueObservation { let result = UDKeyValueObservation(object: self as! NSObject, defaultName: defaultName) { obj, change in let notification = UDKeyValueObservedChange(kind: change.kind, newValue: change.newValue as? Value, oldValue: change.oldValue as? Value, indexes: change.indexes, isPrior: change.isPrior) changeHandler(obj as! Self, notification) } result.start(options) return result } } extension UserDefaults: UDKeyValueCodingAndObserving {} class Hoge { var observation: UDKeyValueObservation? init() { observation = UserDefaults.standard.observe(String.self, forKey: "key-1", options: [.new, .old]) { _, change in print(change) } } } var hoge = Hoge() print("1") UserDefaults.standard.set("hoge", forKey: "key-1") print("2") UserDefaults.standard.set("hoge", forKey: "key-1") print("3") UserDefaults.standard.set("fuga", forKey: "key-1") print("4") UserDefaults.standard.set(nil, forKey: "key-2") print("5") hoge.observation = nil UserDefaults.standard.set("hoge", forKey: "key-1") // 1 // Hoge Optional("hoge") nil // Hoge Optional("hoge") nil // 2 // 3 // Hoge Optional("fuga") Optional("hoge") // Hoge Optional("fuga") Optional("hoge") // 4 // Hoge nil Optional("fuga") // Hoge nil Optional("fuga") // 5
true
834daee17b821db31ce3dee77d84e34a214f0041
Swift
duongpdgc/Passing_Data_By_Delegate
/Passing_Data_By_Delegate/DataSource_String.swift
UTF-8
1,885
2.984375
3
[]
no_license
// // DataSource_String.swift // Passing_Data_By_Delegate // // Created by Admin on 1/7/18. // Copyright © 2018 DuongPham. All rights reserved. // import Foundation import UIKit class DataSource_String: NSObject, UITableViewDataSource { // MARK : Properties var arr_String = ["Duong","Dep","Trai"] // var create_A = ViewController().createAlert(title: "WARNINg", message: "NO_DATA") let alertController = UIAlertController(title: "Alert", message: "This is an alert.", preferredStyle: .alert) func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr_String.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = arr_String[indexPath.row] return cell } // MARK: Coding the function Delete func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source arr_String.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) if arr_String.count == 0 { // self.present(alertController, animated: true, completion: nil) } } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } // Override to support conditional editing of the table view. func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } }
true
4453c671211f39476e6742e42f05b41aa2a1c820
Swift
kirualex/Flamingo
/Flamingo/Classes/Views/TableViewCells/PrototypeTableCell.swift
UTF-8
1,202
3.015625
3
[ "MIT" ]
permissive
// // PrototypeTableCell.swift // import UIKit protocol PrototypeTableCellProtocol { func setPrototypeContent(_ content: PrototypeTableCellContent) } class PrototypeTableCellContent: NSObject { var cellType: AnyClass var identifier: Int? var payload: Any? var height: CGFloat = 50 var estimatedHeight: CGFloat = UITableView.automaticDimension var backgroundColor: UIColor = UIColor.clear var reuseIdentifier : String { get { return String(describing: cellType) } } init(_ type: AnyClass) { self.cellType = type } } class PrototypeTableCell : UITableViewCell, PrototypeTableCellProtocol { var cellContent = PrototypeTableCellContent(UITableViewCell.self) func setPrototypeContent(_ content: PrototypeTableCellContent) { self.cellContent = content self.backgroundColor = self.cellContent.backgroundColor } override func awakeFromNib() { super.awakeFromNib() let selView = UIView() selView.backgroundColor = UIColor.label.withAlphaComponent(0.05) self.selectedBackgroundView = selView self.selectionStyle = .none } }
true
d5ce1eff157dd3901f5d4f169063ca145061191d
Swift
microsoft/soundscape
/apps/ios/GuideDogs/Code/Behaviors/Protocols/AutomaticGenerator.swift
UTF-8
937
2.84375
3
[ "MIT" ]
permissive
// // AutomaticGenerator.swift // Soundscape // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // import Foundation protocol AutomaticGenerator { /// Indicates if this automatic callout generator is allowed to interrupt other callouts /// that are already playing when it generates callouts. This should be used for /// automatic callout generators related to safety or critical information. var canInterrupt: Bool { get } /// Can be called by other `AutomaticGenerator`'s to signal that they have already generated /// a callout for a particular entity so no additional callouts should be generated. /// /// - Parameter id: ID/Key of the entity that was called out func cancelCalloutsForEntity(id: String) func respondsTo(_ event: StateChangedEvent) -> Bool func handle(event: StateChangedEvent, verbosity: Verbosity) -> HandledEventAction? }
true
ef940a89f49fecf67150ebb242cc10536f7af5f9
Swift
elinazekunde/LatvianNewsFeed
/LatvianNewsFeed/Controllers/SavedItemsTableViewController.swift
UTF-8
4,250
2.796875
3
[]
no_license
// // SavedItemsTableViewController.swift // LatvianNewsFeed // // Created by Elīna Zekunde on 16/02/2021. // import UIKit import CoreData class SavedItemsTableViewController: UITableViewController { var news = [News]() var context: NSManagedObjectContext? override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.shared.delegate as! AppDelegate context = appDelegate.persistentContainer.viewContext // Display an Edit button in the navigation bar for this view controller. self.navigationItem.rightBarButtonItem = self.editButtonItem loadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadData() } func loadData() { let request: NSFetchRequest<News> = News.fetchRequest() do { news = try (context?.fetch(request))! } catch { warningPopup(withTitle: "Error!", withMessage: error.localizedDescription) } } func saveData() { do { try context?.save() } catch { warningPopup(withTitle: "Error!", withMessage: error.localizedDescription) } tableView.reloadData() } func warningPopup(withTitle title: String?, withMessage message: String?) { DispatchQueue.main.async { let popup = UIAlertController(title: title, message: message, preferredStyle: .alert) let okButton = UIAlertAction(title: "OK", style: .cancel, handler: nil) popup.addAction(okButton) self.present(popup, animated: true, completion: nil) } } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows return news.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "savedCell", for: indexPath) as? NewsFeedCell else { return UITableViewCell() } let item = news[indexPath.row] if item.image != nil { if let image = UIImage(data: item.image!) { cell.imageView!.image = image } } else { cell.imageView!.image = nil } cell.titleLabel.text = item.title return cell } // MARK: - Table view Delegate override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 130 } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let alert = UIAlertController(title: "Delete", message: "Are you sure to delete?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { _ in let item = self.news[indexPath.row] self.context?.delete(item) self.saveData() })) self.present(alert, animated: true) } } // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { let currentItem = news.remove(at: fromIndexPath.row) news.insert(currentItem, at: to.row) saveData() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) guard let vc = storyboard.instantiateViewController(identifier: "WebViewController") as? WebViewController else { return } vc.urlString = news[indexPath.row].url! navigationController?.pushViewController(vc, animated: true) } }
true
297f498b67363031fd904e1213991c0a1875c54e
Swift
AmrAli22/EraAlbum2
/EraAlbum/Controller/AlbumsTableViewController.swift
UTF-8
4,003
2.578125
3
[]
no_license
// // AlbumsTableViewController.swift // Albumera // // Created by Sayed Abdo on 7/23/18. // Copyright © 2018 TheAmrAli. All rights reserved. // import UIKit class AlbumsTableViewController: UITableViewController { //Outlets @IBOutlet weak var LblNoExsitingAlbums: UILabel! let userDefaults = UserDefaults.standard var Albums = [Album]() //////////// override func viewDidLoad() { super.viewDidLoad() //Add Array Of Albums in UserDefaults let AlbumArray = [Album]() let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: AlbumArray) userDefaults.set(encodedData, forKey: "AlbumArray") userDefaults.synchronize() //Checking For Exsiting Album if (UserDefaults.standard.array(forKey: "AlbumsArray")?.isEmpty)! == true { self.LblNoExsitingAlbums.isHidden = false self.tableView.isHidden = true }else{ self.tableView.isHidden = false self.LblNoExsitingAlbums.isHidden = true //Retrive AlbumArray From UserDefaults let decoded = userDefaults.object(forKey: "AlbumArray") as! Data self.Albums = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Album] } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) } override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return Albums.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumCell", for: indexPath) as? AlbumsTableViewCell cell?.configureCell(ImagesCount: Albums[indexPath.row]._imagesArray.count , AlbumName: Albums[indexPath.row]._title , Imgpreview: Albums[indexPath.row]._PreviewImage) return cell! } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // 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
44345f90f78a33ffa368f3f67b0234adf1feafbc
Swift
sinhlhhn/APIGoogleSheet
/DoAn/TableViewCell.swift
UTF-8
532
2.59375
3
[]
no_license
// // TableViewCell.swift // DoAn // // Created by Lê Hoàng Sinh on 05/02/2021. // import UIKit class TableViewCell: UITableViewCell { @IBOutlet weak var lblName: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setup(name: String) { lblName.text = name } }
true
fef89db4c78b2637747699849d4ce1e88f769e9f
Swift
MaTriXy/Swift-MathEagle
/MathEagleTests/Statistics/RandomTests.swift
UTF-8
58,486
2.828125
3
[ "MIT" ]
permissive
// // RandomTests.swift // MathEagle // // Created by Rugen Heidbuchel on 01/04/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Cocoa import XCTest import MathEagle class RandomTests: XCTestCase { var N = 10000 var MAX = 100 func testRangeConstructors() { print(String(describing:type(of:10.0..<20.0))) print(String(describing:type(of:10.0...20.0))) print(String(describing:type(of:10..<20))) print(String(describing:type(of:10...20))) XCTAssert((10.0..<20.0 as Any) is Range<Double>) XCTAssert((10.0...20.0 as Any) is ClosedRange<Double>) XCTAssert((10..<20 as Any) is CountableRange<Int>) XCTAssert((10...20 as Any) is CountableClosedRange<Int>) } // MARK: random within upperBound func testRandomInt() { for _ in 1...N { let x=Int.random() XCTAssert((x as Any) is Int) XCTAssert(0<=x && x<=1) } let m=Int.random(Int(MAX)) XCTAssert((m as Any) is Int) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=Int.random(m) XCTAssert((x as Any) is Int) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=Int.random(-m) XCTAssert((x as Any) is Int) XCTAssert(-m<=x && x<=0) } } func testRandomInt8() { for _ in 1...N { let x=Int8.random() XCTAssert((x as Any) is Int8) XCTAssert(0<=x && x<=1) } let m=Int8.random(Int8(MAX)) XCTAssert((m as Any) is Int8) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=Int8.random(m) XCTAssert((x as Any) is Int8) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=Int8.random(-m) XCTAssert((x as Any) is Int8) XCTAssert(-m<=x && x<=0) } } func testRandomInt16() { for _ in 1...N { let x=Int16.random() XCTAssert((x as Any) is Int16) XCTAssert(0<=x && x<=1) } let m=Int16.random(Int16(MAX)) XCTAssert((m as Any) is Int16) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=Int16.random(m) XCTAssert((x as Any) is Int16) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=Int16.random(-m) XCTAssert((x as Any) is Int16) XCTAssert(-m<=x && x<=0) } } func testRandomInt32() { for _ in 1...N { let x=Int32.random() XCTAssert((x as Any) is Int32) XCTAssert(0<=x && x<=1) } let m=Int32.random(Int32(MAX)) XCTAssert((m as Any) is Int32) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=Int32.random(m) XCTAssert((x as Any) is Int32) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=Int32.random(-m) XCTAssert((x as Any) is Int32) XCTAssert(-m<=x && x<=0) } } func testRandomInt64() { for _ in 1...N { let x=Int64.random() XCTAssert((x as Any) is Int64) XCTAssert(0<=x && x<=1) } let m=Int64.random(Int64(MAX)) XCTAssert((m as Any) is Int64) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=Int64.random(m) XCTAssert((x as Any) is Int64) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=Int64.random(-m) XCTAssert((x as Any) is Int64) XCTAssert(-m<=x && x<=0) } } func testRandomUInt() { for _ in 1...N { let x=UInt.random() XCTAssert((x as Any) is UInt) XCTAssert(0<=x && x<=1) } let m=UInt.random(UInt(MAX)) XCTAssert((m as Any) is UInt) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=UInt.random(m) XCTAssert((x as Any) is UInt) XCTAssert(0<=x && x<=m) } } func testRandomUInt8() { for _ in 1...N { let x=UInt8.random() XCTAssert((x as Any) is UInt8) XCTAssert(0<=x && x<=1) } let m=UInt8.random(UInt8(MAX)) XCTAssert((m as Any) is UInt8) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=UInt8.random(m) XCTAssert((x as Any) is UInt8) XCTAssert(0<=x && x<=m) } } func testRandomUInt16() { for _ in 1...N { let x=UInt16.random() XCTAssert((x as Any) is UInt16) XCTAssert(0<=x && x<=1) } let m=UInt16.random(UInt16(MAX)) XCTAssert((m as Any) is UInt16) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=UInt16.random(m) XCTAssert((x as Any) is UInt16) XCTAssert(0<=x && x<=m) } } func testRandomUInt32() { for _ in 1...N { let x=UInt32.random() XCTAssert((x as Any) is UInt32) XCTAssert(0<=x && x<=1) } let m=UInt32.random(UInt32(MAX)) XCTAssert((m as Any) is UInt32) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=UInt32.random(m) XCTAssert((x as Any) is UInt32) XCTAssert(0<=x && x<=m) } } func testRandomUInt64() { for _ in 1...N { let x=UInt64.random() XCTAssert((x as Any) is UInt64) XCTAssert(0<=x && x<=1) } let m=UInt64.random(UInt64(MAX)) XCTAssert((m as Any) is UInt64) XCTAssert(0<=m && m<=MAX) for _ in 1...N { let x=UInt64.random(m) XCTAssert((x as Any) is UInt64) XCTAssert(0<=x && x<=m) } } func testRandomFloat() { for _ in 1...N { let x=Float.random() XCTAssert((x as Any) is Float) XCTAssert(0<=x && x<=1) } let m=Float.random(Float(MAX)) XCTAssert((m as Any) is Float) XCTAssert(0<=m && m<=Float(MAX)) for _ in 1...N { let x=Float.random(m) XCTAssert((x as Any) is Float) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=Float.random(-m) XCTAssert((x as Any) is Float) XCTAssert(-m<=x && x<=0) } } func testRandomDouble() { for _ in 1...N { let x=Double.random() XCTAssert((x as Any) is Double) XCTAssert(0<=x && x<=1) } let m=Double.random(Double(MAX)) XCTAssert((m as Any) is Double) XCTAssert(0<=m && m<=Double(MAX)) for _ in 1...N { let x=Double.random(m) XCTAssert((x as Any) is Double) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=Double.random(-m) XCTAssert((x as Any) is Double) XCTAssert(-m<=x && x<=0) } } func testRandomCGFloat() { for _ in 1...N { let x=CGFloat.random() XCTAssert((x as Any) is CGFloat) XCTAssert(0<=x && x<=1) } let m=CGFloat.random(CGFloat(MAX)) XCTAssert((m as Any) is CGFloat) XCTAssert(0<=m && m<=CGFloat(MAX)) for _ in 1...N { let x=CGFloat.random(m) XCTAssert((x as Any) is CGFloat) XCTAssert(0<=x && x<=m) } for _ in 1...N { let x=CGFloat.random(-m) XCTAssert((x as Any) is CGFloat) XCTAssert(-m<=x && x<=0) } } // MARK: random in a Range func testRandomInInt() { let m=Int.random(Int(-MAX)..<Int(MAX)) XCTAssert((m as Any) is Int) XCTAssert(-MAX<=m && m<MAX) let n=Int.random((m+1)...Int(MAX)) XCTAssert((n as Any) is Int) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=Int.random(m..<n) XCTAssert((x as Any) is Int) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=Int.random(m...n) XCTAssert((x as Any) is Int) XCTAssert(m<=x && x<=n) } } func testRandomInInt8() { let m=Int8.random(Int8(-MAX)..<Int8(MAX)) XCTAssert((m as Any) is Int8) XCTAssert(-MAX<=m && m<MAX) let n=Int8.random((m+1)...Int8(MAX)) XCTAssert((n as Any) is Int8) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=Int8.random(m..<n) XCTAssert((x as Any) is Int8) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=Int8.random(m...n) XCTAssert((x as Any) is Int8) XCTAssert(m<=x && x<=n) } } func testRandomInInt16() { let m=Int16.random(Int16(-MAX)..<Int16(MAX)) XCTAssert((m as Any) is Int16) XCTAssert(-MAX<=m && m<MAX) let n=Int16.random((m+1)...Int16(MAX)) XCTAssert((n as Any) is Int16) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=Int16.random(m..<n) XCTAssert((x as Any) is Int16) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=Int16.random(m...n) XCTAssert((x as Any) is Int16) XCTAssert(m<=x && x<=n) } } func testRandomInInt32() { let m=Int32.random(Int32(-MAX)..<Int32(MAX)) XCTAssert((m as Any) is Int32) XCTAssert(-MAX<=m && m<MAX) let n=Int32.random((m+1)...Int32(MAX)) XCTAssert((n as Any) is Int32) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=Int32.random(m..<n) XCTAssert((x as Any) is Int32) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=Int32.random(m...n) XCTAssert((x as Any) is Int32) XCTAssert(m<=x && x<=n) } } func testRandomInInt64() { let m=Int64.random(Int64(-MAX)..<Int64(MAX)) XCTAssert((m as Any) is Int64) XCTAssert(-MAX<=m && m<MAX) let n=Int64.random((m+1)...Int64(MAX)) XCTAssert((n as Any) is Int64) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=Int64.random(m..<n) XCTAssert((x as Any) is Int64) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=Int64.random(m...n) XCTAssert((x as Any) is Int64) XCTAssert(m<=x && x<=n) } } func testRandomInUInt() { let m=UInt.random(0..<UInt(MAX)) XCTAssert((m as Any) is UInt) XCTAssert(0<=m && m<MAX) let n=UInt.random((m+1)...UInt(MAX)) XCTAssert((n as Any) is UInt) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=UInt.random(m..<n) XCTAssert((x as Any) is UInt) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=UInt.random(m...n) XCTAssert((x as Any) is UInt) XCTAssert(m<=x && x<=n) } } func testRandomInUInt8() { let m=UInt8.random(0..<UInt8(MAX)) XCTAssert((m as Any) is UInt8) XCTAssert(0<=m && m<MAX) let n=UInt8.random((m+1)...UInt8(MAX)) XCTAssert((n as Any) is UInt8) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=UInt8.random(m..<n) XCTAssert((x as Any) is UInt8) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=UInt8.random(m...n) XCTAssert((x as Any) is UInt8) XCTAssert(m<=x && x<=n) } } func testRandomInUInt16() { let m=UInt16.random(0..<UInt16(MAX)) XCTAssert((m as Any) is UInt16) XCTAssert(0<=m && m<MAX) let n=UInt16.random((m+1)...UInt16(MAX)) XCTAssert((n as Any) is UInt16) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=UInt16.random(m..<n) XCTAssert((x as Any) is UInt16) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=UInt16.random(m...n) XCTAssert((x as Any) is UInt16) XCTAssert(m<=x && x<=n) } } func testRandomInUInt32() { let m=UInt32.random(0..<UInt32(MAX)) XCTAssert((m as Any) is UInt32) XCTAssert(0<=m && m<MAX) let n=UInt32.random((m+1)...UInt32(MAX)) XCTAssert((n as Any) is UInt32) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=UInt32.random(m..<n) XCTAssert((x as Any) is UInt32) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=UInt32.random(m...n) XCTAssert((x as Any) is UInt32) XCTAssert(m<=x && x<=n) } } func testRandomInUInt64() { let m=UInt64.random(0..<UInt64(MAX)) XCTAssert((m as Any) is UInt64) XCTAssert(0<=m && m<MAX) let n=UInt64.random((m+1)...UInt64(MAX)) XCTAssert((n as Any) is UInt64) XCTAssert(m<n && n<=MAX) for _ in 1...N { let x=UInt64.random(m..<n) XCTAssert((x as Any) is UInt64) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=UInt64.random(m...n) XCTAssert((x as Any) is UInt64) if (!(m<=x && x<=n)) { print([m,n,x]) print("Oh Oh") } XCTAssert(m<=x && x<=n) } } func testRandomInFloat() { let m=Float.random(Float(-MAX)..<Float(MAX)) XCTAssert((m as Any) is Float) XCTAssert(-Float(MAX)<=m && m<Float(MAX)) let n=Float.random(m...Float(MAX)) XCTAssert((n as Any) is Float) // Ignoring astronomically small chance m==n XCTAssert(m<n && n<=Float(MAX)) for _ in 1...N { let x=Float.random(m..<n) XCTAssert((x as Any) is Float) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=Float.random(m...n) XCTAssert((x as Any) is Float) XCTAssert(m<=x && x<=n) } } func testRandomInDouble() { let m=Double.random(Double(-MAX)..<Double(MAX)) XCTAssert((m as Any) is Double) XCTAssert(-Double(MAX)<=m && m<Double(MAX)) let n=Double.random(m...Double(MAX)) XCTAssert((n as Any) is Double) // Ignoring astronomically small chance m==n XCTAssert(m<n && n<=Double(MAX)) for _ in 1...N { let x=Double.random(m..<n) XCTAssert((x as Any) is Double) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=Double.random(m...n) XCTAssert((x as Any) is Double) XCTAssert(m<=x && x<=n) } } func testRandomInCGFloat() { let m=CGFloat.random(CGFloat(-MAX)..<CGFloat(MAX)) XCTAssert((m as Any) is CGFloat) XCTAssert(-CGFloat(MAX)<=m && m<CGFloat(MAX)) let n=CGFloat.random(m...CGFloat(MAX)) XCTAssert((n as Any) is CGFloat) // Ignoring astronomically small chance m==n XCTAssert(m<n && n<=CGFloat(MAX)) for _ in 1...N { let x=CGFloat.random(m..<n) XCTAssert((x as Any) is CGFloat) XCTAssert(m<=x && x<n) } for _ in 1...N { let x=CGFloat.random(m...n) XCTAssert((x as Any) is CGFloat) XCTAssert(m<=x && x<=n) } } // MARK: randomArray to one func testRandomArrayInt() { do { let range = Int(0)...Int(1) let X = Int.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt8() { do { let range = Int8(0)...Int8(1) let X = Int8.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt16() { do { let range = Int16(0)...Int16(1) let X = Int16.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt32() { do { let range = Int32(0)...Int32(1) let X = Int32.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt64() { do { let range = Int64(0)...Int64(1) let X = Int64.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt() { do { let range = UInt(0)...UInt(1) let X = UInt.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt8() { do { let range = UInt8(0)...UInt8(1) let X = UInt8.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt16() { do { let range = UInt16(0)...UInt16(1) let X = UInt16.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt32() { do { let range = UInt32(0)...UInt32(1) let X = UInt32.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt64() { do { let range = UInt64(0)...UInt64(1) let X = UInt64.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = 0.5 let s = 1.0/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayFloat() { do { let range = Float(0)...Float(1) let X = Float.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Float(0.5) let s = Float(1.0/sqrt(12.0)) XCTAssert(s>0) XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let z = (X.mean()-mu)/(s/sqrt(Float(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayDouble() { do { let range = Double(0)...Double(1) let X = Double.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(0.5) let s = Double(1.0/sqrt(12.0)) XCTAssert(s>0) XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let z = (X.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayCGFloat() { do { let range = CGFloat(0)...CGFloat(1) let X = CGFloat.randomArray(N) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = CGFloat(0.5) let s = CGFloat(1.0/sqrt(12.0)) XCTAssert(s>0) XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let z = (X.mean()-mu)/(s/sqrt(CGFloat(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayComplex() { do { let X = Complex.randomArray(N) if (N>=100) { let mu_X : Complex = X.mean() do { let mu_real = 0.5 let s_real = 1.0/sqrt(12.0) let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N))) XCTAssert(abs(z_real)<6.0) } do { let mu_imaginary = 0.5 let s_imaginary = 1.0/sqrt(12.0) let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N))) XCTAssert(abs(z_imaginary)<6.0) } } } } // MARK: randomArray to upperBound func testRandomArrayIntUpperBound() { let n=Int.random(1...Int(MAX)) XCTAssert((n as Any) is Int) XCTAssert(n<=MAX) do { let range = 0...n let X = Int.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt8UpperBound() { let n=Int8.random(1...Int8(MAX)) XCTAssert((n as Any) is Int8) XCTAssert(n<=MAX) do { let range = 0...n let X = Int8.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt16UpperBound() { let n=Int16.random(1...Int16(MAX)) XCTAssert((n as Any) is Int16) XCTAssert(n<=MAX) do { let range = 0...n let X = Int16.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt32UpperBound() { let n=Int32.random(1...Int32(MAX)) XCTAssert((n as Any) is Int32) XCTAssert(n<=MAX) do { let range = 0...n let X = Int32.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt64UpperBound() { let n=Int64.random(1...Int64(MAX)) XCTAssert((n as Any) is Int64) XCTAssert(n<=MAX) do { let range = 0...n let X = Int64.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUIntUpperBound() { let n=UInt.random(1...UInt(MAX)) XCTAssert((n as Any) is UInt) XCTAssert(n<=MAX) do { let range = 0...n let X = UInt.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt8UpperBound() { let n=UInt8.random(1...UInt8(MAX)) XCTAssert((n as Any) is UInt8) XCTAssert(n<=MAX) do { let range = 0...n let X = UInt8.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt16UpperBound() { let n=UInt16.random(1...UInt16(MAX)) XCTAssert((n as Any) is UInt16) XCTAssert(n<=MAX) do { let range = 0...n let X = UInt16.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt32UpperBound() { let n=UInt32.random(1...UInt32(MAX)) XCTAssert((n as Any) is UInt32) XCTAssert(n<=MAX) do { let range = 0...n let X = UInt32.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt64UpperBound() { let n=UInt64.random(1...UInt64(MAX)) XCTAssert((n as Any) is UInt64) XCTAssert(n<=MAX) do { let range = 0...n let X = UInt64.randomArray(N,upperBound:n) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = Double(n)/2.0 let s = Double(n)/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayFloatUpperBound() { let n=Float.random(Float(0.0)...Float(MAX)) XCTAssert((n as Any) is Float) // Ignoring astronomically small chance 0.0==n XCTAssert(n<=Float(MAX)) do { let range = 0...n let X = Float.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = n/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = n/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(Float(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayDoubleUpperBound() { let n=Double.random(Double(0.0)...Double(MAX)) XCTAssert((n as Any) is Double) // Ignoring astronomically small chance 0.0==n XCTAssert(n<=Double(MAX)) do { let range = 0...n let X = Double.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = n/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = n/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayCGFloatUpperBound() { let n=CGFloat.random(CGFloat(0.0)...CGFloat(MAX)) XCTAssert((n as Any) is CGFloat) // Ignoring astronomically small chance 0.0==n XCTAssert(n<=CGFloat(MAX)) do { let range = 0...n let X = CGFloat.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = n/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = n/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(CGFloat(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayComplexUpperBound() { let n_real=Double.random(0.0...Double(MAX)) XCTAssert((n_real as Any) is Double) // Ignoring astronomically small chance 0.0==n_real XCTAssert(0.0<n_real && n_real<=Double(MAX)) let n_imaginary=Double.random(0.0...Double(MAX)) XCTAssert((n_imaginary as Any) is Double) // Ignoring astronomically small chance 0.0==n_imaginary XCTAssert(0.0<n_imaginary && n_imaginary<=Double(MAX)) // Complex n let n=Complex(n_real,n_imaginary) do { let X = Complex.randomArray(N,upperBound:n) if (N>=100) { let mu_X : Complex = X.mean() do { let mu_real = n_real/2 let s_real = n_real/sqrt(12.0) let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N))) XCTAssert(abs(z_real)<6.0) } do { let mu_imaginary = n_imaginary/2 let s_imaginary = n_imaginary/sqrt(12.0) let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N))) XCTAssert(abs(z_imaginary)<6.0) } } } } // MARK: randomArray in a range func testRandomArrayIntRange() { let m=Int.random(Int(-MAX)..<Int(MAX)) XCTAssert((m as Any) is Int) XCTAssert(-MAX<=m && m<MAX) let n=Int.random((m+1)...Int(MAX)) XCTAssert((n as Any) is Int) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = Int.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = Int.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt8Range() { let m=Int8.random(Int8(-MAX)..<Int8(MAX)) XCTAssert((m as Any) is Int8) XCTAssert(-MAX<=m && m<MAX) let n=Int8.random((m+1)...Int8(MAX)) XCTAssert((n as Any) is Int8) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = Int8.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = Int8.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt16Range() { let m=Int16.random(Int16(-MAX)..<Int16(MAX)) XCTAssert((m as Any) is Int16) XCTAssert(-MAX<=m && m<MAX) let n=Int16.random((m+1)...Int16(MAX)) XCTAssert((n as Any) is Int16) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = Int16.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = Int16.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt32Range() { let m=Int32.random(Int32(-MAX)..<Int32(MAX)) XCTAssert((m as Any) is Int32) XCTAssert(-MAX<=m && m<MAX) let n=Int32.random((m+1)...Int32(MAX)) XCTAssert((n as Any) is Int32) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = Int32.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = Int32.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayInt64Range() { let m=Int64.random(Int64(-MAX)..<Int64(MAX)) XCTAssert((m as Any) is Int64) XCTAssert(-MAX<=m && m<MAX) let n=Int64.random((m+1)...Int64(MAX)) XCTAssert((n as Any) is Int64) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = Int64.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = Int64.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUIntRange() { let m=UInt.random(0..<UInt(MAX)) XCTAssert((m as Any) is UInt) XCTAssert(-MAX<=m && m<MAX) let n=UInt.random((m+1)...UInt(MAX)) XCTAssert((n as Any) is UInt) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = UInt.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = UInt.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt8Range() { let m=UInt8.random(0..<UInt8(MAX)) XCTAssert((m as Any) is UInt8) XCTAssert(-MAX<=m && m<MAX) let n=UInt8.random((m+1)...UInt8(MAX)) XCTAssert((n as Any) is UInt8) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = UInt8.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = UInt8.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt16Range() { let m=UInt16.random(0..<UInt16(MAX)) XCTAssert((m as Any) is UInt16) XCTAssert(-MAX<=m && m<MAX) let n=UInt16.random((m+1)...UInt16(MAX)) XCTAssert((n as Any) is UInt16) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = UInt16.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = UInt16.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt32Range() { let m=UInt32.random(0..<UInt32(MAX)) XCTAssert((m as Any) is UInt32) XCTAssert(-MAX<=m && m<MAX) let n=UInt32.random((m+1)...UInt32(MAX)) XCTAssert((n as Any) is UInt32) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = UInt32.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = UInt32.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayUInt64Range() { let m=UInt64.random(0..<UInt64(MAX)) XCTAssert((m as Any) is UInt64) XCTAssert(-MAX<=m && m<MAX) let n=UInt64.random((m+1)...UInt64(MAX)) XCTAssert((n as Any) is UInt64) XCTAssert(m<n && n<=MAX) do { let range = m..<n let X = UInt64.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let b = n-1 let mu = (Double(m)+Double(b))/2.0 let s = (Double(b)-Double(m))/sqrt(12.0) if (s>0) { let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } do { let range = m...n let X = UInt64.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (Double(m)+Double(n))/2.0 let s = (Double(n)-Double(m))/sqrt(12.0) XCTAssert(s>0) let D = X.asDoubleArray() XCTAssert(D.min()!<mu) XCTAssert(D.max()!>mu) let z = (D.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayFloatRange() { let m=Float.random(Float(-MAX)..<Float(MAX)) XCTAssert((m as Any) is Float) XCTAssert(-Float(MAX)<=m && m<Float(MAX)) let n=Float.random(m...Float(MAX)) XCTAssert((n as Any) is Float) // Ignoring astronomically small chance m==n XCTAssert(m<n && n<=Float(MAX)) do { let range = m..<n let X = Float.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (m+n)/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = (n-m)/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(Float(N))) XCTAssert(abs(z)<6.0) } } do { let range = m...n let X = Float.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (m+n)/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = (n-m)/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(Float(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayDoubleRange() { let m=Double.random(Double(-MAX)..<Double(MAX)) XCTAssert((m as Any) is Double) XCTAssert(-Double(MAX)<=m && m<Double(MAX)) let n=Double.random(m...Double(MAX)) XCTAssert((n as Any) is Double) // Ignoring astronomically small chance m==n XCTAssert(m<n && n<=Double(MAX)) do { let range = m..<n let X = Double.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (m+n)/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = (n-m)/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } do { let range = m...n let X = Double.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (m+n)/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = (n-m)/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(Double(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayCGFloatRange() { let m=CGFloat.random(CGFloat(-MAX)..<CGFloat(MAX)) XCTAssert((m as Any) is CGFloat) XCTAssert(-CGFloat(MAX)<=m && m<CGFloat(MAX)) let n=CGFloat.random(m...CGFloat(MAX)) XCTAssert((n as Any) is CGFloat) // Ignoring astronomically small chance m==n XCTAssert(m<n && n<=CGFloat(MAX)) do { let range = m..<n let X = CGFloat.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (m+n)/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = (n-m)/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(CGFloat(N))) XCTAssert(abs(z)<6.0) } } do { let range = m...n let X = CGFloat.randomArray(N,range:range) for x in X { XCTAssert(range.contains(x)) } if (N>=100) { let mu = (m+n)/2 XCTAssert(X.min()!<mu) XCTAssert(X.max()!>mu) let s = (n-m)/sqrt(12.0) let z = (X.mean()-mu)/(s/sqrt(CGFloat(N))) XCTAssert(abs(z)<6.0) } } } func testRandomArrayComplexRange() { let m_real=Double.random(Double(-MAX)..<Double(MAX)) XCTAssert((m_real as Any) is Double) XCTAssert(-Double(MAX)<=m_real && m_real<Double(MAX)) let n_real=Double.random(m_real...Double(MAX)) XCTAssert((n_real as Any) is Double) // Ignoring astronomically small chance m_real==n_real XCTAssert(m_real<n_real && n_real<=Double(MAX)) let m_imaginary=Double.random(Double(-MAX)..<Double(MAX)) XCTAssert((m_imaginary as Any) is Double) XCTAssert(-Double(MAX)<=m_imaginary && m_imaginary<Double(MAX)) let n_imaginary=Double.random(m_imaginary...Double(MAX)) XCTAssert((n_imaginary as Any) is Double) // Ignoring astronomically small chance m_imaginary==n_imaginary XCTAssert(m_imaginary<n_imaginary && n_imaginary<=Double(MAX)) // Complex m and n let m=Complex(m_real,m_imaginary) let n=Complex(n_real,n_imaginary) do { let range = m..<n let X = Complex.randomArray(N,range:range) if (N>=100) { let mu_X : Complex = X.mean() do { let mu_real = (m_real+n_real)/2 let s_real = (n_real-m_real)/sqrt(12.0) let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N))) XCTAssert(abs(z_real)<6.0) } do { let mu_imaginary = (m_imaginary+n_imaginary)/2 let s_imaginary = (n_imaginary-m_imaginary)/sqrt(12.0) let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N))) XCTAssert(abs(z_imaginary)<6.0) } } } do { let range = m...n let X = Complex.randomArray(N,range:range) if (N>=100) { let mu_X : Complex = X.mean() do { let mu_real = (m_real+n_real)/2 let s_real = (n_real-m_real)/sqrt(12.0) let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N))) XCTAssert(abs(z_real)<6.0) } do { let mu_imaginary = (m_imaginary+n_imaginary)/2 let s_imaginary = (n_imaginary-m_imaginary)/sqrt(12.0) let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N))) XCTAssert(abs(z_imaginary)<6.0) } } } } // MARK: randomArray Performance func testRandomArrayUIntPerformance() { compareBaseline(0.000478798151016235, title: "Random UInt Array of length 10000", n: 10) { UInt.randomArray(10000) } } func testRandomArrayIntPerformance() { compareBaseline(0.000473904609680176, title: "Random Int Array of length 10000", n: 10) { Int.randomArray(10000) } } func testRandomArrayInt8Permormance() { compareBaseline(0.000310802459716797, title: "Random Int8 Array of length 10000", n: 10) { UInt8.randomArray(10000) } } func testRandomArrayInt16Permormance() { compareBaseline(0.000315195322036743, title: "Random Int16 Array of length 10000", n: 10) { Int16.randomArray(10000) } } func testRandomArrayInt32Permormance() { compareBaseline(0.0002532958984375, title: "Random Int32 Array of length 10000", n: 10) { Int32.randomArray(10000) } } func testRandomArrayInt64Permormance() { compareBaseline(0.000450801849365234, title: "Random Int64 Array of length 10000", n: 10) { Int64.randomArray(10000) } } func testRandomArrayFloatPerformance() { compareBaseline(0.000304659207661947, title: "Random Float Array of length 10000", n: 10) { Float.randomArray(10000) } } func testRandomArrayDoublePerformance() { compareBaseline(0.000660339991251628, title: "Random Double Array of length 10000", n: 10) { Double.randomArray(10000) } } }
true
4cb7eef259d5815c24c0e3602c5161f65ae14ac8
Swift
tosunkaya/AppleMusicUltra
/macOS/Ultra/TypeSwift/TypeSwift.swift
UTF-8
2,486
3.09375
3
[]
no_license
// // TypeSwift.swift // https://github.com/TypeSwift // // Created by Justin Bush on 2021-06-10. // // Generated with TypeSwift v0.0.1 // THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT TOUCH. // import Foundation /// **Core TypeSwift Controller:** All things TypeScript go thorugh this structure. enum TypeSwift { // MARK: Functions case didLoad(Void = ()) /// Raw JavaScript-generated code to `evaluate` in some WKWebView. var js: String { switch self { case .didLoad: return JSU.function("didLoad()") case .anchorDelay: return JSU.variable("anchorDelay") case .actionDelay: return JSU.variable("actionDelay") case .toggle: return JSU.function("toggle()") case .setLabel(let text): return JSU.function("setLabel(\"\(text)\")") case .hideObject(let hidden): return JSU.function("hideObject(\(hidden))") case .addNumbers(let a, let b): return JSU.function("addNumbers(\(a), \(b))") case .selectDevice(let device): return JSU.function("selectDevice(\(device.js))") } } // MARK: Variables case anchorDelay case actionDelay // MARK: Functions case toggle(Void = ()) case setLabel(_ text: String) case hideObject(_ hidden: Bool = false) case addNumbers(_ a: Double, _ b: Double) case selectDevice(_ device: Device) // MARK:- enums enum Device: String { case phone = "iOS" case pad = "iPadOS" case mac = "macOS" var js: String { switch self { case .phone: return "Device.Phone" case .pad: return "Device.Pad" case .mac: return "Device.Mac" } } } } /* struct TypeSwift { /// The type-safe Swift code equivalent of the parsed and generated TypeScript files. ie. `index.ts` → `index` (camelCase) enum File: String { /// `global.ts` case global = "global" /// `index.ts` case index = "index" } enum Body { /// `global.ts` case global(global) /// `index.ts` case index(index) /// The executable JavaScript code, transpiled from TypeScript, to be evaluated in some WKWebView object. var js: String { switch self { case .global(let io): return io.js case .index(let io): return io.js } } } } */
true
2dc893b209e81cf99a6b03fc1c25e16f626f9561
Swift
krazzbeluh/monSuperRPG
/monSuperRPG/Characters/Fighter.swift
UTF-8
398
2.703125
3
[]
no_license
// // Fighter.swift // monSuperRPG // // Created by Paul Leclerc on 24/12/2018. // Copyright © 2018 Paul Leclerc. All rights reserved. // import Foundation class Fighter: Character { init(name: String) { let sword = Sword() super.init(maxLife: 100, weapon: sword, name: name) } override func getCharacterName() -> String { return "Simple Combattant" } }
true
b168f95bca7134e0a5a19a1739f7dca43a8416c7
Swift
ss18/iOS
/DuckDuckGo/WhitelistManager.swift
UTF-8
1,826
2.703125
3
[ "Apache-2.0" ]
permissive
// // WhitelistManager.swift // DuckDuckGo // // Copyright © 2017 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public class WhitelistManager { private let contentBlockerConfigurationStore: ContentBlockerConfigurationStore public var count: Int { return contentBlockerConfigurationStore.domainWhitelist.count } private var domains: [String]? public init(contentBlockerConfigurationStore: ContentBlockerConfigurationStore = ContentBlockerConfigurationUserDefaults()) { self.contentBlockerConfigurationStore = contentBlockerConfigurationStore } public func add(domain: String) { contentBlockerConfigurationStore.addToWhitelist(domain: domain) domains = nil } public func remove(domain: String) { contentBlockerConfigurationStore.removeFromWhitelist(domain: domain) domains = nil } public func isWhitelisted(domain: String) -> Bool { return contentBlockerConfigurationStore.domainWhitelist.contains(domain) } public func domain(at index: Int) -> String? { if self.domains == nil { self.domains = Array(contentBlockerConfigurationStore.domainWhitelist).sorted() } return self.domains?[index] } }
true
e46d463ba3acb135c3ecfd334e84d5e224a785d1
Swift
Dean151/FeedTheCat-iOS
/FeedTheCat-iOS/View/Feeding/FeederList.swift
UTF-8
2,160
2.828125
3
[]
no_license
// // FeedersView.swift // FeedTheCat-iOS // // Created by Thomas DURAND on 12/08/2020. // Copyright © 2020 Thomas DURAND. All rights reserved. // import Aln import SwiftUI struct FeederList: View { let feeders: [Feeder] @State private var selection: Int = 0 @State private var refresh: Int = 0 var currentFeeder: Feeder? { if selection >= feeders.count { return nil } return feeders[selection] } #warning("FIXME: Name is not refreshed when updating from settings.") var title: LocalizedStringKey { guard let feeder = currentFeeder else { return "Misc settings" } if let name = feeder.name { return "\(name)'s Feeder" } return "Cat feeder" } var body: some View { ZStack { // WORKAROUND for having always big title with vertical scroll on pagetab NavigationView { ZStack { EmptyView() } .navigationTitle(title) } Group { if feeders.isEmpty { AssociateFeederStart() } else { TabView(selection: $selection) { ForEach(feeders.indices) { index in FeederBoard(feeder: feeders[index]).tag(index) } AdminMenu().tag(feeders.count) } .tabViewStyle(PageTabViewStyle()) .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always)) } } .padding(.top, 100) } } } struct FeederList_Previews: PreviewProvider { static var previews: some View { Group { FeederList(feeders: [Feeder(id: 1, name: "Newton", defaultAmount: 5)]) FeederList(feeders: [ Feeder(id: 1, name: "Newton", defaultAmount: 5), Feeder(id: 2, name: "Fake", defaultAmount: 5) ]) FeederList(feeders: []) }.accentColor(.accent) } }
true
9de55558ac11ca0b2bf5ad526ee7911f651f9dcb
Swift
asmtechnology/Lesson06.iOSTesting.2017.Apress
/PhotoBook/PhotoBook/CollectionViewCellViewModel.swift
UTF-8
1,219
2.75
3
[]
no_license
// // CollectionViewCellViewModel.swift // PhotoBook // // Created by Abhishek Mishra on 26/12/2016. // Copyright © 2016 ASM Technology Ltd. All rights reserved. // import Foundation class CollectionViewCellViewModel : NSObject { weak var photo:Photo? var collectionViewCell:CollectionViewCellProtocol? init?(model:Photo?) { guard let model = model else { return nil } super.init() self.photo = model } func setView(_ view:CollectionViewCellProtocol) { self.collectionViewCell = view } func setup() { guard let collectionViewCell = collectionViewCell , let photo = photo, let imageName = photo.imageName, let aperture = photo.aperture, let shutterSpeed = photo.shutterSpeed, let iso = photo.iso, let comments = photo.comments else { return } collectionViewCell.loadImage(resourceName: imageName) collectionViewCell.setCaption(captionText: comments) collectionViewCell.setShotDetails(shotDetailsText: "\(aperture), \(shutterSpeed), ISO \(iso)") } }
true
2e268cbb8500a2d1112c2d9f53c42968c860943e
Swift
miyamoto634/watchq
/WatchQ/PetBoard/BWWalkthrough/BWWalkthroughViewController.swift
UTF-8
14,172
2.671875
3
[ "MIT" ]
permissive
import UIKit import Social // MARK: - Protocols - /** Walkthrough Delegate: This delegate performs basic operations such as dismissing the Walkthrough or call whatever action on page change. Probably the Walkthrough is presented by this delegate. **/ @objc protocol BWWalkthroughViewControllerDelegate { @objc optional func walkthroughCloseButtonPressed() // If the skipRequest(sender:) action is connected to a button, this function is called when that button is pressed. @objc optional func walkthroughNextButtonPressed() // @objc optional func walkthroughPrevButtonPressed() // @objc optional func walkthroughPageDidChange(pageNumber:Int) // Called when current page changes } /** Walkthrough Page: The walkthrough page represents any page added to the Walkthrough. At the moment it's only used to perform custom animations on didScroll. **/ @objc protocol BWWalkthroughPage{ // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. @objc func walkthroughDidScroll(position:CGFloat, offset:CGFloat) // Called when the main Scrollview...scrolls } @objc class BWWalkthroughViewController: UIViewController, UIScrollViewDelegate,PetViewControllerDelegate{ var defaults = NSUserDefaults.standardUserDefaults(); func goToPetViewController()// this to call petView Without pages controller { let petStb = UIStoryboard(name: "Pet", bundle: nil) let PetView = petStb.instantiateViewControllerWithIdentifier("petView") as! PetViewController self.presentViewController(PetView, animated: false, completion: nil); } // MARK: - Public properties - weak var delegate:BWWalkthroughViewControllerDelegate? // TODO: If you need a page control, next or prev buttons add them via IB and connect them with these Outlets @IBOutlet var pageControl:UIPageControl? @IBOutlet var nextButton:UIButton? @IBOutlet var prevButton:UIButton? @IBOutlet var closeButton:UIButton? @IBOutlet weak var DiaBuyButton: UIButton! var currentPage:Int { // The index of the current page (readonly) get { let page = Int((scrollview.contentOffset.x / view.bounds.size.width)) return page } } // MARK: - Private properties - private let scrollview:UIScrollView! private var controllers:[UIViewController]! private var lastViewConstraint:NSArray? // MARK: - Overrides - required init?(coder aDecoder: NSCoder) { // Setup the scrollview scrollview = UIScrollView() scrollview.showsHorizontalScrollIndicator = false scrollview.showsVerticalScrollIndicator = false scrollview.pagingEnabled = true // Controllers as empty array controllers = Array() super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { scrollview = UIScrollView() controllers = Array() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() scrollview.delegate = self scrollview.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(scrollview, atIndex: 0) //scrollview is inserted as first view of the hierarchy // iphone以外ならダイヤボタン非表示 if String(UIDevice.currentDevice().model) == "iPad" { DiaBuyButton.hidden = true } // Set scrollview related constraints view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview])) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); pageControl?.numberOfPages = controllers.count pageControl?.currentPage = 0; if(defaults.integerForKey("pageNo") != 0) { //active black image to hide every thing in background } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if(defaults.integerForKey("pageNo") != 0) { goToPage(defaults.integerForKey("pageNo")); } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let controller = controllers![0] as? PetViewController { controller.delegate = self; } if(defaults.stringForKey("swichDeviceV") == nil || defaults.stringForKey("swichDeviceV")! == "watch") { } } func goToPage(pageNo : Int) { delegate?.walkthroughNextButtonPressed?() var frame = scrollview.frame frame.origin.x = CGFloat(pageNo) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } // MARK: - Internal methods - @IBAction func nextPage(){ if (currentPage + 1) < controllers.count { delegate?.walkthroughNextButtonPressed?() var frame = scrollview.frame frame.origin.x = CGFloat(currentPage + 1) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } @IBAction func prevPage(){ if currentPage > 0 { delegate?.walkthroughPrevButtonPressed?() var frame = scrollview.frame frame.origin.x = CGFloat(currentPage - 1) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } // TODO: If you want to implement a "skip" option // connect a button to this IBAction and implement the delegate with the skipWalkthrough @IBAction func close(sender: AnyObject) { goToMainView(); } func goToMainView() { delegate?.walkthroughCloseButtonPressed?() let mainStb = UIStoryboard(name: "Main", bundle: nil) let quizCategory = mainStb.instantiateViewControllerWithIdentifier("mainView") as! ViewController self.presentViewController(quizCategory, animated: true, completion: nil); } /** addViewController Add a new page to the walkthrough. To have information about the current position of the page in the walkthrough add a UIVIewController which implements BWWalkthroughPage */ func addViewController(vc:UIViewController)->Void{ controllers.append(vc) // Setup the viewController view vc.view.translatesAutoresizingMaskIntoConstraints = false scrollview.addSubview(vc.view) // Constraints let metricDict = ["w":vc.view.bounds.size.width,"h":vc.view.bounds.size.height] // - Generic cnst vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view(h)]", options:[], metrics: metricDict, views: ["view":vc.view])) vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view(w)]", options:[], metrics: metricDict, views: ["view":vc.view])) scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]|", options:[], metrics: nil, views: ["view":vc.view,])) // cnst for position: 1st element if controllers.count == 1{ scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]", options:[], metrics: nil, views: ["view":vc.view,])) // cnst for position: other elements }else{ let previousVC = controllers[controllers.count-2] let previousView = previousVC.view; scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[previousView]-0-[view]", options:[], metrics: nil, views: ["previousView":previousView,"view":vc.view])) if let cst = lastViewConstraint{ scrollview.removeConstraints(cst as! [NSLayoutConstraint]) } lastViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[view]-0-|", options:[], metrics: nil, views: ["view":vc.view]) scrollview.addConstraints(lastViewConstraint! as! [NSLayoutConstraint]) } } /** Update the UI to reflect the current walkthrough situation **/ private func updateUI(){ // Get the current page pageControl?.currentPage = currentPage // Notify delegate about the new page delegate?.walkthroughPageDidChange?(currentPage) // Hide/Show navigation buttons if currentPage == controllers.count - 1{ nextButton?.hidden = true }else{ nextButton?.hidden = false } if currentPage == 0{ prevButton?.hidden = true }else{ prevButton?.hidden = false } } // MARK: - Scrollview Delegate - func scrollViewDidScroll(sv: UIScrollView) { for var i=0; i < controllers.count; i++ { if let vc = controllers[i] as? BWWalkthroughPage{ let mx = ((scrollview.contentOffset.x + view.bounds.size.width) - (view.bounds.size.width * CGFloat(i))) / view.bounds.size.width // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. // print the mx value to get more info. // println("\(i):\(mx)") // We animate only the previous, current and next page if(mx < 2 && mx > -2.0){ vc.walkthroughDidScroll(scrollview.contentOffset.x, offset: mx) } } } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { updateUI() } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { updateUI() } /* WIP */ override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { print("CHANGE") } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { print("SIZE") } //設定ボタン @IBAction func onTouchUpSettingButton(sender: AnyObject) { let mainStb = UIStoryboard(name: "Main", bundle: nil) let nextview = mainStb.instantiateViewControllerWithIdentifier("SettingViewController") as! SettingViewController self.presentViewController(nextview, animated: false, completion: nil); } @IBAction func contactUs(sender: AnyObject)//to delete, not used any more { } //twitter投稿 @IBAction func postTwitter(sender: AnyObject) { //投稿画面を作る let twitterPostView:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)! //現在の画面のスクリーンショットを取得 let layer = UIApplication.sharedApplication().keyWindow!.layer let scale = UIScreen.mainScreen().scale UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale); layer.renderInContext(UIGraphicsGetCurrentContext()!) let screenshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); //テキストとスクリーンショット画像を添付 twitterPostView.setInitialText(" #WatchQ ") twitterPostView.addImage(screenshot) //ツイッター投稿画面へ遷移 self.presentViewController(twitterPostView, animated: true, completion: nil) } //ヘルプボタン @IBAction func onTouchUpHelpButton(sender: AnyObject) { let mainStb = UIStoryboard(name: "Main", bundle: nil) let nextview = mainStb.instantiateViewControllerWithIdentifier("HelpViewController") as! HelpViewController self.presentViewController(nextview, animated: false, completion: nil); } //ダイヤボタン @IBAction func onTouchUpShopButton(sender: AnyObject) { let mainStb = UIStoryboard(name: "Main", bundle: nil) let nextview = mainStb.instantiateViewControllerWithIdentifier("ShopList") as! ShopListViewController self.presentViewController(nextview, animated: false, completion: nil); } }
true
2256648bdc50dc4de733ea19c82e874b8863e499
Swift
wapsan/Dairy-train
/DairyTraining/Features/Profile/Features/Setting/SettingModel.swift
UTF-8
1,430
2.53125
3
[]
no_license
import UIKit class SettingDepartament { static let shared = SettingDepartament let colorSetting = SettingDepartament(departamentTittle: "Style",name: "Color setting", parametrs: ["Dark", "Ligh"]) let commonSetting = SettingDepartament(departamentTittle: "Common",name: "Weight metric", parametrs: ["Kilogramm", "Pounds"], aditionalParametrs: ["kg.","lbs"]) private let departamentTittle: String private let settingTittle: String private let parametrs: [String] private let aditionalParametrs: [String]? init() { self.settingTittle = nil self.parametrs = self.settingTittle = name self.parametrs = parametrs self.aditionalParametrs = aditionalParametrs self.departamentTittle = departamentTittle self.aditionalParametrs = aditionalParametrs self.departamentTittle = departamentTittle } init(departamentTittle: String,name: String, parametrs: [String], aditionalParametrs: [String]?) { self.settingTittle = name self.parametrs = parametrs self.aditionalParametrs = aditionalParametrs self.departamentTittle = departamentTittle } init(departamentTittle: String,name: String, parametrs: [String]) { self.settingTittle = name self.parametrs = parametrs self.aditionalParametrs = nil self.departamentTittle = departamentTittle } }
true
b2a4eedf416f5742cce09d90ac9c408c98562b95
Swift
jmvgcomp/ProjetoFinaliOS
/meusLivros/AuthorManage.swift
UTF-8
917
2.90625
3
[]
no_license
// // AuthorManage.swift // meusLivros // // Created by Professor on 16/06/18. // Copyright © 2018 Joanantha. All rights reserved. // import CoreData class AuthorManage{ static let shared = AuthorManage() var author: [Author] = [] func loadAuthor(with context: NSManagedObjectContext){ let fetchRequest: NSFetchRequest<Author> = Author.fetchRequest() let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] do{ author = try context.fetch(fetchRequest) }catch{ print(error.localizedDescription) } } func deleteAuthor(index: Int, context: NSManagedObjectContext){ let authors = author[index] context.delete(authors) do{try context.save()}catch{print(error.localizedDescription)} } private init(){ } }
true
bf8b2b5b122ce2892d0e3d8fcb49a0014cbeee99
Swift
plahteenlahti/zeitgeist
/Shared/Views/Deployments/DeploymentsFilterView.swift
UTF-8
3,265
2.734375
3
[ "MIT" ]
permissive
// // DeploymentsFilterView.swift // Zeitgeist // // Created by Daniel Eden on 29/12/2020. // Copyright © 2020 Daniel Eden. All rights reserved. // import SwiftUI enum StateFilter: Hashable { case allStates case filteredByState(state: DeploymentState) } enum TargetFilter: Hashable { case allTargets case filteredByTarget(target: DeploymentTarget) } enum ProjectNameFilter: Hashable { case allProjects case filteredByProjectName(name: String) } struct DeploymentsFilterView: View { @Environment(\.presentationMode) var presentationMode var projects: [Project] @Binding var projectFilter: ProjectNameFilter @Binding var stateFilter: StateFilter @Binding var productionFilter: Bool var body: some View { return NavigationView { Form { Section(header: Text("Filter deployments by:")) { Picker("Project", selection: $projectFilter) { Text("All projects").tag(ProjectNameFilter.allProjects) ForEach(projects, id: \.self) { project in Text(project.name).tag(ProjectNameFilter.filteredByProjectName(name: project.name)) } } Picker("Status", selection: $stateFilter) { Text("All statuses").tag(StateFilter.allStates) Label("Deployed", systemImage: "checkmark.circle.fill") .tag(StateFilter.filteredByState(state: .ready)) Label("Building", systemImage: "timer") .tag(StateFilter.filteredByState(state: .building)) Label("Build error", systemImage: "exclamationmark.circle.fill") .tag(StateFilter.filteredByState(state: .error)) Label("Cancelled", systemImage: "x.circle.fill") .tag(StateFilter.filteredByState(state: .cancelled)) Label("Queued", systemImage: "hourglass") .tag(StateFilter.filteredByState(state: .queued)) } Toggle(isOn: self.$productionFilter) { Label("Production deployents only", systemImage: "bolt.fill") } } Section { Button(action: { withAnimation { self.projectFilter = .allProjects self.productionFilter = false self.stateFilter = .allStates } }, label: { Text("Clear filters") }) .disabled(!filtersApplied()) } #if os(macOS) Section { Button(action: { self.presentationMode.wrappedValue.dismiss() }, label: { Text("Close") }) .keyboardShortcut(.escape) } #endif } .if(IS_MACOS) { $0.padding() } .navigationTitle(Text("Filters")) } } func filtersApplied() -> Bool { return self.projectFilter != .allProjects || self.productionFilter || self.stateFilter != .allStates } } struct DeploymentsFilterView_Previews: PreviewProvider { static var previews: some View { DeploymentsFilterView( projects: [], projectFilter: .constant(.allProjects), stateFilter: .constant(.allStates), productionFilter: .constant(false) ) } }
true
fe9816b94ee9250346fed449e82cfbddc7c738b9
Swift
dev-roy/UISwitch
/UISwitch/ViewController.swift
UTF-8
802
2.703125
3
[]
no_license
// // ViewController.swift // UISwitch // // Created by Field Employee on 3/26/20. // Copyright © 2020 Field Employee. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var lightBulbImage: UIImageView! @IBOutlet weak var stateLabel: UILabel! @IBOutlet weak var lightSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() lightSwitch.isOn = false stateLabel.text = "Off" } @IBAction func stateDidChange(_ sender: Any) { if lightSwitch.isOn { stateLabel.text = "On" lightBulbImage.image = UIImage(named: "lightOn") } else { stateLabel.text = "Off" lightBulbImage.image = UIImage(named: "lightOff") } } }
true
0945901ae8042f13615e00f10a14911ed2f46088
Swift
asambharwal1/MoneyManger
/MoneyManger/TabsViewController.swift
UTF-8
5,412
2.625
3
[]
no_license
// // TabsViewController.swift // MoneyManger // // Created by Aashish Sambharwal on 3/3/18. // Copyright © 2018 TeamMoney. All rights reserved. // import UIKit class TabsViewController: UITableViewController { @IBOutlet weak var addDebtLent: UIBarButtonItem! @IBOutlet var uitable: UITableView! func getConverted (amount: Double) -> String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.maximumFractionDigits = 2 return formatter.string(from: NSNumber(value: amount))! } 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) addDebtLent.isEnabled = false addDebtLent.isEnabled = true uitable.reloadData() if amountLeft < (amountLimit * 0.10) { self.view.backgroundColor = lightRed } else { self.view.backgroundColor = lightGreen } } func updateBackgroundColor () { amountLeft = amountLimit - (amountOwed + amountLent) if amountLeft < (amountLimit * 0.10) { self.view.backgroundColor = lightRed } else { self.view.backgroundColor = lightGreen } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return tabs.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) let tabIns = tabs[indexPath.row] cell.textLabel?.text = "\(tabIns.getName())" cell.detailTextLabel?.text = "Amount \( (tabIns.getifDebt() ? "Owed" : "Lent" ) ): \(getConverted(amount: tabIns.getAmount()))" let colorText = (tabIns.getifDebt()) ? lightRed : lightGreen /*cell.textLabel?.textColor = colorText cell.detailTextLabel?.textColor = colorText */ cell.backgroundColor = colorText cell.imageView?.image = tabIns.getImage() // Configure the cell... return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source let tabsDL = tabs[indexPath.row] if tabsDL.getifDebt() { amountOwed -= tabsDL.getAmount() } else { amountLent -= tabsDL.getAmount() } tabs.remove(at: indexPath.row) updateBackgroundColor() tableView.reloadData() } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // 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. guard let detailViewController = segue.destination as? DetailViewController else { return } guard let cell = sender as? UITableViewCell else { return } guard let indexPath = self.tableView.indexPath(for: cell) else { return } detailViewController.personTab = tabs[indexPath.row] detailViewController.indexNum = indexPath.row } }
true
267d551050e6d416199446fdc1c15fb965c3d039
Swift
Jyhwenchai/SwiftUIExample
/Categorys/AppStructure/AppStructure/ThirdSceneView.swift
UTF-8
346
2.515625
3
[]
no_license
// // ThirdSceneView.swift // AppStructure // // Created by 蔡志文 on 6/28/23. // import SwiftUI struct ThirdSceneView: View { @Environment(\.dismiss) private var dismiss var body: some View { VStack { Text("Third Scene View") Button("Dismiss") { dismiss() } } } } #Preview { ThirdSceneView() }
true
c6fb9946dd6a97b3a2751226b42c58ce785beb15
Swift
cristianspiridon/connectFilm
/ConnectFilm-UIKIT/Presentation/Movies/MoviesListViewModel.swift
UTF-8
1,461
2.765625
3
[]
no_license
// // MoviesListViewModel.swift // ConnectFilm-UIKIT // // Created by The Spiridon's on 03/02/2020. // Copyright © 2020 The Spiridon's. All rights reserved. // import Foundation class MoviesListViewModel { weak var viewController: MoviesViewControllerDisplayLogic? private let dataStore: MoviesDataSource? var onSelectMovie: ((Movie) -> Void)? private var movies = [Movie]() var moviesCount: Int { return movies.count } init(dataStore: MoviesDataSource) { self.dataStore = dataStore } func loadNextPage() { guard let dataStore = dataStore else { return } viewController?.setActivityIndicator(isVisible: true) dataStore.loadPopularMovies(pageIndex: dataStore.lastPage + 1) { [weak self] result in switch result { case let .success(popularMovies): self?.movies += popularMovies.results DispatchQueue.main.async { self?.viewController?.reloadData() } case let .failure(error): self?.viewController?.showError(error: error.localizedDescription) } } } func movie(at index: Int) -> Movie? { if movies.indices.contains(index) { return movies[index] } return nil } func selectMovie(at index: Int) { guard let movie = movie(at: index) else { return } onSelectMovie?(movie) } }
true
0a90b88954721ea8b131d596ec3621fb4f9563a8
Swift
ralph-bergmann/xcode-submodules
/main/main/ContentView.swift
UTF-8
342
2.546875
3
[]
no_license
// // ContentView.swift // main // // Created by Ralph Bergmann on 25.01.21. // import SwiftUI import core struct ContentView: View { var body: some View { Text("Today in one year is: \(nextYear())").padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
7cc003688bf34358b976ebdc191141072e42f436
Swift
TYRONEMICHAEL/sicp-swift
/SICP.playground/Pages/1.2.2 Tree Recursion.xcplaygroundpage/Contents.swift
UTF-8
1,142
4.09375
4
[]
no_license
// Fibonacci using tree recursion // 0 1 1 2 3 5 8 13 21 func fib(_ x: Int) -> Int { if x == 0 { return 0 } if x == 1 { return 1 } return fib(x - 1) + fib(x - 2) } fib(8) // Fibonacci using iteration // 0 1 1 2 3 5 8 13 21 func fibIter(_ x: Int, _ v: Int, _ prev: Int, _ counter: Int = 0) -> Int { if counter == x + 1 { return v } if counter == 0 { return fibIter(x, 0, 0, counter + 1) } if counter == 1 { return fibIter(x, 1, 0, counter + 1) } return fibIter(x, v + prev, v, counter + 1) } fibIter(8, 0, 0) // Exercise 1.11 // Recursive func f(_ n: Int) -> Int { if n < 3 { return n } return f(n - 1) + (2 * f(n - 2)) + (3 * f(n - 3)) } f(7) // Exercise 1.11 // Iterative func fIter(_ n: Int, _ a: Int, _ b: Int, _ c: Int, _ counter: Int = 0) -> Int { if counter == n { return a } return fIter(n, a + (2 * b) + (3 * c), a, b, counter + 1) } fIter(6, 2, 1, 0, 2) // Exercise 1.12 func pascal(_ row: Int, _ column: Int) -> Int { if row == 1 || column == 1 || column == row { return 1 } return pascal(row - 1, column - 1) + pascal(row - 1, column) } pascal(5, 3)
true
fb6f9b1d48bd2a16a82159e04298f71131a3c91a
Swift
rausnitz/sql
/Sources/SQL/SQLJoinMethod.swift
UTF-8
895
3.3125
3
[ "MIT" ]
permissive
/// `JOIN` clause method, i.e., `INNER`, `LEFT`, etc. public protocol SQLJoinMethod: SQLSerializable { /// Default join method, usually `INNER`. static var `default`: Self { get } } // MARK: Generic /// Generic implementation of `SQLJoinMethod`. public enum GenericSQLJoinMethod: SQLJoinMethod { /// See `SQLJoinMethod`. public static var `default`: GenericSQLJoinMethod { return .inner } /// See `SQLJoinMethod`. case inner /// See `SQLJoinMethod`. case left /// See `SQLJoinMethod`. case right /// See `SQLJoinMethod`. case full /// See `SQLSerializable`. public func serialize(_ binds: inout [Encodable]) -> String { switch self { case .inner: return "INNER" case .left: return "LEFT" case .right: return "RIGHT" case .full: return "FULL" } } }
true
369911367bdb0d5bd52f1e63e314b6d5cdf19554
Swift
tkrajina/expo
/packages/expo-modules-core/ios/Swift/Promise.swift
UTF-8
463
2.5625
3
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
public struct Promise: AnyMethodArgument { public typealias ResolveClosure = (Any?) -> Void public typealias RejectClosure = (String, String, Error?) -> Void public var resolve: ResolveClosure public var reject: RejectClosure public func reject(_ description: String, _ error: Error? = nil) -> Void { reject("ERR", description, error) } public func reject(_ error: Error) -> Void { reject("ERR", error.localizedDescription, error) } }
true
dcfd17e4ba844e9cc140cd30864ebb182aaf4465
Swift
nsomar/OAStatusItemKit
/Pod/Classes/ImageDrawer.swift
UTF-8
899
3.015625
3
[ "MIT" ]
permissive
// // ImageDrawer.swift // OAStatusItemKit // // Created by Omar Abdelhafith on 20/01/2016. // Copyright © 2016 Omar Abdelhafith. All rights reserved. // import Cocoa struct ImageDrawer { /** Draws an image in the current graphical context - parameter image: image to draw - parameter rect: rect to draw the image in */ static func draw(image: NSImage, inRect rect: NSRect) { image.draw( at: imageDrawingPoint(forImageSize: image.size, inRect: rect), from: .zero, operation: .sourceOver, fraction: 1.0) } /** The point at where to draw the image */ static func imageDrawingPoint(forImageSize imageSize: NSSize, inRect rect: NSRect) -> NSPoint { let iconX = roundf(Float(NSWidth(rect) - imageSize.width) / 2.0) let iconY = roundf(Float(NSHeight(rect) - imageSize.height) / 2.0) return NSMakePoint(CGFloat(iconX), CGFloat(iconY)) } }
true
0e1672600a23bdebbc5ee29827f403677fdc838c
Swift
Vzhukov74/five_seconds
/five_seconds/ui/interim result/view/ResultView.swift
UTF-8
6,088
2.578125
3
[]
no_license
// // ResultView.swift // 5second // // Created by Vlad on 16.08.2018. // Copyright © 2018 vz. All rights reserved. // import UIKit class ResultView: UIView { let animationDuration: CFTimeInterval = 2.5 let resultColumnColors = [UIColor.red, UIColor.blue, UIColor.cyan, UIColor.brown, UIColor.darkGray] func showResult(for result: GameResult) { layer.sublayers = nil var x: CGFloat = 20 let space: CGFloat = 10 let offset: CGFloat = 24 let columnWidth = (bounds.width - space * CGFloat(result.players.count) - CGFloat(2) * x) / CGFloat(result.players.count) let columnHeightSpan = (bounds.height - CGFloat(34) - columnWidth) / CGFloat(10) for index in 0..<result.players.count { let color = self.color(for: index) let columnHeight: CGFloat = columnHeightSpan * CGFloat(result.players[index].result) let y: CGFloat = bounds.height - columnHeight - offset //ResultColumnLayer let _resultLayer = ResultColumnLayer(width: columnWidth, height: columnHeight) _resultLayer.frame = CGRect(x: x, y: y, width: columnWidth, height: columnHeight) _resultLayer.fillColor = color.cgColor _resultLayer.strokeColor = UIColor.clear.cgColor _resultLayer.backgroundColor = UIColor.clear.cgColor layer.addSublayer(_resultLayer) _resultLayer.expand() //ResultLabelLayer let _resultLabelLayer = resultLabelLayer(for: result.players[index].result) _resultLabelLayer.frame = CGRect(x: x, y: (bounds.height - 25 - offset), width: columnWidth, height: 25) layer.addSublayer(_resultLabelLayer) //AvatarLayer let _avatarLayer = avatarLayer(for: result.players[index].player, index: index, color: color) let avatarLayerStartY: CGFloat = (bounds.height - columnWidth - 10 - offset) let avatarLayerEndY: CGFloat = (y - columnWidth + 5) _avatarLayer.frame = CGRect(x: x, y: avatarLayerStartY, width: columnWidth, height: columnWidth) let avatarAnimation = self.avatarAnimation(start: avatarLayerStartY, end: avatarLayerEndY) _avatarLayer.add(avatarAnimation, forKey: "avataranimation") layer.addSublayer(_avatarLayer) //NameLayer let _nameLayer = nameLayer(for: result.players[index].player, index: index, color: color) let nameLayerStartY: CGFloat = (bounds.height - 10 - offset) let nameLayerEndY: CGFloat = (y - 6) _nameLayer.frame = CGRect(x: x, y: nameLayerStartY, width: columnWidth, height: 12) let nameAnimation = self.nameAnimation(start: nameLayerStartY, end: nameLayerEndY) _nameLayer.add(nameAnimation, forKey: "nameAnimation") layer.addSublayer(_nameLayer) x += columnWidth + space } } // color private func color(for index: Int) -> UIColor { if index < resultColumnColors.count { return resultColumnColors[index] } else { var newIndex = index while newIndex > resultColumnColors.count { newIndex = index - resultColumnColors.count } guard newIndex < resultColumnColors.count else { return resultColumnColors[0] } return resultColumnColors[newIndex] } } // animations private func avatarAnimation(start: CGFloat, end: CGFloat) -> CAAnimation { let basicAnimation = CABasicAnimation(keyPath: "position.y") basicAnimation.fromValue = start basicAnimation.toValue = end basicAnimation.duration = animationDuration basicAnimation.isRemovedOnCompletion = false basicAnimation.fillMode = kCAFillModeForwards basicAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return basicAnimation } private func nameAnimation(start: CGFloat, end: CGFloat) -> CABasicAnimation { let basicAnimation = CABasicAnimation(keyPath: "position.y") basicAnimation.fromValue = start basicAnimation.toValue = end basicAnimation.duration = animationDuration basicAnimation.isRemovedOnCompletion = false basicAnimation.fillMode = kCAFillModeForwards basicAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return basicAnimation } // layers private func avatarLayer(for player: Player, index: Int, color: UIColor) -> CAShapeLayer { let avatar = AvatarStore.avatar(for: player.avatarKey) let _layer = CAShapeLayer() _layer.contents = avatar.cgImage return _layer } private func nameLayer(for player: Player, index: Int, color: UIColor) -> CATextLayer { let _layer = CATextLayer() let attributes = [ NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 12.0)!, NSAttributedStringKey.foregroundColor: UIColor.white ] let attributedString = NSAttributedString(string: player.name, attributes: attributes) _layer.string = attributedString _layer.alignmentMode = "center" _layer.display() return _layer } private func resultLabelLayer(for result: Int) -> CATextLayer { let _layer = CATextLayer() let attributes = [ NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 18.0)!, NSAttributedStringKey.foregroundColor: UIColor.white ] let attributedString = NSAttributedString(string: String(result), attributes: attributes) _layer.string = attributedString _layer.backgroundColor = UIColor.clear.cgColor _layer.alignmentMode = "center" _layer.display() return _layer } }
true
b7ed517f3cdc97800c6732a539eb9772dc89e4c7
Swift
FrankvandenBerg/ConfettiSwiftUIDemo
/ConfettiSwiftUIDemo/ConfiguratorTab.swift
UTF-8
6,383
3.125
3
[]
no_license
// // ConfiguratorTab.swift // ConfettiSwiftUIDemo // // Created by Simon Bachmann on 28.11.20. // import SwiftUI import ConfettiSwiftUI struct ConfiguratorTab: View{ @State var num:Int = 20 @State var confettis:[ConfettiType] = ConfettiType.allCases @State var colors:[Color] = [.blue, .red, .green, .yellow, .pink, .purple, .orange] @State var confettiSize:CGFloat = 10.0 @State var rainHeight: CGFloat = 600.0 @State var fadesOut:Bool = true @State var opacity:Double = 1.0 @State var openingAngle:Double = 60 @State var closingAngle:Double = 120 @State var radius:CGFloat = 300 @State var repetitions:Int = 0 @State var repetitionInterval:Double = 1.0 @State var showSheet = false var body: some View{ NavigationView{ Form{ Section(header: Text("Confetti")) { NavigationLink(destination: ConfettiSelectionView(confettis: $confettis)) { Text("Select Shapes: \(confettis.count)") } NavigationLink(destination: ColorSelectionView(colors: $colors)) { Text("Select Colors: \(colors.count)") } Stepper("Confettis: \(num)", value: $num, in: 1...100, step: 5) Stepper("Size: \(String(format: "%.2f", confettiSize))", value: $confettiSize, in: 1...50, step: 1) Stepper("Rain Height: \(String(format: "%.0f", rainHeight))", value: $rainHeight, in: 0...1000, step: 50) Stepper("Opacity: \(String(format: "%.2f", opacity))", value: $opacity, in: 0...1, step: 0.1) } Section(header: Text("Animation")){ Toggle(isOn: $fadesOut) { Text("Fades out") } Stepper("Opening Angle: \(String(format: "%.2f", openingAngle))", value: $openingAngle, in: 0...360, step: 10) Stepper("Closing Angle: \(String(format: "%.2f", closingAngle))", value: $closingAngle, in: 0...360, step: 10) Stepper("Radius: \(String(format: "%.2f", radius))", value: $radius, in: 1...1000, step: 20) Stepper("Repetitions: \(repetitions)", value: $repetitions, in: 1...100, step: 1) Stepper("Repetition Intervall: \(String(format: "%.2f", repetitionInterval))", value: $repetitionInterval, in: 0.1...10, step: 0.1) } } .toolbar { ToolbarItem(placement: .primaryAction) { Label("Preview", systemImage:"eye").onTapGesture { showSheet.toggle() } } } .sheet(isPresented: $showSheet){ ConfiguratorPreview(num: num, confettis: confettis, colors: colors, confettiSize: confettiSize, rainHeight: rainHeight, fadesOut: fadesOut, opacity: opacity, openingAngle: .degrees(openingAngle), closingAngle: .degrees(closingAngle), radius: radius, repetitions: repetitions, repetitionInterval: repetitionInterval) } .navigationTitle("Cofigurator") }.navigationViewStyle(StackNavigationViewStyle()) } } struct ColorSelectionView:View{ @Binding var colors:[Color] @State private var selectedColor = Color.yellow @State private var showColorPicker = false var body: some View{ Form{ Section(header: Text("Add new color")){ ColorPicker("Select a color", selection: $selectedColor) Button("Add selected color"){colors.append(selectedColor)} } Section(header: Text("Selected colors")){ List{ ForEach(0..<colors.count, id:\.self){i in colors[i].clipShape(Circle()) } .onDelete(perform: delete) } } } .navigationTitle("Colors") } func delete(at offsets: IndexSet) { colors.remove(atOffsets: offsets) } } struct ConfettiSelectionView:View{ @Binding var confettis:[ConfettiType] var body: some View{ Form{ List{ ForEach(ConfettiType.allCases, id:\.self){type in MultipleSelectionRow(type: type, isSelected: confettis.contains(type)){ if confettis.contains(type) && confettis.count > 1 { confettis.removeAll(where: { $0 == type }) } else if !confettis.contains(type){ confettis.append(type) } } } } } .navigationTitle("Confetti Shapes") } } struct MultipleSelectionRow: View { var type: ConfettiType var isSelected: Bool var action: () -> Void var body: some View { Button(action: self.action) { HStack { type.view.frame(width: 30, height: 30) if self.isSelected { Spacer() Image(systemName: "checkmark") } } } } } struct ConfiguratorPreview: View{ @State var counter = 1 let num:Int let confettis:[ConfettiType] let colors:[Color] let confettiSize:CGFloat let rainHeight:CGFloat let fadesOut:Bool let opacity:Double let openingAngle:Angle let closingAngle:Angle let radius:CGFloat let repetitions:Int let repetitionInterval:Double var body: some View{ ZStack{ ConfettiCannon( counter: $counter, num: num, confettis: confettis, colors: colors, confettiSize: confettiSize, rainHeight: rainHeight, fadesOut: fadesOut, opacity: opacity, openingAngle: openingAngle, closingAngle: closingAngle, radius: radius, repetitions: repetitions, repetitionInterval: repetitionInterval) Button("Trigger Animation"){counter += 1} } } } struct ConfiguratorTab_Previews: PreviewProvider { static var previews: some View { ConfiguratorTab() } }
true
d7c1400fa9c76984484a719070531dd9bf42da5f
Swift
AOx0/pySwift-Ahorcado
/Ahorcado/Objects/MusicPlayer.swift
UTF-8
759
2.84375
3
[ "MIT" ]
permissive
// // MusicPlayer.swift // Ahorcado // // Created by Alejandro D on 28/11/20. // import Foundation import AVKit enum MusicState { case paused case playing case stopped } struct GameMusicPlayer { public static var isSoundEnabled : Bool = true public static var sound : NSSound = NSSound(contentsOfFile: "\(Bundle.main.bundlePath)/Contents/Resources/Music.m4a", byReference: true)! public static func playSound() { GameMusicPlayer.sound.play() } public static func stopSound() { GameMusicPlayer.sound.stop() } public static func pauseSound() { GameMusicPlayer.sound.pause() } public static func resumeSound() { GameMusicPlayer.sound.resume() } }
true
be2a065e49e501de3fef846fd3db6272264a525b
Swift
MathildeTrb/festival-mobile
/festival-mobile/View/GameDetails.swift
UTF-8
2,154
2.984375
3
[]
no_license
// // DisplayGameDetails.swift // festival-mobile // // Created by user188238 on 3/25/21. // import SwiftUI struct GameDetails: View { var game : GameViewModel init(game: GameViewModel) { self.game = game } var body: some View { VStack { game.image? .clipShape(Circle()) .overlay(Circle().stroke(Color.white, lineWidth: 4)) .shadow(radius: 7) .offset(y: -130) .padding(.bottom, -130) VStack(alignment: .leading) { Text(game.name) .font(.title) Divider() HStack { Text("Nombre de joueurs") Spacer() Text(game.minNumberPlayer == game.maxNumberPlayer ? "\(game.minNumberPlayer)" : "\(game.minNumberPlayer) - \(game.maxNumberPlayer)") } HStack { Text("Âge minimum") Spacer() Text("\(game.minYearPlayer) ans") } HStack { Text("Durée") Spacer() Text("\(game.duration) min") } HStack { Text("Type") Spacer() Text(game.type.label) } Spacer().frame(height:50) if let manual = game.manual { HStack { Spacer() Link(destination: URL(string: manual)!) { VStack{ Image(systemName: "eyes") Text("Manuel") } }.foregroundColor(.black) Spacer() } } }.padding() } } }
true
4548800e3631b4963400bf0aabdb21d0cf465b4f
Swift
soggybag/Asteroid-Runner
/Asteroid Runner/States/GameOverState.swift
UTF-8
1,336
2.84375
3
[]
no_license
// // Ready.swift // StateMachine2 // // Created by mitchell hudson on 6/20/16. // Copyright © 2016 mitchell hudson. All rights reserved. // import GameplayKit import SpriteKit class GameOverState: GKState { unowned let scene: GameScene init(scene: GameScene) { self.scene = scene } // ----------------------------------- // Did enter Game Over State // ----------------------------------- override func didEnter(from previousState: GKState?) { // print("Enter Game Over State") scene.menu.show() } // ----------------------------------- // Is Valid Next State // ----------------------------------- override func isValidNextState(_ stateClass: AnyClass) -> Bool { // print("Game Over is valid next state") if stateClass == ReadyState.self { // print("\(stateClass) is valid next state") return true } // print("\(stateClass) is NOT valid next state") return false } // ----------------------------------- // Will Exit to State // ----------------------------------- override func willExit(to nextState: GKState) { } // ----------------------------------- // Update State // ----------------------------------- override func update(deltaTime seconds: TimeInterval) { // print("Game over State update") } }
true
7655d32220471f2eb2d9e0b7365444a95b4f98e6
Swift
FuzzyBuckBeak/SampleApps
/ListImagesFileManager/ListImagesFileManager/ViewController.swift
UTF-8
2,087
2.90625
3
[]
no_license
// // ViewController.swift // ListImagesFileManager // // Created by: FuzzyBuckBeak on 4/4/19 // Copyright © 2018 FuzzyBuckBeak. All rights reserved. /***************************************************************************************************************************** *****************************************************************************************************************************/ import UIKit class ViewController: UITableViewController { var pictures: [String] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. loadData() title = "Storm Viewer" navigationController?.navigationBar.prefersLargeTitles = true } func loadData() { let fileManager = FileManager.default guard let path = Bundle.main.resourcePath else { fatalError("Cant find resource Path")} do { pictures = try fileManager.contentsOfDirectory(atPath: path) } catch { print("Could not read contents of file"); } print(pictures.sort()) } } extension ViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pictures.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = pictures[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let detail = storyboard?.instantiateViewController(withIdentifier: "detail") as? DetailedViewController { detail.selectedPicture = indexPath.row + 1 detail.totalPicture = pictures.count detail.selectedImage = pictures[indexPath.row] navigationController?.pushViewController(detail, animated: true) } } }
true
ab02e9a39843e7b01eff34bfccbf97161f1d6cf9
Swift
AmishaChordia/Ting
/Ting/AIIntentValidationClient.swift
UTF-8
2,172
2.640625
3
[]
no_license
// // AIIntentValidationClient.swift // Ting // // Created by Chordia, Amisha (US - Mumbai) on 9/26/15. // Copyright © 2015 Chordia, Amisha (US - Mumbai). All rights reserved. // import UIKit let intentValues : NSDictionary = [Constants.WITIntents.WITBlockCard : "Are you sure you want to block your card?",Constants.WITIntents.WITChangePIN : "Are you sure you want to change your PIN?"] let intentSuccessMessage : NSDictionary = [Constants.WITIntents.WITBlockCard : "Your card has been successfully blocked",Constants.WITIntents.WITChangePIN : "We will contact you soon to reset your ATM PIN!"] class AIIntentValidationClient: NSObject { func generateStringForIntent(intentObj : AIIntentModel) -> String { if intentObj.intent == Constants.WITIntents.WITTransferMoney { return getStringWithEntitiesForTranferMoney(intentObj) } let intentValueString = intentValues.valueForKey(intentObj.intent!) as! String return intentValueString } func getStringWithEntitiesForTranferMoney(intentObj : AIIntentModel) -> String { if let money = intentObj.entity?.money { if let person = intentObj.entity?.contact { let str = "Are you sure you want to send \(money) to \(person) ?" return str } else { AISpeechClient.readCurrentString(Constants.AIStrings.AIPersonErrorString) } } else { AISpeechClient.readCurrentString(Constants.AIStrings.AIMoneyErrorString) } return "" } func generateSuccessMessage(intentObj : AIIntentModel) -> String { if intentObj.intent == Constants.WITIntents.WITTransferMoney { if let money = intentObj.entity?.money { if let person = intentObj.entity?.contact { return "You have successfully transferred \(money) to \(person)" } } } let successMessageString = intentSuccessMessage.valueForKey(intentObj.intent!) as! String return successMessageString } }
true
b533914a0105ffac7d01f3eb86a0f8bfadb230ef
Swift
NUDelta/Zombies-Interactive
/Zombies Interactive/classes/ExperienceKit/Stage.swift
UTF-8
6,503
2.765625
3
[]
no_license
// // MomentBlock.swift // Zombies Interactive // // Created by Scott Cambo on 8/19/15. // Copyright (c) 2015 Scott Cambo. All rights reserved. // import Foundation // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // MomentBlock: a sub-experience comprised of moments class MomentBlock: NSObject{ // TODO: organize methods better var MomentBlockStarted = false var isPlaying = false var moments:[Moment] var currentMomentIdx = -1 var title: String let eventManager = EventManager() var MomentBlockSimpleInsertionIndices: [Int]? var MomentBlockSimplePool: [MomentBlockSimple]? var currentMoment: Moment? { get { return moments[safe: currentMomentIdx] } } init(moments: [Moment], title: String, MomentBlockSimpleInsertionIndices:[Int]?=nil, MomentBlockSimplePool:[MomentBlockSimple]?=nil) { if MomentBlockSimplePool?.count < MomentBlockSimpleInsertionIndices?.count { fatalError("MomentBlockSimpleInsertionPool must be larger than the number of MomentBlockSimple insertion indices, as none will be repeated") } self.moments = moments self.title = title self.MomentBlockSimplePool = MomentBlockSimplePool self.MomentBlockSimpleInsertionIndices = MomentBlockSimpleInsertionIndices super.init() for moment in self.moments { moment.eventManager.listenTo("startingMoment", action: startingMoment) moment.eventManager.listenTo("nextMoment", action: nextMoment) moment.eventManager.listenTo("startingInterim", action: startingInterim) moment.eventManager.listenTo("startingSound", action: startingSound) moment.eventManager.listenTo("foundWorldObject", action: recordWorldObject) } } func insertAnyRandomMomentBlockSimples() { // should this be done at runtime to allow for better "audibles"? if let insertionIndices = MomentBlockSimpleInsertionIndices, let _ = self.MomentBlockSimplePool { var numMomentsInserted = 0 for idx in insertionIndices { let idxNew = idx + numMomentsInserted let randomMomentBlockSimpleIdx = self.MomentBlockSimplePool!.randomItemIndex() let randomMomentBlockSimple = self.MomentBlockSimplePool!.remove(at: randomMomentBlockSimpleIdx) eventManager.trigger("choseRandomMomentBlockSimple", information: ["MomentBlockSimpleTitle": randomMomentBlockSimple.title]) self.insertMomentsAtIndex(randomMomentBlockSimple.moments, idx: idxNew) numMomentsInserted += randomMomentBlockSimple.moments.count } print("\n(MomentBlock.title:\(self.title)) MomentBlockSimples inserted at random (count:\(numMomentsInserted)). All moments:\n\(self.moments)") } } func startingMoment(_ information: Any?) { self.eventManager.trigger("startingMoment", information: information) } func startingSound() { self.eventManager.trigger("startingSound") } func startingInterim(_ information: Any?) { print("(MomentBlock::startingInterim) triggered") self.eventManager.trigger("startingInterim", information: information) } func start() { insertAnyRandomMomentBlockSimples() print("\n(MomentBlock::start) Starting MomentBlock: " + self.title) MomentBlockStarted = true self.nextMoment() } func play() { self.currentMoment?.play() } func pause() { self.currentMoment?.pause() } func nextMoment() { //[PERHAPS I SHOULD DO OPPORTUNITY CHECKING HERE INSTEAD] // TODO this is sloppy checking types, fix this if let _ = self.currentMoment as? SensorCollector { self.eventManager.trigger("sensorCollectorEnded") } else if let _ = self.currentMoment as? CollectorWithSound { self.eventManager.trigger("sensorCollectorEnded") } // stop the current moment's audio here instead of ExperienceManager? self.currentMomentIdx += 1 if self.currentMomentIdx < moments.count { if let currentMoment = self.currentMoment as? SensorCollector { self.eventManager.trigger("sensorCollectorStarted", information: ["sensors": currentMoment.sensors.rawValues, "label": currentMoment.dataLabel, "MomentBlockSimple": currentMoment.title]) } else if let currentMoment = self.currentMoment as? CollectorWithSound { self.eventManager.trigger("sensorCollectorStarted", information: ["sensors": currentMoment.sensors.rawValues, "label": currentMoment.dataLabel, "MomentBlockSimple": currentMoment.title]) } print("\n--starting next moment (idx:\(currentMomentIdx))") self.currentMoment?.start() } else { print("Finished MomentBlock: \(self.title)") self.eventManager.trigger("MomentBlockFinished") } } func next(_ notification: Notification) { print("--next(???)--") self.nextMoment() } func recordWorldObject(_ information: Any?) { print(" MomentBlock.recordWorldObject called") self.eventManager.trigger("foundWorldObject", information: information) } func insertMomentsAtIndex(_ insertedMoments:[Moment], idx:Int) { for moment in insertedMoments { moment.eventManager.listenTo("startingMoment", action: self.startingMoment) moment.eventManager.listenTo("nextMoment", action: self.nextMoment) moment.eventManager.listenTo("startingInterim", action: self.startingInterim) moment.eventManager.listenTo("startingSound", action: self.startingSound) moment.eventManager.listenTo("foundWorldObject", action: self.recordWorldObject) } self.moments = self.moments[0..<idx] + insertedMoments + self.moments[idx..<self.moments.count] } }
true
4a3e8d700ee7b4733e08376ad4d9cd53b05fcb86
Swift
bootchk/Swift-Spritekit-Score-Module
/Score/HighScore.swift
UTF-8
1,568
3.140625
3
[ "MIT" ]
permissive
import Foundation class HighScore { /* Persistent high score. Implementation: userDefaults Responsibility: - understand gameMode and set the proper score for the mode Solitary sets one persistent recordScore. Two-player cooperative sets a different recordScore. In two-player cooperative, there is only one clock. One person can set a new recordScore (for themselves) while the same time does not set a new recordScore for the other. (They have their own record, and it might not be exceeded.) */ // TODO: low separate recordScores for two-player cooperative /* if gameMode.isSolitary else two_player_high_score_preference var recordTimeTwoPlayerCooperative : NSTimeInterval = 0 */ // Canonical use of singletong UserDefaults let userDefaults = NSUserDefaults.standardUserDefaults() var recordTimeSolitary : NSTimeInterval { let result = userDefaults.doubleForKey("solitary_high_score_preference") // result is zero if never set before return result } // MARK: Solitary func checkAndRecordTimeRecordSet(newTime: NSTimeInterval) -> Bool { let result = newTime > recordTimeSolitary if result { recordNewTimeRecord(newTime) } return result } private func recordNewTimeRecord(newTime : NSTimeInterval) { // recordMaxTime = newTime // TODO: Enhancement Make record score retrievable at any time. // Currently it is visible to user only at end of round. userDefaults.setDouble(newTime, forKey:"solitary_high_score_preference") } }
true
08d4e5827e75d4a7054cafca1e8815dd9965a5e7
Swift
jonnattanChoque/swiftUI
/4-Scroll/Scroll/ContentView.swift
UTF-8
1,382
2.84375
3
[]
no_license
// // ContentView.swift // Scroll // // Created by MacBook Retina on 12/11/20. // Copyright © 2020 com.valid. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { VStack{ ScrollView(.vertical){ Header() CardsHorizont() CardsHorizont() CardsHorizont() CardsHorizont() }.background(Color.blue) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct CardsHorizont: View { var body: some View { ScrollView(.horizontal, showsIndicators: false){ HStack { Card(imageNam: "spiderman", author: "Jonnattan Choque", title: "Curso 1 de programación", price: "$11.99", oldPrice: "$111.99").frame(width:300) Card(imageNam: "spiderman", author: "Jonnattan Choque", title: "Diseño 2 de programación", price: "$11.99", oldPrice: "$111.99").frame(width:300) Card(imageNam: "spiderman", author: "Jonnattan Choque", title: "Curso 3 de programación", price: "$11.99", oldPrice: "$111.99").frame(width:300) Card(imageNam: "spiderman", author: "Jonnattan Choque", title: "Diseño 4 de programación", price: "$11.99", oldPrice: "$111.99").frame(width:300) } Spacer() } } }
true
dae5341f8b225aacb59cb4745230e36aaa776ea7
Swift
developersancho/VivoFinder
/VivoFinder/SlidingPanel/SlidingUpPanel.swift
UTF-8
7,107
2.640625
3
[]
no_license
// // SlidingUpPanel.swift // VivoFinder // // Created by developersancho on 12.05.2018. // Copyright © 2018 developersancho. All rights reserved. // import UIKit protocol SlidingUpPanelDelegate { func willOpen() func didOpen() func willHalfOpen() func didHalfOpen() func willClose() func didClose() } class SlidingUpPanel: UIView { enum SlidingState { case closed; case halfOpened; case opened; } //MARK: Variables var delegate: SlidingUpPanelDelegate?; var state:SlidingState = .closed; var topView: UIView?; var topViewHeight: CGFloat { get { return self.topView?.frame.height ?? 0 } }; var tooltipHeight: CGFloat { get { return self.tooltip?.frame.height ?? 0 } }; var animationDuration = 0.2; var threshold: CGFloat = 30.0; var lastLocation:CGPoint = CGPoint(x: 0, y: 0) var toolTipLastLocation:CGPoint? = CGPoint(x: 0, y: 0) var tooltip: UIView? //MARK: Life cycle override init(frame: CGRect) { super.init(frame: frame); self.isUserInteractionEnabled = true; let tap = UITapGestureRecognizer(target: self, action: #selector(SlidingUpPanel.togglePanel)); self.addGestureRecognizer(tap); let pan = UIPanGestureRecognizer(target:self, action:#selector(SlidingUpPanel.detectPan(_:))) self.addGestureRecognizer(pan); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { super.didMoveToSuperview(); setup() } //MARK: Private functions func setup() { self.state = .closed; if let tv = topView { var f = tv.frame f.origin.y = 0; tv.frame = f; self.addSubview(tv) } if let parent = superview { frame.origin.y = parent.bounds.height - tooltipHeight; if let tooltipView = tooltip { var tFrame = frame tFrame.size = tooltipView.frame.size tFrame.origin.y = 0 tooltipView.frame = tFrame self.addSubview(tooltipView) } } if let tooltipView = tooltip { tooltipView.isUserInteractionEnabled = true; tooltipView.isExclusiveTouch = false; } } func moveToNearestState(shouldMove: Bool) { if let parent = superview { let parentY = parent.frame.height let y = self.frame.minY if shouldMove { switch state { case .closed: if y < parentY / 2.0 { self.open() } else { self.halfOpen() } break; case .halfOpened: if y < parentY / 2.0 { self.open() } else { self.close() } break; case .opened: if y < parentY / 2.0 { self.halfOpen() } else { self.close() } break; } } else { //earth to earth, dust to dust switch state { case .closed: self.close() break; case .halfOpened: self.halfOpen() break; case .opened: self.open(); break; } } } } //MARK: Public functions @objc func togglePanel() { switch self.state { case .closed: self.halfOpen(); break; case .halfOpened: //self.open(); self.close(); break; default: self.close(); break; } } func open() { self.delegate?.willOpen() UIView.animate(withDuration: self.animationDuration, animations: { if let parent = self.superview { self.frame.origin.y = parent.bounds.height - self.frame.height; self.tooltip?.frame.origin.y = (self.frame.height - self.tooltipHeight) * 2; } }) { (_) in self.state = .opened self.delegate?.didOpen() } } func halfOpen() { self.delegate?.willHalfOpen() UIView.animate(withDuration: self.animationDuration, animations: { if let parent = self.superview { self.frame.origin.y = parent.bounds.height / 2.5; self.tooltip?.frame.origin.y = self.frame.height - self.tooltipHeight * 2 ; } }) { (_) in self.state = .halfOpened self.delegate?.didHalfOpen() } } func close() { self.delegate?.willClose() UIView.animate(withDuration: self.animationDuration, animations: { if let parent = self.superview { self.frame.origin.y = parent.bounds.height - self.tooltipHeight; self.tooltip?.frame.origin.y = 0; } }) { (_) in self.state = .closed self.delegate?.didClose() } } //MARK: Interactions override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { //check if user touching on the top bar let barFrame = CGRect(x: 0,y: 0, width: self.frame.width,height: self.tooltipHeight) return barFrame.contains(point) } @objc func detectPan(_ recognizer:UIPanGestureRecognizer) { if recognizer.state == .began { lastLocation = self.center toolTipLastLocation = tooltip?.center } let translation = recognizer.translation(in: self.superview!) self.center = CGPoint(x: lastLocation.x, y: lastLocation.y + translation.y) if let tooltipView = tooltip , let loc = toolTipLastLocation{ tooltipView.center = CGPoint(x: loc.x, y: loc.y - 2*translation.y) if tooltipView.frame.minY < 0 { tooltipView.frame.origin.y = 0; } if tooltipView.frame.maxY > self.frame.maxY + tooltipView.frame.height{ tooltipView.frame.origin.y = self.frame.maxY + tooltipView.frame.height; } } if(recognizer.state == UIGestureRecognizerState.ended) { //All fingers are lifted. let shouldMove = (translation.y >= self.threshold) || (translation.y <= 0 - self.threshold) self.moveToNearestState(shouldMove: shouldMove); } } }
true
a50909772b3e8ff70463914f587d90727cf25ef8
Swift
ljrocha/100daysofswift-projects
/MilestoneProjects7-9/MilestoneProjects7-9/ViewController.swift
UTF-8
6,539
2.921875
3
[]
no_license
// // ViewController.swift // MilestoneProjects7-9 // // Created by Leandro Rocha on 4/6/19. // Copyright © 2019 Leandro Rocha. All rights reserved. // import UIKit class ViewController: UIViewController { var scoreLabel: UILabel! var attemptsLeftLabel: UILabel! var targetWordLabel: UILabel! var letterButtons = [UIButton]() var words = [String]() var targetWord = "" var usedLetters = [String]() var displayWord: String { var str = "" for letter in targetWord { let strLetter = String(letter) if usedLetters.contains(strLetter) { str += strLetter } else { str += "?" } } return str } var score = 0 { didSet { scoreLabel.text = "Score: \(score)" if score == targetWord.count { showSuccessAlert() } } } var numberOfAttempts = 0 { didSet { attemptsLeftLabel.text = "Attempts left: \(maxNumberOfAttempts - numberOfAttempts)" if numberOfAttempts >= maxNumberOfAttempts { showMaxTriesAlert() } } } let maxNumberOfAttempts = 7 override func loadView() { view = UIView() view.backgroundColor = .white scoreLabel = UILabel() scoreLabel.translatesAutoresizingMaskIntoConstraints = false scoreLabel.text = "Score: 0" view.addSubview(scoreLabel) attemptsLeftLabel = UILabel() attemptsLeftLabel.translatesAutoresizingMaskIntoConstraints = false attemptsLeftLabel.textAlignment = .right attemptsLeftLabel.textColor = .red attemptsLeftLabel.text = "Attempts left: 7" view.addSubview(attemptsLeftLabel) targetWordLabel = UILabel() targetWordLabel.translatesAutoresizingMaskIntoConstraints = false targetWordLabel.font = UIFont.systemFont(ofSize: 30) targetWordLabel.numberOfLines = 0 targetWordLabel.textAlignment = .center targetWordLabel.text = "Word to guess" targetWordLabel.setContentHuggingPriority(UILayoutPriority(1), for: .vertical) view.addSubview(targetWordLabel) let buttonsView = UIView() buttonsView.translatesAutoresizingMaskIntoConstraints = false buttonsView.layer.borderWidth = 1 buttonsView.layer.borderColor = UIColor.lightGray.cgColor view.addSubview(buttonsView) NSLayoutConstraint.activate([ scoreLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor), scoreLabel.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 20), attemptsLeftLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor), attemptsLeftLabel.centerYAnchor.constraint(equalTo: scoreLabel.centerYAnchor), targetWordLabel.topAnchor.constraint(equalTo: scoreLabel.bottomAnchor, constant: 50), targetWordLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), buttonsView.widthAnchor.constraint(equalToConstant: 560), buttonsView.heightAnchor.constraint(equalToConstant: 320), buttonsView.centerXAnchor.constraint(equalTo: view.centerXAnchor), buttonsView.topAnchor.constraint(equalTo: targetWordLabel.bottomAnchor, constant: 20), buttonsView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -50) ]) let width = 80 let height = 80 let maxLetterButtons = 26 var letterButtonsAdded = 0 outerloop: for row in 0..<4 { for column in 0..<7 { if letterButtonsAdded < maxLetterButtons { let letterButton = UIButton(type: .system) letterButton.titleLabel?.font = UIFont.systemFont(ofSize: 36) let letter = String(Unicode.Scalar(65 + letterButtonsAdded)!) letterButton.setTitle(letter, for: .normal) letterButton.addTarget(self, action: #selector(letterTapped), for: .touchUpInside) let frame = CGRect(x: column * width, y: row * height, width: width, height: height) letterButton.frame = frame buttonsView.addSubview(letterButton) letterButtons.append(letterButton) letterButtonsAdded += 1 } else { break outerloop } } } } override func viewDidLoad() { super.viewDidLoad() words += ["HELLO", "WORLD", "APPLE", "SWIFT", "XCODE", "IPHONE", "XBOX"] startNewGame() } @objc func letterTapped(_ sender: UIButton) { guard let buttonLetter = sender.titleLabel?.text else { return } usedLetters.append(buttonLetter) sender.isHidden = true guard targetWord.contains(buttonLetter) else { numberOfAttempts += 1 return } score += targetWord.reduce(0) { total, letter in if letter == Character(buttonLetter) { return total + 1 } return total } targetWordLabel.text = displayWord } func showSuccessAlert() { let ac = UIAlertController(title: "Excellent", message: "You guessed it!", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: startNewGame)) present(ac, animated: true) } func showMaxTriesAlert() { let ac = UIAlertController(title: "Maximum attempts", message: "You've exceeded the maximum allowed attempts", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default, handler: startNewGame)) present(ac, animated: true) } func startNewGame(action: UIAlertAction! = nil) { targetWord = words.randomElement()! score = 0 numberOfAttempts = 0 usedLetters.removeAll() targetWordLabel.text = displayWord for button in letterButtons { button.isHidden = false } } }
true
f355a0a8f8418c6df482464c14370e6892ef0eff
Swift
skyweb07/Snap.swift
/SnapTests/Core/Infrastructure/Extension/CALayer/CALayerImageSpec.swift
UTF-8
971
2.71875
3
[ "MIT" ]
permissive
import XCTest import UIKit final class CALayerImageSpec: XCTestCase { func test_should_render_image_from_calayer() { let layer = CALayer() layer.frame = CGRect(x: 0, y: 0, width: 10, height: 10) layer.backgroundColor = UIColor.red.cgColor let image = layer.image() XCTAssertNotNil(image) } func test_not_render_image_if_layer_if_its_invalid() { let layer = CALayer() let image = layer.image() XCTAssertNil(image) } func test_image_should_have_same_size_as_the_layer() { let layer = CALayer() layer.frame = CGRect(x: 0, y: 0, width: 10, height: 10) let image = layer.image() XCTAssertEqual(image?.size, layer.frame.size) } func test_image_should_have_same_content_scale_as_the_layer() { let layer = CALayer() layer.frame = CGRect(x: 0, y: 0, width: 10, height: 10) let image = layer.image() XCTAssertEqual(image?.scale, layer.contentsScale) } }
true
a6e30da8c298532e9571d623acf3c86effe01340
Swift
zhibincheng/apressios
/11 Presidents/Presidents/DetailViewController.swift
UTF-8
3,480
2.796875
3
[]
no_license
// // DetailViewController.swift // Presidents // // Created by 张晶 on 2019/1/4. // Copyright © 2019 Apress. All rights reserved. // import UIKit class DetailViewController: UIViewController,UIPopoverPresentationControllerDelegate { @IBOutlet weak var detailDescriptionLabel: UILabel! @IBOutlet weak var webView:UIWebView! private var languageButton:UIBarButtonItem? private var languagePopoverController:UIPopoverPresentationController?//UIPopoverController? var languageString: String = "" { didSet { if (languageString != oldValue) { configureView() } } } private func modifyUrlForLanguage(url:String,language lang:String?) -> String{ var newUrl = url if let langStr = lang{ let range = NSMakeRange(7,2) if !langStr.isEmpty && (url as NSString).substring(with: range) != langStr{ newUrl = "http://www.baidu.com" //实际代码在P264 } } newUrl = "http://www.baidu.com" return newUrl } func configureView() { // 更新detailItem的UI //if let的主要作用,就是在{}里面,不再需要解包了。 if let detail:AnyObject = self.detailItem { if let label = self.detailDescriptionLabel { let dict = detail as! [String:String] let urlString = modifyUrlForLanguage(url: dict["url"]!, language: languageString) // let urlString = dict["url"]! label.text = urlString let url = URL(string:urlString)! let request = URLRequest(url:url) webView.loadRequest(request) let name = dict["name"]! title = name // label.text = "这就是:\(detail.description)" //description是NSObject子类自己实现的,恰好NSDate的Description是返回时间与日期 } } } var detailItem: AnyObject? { //当detailItem的值每次变动时,都会调用didSet didSet { // 更新view configureView() } } override func viewDidLoad() { super.viewDidLoad() if UIDevice.current.userInterfaceIdiom == .pad { languageButton = UIBarButtonItem(title: "Choose Language", style: .plain, target: self, action: #selector(toggleLanguagePopover)) navigationItem.rightBarButtonItem = languageButton } configureView() //视图被加载时就调用一次 } //这个方法可是费了好大劲搞定的啊 @objc func toggleLanguagePopover(){ let pop = LanguageListController() pop.modalPresentationStyle = .popover pop.popoverPresentationController?.delegate = self pop.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem; pop.popoverPresentationController?.permittedArrowDirections = .up pop.preferredContentSize = CGSize(width: 200, height: 300) self.present(pop, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } }
true
bdeb7bdb570daed35ee505ed9bfcee9daea48d28
Swift
Benny-iPhone/hackeruJul2018
/OODPatterns.playground/Contents.swift
UTF-8
855
3.828125
4
[]
no_license
//Singleton usage let s1 = MySingy.getInstance(); let s2 = MySingy.getInstance(); print(s1 === s2); let s21 = MySingy2.instance; let s22 = MySingy2.instance; print(s21 === s22); //Factory method usage let vehicles = [ VehicleFactory.createVehicle("Bike")!, VehicleFactory.createVehicle("BIKE")!, VehicleFactory.createVehicle("MotorCycle")!, VehicleFactory.createVehicle("bus")!, VehicleFactory.createVehicle("car")!, ]; for v in vehicles{ v.drive();//polymorphic call } //Builder usage: Rect().x(7).y(8).width(10).height(20).show(); Rect().width(10).color("Red").height(20).show(); Rect().size(width: 100, height: 50).color("Blue").show(); //Flyweight usage let img1 = MyImage.getImage("bubu.jpg"); let img2 = MyImage.getImage("bubu.jpg"); img1.show(); //Facade let mac = Computer(); mac.start(); mac.shutDown();
true
b7a0a5a58604dacd849a6b5234883d57726efba4
Swift
adamnemecek/GPUExample
/GPUExample/KernelSelectionController.swift
UTF-8
764
2.5625
3
[]
no_license
// // KernelSelectionController.swift // GPUExample // // Created by Mateusz Buda on 05/08/15. // Copyright (c) 2015 inFullMobile. All rights reserved. // import UIKit class KernelSelectionController: UITableViewController { var selectedKernel: String! // MARK: - Delegate override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { selectedKernel = indexPath.row > 0 ? "reduce\(indexPath.row)" : "map" return indexPath } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destController: ViewController = segue.destination as! ViewController destController.kernelName = selectedKernel } }
true
60d087f42e5975193cb312fbebf44821353ade07
Swift
toonbertier/badget-native
/Badget/ChallengeOverviewView.swift
UTF-8
4,726
2.640625
3
[]
no_license
// // ChallengeOverviewView.swift // Badget // // Created by Toon Bertier on 02/06/15. // Copyright (c) 2015 Toon Bertier. All rights reserved. // import UIKit protocol ChallengeOverviewViewDelegate:class { func didChooseChallenge(name:ChallengeName) } class ChallengeOverviewView: UIView, UIScrollViewDelegate, UIGestureRecognizerDelegate { let scrollView:UIScrollView let challengeNames:Array<ChallengeName> = [.StraightLine, .CrowdSurfing, .Quiz] let cardNames = ["rechte-lijn-kaart", "geniet-rit-kaart", "wikken-wegen-kaart"] var cardWidth:CGFloat! var originalCenterX:CGFloat! weak var delegate:ChallengeOverviewViewDelegate? override init(frame: CGRect) { self.scrollView = UIScrollView(frame: CGRectMake(0, 0, frame.width, frame.height)) super.init(frame: frame) self.addSubview(UIImageView(image: UIImage(named: "white-bg")!)) setScrollableTickets() self.scrollView.showsHorizontalScrollIndicator = false self.addSubview(self.scrollView) showCardHolder() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func showCardHolder() { let kaarthouderImage = UIImage(named: "kaarthouder") let kaarthouder = UIImageView(image: kaarthouderImage) kaarthouder.frame = CGRectMake(self.center.x - kaarthouderImage!.size.width/2, 385, kaarthouderImage!.size.width, kaarthouderImage!.size.height) self.addSubview(kaarthouder) self.bringSubviewToFront(kaarthouder) } func setScrollableTickets() { var xPos = CGFloat(87) for(var i = 0; i <= 2; i++) { let image = UIImage(named: self.cardNames[i]) var imageView = UIImageView(image: image!) imageView.frame = CGRectMake(xPos, 90, image!.size.width, image!.size.height) imageView.userInteractionEnabled = true imageView.tag = i let swipeDownRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeDownHandler:") swipeDownRecognizer.direction = UISwipeGestureRecognizerDirection.Down imageView.addGestureRecognizer(swipeDownRecognizer) let swipeUpRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeUpHandler:") swipeUpRecognizer.direction = UISwipeGestureRecognizerDirection.Up imageView.addGestureRecognizer(swipeUpRecognizer) xPos += CGFloat(image!.size.width + 50) self.scrollView.addSubview(imageView) if(i == 2) { self.cardWidth = image!.size.width } } self.scrollView.contentSize = CGSizeMake(xPos + 38, 0) } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func swipeDownHandler(sender:UISwipeGestureRecognizer) { var ticket = sender.view! var centerX:CGFloat! self.originalCenterX = ticket.center.x if(self.scrollView.contentOffset.x >= 0 && self.scrollView.contentOffset.x < 95) { centerX = self.scrollView.contentSize.width/3 + self.scrollView.contentOffset.x - 75 } else if(self.scrollView.contentOffset.x > 95 && self.scrollView.contentOffset.x < 290) { centerX = self.scrollView.contentSize.width/3 * 2 + self.scrollView.contentOffset.x - (94 + cardWidth*1.5) } else { centerX = self.scrollView.contentSize.width/3 * 3 + self.scrollView.contentOffset.x - (187 + cardWidth*2.5) } UIView.animateWithDuration(0.5, animations: { () -> Void in ticket.center = CGPointMake(centerX, 390) }) { (completion) -> Void in self.delegate?.didChooseChallenge(self.challengeNames[sender.view!.tag]) } self.scrollView.scrollEnabled = false } func swipeUpHandler(sender:UISwipeGestureRecognizer) { var ticket = sender.view! UIView.animateWithDuration(0.5, animations: { () -> Void in ticket.center = CGPointMake(self.originalCenterX, 205) }) self.scrollView.scrollEnabled = true } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
true
39e2a3fade6ef6460eada82716ba46137c13c54d
Swift
reshmaruksana786/ENUMERATION
/ENUMERATION/ViewController.swift
UTF-8
4,702
3.71875
4
[]
no_license
// // ViewController.swift // ENUMERATION // // Created by Syed.Reshma Ruksana on 8/24/19. // Copyright © 2019 Syed.Reshma Ruksana. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //ENUM //WEEK DAYS enum days { case Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday } var day1:days = .Monday print(day1) var day2:days = .Tuesday print(day2) var day3:days = .Wednesday print(day3) var day4:days = .Thursday print(day4) var day5:days = .Friday print(day5) var day6:days = .Saturday print(day6) var day7:days = .Sunday print(day7) //ENUM WITH RAWVALUES enum weeks:UInt8 { case Monday = 1 ,Tuesday = 2,Wednesday,Thursday,Friday = 5,Saturday,Sunday } var thisDay1:weeks = .Monday print(thisDay1) print(thisDay1.rawValue) var thisDay2:weeks = .Tuesday print(thisDay2) print(thisDay2.rawValue) var thisDay3:weeks = .Wednesday print(thisDay3) print(thisDay3.rawValue) var thisDay4:weeks = .Thursday print(thisDay4) print(thisDay4.rawValue) var thisDay5:weeks = .Friday print(thisDay5) print(thisDay5.rawValue) var thisDay6:weeks = .Saturday print(thisDay6) print(thisDay6.rawValue) var thisDay7:weeks = .Sunday print(thisDay7) print(thisDay7.rawValue) //MONTHS enum months:UInt8 { case January = 1 ,February = 2, March,April,May,June,July=7,August,September,October,November,December } var month1:months = months.January print(month1) print(month1.rawValue) var month2:months = months.February print(month2) print(month2.rawValue) var month3:months = months.March print(month3) print(month3.rawValue) var month4:months = months.April print(month4) print(month4.rawValue) var month5:months = months.May print(month5) print(month5.rawValue) var month6:months = months.June print(month6) print(month6.rawValue) var month7:months = months.July print(month7) var month8:months = months.August print(month8) var month9:months = months.September print(month9) var month10:months = months.October print(month10) var month11:months = months.November print(month11) var month12:months = months.December print(month12) //PLANETS enum planets { case Mercury ,venus , Earth , Mars , Jupiter , Saturn , Uranus , Neptune } var planet1:planets = planets.Mercury print(planet1) print("First planet is \(planet1)") var planet2:planets = planets.venus print(planet2) print("Second planet is \(planet2)") var planet3:planets = planets.Earth print(planet3) print("Third planet is \(planet3)") var planet4:planets = planets.Mars print(planet4) print("Fourth planet is \(planet4)") var planet5:planets = planets.Jupiter print(planet5) print("Fifth planet is \(planet5)") var planet6:planets = planets.Saturn print(planet6) print("Sixth planet is \(planet6)") var planet7:planets = planets.Uranus print(planet7) print("Seventh planet is \(planet7)") var planet8:planets = planets.Neptune print(planet8) print("Eight planet is \(planet8)") // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
b3b4b58a07d137961299afbbb319fdfe47ac3c53
Swift
pallavtrivedi03/H-Bazaar
/H-Bazaar/Network/NetworkManager.swift
UTF-8
1,258
2.765625
3
[ "MIT" ]
permissive
// // NetworkManager.swift // H-Bazaar // // Created by Pallav Trivedi on 02/04/20. // Copyright © 2020 Pallav Trivedi. All rights reserved. // import Foundation final class NetworkManager { static let shared = NetworkManager() let webserviceHelper = WebserviceHelper() private init() { } func getProducts(completion: @escaping (ProductsAPIResponseModel?) -> ()) { guard let url = URL(string: AppConstants.API.products) else { return } webserviceHelper.fetchData(url: url, shouldCancelOtherOps: true) { (data, response, error) in if error != nil { print(error?.localizedDescription ?? "") completion(nil) } else { guard let responseData = data else { return } let jsonDecoder = JSONDecoder() do { let productsResponse = try jsonDecoder.decode(ProductsAPIResponseModel.self, from: responseData) completion(productsResponse) } catch { print("Error occured while parsing products response") completion(nil) } } } } }
true
caff1744d92fefbd679103ceece1387b056d30ce
Swift
Lausbert/Codewars
/Linked Lists - Recursive Reverse.playground/Contents.swift
UTF-8
3,063
3.421875
3
[]
no_license
import Foundation class Node { var data: Int var next: Node? init(_ data: Int) { self.data = data; } convenience init(_ next: Node?, _ data: Int) { self.init(data) self.next = next } } func recursiveReverse(list:Node?) -> Node? { return recursiveReverseHelper(first: nil, list: list) } func recursiveReverseHelper(first: Node?, list:Node?) -> Node? { var first = first var list = list var third:Node? third = list?.next list?.next = first if third == nil {return list} first = list list = third return recursiveReverseHelper(first: first, list: list) } import XCTest func push(_ head:Node?, _ data:Int) -> Node { return Node(head, data) } func linkedListsEqual(first: Node?, second: Node?) -> Bool { if first?.data != second?.data {return false} guard first != nil else {return true} return linkedListsEqual(first: first?.next, second: second?.next) } func buildListFromArray(_ data:[Int]?) -> Node? { if data == nil {return nil} if data?.count == 1 {return push(nil, (data?[0])!)} return push(buildListFromArray(Array(data![1...(data!.count)-1])), (data![0])) } public struct TestRunner { public init() { } public func runTests(testClass:AnyClass) { let tests = testClass as! XCTestCase.Type let testSuite = tests.defaultTestSuite() testSuite.run() _ = testSuite.testRun as! XCTestSuiteRun } } class SolutionTest: XCTestCase { static var allTests = [ ("testRecursiveReverseEmptyList", testRecursiveReverseEmptyList), ("testRecursiveReverseOneItem", testRecursiveReverseOneItem), ("testRecursiveReverseTwoItems", testRecursiveReverseTwoItems), ("testRecursiveReverseFiveItems", testRecursiveReverseFiveItems), ("testRecursiveReverseSeveralItems", testRecursiveReverseSeveralItems), ] func testRecursiveReverseEmptyList() { XCTAssertNil(recursiveReverse(list: nil)) } func testRecursiveReverseOneItem() { let list:Node? = Node(2) XCTAssertTrue(linkedListsEqual(first: recursiveReverse(list: list), second: buildListFromArray([2]))) } func testRecursiveReverseTwoItems() { let list:Node? = buildListFromArray([4, 9]) XCTAssertTrue(linkedListsEqual(first: recursiveReverse(list: list), second: buildListFromArray([9, 4]))) } func testRecursiveReverseFiveItems() { let list:Node? = buildListFromArray([2, 1, 3, 6, 5]) XCTAssertTrue(linkedListsEqual(first: recursiveReverse(list: list), second: buildListFromArray([5, 6, 3, 1, 2]))) } func testRecursiveReverseSeveralItems() { let list:Node? = buildListFromArray([9, 32, 4, 1, 35, 13, 41, 9, 42, 1, 7, 5, 4]) XCTAssertTrue(linkedListsEqual(first: recursiveReverse(list: list), second: buildListFromArray( [4, 5, 7, 1, 42, 9, 41, 13, 35, 1, 4, 32, 9])) ) } } TestRunner().runTests(testClass: SolutionTest.self)
true
21a6741fc23d3a083fe46e1595619a58026bf770
Swift
FuzzyBuckBeak/Algorithms-Datastructures
/Data Structure/Linked List/Count rotations in sorted and rotated linked list/Count rotations in sorted and rotated linked list.swift
UTF-8
1,159
4.03125
4
[]
no_license
// // Count rotations in sorted and rotated linked list.swift // Problems // // Created by: FuzzyBuckBeak on 12/29/18 // Copyright © 2018 FuzzyBuckBeak. All rights reserved. /**************************************************************************************** Count rotations in sorted and rotated linked list Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the value of k. *****************************************************************************************/ import Foundation //Node Class class Node { var value: Int var next: Node? init(value: Int, next: Node?) { self.value = value self.next = next } } class LinkedList { func countRotation(head: Node?) -> Int { var counter = 1 guard head != nil else { return 0 } var referencePointer = head while (referencePointer != nil && referencePointer?.next != nil) { if referencePointer!.value > referencePointer!.next!.value { return counter } counter += 1 referencePointer = referencePointer?.next } return 0 } }
true
c0b21e2ed868825bf105edec014ce803a6a87d23
Swift
Saturn-V/whale-ios
/whale-ios-AlexPena/whale-ios-AlexPena/Models/Question.swift
UTF-8
746
2.953125
3
[]
no_license
// // Question.swift // whale-ios-AlexPena // // Created by Alex Aaron Peña on 4/5/17. // Copyright © 2017 Alex Aaron Peña. All rights reserved. // import Foundation import SwiftyJSON struct Question: Initializable { let id: Int let content: String let sender: User let receiver: User init?(json: JSON) { // decode sender and receiver as users guard let id: Int = json["id"].int, let content: String = json["content"].string, let sender: User = User.init(json: json["sender"]), let receiver: User = User.init(json: json["receiver"]) else { return nil } self.id = id self.content = content self.sender = sender self.receiver = receiver } }
true
8c26ac9b8e4fa6265b4c2849cb0d7c206f9b4d3b
Swift
manglangfeiyuan/SwiftyDB
/SwiftyDB/Statement.swift
UTF-8
24,005
2.734375
3
[]
no_license
// // Statement.swift // TinySQLite // // Created by Øyvind Grimnes on 25/12/15. // import sqlite3 //public enum SQLiteDatatypeTiny: String { // case Text = "TEXT" // case Integer = "INTEGER" // case Real = "REAL" // case Blob = "BLOB" // case Numeric = "NUMERIC" // case Null = "NULL" //} public enum SQLiteDatatype: String { case Text = "TEXT" case Integer = "INTEGER" case Real = "REAL" case Blob = "BLOB" case Numeric = "NUMERIC" case Null = "NULL" init?(type: Value.Type) { switch type { case is Int.Type, is Int8.Type, is Int16.Type, is Int32.Type, is Int64.Type, is UInt.Type, is UInt8.Type, is UInt16.Type, is UInt32.Type, is UInt64.Type, is Bool.Type: self.init(rawValue: "INTEGER") case is Double.Type, is Float.Type, is Date.Type: self.init(rawValue: "REAL") case is Data.Type: self.init(rawValue: "BLOB") case is NSNumber.Type: self.init(rawValue: "NUMERIC") case is String.Type, is NSString.Type, is Character.Type: self.init(rawValue: "TEXT") case is NSArray.Type, is NSDictionary.Type, is NSSet.Type: self.init(rawValue: "BLOB") default: fatalError("DSADSASA") } } public func value()->SQLiteValue? { switch self { case .Text: return "" case .Integer: return 0 case .Real: return 0.0 case .Blob: return nil case .Numeric: return nil case .Null: return nil default: return nil } } } public protocol StatementData { var dictionary: MapSQLiteValues {get} } internal class Statement : StatementData{ // public func printDesc(){ // Swift.print("stat query: \(self.query)") // Swift.print("stat handle: \(self.handle)") // } fileprivate var handle: OpaquePointer? var query: String var isBusy: Bool { return NSNumber(value: sqlite3_stmt_busy(handle) as Int32).boolValue } lazy var indexToNameMapping: [Int32: String] = { var mapping: [Int32: String] = [:] for index in 0..<sqlite3_column_count(self.handle) { let name = NSString(utf8String: sqlite3_column_name(self.handle, index)) as! String mapping[index] = name } return mapping }() lazy var nameToIndexMapping: [String: Int32] = { var mapping: [String: Int32] = [:] for index in 0..<sqlite3_column_count(self.handle) { let name = NSString(utf8String: sqlite3_column_name(self.handle, index)) as! String mapping[name] = index } return mapping }() public init(_ query: String, handle: OpaquePointer? = nil) { self.query = query self.handle = handle } /** Next row in results */ open func step() throws -> Bool { let result = sqlite3_step(handle) try SQLiteResultHandler.verifyResultCode(result, forHandle: handle) if result == SQLITE_DONE { return false } return true } /** Clear memory */ open func finalize() throws { try SQLiteResultHandler.verifyResultCode(sqlite3_finalize(handle), forHandle: handle) } /** ID of the last row inserted */ open func lastInsertRowId() -> Int? { let id = Int(sqlite3_last_insert_rowid(handle)) return id > 0 ? id : nil } //// MARK: - Execute query // internal func executeUpdateOrQuery(_ update: Bool, _ values: ArraySQLiteValues = []) throws -> Statement { // if update{ // try bind(values) // try step() // }else{ // try bind(values) // } // return self // } // // internal func executeUpdateOrQuery(_ update: Bool, _ namedValues: MapSQLiteValues) throws -> Statement { // if update{ // try bind(namedValues) // try step() // }else{ // try bind(namedValues) // } // return self // } internal func executeUpdateOrQuery(_ update: Bool, _ values: SqlValues?) throws -> Statement { if update{ try bind(values) try step() }else{ try bind(values) } return self } public func executeUpdate(_ values: SqlValues? = nil) throws -> Statement { return try self.executeUpdateOrQuery(true, values) } public func execute(_ values: SqlValues? = nil) throws -> Statement { return try self.executeUpdateOrQuery(false, values) } // MARK: - Internal methods internal func reset() throws { try SQLiteResultHandler.verifyResultCode(sqlite3_reset(handle), forHandle: handle) } internal func clearBindings() throws { try SQLiteResultHandler.verifyResultCode(sqlite3_clear_bindings(handle), forHandle: handle) } internal func prepareForDatabase(_ databaseHandle: OpaquePointer) throws { try SQLiteResultHandler.verifyResultCode( sqlite3_prepare_v2(databaseHandle, query, -1, &handle, nil), forHandle: handle) } internal func bind(_ value2: SqlValues?) throws { if let value = value2{ if let array = value.arrayx{ try bindArray(array) return } if let map = value.mapx{ try bindMap(map) return } }else{ try bindArray([]) return } } internal func bindMap(_ namedValues: MapSQLiteValues) throws { var parameterNameToIndexMapping: [String: Int32] = [:] for (name, _) in namedValues { let index = sqlite3_bind_parameter_index(handle, ":\(name)") parameterNameToIndexMapping[name] = index } let values: ArraySQLiteValues = namedValues.keys.sorted { parameterNameToIndexMapping[$0]! < parameterNameToIndexMapping[$1]! }.map {namedValues[$0]!} try bindArray(values) } internal func bindArray(_ values: ArraySQLiteValues) throws { try reset() try clearBindings() let totalBindCount = sqlite3_bind_parameter_count(handle) var bindCount: Int32 = 0 for (index, value) in values.enumerated() { try bindValue(value, forIndex: Int32(index+1)) bindCount += 1 } if bindCount != totalBindCount { throw SQLError.numberOfBindings } } // MARK: - Private methods fileprivate func bindValue(_ value: SQLiteValue?, forIndex index: Int32) throws { if value == nil { try SQLiteResultHandler.verifyResultCode(sqlite3_bind_null(handle, index), forHandle: handle) return } let result: Int32 switch value { /* Bind special values */ case let dateValue as Date: result = sqlite3_bind_double(handle, index, dateValue.timeIntervalSince1970) case let dataValue as Data: if dataValue.count == 0 { Swift.print("[ WARNING: Data values with zero bytes are treated as NULL by SQLite ]") } result = sqlite3_bind_blob(handle, index, (dataValue as NSData).bytes, Int32(dataValue.count), SQLITE_TRANSIENT) case let numberValue as NSNumber: result = try bindNumber(numberValue, forIndex: index) /* Bind integer values */ case let integerValue as Int: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as UInt: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as Int8: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as Int16: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as Int32: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as Int64: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as UInt8: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as UInt16: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as UInt32: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) case let integerValue as UInt64: result = sqlite3_bind_int64(handle, index, Int64(integerValue)) /* Bind boolean values */ case let boolValue as Bool: result = sqlite3_bind_int64(handle, index, boolValue ? 1 : 0) /* Bind real values */ case let floatValue as Float: result = sqlite3_bind_double(handle, index, Double(floatValue)) case let doubleValue as Double: result = sqlite3_bind_double(handle, index, doubleValue) /* Bind text values */ case let stringValue as String: result = sqlite3_bind_text(handle, index, stringValue, -1, SQLITE_TRANSIENT) case let stringValue as NSString: result = sqlite3_bind_text(handle, index, stringValue.utf8String, -1, SQLITE_TRANSIENT) case let characterValue as Character: result = sqlite3_bind_text(handle, index, String(characterValue), -1, SQLITE_TRANSIENT) default: result = sqlite3_bind_text(handle, index, value as! String, -1, SQLITE_TRANSIENT) } try SQLiteResultHandler.verifyResultCode(result, forHandle: handle) } /** Bind the value wrapped in an NSNumber object based on the values type */ fileprivate func bindNumber(_ numberValue: NSNumber, forIndex index: Int32) throws -> Int32 { let typeString = String(cString: numberValue.objCType) if typeString == "" || typeString.isEmpty { throw SQLError.bindingType } let result: Int32 switch typeString { case "c": result = sqlite3_bind_int64(handle, index, Int64(numberValue.int8Value)) case "i": result = sqlite3_bind_int64(handle, index, Int64(numberValue.int32Value)) case "s": result = sqlite3_bind_int64(handle, index, Int64(numberValue.int16Value)) case "l": result = sqlite3_bind_int64(handle, index, Int64(numberValue.intValue)) case "q": result = sqlite3_bind_int64(handle, index, numberValue.int64Value) case "C": result = sqlite3_bind_int64(handle, index, Int64(numberValue.int8Value)) case "I": result = sqlite3_bind_int64(handle, index, Int64(numberValue.uint32Value)) case "S": result = sqlite3_bind_int64(handle, index, Int64(numberValue.uint16Value)) case "L": result = sqlite3_bind_int64(handle, index, Int64(numberValue.uintValue)) case "Q": result = sqlite3_bind_int64(handle, index, Int64(numberValue.uint64Value)) case "B": result = sqlite3_bind_int64(handle, index, Int64(numberValue.boolValue ? 1 : 0)) case "f", "d": result = sqlite3_bind_double(handle, index, numberValue.doubleValue) default: result = sqlite3_bind_text(handle, index, numberValue.description, -1, SQLITE_TRANSIENT) } return result } } //MARK: - Values for indexed columns extension Statement { /** Returns the datatype for the column given by an index */ public func typeForColumn(_ index: Int32) -> SQLiteDatatype? { switch sqlite3_column_type(handle, index) { case SQLITE_INTEGER: return .Integer case SQLITE_FLOAT: return .Real case SQLITE_TEXT, SQLITE3_TEXT: return .Text case SQLITE_BLOB: return .Blob case SQLITE_NULL: return .Null default: return nil } } /** Returns a value for the column given by the index based on the columns datatype */ public func valueForColumn(_ index: Int32) -> SQLiteValue? { let columnType = sqlite3_column_type(handle, index) switch columnType { case SQLITE_INTEGER: return integerForColumn(index) case SQLITE_FLOAT: return doubleForColumn(index) case SQLITE_TEXT: return stringForColumn(index) case SQLITE_BLOB: return dataForColumn(index) case SQLITE_NULL: fallthrough default: return nil } } /** Returns an integer for the column given by the index */ public func integerForColumn(_ index: Int32) -> Int? { if let value = integer64ForColumn(index) { return Int(value) } return nil } /** Returns a 64-bit integer for the column given by the index */ public func integer64ForColumn(_ index: Int32) -> Int64? { if typeForColumn(index) == .Null { return nil } return sqlite3_column_int64(handle, index) } /** Returns a 32-bit integer for the column given by the index */ public func integer32ForColumn(_ index: Int32) -> Int32? { if let value = integer64ForColumn(index) { return Int32(value) } return nil } /** Returns a 16-bit integer for the column given by the index */ public func integer16ForColumn(_ index: Int32) -> Int16? { if let value = integer64ForColumn(index) { return Int16(value) } return nil } /** Returns a 8-bit integer for the column given by the index */ public func integer8ForColumn(_ index: Int32) -> Int8? { if let value = integer64ForColumn(index) { return Int8(value) } return nil } /** Returns an unsigned 64-bit integer for the column given by the index */ public func unsignedInteger64ForColumn(_ index: Int32) -> UInt64? { if let value = integer64ForColumn(index) { return UInt64(value) } return nil } /** Returns an unsigned 32-bit integer for the column given by the index */ public func unsignedInteger32ForColumn(_ index: Int32) -> UInt32? { if let value = integer64ForColumn(index) { return UInt32(value) } return nil } /** Returns an unsigned 16-bit integer for the column given by the index */ public func unsignedInteger16ForColumn(_ index: Int32) -> UInt16? { if let value = integer64ForColumn(index) { return UInt16(value) } return nil } /** Returns an unsigned 8-bit integer for the column given by the index */ public func unsignedInteger8ForColumn(_ index: Int32) -> UInt8? { if let value = integer64ForColumn(index) { return UInt8(value) } return nil } /** Returns an unsigned integer for the column given by the index */ public func unsignedIntegerForColumn(_ index: Int32) -> UInt? { if let value = integer64ForColumn(index) { return UInt(value) } return nil } /** Returns a double for the column given by the index */ public func doubleForColumn(_ index: Int32) -> Double? { if typeForColumn(index) == .Null { return nil } return sqlite3_column_double(handle, index) } /** Returns a float for the column given by the index */ public func floatForColumn(_ index: Int32) -> Float? { if let value = doubleForColumn(index) { return Float(value) } return nil } /** Returns a boolean for the column given by the index */ public func boolForColumn(_ index: Int32) -> Bool? { if let value = integerForColumn(index) { return Bool(value != 0) } return nil } /** Returns a data for the column given by the index */ public func dataForColumn(_ index: Int32) -> Data? { if typeForColumn(index) == .Null { return nil } return Data(bytes: UnsafeRawPointer(sqlite3_column_blob(handle, index)), count: Int(sqlite3_column_bytes(handle, index))) } /** Returns an date for the column given by the index */ public func dateForColumn(_ index: Int32) -> Date? { if typeForColumn(index) == .Null { return nil } return doubleForColumn(index) != nil ? Date(timeIntervalSince1970: doubleForColumn(index)!) : nil } /** Returns a string for the column given by the index */ public func stringForColumn(_ index: Int32) -> String? { return nsstringForColumn(index) as? String } /** Returns a character for the column given by the index */ public func characterForColumn(_ index: Int32) -> Character? { return stringForColumn(index)?.characters.first } /** Returns a string for the column given by the index */ public func nsstringForColumn(_ index: Int32) -> NSString? { return NSString(bytes: sqlite3_column_text(handle, index), length: Int(sqlite3_column_bytes(handle, index)), encoding: String.Encoding.utf8.rawValue) } /** Returns a number for the column given by the index */ public func numberForColumn(_ index: Int32) -> NSNumber? { switch sqlite3_column_type(handle, index) { case SQLITE_INTEGER: return integerForColumn(index) as NSNumber? case SQLITE_FLOAT: return doubleForColumn(index) as NSNumber? case SQLITE_TEXT: if let stringValue = stringForColumn(index) { return Int(stringValue) as NSNumber? } return nil default: return nil } } } //MARK: - Dictionary representation of row extension Statement { /** A dictionary representation of the data contained in the row */ public var dictionary: MapSQLiteValues { var dictionary: MapSQLiteValues = [:] for i in 0..<sqlite3_column_count(handle) { dictionary[indexToNameMapping[i]!] = valueForColumn(i) } return dictionary } } //MARK: - Values for named columns extension Statement { /** Returns the datatype for the column given by a column name */ public func typeForColumn(_ name: String) -> SQLiteDatatype? { return typeForColumn(nameToIndexMapping[name]!) } /** Returns a value for the column given by the column name, based on the SQLite datatype of the column */ public func valueForColumn(_ name: String) -> SQLiteValue? { return valueForColumn(nameToIndexMapping[name]!) } /** Returns an integer for the column given by the column name */ public func integerForColumn(_ name: String) -> Int? { return integerForColumn(nameToIndexMapping[name]!) } /** Returns a 64-bit integer for the column given by the column name */ public func integer64ForColumn(_ name: String) -> Int64? { return integer64ForColumn(nameToIndexMapping[name]!) } /** Returns a 32-bit integer for the column given by the column name */ public func integer32ForColumn(_ name: String) -> Int32? { return integer32ForColumn(nameToIndexMapping[name]!) } /** Returns a 16-bit integer for the column given by the column name */ public func integer16ForColumn(_ name: String) -> Int16? { return integer16ForColumn(nameToIndexMapping[name]!) } /** Returns a 8-bit integer for the column given by the column name */ public func integer8ForColumn(_ name: String) -> Int8? { return integer8ForColumn(nameToIndexMapping[name]!) } /** Returns an unsigned 64-bit integer for the column given by the column name */ public func unsignedInteger64ForColumn(_ name: String) -> UInt64? { return unsignedInteger64ForColumn(nameToIndexMapping[name]!) } /** Returns an unsigned 32-bit integer for the column given by the column name */ public func unsignedInteger32ForColumn(_ name: String) -> UInt32? { return unsignedInteger32ForColumn(nameToIndexMapping[name]!) } /** Returns an unsigned 16-bit integer for the column given by the column name */ public func unsignedInteger16ForColumn(_ name: String) -> UInt16? { return unsignedInteger16ForColumn(nameToIndexMapping[name]!) } /** Returns an unsigned 8-bit integer for the column given by the index */ public func unsignedInteger8ForColumn(_ name: String) -> UInt8? { return unsignedInteger8ForColumn(nameToIndexMapping[name]!) } /** Returns an unsigned integer for the column given by the column name */ public func unsignedIntegerForColumn(_ name: String) -> UInt? { return unsignedIntegerForColumn(nameToIndexMapping[name]!) } /** Returns a double for the column given by the column name */ public func doubleForColumn(_ name: String) -> Double? { return doubleForColumn(nameToIndexMapping[name]!) } /** Returns a float for the column given by the column name */ public func floatForColumn(_ name: String) -> Float? { return floatForColumn(nameToIndexMapping[name]!) } /** Returns a boolean for the column given by the column name */ public func boolForColumn(_ name: String) -> Bool? { return boolForColumn(nameToIndexMapping[name]!) } /** Returns data for the column given by the column name */ public func dataForColumn(_ name: String) -> Data? { return dataForColumn(nameToIndexMapping[name]!) } /** Returns a date for the column given by the column name */ public func dateForColumn(_ name: String) -> Date? { return dateForColumn(nameToIndexMapping[name]!) } /** Returns a string for the column given by the column name */ public func stringForColumn(_ name: String) -> String? { return stringForColumn(nameToIndexMapping[name]!) } /** Returns a character for the column given by the column name */ public func characterForColumn(_ name: String) -> Character? { return characterForColumn(nameToIndexMapping[name]!) } /** Returns a string for the column given by the column name */ public func nsstringForColumn(_ name: String) -> NSString? { return nsstringForColumn(nameToIndexMapping[name]!) } /** Returns a number for the column given by the column name */ public func numberForColumn(_ name: String) -> NSNumber? { return numberForColumn(nameToIndexMapping[name]!) } } // MARK: - Generator and sequence type extension Statement: IteratorProtocol, Sequence { /** Easily iterate through the rows. Performs a sqlite_step() and returns itself */ public func next() -> Statement? { do { let moreRows = try step() return moreRows ? self : nil } catch { return nil } } public func makeIterator() -> Statement { let _ = try? self.reset() return self } }
true
dd449248efc27f96d6630225543ef1f94e1f6a3a
Swift
JosiahRininger/Intervally
/Intervally WatchKit Extension/TimerView/TimerState.swift
UTF-8
1,193
3.109375
3
[]
no_license
// // TimerState.swift // Intervally WatchKit Extension // // Created by Josiah Rininger on 8/3/20. // Copyright © 2020 Josiah Rininger. All rights reserved. // import SwiftUI enum TimerState: Int, CaseIterable { case playing, paused, done var isDone: Bool { self == .done } var leaveImage: Image { self == .done ? Image("arrow.left") : Image("xmark") } var toggleImage: Image { self == .playing ? Image("pause.fill") : Image("play.fill") } var toggleState: TimerState { switch self { case .playing: return .paused case .paused: return .playing case .done: return .done } } func playLeaveSound() { if self != .done { WKInterfaceDevice.current().play(.retry) } } func playToggleSound() { switch self { case .paused: WKInterfaceDevice.current().play(.failure) case .playing: WKInterfaceDevice.current().play(.success) default: break } } func playTimerSound() { switch self { case .done: WKInterfaceDevice.current().play(.stop) default: WKInterfaceDevice.current().play(.start) } } }
true
335b9c812471506a7711b624a3747c40ea6b4bbe
Swift
matzsoft/adventofcode
/2022/day14.swift
UTF-8
3,081
3.03125
3
[]
no_license
// // FILE: main.swift // DESCRIPTION: day14 - Regolith Reservoir // NOTES: --- // AUTHOR: Mark T. Johnson, markj@matzsoft.com // COPYRIGHT: © 2022 MATZ Software & Consulting. All rights reserved. // VERSION: 1.0 // CREATED: 12/13/22 21:00:13 // import Foundation import Library // Note - in order to use existing Direction8, treat gravity as pulling the sand North. let directions: [Direction8] = [ .N, .NW, .NE ] let drip = Point2D( x: 500, y: 0 ) extension Array { var pairs: [ ( Element, Element ) ] { return ( 0 ..< count - 1 ).map { ( self[$0], self[$0+1] ) } } } func line( from: Point2D, to: Point2D ) -> Set<Point2D> { if from.x == to.x { let start = min( from.y, to.y ) let end = max( from.y, to.y ) return ( start ... end ).reduce( into: Set<Point2D>() ) { set, y in set.insert( Point2D( x: from.x, y: y ) ) } } else if from.y == to.y { let start = min( from.x, to.x ) let end = max( from.x, to.x ) return ( start ... end ).reduce( into: Set<Point2D>() ) { set, x in set.insert( Point2D( x: x, y: from.y ) ) } } fatalError( "Can't do diagonal lines" ) } func sandCount( blocks: Set<Point2D>, bounds: Rect2D, limit: Int? ) -> Int { var sand = Set<Point2D>() while true { var next = drip FALL: while true { if next.y == limit { sand.insert( next ) break } for direction in directions { let trial = next.move( direction: direction ) if limit == nil && !bounds.contains( point: trial ) { return sand.count } guard blocks.contains( trial ) || sand.contains( trial ) else { next = trial continue FALL } } sand.insert( next ) if next == drip { return sand.count } break } } } func parse( input: AOCinput ) -> Set<Point2D> { let structures = input.lines.map { $0.split( whereSeparator: { " ->".contains( $0 ) } ).map { pair in let coordinates = pair.split( separator: "," ).map { Int( $0 )! } return Point2D( x: coordinates[0], y: coordinates[1] ) }.pairs.map { line( from: $0.0, to: $0.1 ) } } return structures.flatMap { $0 }.reduce( Set<Point2D>() ) { $0.union( $1 ) } } func part1( input: AOCinput ) -> String { let blocks = parse( input: input ) let bounds = Rect2D( points: Array( blocks ) ).expand( with: drip ) return "\( sandCount( blocks: blocks, bounds: bounds, limit: nil ) )" } func part2( input: AOCinput ) -> String { let blocks = parse( input: input ) let bounds = Rect2D( points: Array( blocks ) ).expand( with: drip ) return "\( sandCount( blocks: blocks, bounds: bounds, limit: bounds.max.y + 1 ) )" } try print( projectInfo() ) try runTests( part1: part1 ) try runTests( part2: part2 ) try solve( part1: part1 ) try solve( part2: part2 )
true
19032fbe38fa7f4a89d7764d437b91426afc259d
Swift
irohafox/ios_core
/ArrvisCore/Services/HTTPRouter/HTTPError.swift
UTF-8
521
2.8125
3
[ "Apache-2.0" ]
permissive
// // HTTPError.swift // Arrvis // // Created by Yutaka Izumaru on 2018/02/23. // Copyright © 2018年 Arrvis Co., Ltd. All rights reserved. // /// HTTPエラー public class HTTPError: Error { /// HTTPステータスコード public let httpStatusCode: HttpStatusCode? /// エラーソース public let error: Error init(_ httpStatusCode: Int?, _ error: Error) { self.httpStatusCode = httpStatusCode == nil ? nil : HttpStatusCode(rawValue: httpStatusCode!) self.error = error } }
true
dea998b6896061eddc787ecc82e44f9673ad8151
Swift
quickthyme/graffeine-demo
/Sources/Graffeine-Demo/DemoCells/Candlestick/CandlestickCell+TradingDay.swift
UTF-8
2,793
3.125
3
[ "MIT" ]
permissive
import UIKit import Graffeine extension CandlestickCell { struct TradingDay { let open: Double let close: Double let peakHi: Double let peakLo: Double static func generateRandom(numberOfDays: Int, lowest: Double, highest: Double) -> [TradingDay] { return Array(0..<numberOfDays).reduce([], { result, _ in let yesterdayClose = result.last?.close ?? rnd(min: lowest, max: highest) let todayOpen = yesterdayClose let todayClose = rnd(min: lowest, max: highest) let hi = max(todayOpen, todayClose) let lo = min(todayOpen, todayClose) let range = hi - lo let peakHi = rnd(min: hi, max: min(hi + (range * 0.30), highest)) let peakLo = rnd(min: max(lo - (range * 0.30), lowest), max: lo) return result + [TradingDay(open: todayOpen, close: todayClose, peakHi: peakHi, peakLo: peakLo)] }) } private static func rnd(min: Double, max: Double) -> Double { return ceil(Double.random(in: min...max) * 100) / 100 } } struct TradingDayLanes { let hi: [Double] let lo: [Double] let peakHi: [Double] let peakLo: [Double] let colors: [UIColor] let labels: [String] static func `import`(_ input: [TradingDay]) -> TradingDayLanes { let nf = NumberFormatter() nf.numberStyle = .currency func formatted(_ val: Double) -> String { return nf.string(from: NSNumber(value: val)) ?? "" } return input.reduce(TradingDayLanes(hi: [], lo: [], peakHi: [], peakLo: [], colors: [], labels: [])) { let didCloseHi = ($1.close > $1.open) let hi = (didCloseHi) ? $1.close : $1.open let lo = (didCloseHi) ? $1.open : $1.close let color: UIColor = (didCloseHi) ? .systemGreen : .systemRed let label = "OPEN: \(formatted($1.open))" + " CLOSE: \(formatted($1.close))" + " HI: \(formatted($1.peakHi))" + " LO: \(formatted($1.peakLo))" return TradingDayLanes(hi: $0.hi + [hi], lo: $0.lo + [lo], peakHi: $0.peakHi + [$1.peakHi], peakLo: $0.peakLo + [$1.peakLo], colors: $0.colors + [color], labels: $0.labels + [label]) } } } }
true
5a05b0338d7e6010c0e42b553eb37f3541faaa13
Swift
Haibo-Zhou/Movie-World
/MovieWorld/Models/TMDB Response/PersonImages.swift
UTF-8
591
2.734375
3
[ "MIT" ]
permissive
// // PersonImages.swift // MovieWorld // // Created by Chuck.Zhou on 4/10/20. // Copyright © 2020 Haibo Family. All rights reserved. // import Foundation struct PersonImages: Codable { let id: Int let profiles: [Profile] } struct Profile: Codable { let aspectRatio: Float? let filePath: String? let height: Int? let iso6391: String? let voteAverage: Float? let voteCount: Int? let width: Int? static var `default`: Profile { Profile(aspectRatio: 0, filePath: "", height: 0, iso6391: "", voteAverage: 0, voteCount: 0, width: 0) } }
true
20111b2c6198c9dd2c2125fccb07523c744865e6
Swift
ianjsikes/swiftiled
/SwifTile/TMXReader.swift
UTF-8
4,270
2.703125
3
[]
no_license
// // TMXReader.swift // SwifTile // // Created by Avelina Kim on 10/27/15. // Copyright © 2015 ian. All rights reserved. // import Foundation class TMXReader : NSObject, NSXMLParserDelegate { var parser : NSXMLParser = NSXMLParser() var map : TMXMap = TMXMap() var tagStack : Stack<String> = Stack<String>() var currLayer : TMXLayer? var currData : TMXData? var currTileset : TMXTileset? var currTile : TMXTile? var delegate : TMXReaderDelegate? init?(fileName : String, delegate : TMXReaderDelegate?){ self.delegate = delegate super.init() if let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "tmx"){ if let tempParser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: path)) { self.parser = tempParser } else { return nil } } else { return nil } } func beginParsing() { parser.delegate = self parser.parse() } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { tagStack.push(elementName) //print("<\(elementName) \(attributeDict)>") switch elementName { case "map": self.map.createMap(attributeDict) //print("Map found") case "tileset": let tileset = TMXTileset() self.map.tilesets.append(tileset) self.currTileset = tileset tileset.createTileset(attributeDict) //print("Tileset found") case "tile": if let set = self.currTileset { let tile = TMXTile() self.currTile = tile tile.createTile(attributeDict) set.tiles.append(tile) } case "property": if let tile = self.currTile { tile.addProperty(attributeDict) } case "image": if let source = attributeDict["source"] { var split = source.componentsSeparatedByString("/") var filename = split[split.count - 1] split = filename.componentsSeparatedByString(".") filename = split[0] print("Filename: \(filename)") self.currTileset!.imageName = filename self.currTileset!.setSpriteSheet() } //print("Image found") case "layer": let layer = TMXLayer() self.currLayer = layer layer.createLayer(attributeDict) self.map.layers.append(layer) //print("Layer found") case "data": let data = TMXData() self.currData = data if let layer = self.currLayer { layer.data = data } data.createData(attributeDict) //print("Data found") default: break } } func parser(parser: NSXMLParser, foundCharacters string: String) { //print(string) if tagStack.peek() == "data" { if let data = self.currData { data.dataString += string } } } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { tagStack.pop() switch elementName { case "tile": self.currTile = nil case "layer": self.currLayer = nil case "tileset": self.currTileset = nil case "data": currData!.dataString = currData!.dataString.stringByReplacingOccurrencesOfString("\n", withString: "") currData!.processDataString() //print("Data string: \(currData!.dataString)") //currData!.base64Decode() default: break } } func parserDidEndDocument(parser: NSXMLParser) { print("Finished reading TMX File") self.delegate?.onReaderCompleted(self.map) print(self.map) } }
true
68a725b337c86768a55e826eae43845653d3fa2d
Swift
DiksonSamuel/SwiftLearning
/SwiftLearning/Screens/Home/Home.swift
UTF-8
1,155
3
3
[]
no_license
// // Home.swift // SwiftLearning // // Created by Dikson Samuel on 15/02/20. // Copyright © 2020 Dikson Samuel. All rights reserved. // import SwiftUI import CoreLocation struct Home: View { @ObservedObject var locationManager = LocationManager() var loader = true; var userLatitude: String { return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)" } var userLongitude: String { return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)" } var body: some View { VStack { Button(action: { deleteData() }) { Text("logout") } }.onAppear { self.callWeatherData() } } func callWeatherData() { var loader1 = true; Weather.getWeatherData(lattitude: userLatitude, longitude: userLongitude, completionHandler: { results, error in loader1 = false; //loader = loader1 }) } } func deleteData() { Auth.deleteCurrentUser(); } struct Home_Previews: PreviewProvider { static var previews: some View { Home() } }
true
c11215534e2eb02ca216c525d3c6bb50d8d8b962
Swift
puchog/RedditReader_ios
/RedditReader/Extensions/UIButton+RRAdditions.swift
UTF-8
655
2.515625
3
[]
no_license
// // UIButton+RRAdditions.swift // RedditReader // // Created by Juan Giannuzzo on 2/3/17. // Copyright © 2017 Puchog. All rights reserved. // import UIKit extension UIButton { public func imageFromServerURL(urlString: String) { self.setImage( UIImage(named: "missing_image"), for: .normal) URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in if error != nil { return } DispatchQueue.main.async(execute: { () -> Void in let image = UIImage(data: data!) self.setImage(image, for: .normal) }) }).resume() }}
true
1b9d35791dc84ffd4af383022bd6561312465996
Swift
darraes/trainit-ios
/Trainit/Log.swift
UTF-8
906
2.8125
3
[]
no_license
// // Log.swift // Trainit // // Created by Daniel Pereira on 5/29/17. // Copyright © 2017 Daniel Arraes. All rights reserved. // import Foundation class Log { static func write(level: String, _ msg: String, _ srcFn: String) { print("\(level)\(short(for: Date())) \(srcFn): \(msg)") } static func debug(_ msg: String, _ srcFn: String = #function) { Log.write(level: "D", msg, srcFn) } static func info(_ msg: String, _ srcFn: String = #function) { Log.write(level: "I", msg, srcFn) } static func warning(_ msg: String, _ srcFn: String = #function) { Log.write(level: "W", msg, srcFn) } static func error(_ msg: String, _ srcFn: String = #function) { Log.write(level: "E", msg, srcFn) } static func critical(_ msg: String, _ srcFn: String = #function) { Log.write(level: "C", msg, srcFn) } }
true
032cf76d4999578165cc8d6b9903dac88a4d05ed
Swift
li1024316925/Swift-TimeMovie
/Swift-TimeMovie/Swift-TimeMovie/DiscoverViewController.swift
UTF-8
3,701
2.671875
3
[ "Apache-2.0" ]
permissive
// // DiscoverViewController.swift // Swift-TimeMovie // // Created by DahaiZhang on 16/10/14. // Copyright © 2016年 LLQ. All rights reserved. // import UIKit class DiscoverViewController: BaseViewController { //新闻视图 var newsView:NewsView? //预告片 var trailerView:TrailerView? //排行榜 var topListView:TopListView? //评论 var criticismView:CriticismView? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(patternImage: UIImage(named: "actor_detail_top_background.jpg")!) //导航栏按钮组 createSegmentView() //创建视图 createView() } //创建视图 func createView() -> Void { //新闻 createNewsView() //预告 createTrailerView() //排行榜 createTopListView() //影评 createCriticismView() } //新闻 func createNewsView() -> Void { newsView = NewsView(frame: CGRect(x: 0, y: 0, width: kScreen_W(), height: kScreen_H()-50-10-50)) //数据 weak var weakSelf = self DiscoverViewModel().newsData { (data) in weakSelf!.newsView?.dataList = data } view.addSubview(newsView!) } //预告 func createTrailerView() -> Void { trailerView = TrailerView(frame: CGRect(x: kScreen_W(), y: 0, width: kScreen_W(), height: kScreen_H()-60-50)) weak var weakSelf = self DiscoverViewModel().trailersData { (data) in weakSelf!.trailerView?.dataList = data } view.addSubview(trailerView!) } //排行榜 func createTopListView() -> Void { topListView = TopListView(frame: CGRect(x: 2*kScreen_W(), y: 0, width: kScreen_W(), height: kScreen_H()-60-50)) weak var weakSelf = self DiscoverViewModel().topListData { (data) in weakSelf!.topListView?.dataList = data } view.addSubview(topListView!) } //影评 func createCriticismView() -> Void { criticismView = CriticismView(frame: CGRect(x: 3*kScreen_W(), y: 0, width: kScreen_W(), height: kScreen_H()-60-50)) weak var weakSelf = self DiscoverViewModel().criticismData { (data) in weakSelf!.criticismView?.dataList = data } view.addSubview(criticismView!) } //按钮组 func createSegmentView() -> Void { let segmentView = SegmentView(frame: CGRect(x: 0, y: 0, width: kScreen_W(), height: 50)) segmentView.titleArray = ["新闻","预告片","排行榜","影评"] //点击方法 weak var weakSelf = self segmentView.selectAction { (index) in weakSelf!.viewMoveAction(index: index) } navigationItem.titleView = segmentView } //切换视图方法 func viewMoveAction(index: Int) -> Void { weak var weakSelf = self UIView.animate(withDuration: 0.3) { weakSelf!.newsView?.transform = CGAffineTransform(translationX: -kScreen_W()*CGFloat(index), y: 0) weakSelf!.trailerView?.transform = CGAffineTransform(translationX: -kScreen_W()*CGFloat(index), y: 0) weakSelf!.topListView?.transform = CGAffineTransform(translationX: -kScreen_W()*CGFloat(index), y: 0) weakSelf!.criticismView?.transform = CGAffineTransform(translationX: -kScreen_W()*CGFloat(index), y: 0) } } }
true
9ded5848027b975bae150184b3a491cb829a3b01
Swift
RicardoBravoA/ToDoListApp
/ToDoListApp/ToDoList.swift
UTF-8
908
3.421875
3
[]
no_license
// // ToDoList.swift // ToDoListApp // // Created by Ricardo Bravo Acuña on 10/19/19. // Copyright © 2019 Ricardo Bravo Acuña. All rights reserved. // import Foundation class ToDoList{ var list = [Item]() init() { for i in 1...5 { let item = Item() item.text = "Text \(i)" list.append(item) } } func addItem() -> Item{ let item = Item() item.text = "New Item" list.append(item) return item } func move(item: Item, index: Int){ guard let currentIndex = list.firstIndex(of: item) else { return } list.remove(at: currentIndex) list.insert(item, at: index) } func delete(items: [Item]) { for item in items { if let index = list.firstIndex(of: item){ list.remove(at: index) } } } }
true
9a5a728d6998262758225fbecac8e6d31e6d021e
Swift
thachgiasoft/Agile-Board-Team
/Agile Board Team/Network/NetworkRequest.swift
UTF-8
1,499
2.859375
3
[]
no_license
// // NetworkRequest.swift // Agile Board Team // // Created by Huynh Tan Phu on 3/19/20. // Copyright © 2020 Filesoft. All rights reserved. // import Foundation import Combine private let fakeToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvdGFzay5odXVoaWVucXQuZGV2XC9hcGlcL3YxXC9sb2dpbiIsImlhdCI6MTU4NjMzNjcwMywiZXhwIjoxNTg2OTQxNTAzLCJuYmYiOjE1ODYzMzY3MDMsImp0aSI6IkR3YkJMWFUzdXJGckZxb0MiLCJzdWIiOiI3ZjY0ZmI1MC02ZTQzLTExZWEtOGM4OC0xMWY5MmRjYWNhMmEiLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.P40b7VZ-zmIr1PXp-2vrEZ9tyW1yt-4RjhZmEPRZvgI" protocol NetworkRequest {} extension NetworkRequest { private var accessToken: String { AppState.shared.session?.accessToken ?? fakeToken } var jsonDecoder: JSONDecoder { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 decoder.keyDecodingStrategy = .convertFromSnakeCase return decoder } func post(url: URL, authen: Bool = false) -> URLRequest { var request = self.request(url: url, authen: authen) request.httpMethod = "POST" return request } func get(url: URL, authen: Bool = false) -> URLRequest { var request = self.request(url: url, authen: authen) request.httpMethod = "GET" return request } private func request(url: URL, authen: Bool = false) -> URLRequest { var request = URLRequest(url: url) request.setValue("application/json", forHTTPHeaderField: "Content-Type") if authen { request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization") } return request } func printJSON(data: Data?) { if let data = data, let dataString = String(data: data, encoding: .utf8) { print(dataString) } } }
true
a408422bcb498d7363a99740944556de20a3dff4
Swift
SAP/cloud-sdk-ios-fiori
/Tests/FioriSwiftUITests/FioriCharts/Model/ChartSeriesPaletteTests.swift
UTF-8
3,718
2.671875
3
[ "Apache-2.0" ]
permissive
@testable import FioriCharts import SwiftUI import XCTest class ChartSeriesPaletteTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testInit() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let sp = ChartSeriesPalette(colors: [.preferredColor(.secondaryLabel)], fillColor: .preferredColor(.primaryLabel), labelColor: .preferredColor(.chart1), positiveMaxColor: .preferredColor(.chart2), positiveMinColor: .preferredColor(.chart3), negativeMaxColor: .preferredColor(.chart4), negativeMinColor: .preferredColor(.chart5)) XCTAssertEqual(sp.colors.compactMap { $0.resolvedColor(with: .light) }, [Color.preferredColor(.secondaryLabel).resolvedColor(with: .light)]) XCTAssertEqual(sp.fillColor.resolvedColor(with: .light), Color.preferredColor(.primaryLabel).resolvedColor(with: .light)) XCTAssertEqual(sp.labelColor.resolvedColor(with: .light), Color.preferredColor(.chart1).resolvedColor(with: .light)) XCTAssertEqual(sp.positiveMaxColor.resolvedColor(with: .light), Color.preferredColor(.chart2).resolvedColor(with: .light)) XCTAssertEqual(sp.positiveMinColor.resolvedColor(with: .light), Color.preferredColor(.chart3).resolvedColor(with: .light)) XCTAssertEqual(sp.negativeMaxColor.resolvedColor(with: .light), Color.preferredColor(.chart4).resolvedColor(with: .light)) XCTAssertEqual(sp.negativeMinColor.resolvedColor(with: .light), Color.preferredColor(.chart5).resolvedColor(with: .light)) } func testInit2() throws { let sp = ChartSeriesPalette(colors: [.preferredColor(.secondaryLabel)]) XCTAssertEqual(sp.colors.compactMap { $0.resolvedColor(with: .dark) }, [Color.preferredColor(.secondaryLabel).resolvedColor(with: .dark)]) XCTAssertEqual(sp.labelColor.resolvedColor(with: .dark), Color.preferredColor(.secondaryLabel).resolvedColor(with: .dark)) XCTAssertEqual(sp.positiveMaxColor.resolvedColor(with: .dark), Color.preferredColor(.secondaryLabel).resolvedColor(with: .dark)) XCTAssertEqual(sp.positiveMinColor.resolvedColor(with: .dark), Color.preferredColor(.secondaryLabel).resolvedColor(with: .dark)) XCTAssertEqual(sp.negativeMaxColor.resolvedColor(with: .dark), Color.preferredColor(.secondaryLabel).resolvedColor(with: .dark)) XCTAssertEqual(sp.negativeMinColor.resolvedColor(with: .dark), Color.preferredColor(.secondaryLabel).resolvedColor(with: .dark)) } func testCopy() throws { let sp = ChartSeriesPalette(colors: [.preferredColor(.secondaryLabel)], fillColor: .preferredColor(.primaryLabel), labelColor: .preferredColor(.chart1), positiveMaxColor: .preferredColor(.chart2), positiveMinColor: .preferredColor(.chart3), negativeMaxColor: .preferredColor(.chart4), negativeMinColor: .preferredColor(.chart5)) let spCopy = sp.copy() as! ChartSeriesPalette XCTAssertEqual(sp, spCopy) } }
true
2440abd06e6331cb454c70c6aaa4413584c35dc6
Swift
hammadar/personalcovidapp
/PersonalCovidTracker/ContentView.swift
UTF-8
4,753
2.8125
3
[]
no_license
// // ContentView.swift // PersonalCovidTracker // // Created by Hammad Rehman on 2020-10-31. // import SwiftUI import CoreData struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @State var checkedON = false @State var checkedQC = false @State var checkedPEI = false @State var checkedNB = false @State var checkedNS = false @State var checkedNL = false @State var checkedMB = false @State var checkedSK = false @State var checkedAB = false @State var checkedBC = false @State var checkedTerr = false var body: some View { VStack(alignment:.leading) { HStack(alignment: .top) { Button(action: { self.checkedON.toggle() }) { HStack { CheckBoxView(checked: $checkedON) Text("ON") } } Button(action: { self.checkedQC.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("QC") } } Button(action: { self.checkedPEI.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("PEI") } } Button(action: { self.checkedNB.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("NB") } } Button(action: { self.checkedNS.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("NS") } } Button(action: { self.checkedNL.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("NL") } } Button(action: { self.checkedMB.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("MB") } } Button(action: { self.checkedSK.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("SK") } } } HStack(alignment:.top) { Button(action: { self.checkedAB.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("AB") } } Button(action: { self.checkedBC.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("BC") } } Button(action: { self.checkedTerr.toggle() }) { HStack { CheckBoxView(checked: $checkedQC) Text("Territories") } } } } } private func addItem() { } private func deleteItems(offsets: IndexSet) { } } private let itemFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .medium return formatter }() struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext) } } struct CheckBoxView: View { @Binding var checked : Bool var body: some View { ZStack { RoundedRectangle(cornerRadius: 1) .frame(width: 10, height: 10) .foregroundColor(checked ? Color.green : Color.gray.opacity(0.2)) if checked { Image(systemName: "checkmark") .foregroundColor(Color.white) } } } }
true
77c53b398c30ea15733f3ba438cc372ffe3cb65d
Swift
vlourme/Swloader
/Sources/Swloader/Swloader.swift
UTF-8
2,295
3.234375
3
[]
no_license
// // Swloader.swift // Main file // // Created by Victor Lourme on 03/08/2020. // // Dependencies import SwiftUI /// /// Loader modifier /// @available(iOS 13.0, *) public struct Loader: ViewModifier { // isPresented -> Displays animation when true @Binding public var isPresented: Bool // title -> Displays a title when filled @State public var style: LoaderStyle = .default() var loader: some View { ZStack { Blur() .cornerRadius(10) VStack { if style.icon.isEmpty { CircleView(duration: style.speed) } else { IconView(icon: style.icon, duration: style.speed, animate: style.isSpinning) } Group { if !style.title.isEmpty { Text(style.title) .font(.headline) .multilineTextAlignment(.center) .padding(.top) } if !style.legend.isEmpty { Text(style.legend) .font(.footnote) .multilineTextAlignment(.center) .padding(.top, style.title.isEmpty ? 15 : 0) } }.padding([.leading, .trailing]) } } .frame(minWidth: 200, idealWidth: 220, maxWidth: 250, minHeight: 200, idealHeight: 220, maxHeight: 250) .scaleEffect(isPresented ? 1 : 0) .animation(.easeInOut) .transition(.scale) .zIndex(1) } public func body(content: Content) -> some View { ZStack { loader content } } } /// /// View extension /// @available(iOS 13.0, *) public extension View { /// /// Show a loader on top of the view /// - parameters: /// - isPresented: If true, it will display the loader /// - style: LoaderStyle, defaults to spinning circle /// func loader(isPresented: Binding<Bool>, style: LoaderStyle = .default()) -> some View { return self.modifier(Loader(isPresented: isPresented, style: style)) } }
true
786f45ebdbbcf9c58501a54e8dadf82f0c77b616
Swift
nholloh/Hanson
/HansonTests/EventPublisherTests.swift
UTF-8
6,679
3.078125
3
[ "ISC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // EventPublisherTests.swift // Hanson // // Created by Joost van Dijk on 26/01/2017. // Copyright © 2017 Blendle. All rights reserved. // import XCTest @testable import Hanson class EventPublisherTests: XCTestCase { func testPublishingEventWithoutEventHandlers() { let eventPublisher = TestEventPublisher() eventPublisher.publish("Sample event") } func testPublishingMultipleEvents() { let eventPublisher = TestEventPublisher() var latestEvent: String! eventPublisher.addEventHandler { event in latestEvent = event } // No event should have been published yet. XCTAssertNil(latestEvent) // When publishing an event, the event handler should be invoked with the published event. eventPublisher.publish("First event") XCTAssertEqual(latestEvent, "First event") eventPublisher.publish("Second event") XCTAssertEqual(latestEvent, "Second event") } func testPublishingMultipleEventsWithMultipleEventHandlers() { let eventPublisher = TestEventPublisher() var numberOfFirstEventHandlerInvocations = 0 let firstEventHandlerToken = eventPublisher.addEventHandler { _ in numberOfFirstEventHandlerInvocations += 1 } var numberOfSecondEventHandlerInvocations = 0 let secondEventHandlerToken = eventPublisher.addEventHandler { _ in numberOfSecondEventHandlerInvocations += 1 } // When an event is published, both counter should increment. eventPublisher.publish("Sample event") XCTAssertEqual(numberOfFirstEventHandlerInvocations, 1) XCTAssertEqual(numberOfSecondEventHandlerInvocations, 1) // After removing an event handler, only one counter should increment when publishing an event. eventPublisher.removeEventHandler(with: firstEventHandlerToken) eventPublisher.publish("Sample event") XCTAssertEqual(numberOfFirstEventHandlerInvocations, 1) XCTAssertEqual(numberOfSecondEventHandlerInvocations, 2) // After removing the other event handler, neither of the counters should increment when publishing an event. eventPublisher.removeEventHandler(with: secondEventHandlerToken) XCTAssertEqual(numberOfFirstEventHandlerInvocations, 1) XCTAssertEqual(numberOfSecondEventHandlerInvocations, 2) } func testPublishingMultipleEventsOnMultipleQueuesWhileAddingEventHandlers() { let eventPublisher = TestEventPublisher() var numberOfEvents = 0 eventPublisher.addEventHandler { _ in numberOfEvents += 1 } // Publish 100 events and add 100 event handlers on different queues. for i in 0..<100 { let publishExpectation = expectation(description: "Event \(i) published") let queue = DispatchQueue(label: "com.blendle.hanson.tests.event-publisher.queue\(i)") queue.async { eventPublisher.publish("Event \(i)") eventPublisher.addEventHandler { _ in } publishExpectation.fulfill() } } // Wait until all events have been published and event handlers have been added. waitForExpectations(timeout: 10, handler: nil) // Verify that 100 events have been published. XCTAssertEqual(numberOfEvents, 100) // Verify that 100 event handlers have been added, on top of the original one. XCTAssertEqual(eventPublisher.eventHandlers.count, 101) } func testAddingAndRemovingEventHandlers() { let eventPublisher = TestEventPublisher() // Initially, the event publisher shouldn't have any event handlers. XCTAssertTrue(eventPublisher.eventHandlers.isEmpty) // After adding the first event handler, the event publisher should have one event handler. let firstEventHandlerToken = eventPublisher.addEventHandler { _ in } XCTAssertEqual(eventPublisher.eventHandlers.count, 1) // After adding the second event handler, the event publisher should have two event handlers. let secondEventHandlerToken = eventPublisher.addEventHandler { _ in } XCTAssertEqual(eventPublisher.eventHandlers.count, 2) // After removing the first event handler, the event publisher should have one event handler. eventPublisher.removeEventHandler(with: firstEventHandlerToken) XCTAssertEqual(eventPublisher.eventHandlers.count, 1) // After removing the second and last event handler, the event publisher shouldn't have any event handlers. eventPublisher.removeEventHandler(with: secondEventHandlerToken) XCTAssertTrue(eventPublisher.eventHandlers.isEmpty) } func testAddingAndRemovingEventHandlersOnMultipleQueues() { let eventPublisher = TestEventPublisher() // Add 100 event handlers on different queues. for i in 0..<100 { let eventHandlerExpectation = expectation(description: "Event handler \(i) registered") let queue = DispatchQueue(label: "com.blendle.hanson.tests.event-publisher.queue\(i)") queue.async { eventPublisher.addEventHandler { _ in } eventHandlerExpectation.fulfill() } } // Wait until all event handlers have been added. waitForExpectations(timeout: 10, handler: nil) // Verify that all event handlers have been added. XCTAssertEqual(eventPublisher.eventHandlers.count, 100) // Remove the event handlers on different queues. for (i, element) in eventPublisher.eventHandlers.enumerated() { let eventHandlerToken = element.key let eventHandlerExpectation = expectation(description: "Event handler \(i) deregistered") let queue = DispatchQueue(label: "com.blendle.hanson.tests.event-publisher.queue\(i)") queue.async { eventPublisher.removeEventHandler(with: eventHandlerToken) eventHandlerExpectation.fulfill() } } // Wait until all event handlers have been removed. waitForExpectations(timeout: 10, handler: nil) // Verify that all event handlers have been removed. XCTAssertTrue(eventPublisher.eventHandlers.isEmpty) } }
true
becb3303adfa8922c8d799cd6189fe4ac4685a82
Swift
brandoncov/video-game-library
/Game library/main.swift
UTF-8
2,777
3.4375
3
[]
no_license
// // main.swift // Game library // // Created by Brandon Covington on 2/13/18. // Copyright © 2018 Brandon Covington. All rights reserved. // import Foundation var game = true var ArrayofGames: [videogame] = [] func Addgame() { var Addgame = readLine() var Game = videogame(name: Addgame!) ArrayofGames.append(Game) } func remove() { for game in ArrayofGames { print(game.name) } var remove = readLine() for i in 0...ArrayofGames.count - 1 { if ArrayofGames[i].name == remove { ArrayofGames.remove(at: i) } } } func Checkout() { for game in ArrayofGames { if game.checkedOut == false{ print(game.name) let currentDate = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy HH:mm" } } var Checkout = readLine() for i in ArrayofGames { if i.name == Checkout { i.checkedOut = true print("\(i.name)has been checked out") } } } func Checkin() { for game in ArrayofGames { if game.checkedOut == false { print(game.name) } } var Checkin = readLine() for i in ArrayofGames { if i.name == Checkin { i.checkedOut = true print("\(i.name)has been checked in") } } } while game { func menu() { print("1) Add game") print("2) remove a game") print("3) check a game out") print("4) check a game in") print("5) Quit program") let option = Int(readLine()!)! if option == 1 { print("What game would you like to add") Addgame() } else if option == 2 { print("What game would you like to remove") remove() } else if option == 3 { print("What game would you like to check out") Checkout() } else if option == 4 { print("What game would you like to check in") Checkin() } else if option == 5 { print("You have exited the program") game = false } else {print("please enter a valid option")} } menu() //class VideoGame { // let name: String // // // init(name: String) { // self.name = name // } // //} //var videoGames = [VideoGame]() //var newGame1 = VideoGame(name: "fortnite") //var newGame2 = VideoGame(name: "DayZ") //videoGames.append(newGame1) //videoGames.append(newGame2) //for game in videoGames { // print(game.name) //} }
true
afa16a5fc07a5d662a6475d4fe405325838e98a2
Swift
YukJiSoo/umchan-ios
/Umchan/Services/Crew/CrewService.swift
UTF-8
10,648
2.640625
3
[]
no_license
// // CrewService.swift // Umchan // // Created by 육지수 on 9/21/19. // Copyright © 2019 JSYuk. All rights reserved. // // import Foundation typealias CrewQueryType = CrewQuery.Data.Crew.Crew typealias CrewListQueryResult = CrewListQuery.Data.Crew.Crew typealias GetCrewCompletion = (_ Response: Result<(CrewQuery.Data.Crew.Crew, MemberStateType), CrewAPIError>) -> Void typealias GetCrewListCompletion = (_ Response: Result<[CrewListQueryResult], CrewAPIError>) -> Void typealias CrewCompletion = (_ Response: Result<Bool, CrewAPIError>) -> Void protocol CrewServiceType { func crew(id: String, district: String, completion: @escaping GetCrewCompletion) func crewList(name: String?, completion: @escaping GetCrewListCompletion) func createCrew(name: String, oneLine: String, district: String, completion: @escaping CrewCompletion) } final class CrewService: CrewServiceType { static let shared = CrewService() func crew(id: String, district: String, completion: @escaping GetCrewCompletion) { let crewInput = CrewInput(id: id, district: district) Apollo.shared.client.fetch(query: CrewQuery(input: crewInput), cachePolicy: .fetchIgnoringCacheData) { result in guard let data = try? result.get().data, let code = data.crew?.code, let message = data.crew?.message else { completion(.failure(.crew(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.crew(message))) return } // response from server guard let crew = data.crew?.crew else { completion(.failure(.crew("Fail Convert json data"))) return } var memberState: MemberStateType = .none if let isApplied = data.crew?.isApplied { memberState = isApplied ? .wait : memberState } if let isMember = data.crew?.isMember { memberState = isMember ? .member : memberState } completion(.success((crew, memberState))) } } func crewList(name: String? = nil, completion: @escaping GetCrewListCompletion) { Apollo.shared.client.fetch(query: CrewListQuery(name: name), cachePolicy: .fetchIgnoringCacheData) { result in guard let data = try? result.get().data, let code = data.crews?.code, let message = data.crews?.message else { completion(.failure(.crewList(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.crewList(message))) return } // response from server guard let crews = data.crews?.crews else { completion(.failure(.crewList("Fail Convert json data"))) return } completion(.success(crews)) } } func createCrew(name: String, oneLine: String, district: String, completion: @escaping CrewCompletion) { guard let nickname = UserDataService.shared.user?.nickname else { completion(.failure(.createCrew(("Nickname is nil")))) return } let crewDateInput = Date.convertToDateInput(date: Date()) let createCrewInput = CreateCrewInput(nickname: nickname, name: name, oneLine: oneLine, district: district, creationDate: crewDateInput) let createCrewMutation = CreateCrewMutation(input: createCrewInput) Apollo.shared.client.perform(mutation: createCrewMutation) { result in guard let data = try? result.get().data, let code = data.createCrew?.code, let message = data.createCrew?.message else { completion(.failure(.createCrew(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.createCrew(message))) return } // response from server completion(.success(true)) } } func applyCrew(id: String, district: String, completion: @escaping CrewCompletion) { guard let user = UserDataService.shared.user else { completion(.failure(.applyCrew(("User data is nil")))) return } let memberInput = MemberInput(name: user.name, nickname: user.nickname, district: user.district) let applyCrewInput = ApplyCrewInput(id: id, district: district, user: memberInput) let applyCrewMutation = ApplyCrewMutation(input: applyCrewInput) Apollo.shared.client.perform(mutation: applyCrewMutation) { result in guard let data = try? result.get().data, let code = data.applyCrew?.code, let message = data.applyCrew?.message else { completion(.failure(.applyCrew(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.applyCrew(message))) return } // response from server completion(.success(true)) } } func goOutCrew(id: String, district: String, completion: @escaping CrewCompletion) { let goOutCrewInput = GoOutCrewInput(id: id, district: district) let goOutCrewMutation = GoOutCrewMutation(input: goOutCrewInput) Apollo.shared.client.perform(mutation: goOutCrewMutation) { result in guard let data = try? result.get().data, let code = data.goOutCrew?.code, let message = data.goOutCrew?.message else { completion(.failure(.goOutCrew(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.goOutCrew(message))) return } // response from server completion(.success(true)) } } func disassembleCrew(id: String, district: String, completion: @escaping CrewCompletion) { let disassembleCrewInput = DisassembleCrewInput(id: id, district: district) let disassembleCrewMutation = DisassembleCrewMutation(input: disassembleCrewInput) Apollo.shared.client.perform(mutation: disassembleCrewMutation) { result in guard let data = try? result.get().data, let code = data.disassembleCrew?.code, let message = data.disassembleCrew?.message else { completion(.failure(.disassembleCrew(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.disassembleCrew(message))) return } // response from server completion(.success(true)) } } func acceptMember(id: String, district: String, memberID: String, completion: @escaping CrewCompletion) { let acceptCrewMemberInput = AcceptCrewMemberInput(id: id, district: district, memberId: memberID) let acceptCrewMemberMutation = AcceptCrewMemeberMutation(input: acceptCrewMemberInput) Apollo.shared.client.perform(mutation: acceptCrewMemberMutation) { result in guard let data = try? result.get().data, let code = data.acceptCrewMember?.code, let message = data.acceptCrewMember?.message else { completion(.failure(.acceptCrewMember(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.acceptCrewMember(message))) return } // response from server completion(.success(true)) } } func rejectMember(id: String, district: String, memberID: String, completion: @escaping CrewCompletion) { let rejectCrewMemberInput = RejectCrewMemberInput(id: id, district: district, memberId: memberID) let rejectCrewMemberMutation = RejectCrewMemeberMutation(input: rejectCrewMemberInput) Apollo.shared.client.perform(mutation: rejectCrewMemberMutation) { result in guard let data = try? result.get().data, let code = data.rejectCrewMember?.code, let message = data.rejectCrewMember?.message else { completion(.failure(.rejectCrewMember(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.rejectCrewMember(message))) return } // response from server completion(.success(true)) } } func exceptMember(id: String, district: String, memberID: String, completion: @escaping CrewCompletion) { let exceptCrewMemberInput = ExceptCrewMemberInput(id: id, district: district, memberId: memberID) let exceptCrewMemberMutation = ExceptCrewMemeberMutation(input: exceptCrewMemberInput) Apollo.shared.client.perform(mutation: exceptCrewMemberMutation) { result in guard let data = try? result.get().data, let code = data.exceptCrewMember?.code, let message = data.exceptCrewMember?.message else { completion(.failure(.exceptCrewMember(("Internal server error")))) return } // check reseponse HTTP code guard code.isSuccessfulResponse else { completion(.failure(.exceptCrewMember(message))) return } // response from server completion(.success(true)) } } }
true
0a82c9f7bfebf31934a95fd8a4ce8c13805a0c80
Swift
kukushi/Lily
/LilyTests/DiskCacheTest.swift
UTF-8
1,892
2.890625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // DiskCacheTest.swift // Lily // // Created by kukushi on 4/13/15. // Copyright (c) 2015 kukushi. All rights reserved. // import XCTest @testable import Lily class Object: NSObject, NSCoding { var lily = "poi" override init() { } required init?(coder aDecoder: NSCoder) { lily = aDecoder.decodeObjectForKey("lily") as! String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(lily, forKey: "lily") } } class DiskCacheTest: XCTestCase { var diskCache: Lily.DiskCache! // MARK: Setup override func setUp() { super.setUp() diskCache = Lily.DiskCache() } override func tearDown() { super.tearDown() } func testCacheInt() { diskCache["1"] = 1 XCTAssert(self.diskCache["1"].int == 1) let expectation = expectationWithDescription("Wait for clearing disk cache") self.diskCache["1"].fetch { object in let valid = (object as! Int == 1) && (FileManager.fileExistsAtDirectory("Default/1")) XCTAssertTrue(valid) expectation.fulfill() } waitForExpectationsWithTimeout(2, handler:nil) } func testCacheDictionary() { let object = Object() let dict = ["object": object] diskCache["objectdictionary"] = dict let expectation = expectationWithDescription("Wait for clearing disk cache") self.diskCache["objectdictionary"].fetch { object in let isObjectCorrect = (object as! [String: Object] == dict) let isFileExist = FileManager.fileExistsAtDirectory("Default/objectdictionary") XCTAssertTrue(isObjectCorrect && isFileExist) expectation.fulfill() } waitForExpectationsWithTimeout(2, handler:nil) } }
true
1c4e2d1a4ab09562e939e29dcd8ab8885ec11a85
Swift
cotkjaer/SwiftPlus
/SwiftPlus/UICollectionView.swift
UTF-8
12,296
2.734375
3
[]
no_license
// // UICollectionView.swift // Silverback // // Created by Christian Otkjær on 22/10/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import UIKit // MARK: - CustomDebugStringConvertible extension UICollectionViewScrollDirection : CustomDebugStringConvertible, CustomStringConvertible { public var description : String { return debugDescription } public var debugDescription : String { switch self { case .vertical: return "Vertical" case .horizontal: return "Horizontal" } } } //MARK: - IndexPaths extension UICollectionView { public func indexPathForLocation(_ location : CGPoint) -> IndexPath? { for cell in visibleCells { if cell.bounds.contains(convert(location, to: cell)) { return indexPath(for: cell) } } return nil } } open class LERPCollectionViewLayout: UICollectionViewLayout { public enum Alignment { case top, bottom, left, right } open var alignment = Alignment.left { didSet { if oldValue != alignment { invalidateLayout() } } } public enum Axis { case vertical, horizontal } open var axis = Axis.horizontal { didSet { if oldValue != axis { invalidateLayout() } } } public enum Distribution { case fill, stack } open var distribution = Distribution.fill { didSet { if oldValue != distribution { invalidateLayout() } } } fileprivate var attributes = Array<UICollectionViewLayoutAttributes>() override open func prepare() { super.prepare() attributes.removeAll() if let sectionCount = collectionView?.numberOfSections { for section in 0..<sectionCount { if let itemCount = collectionView?.numberOfItems(inSection: section) { for item in 0..<itemCount { let indexPath = IndexPath(item: item, section: section) if let attrs = layoutAttributesForItem(at: indexPath) { attributes.append(attrs) } } } } } } override open var collectionViewContentSize : CGSize { if var frame = attributes.first?.frame { for attributesForItemAtIndexPath in attributes { frame.union(attributesForItemAtIndexPath.frame) } return CGSize(width: frame.right, height: frame.top) } return CGSize.zero } override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return collectionView?.bounds != newBounds } override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributesForElementsInRect = [UICollectionViewLayoutAttributes]() for attributesForItemAtIndexPath in attributes { if attributesForItemAtIndexPath.frame.intersects(rect) { attributesForElementsInRect.append(attributesForItemAtIndexPath) } } return attributesForElementsInRect } func factorForIndexPath(_ indexPath: IndexPath) -> CGFloat { if let itemCount = collectionView?.numberOfItems(inSection: (indexPath as NSIndexPath).section) { let factor = itemCount > 1 ? CGFloat((indexPath as NSIndexPath).item) / (itemCount - 1) : 0 return factor } return 0 } func zIndexForIndexPath(_ indexPath: IndexPath) -> Int { if let selectedItem = (collectionView?.indexPathsForSelectedItems?.first as NSIndexPath?)?.item, let itemCount = collectionView?.numberOfItems(inSection: (indexPath as NSIndexPath).section) { return itemCount - abs(selectedItem - (indexPath as NSIndexPath).item) } return 0 } override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let collectionView = self.collectionView // let attrs = super.layoutAttributesForItemAtIndexPath(indexPath) { let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath) let factor = factorForIndexPath(indexPath) let l = ceil(min(collectionView.bounds.height, collectionView.bounds.width)) let l_2 = l / 2 var lower = collectionView.contentOffset + CGPoint(x: l_2, y: l_2) var higher = lower//CGPoint(x: l_2, y: l_2) switch axis { case .horizontal: higher.x += collectionView.bounds.width - l case .vertical: higher.y += collectionView.bounds.height - l } switch alignment { case .top, .left: break case .bottom: swap(&higher.y, &lower.y) case .right: swap(&higher.x, &lower.x) } attrs.frame = CGRect(center: (lower, higher) ◊ factor, size: CGSize(l)) attrs.zIndex = zIndexForIndexPath(indexPath) return attrs } return nil } } // MARK: - Sections extension UICollectionView { fileprivate func indexSet(_ sections: [Int]) -> IndexSet { let indexSet = NSMutableIndexSet() sections.forEach { indexSet.add($0)} return indexSet as IndexSet } public func insertSections(_ sections: Int...) { insertSections( indexSet(sections) ) } public func insertSection(_ section: Int?) { guard let section = section else { return } insertSections(IndexSet(integer: section)) } public func deleteSections(_ sections: Int...) { deleteSections( indexSet(sections) ) } public func deleteSection(_ section: Int?) { guard let section = section else { return } deleteSections(IndexSet(integer: section)) } public func reloadSections(_ sections: Int...) { reloadSections( indexSet(sections) ) } public func reloadSection(_ section: Int?) { guard let section = section else { return } reloadSections(IndexSet(integer: section)) } // MARK: Items public func insertItem(at indexPath: IndexPath?) { guard let indexPath = indexPath else { return } insertItems( at: [indexPath] ) } public func deleteItem(at indexPath: IndexPath?) { guard let indexPath = indexPath else { return } deleteItems( at: [indexPath] ) } public func reloadItem(at indexPath: IndexPath?) { guard let indexPath = indexPath else { return } reloadItems( at: [indexPath] ) } public func moveItem(at: IndexPath?, to: IndexPath?) { guard let at = at, let to = to else { return } moveItem(at: at, to: to) } } // MARK: - Lookup extension UICollectionView { public func numberOfItems(inSection: Int?) -> Int { guard let section = inSection else { return 0 } return numberOfItems(inSection: section) } public func numberOfItemsInSectionForIndexPath(_ indexPath: IndexPath?) -> Int { return numberOfItems(inSection: (indexPath as NSIndexPath?)?.section) } } //MARK: - FlowLayout extension UICollectionViewController { public var flowLayout : UICollectionViewFlowLayout? { return collectionViewLayout as? UICollectionViewFlowLayout } } //MARK: - batch updates public extension UICollectionView { public func performBatchUpdates(_ updates: (() -> Void)?) { performBatchUpdates(updates, completion: nil) } public func reloadSection(_ section: Int) { if section >= 0 && section < numberOfSections { self.reloadSections(IndexSet(integer: section)) } } } //MARK: refresh public extension UICollectionView { public func refreshVisible(_ animated: Bool = true, completion: ((Bool) -> ())? = nil) { let animations = { self.reloadItems(at: self.indexPathsForVisibleItems) } if animated { performBatchUpdates(animations, completion: completion) } else { animations() completion?(true) } } } // MARK: - Index Paths public extension UICollectionView { var lastIndexPath : IndexPath? { let section = numberOfSections - 1 if section >= 0 { let item = numberOfItems(inSection: section) - 1 if item >= 0 { return IndexPath(item: item, section: section) } } return nil } var firstIndexPath : IndexPath? { if numberOfSections > 0 { if numberOfItems(inSection: 0) > 0 { return IndexPath(item: 0, section: 0) } } return nil } } // MARK: - TODO: Move to own file class PaginationCollectionViewFlowLayout: UICollectionViewFlowLayout { init(flowLayout: UICollectionViewFlowLayout) { super.init() itemSize = flowLayout.itemSize sectionInset = flowLayout.sectionInset minimumLineSpacing = flowLayout.minimumLineSpacing minimumInteritemSpacing = flowLayout.minimumInteritemSpacing scrollDirection = flowLayout.scrollDirection } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } func applySelectedTransform(_ attributes: UICollectionViewLayoutAttributes?) -> UICollectionViewLayoutAttributes? { return attributes } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if let layoutAttributesList = super.layoutAttributesForElements(in: rect) { return layoutAttributesList.flatMap( self.applySelectedTransform ) } return nil } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = super.layoutAttributesForItem(at: indexPath) return applySelectedTransform(attributes) } // Mark : - Pagination var pageWidth : CGFloat { return itemSize.width + minimumLineSpacing } let flickVelocity : CGFloat = 0.3 override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { var contentOffset = proposedContentOffset if let collectionView = self.collectionView { let rawPageValue = collectionView.contentOffset.x / pageWidth let currentPage = velocity.x > 0 ? floor(rawPageValue) : ceil(rawPageValue) let nextPage = velocity.x > 0 ? ceil(rawPageValue) : floor(rawPageValue); let pannedLessThanAPage = abs(1 + currentPage - rawPageValue) > 0.5 let flicked = abs(velocity.x) > flickVelocity if pannedLessThanAPage && flicked { contentOffset.x = nextPage * pageWidth } else { contentOffset.x = round(rawPageValue) * pageWidth } } return contentOffset } }
true
2965e171116706eb2332801e096b9b52c6c53a3f
Swift
oneGain/Hello-New-World
/WGCarry/blockly-ios-develop 2/Sources/Model/XML/Workspace+XML.swift
UTF-8
3,042
2.59375
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
/* * Copyright 2016 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import AEXML // MARK: - XML Parsing extension Workspace { // MARK: - Public /** Loads blocks from an XML string into the workspace. - parameter xmlString: The string that contains all the block data. - parameter factory: The `BlockFactory` to use to build blocks. - throws: `BlocklyError`: Occurs if there is a problem parsing the xml (eg. insufficient data, malformed data, or contradictory data). */ public func loadBlocks(fromXMLString xmlString: String, factory: BlockFactory) throws { let xmlDoc = try AEXMLDocument(xml: xmlString) try loadBlocks(fromXML: xmlDoc.root, factory: factory) } /** Loads blocks from an XML object into the workspace. - parameter xml: The object that contains all the block data. - parameter factory: The `BlockFactory` to use to build blocks. - throws: `BlocklyError`: Occurs if there is a problem parsing the xml (eg. insufficient data, malformed data, or contradictory data). */ public func loadBlocks(fromXML xml: AEXMLElement, factory: BlockFactory) throws { if let allBlocksXML = xml["block"].all { var blockTrees = Array<Block.BlockTree>() for blockXML in allBlocksXML { let blockTree = try Block.blockTree(fromXML: blockXML, factory: factory) blockTrees.append(blockTree) } try addBlockTrees(blockTrees.map({ $0.rootBlock })) } } } // MARK: - XML Serialization extension Workspace { // MARK: - Public /** Returns an XML string representing the current state of this workspace. - returns: The XML string. - throws: `BlocklyError`: Thrown if there was an error serializing any of the blocks in the workspace. */ @objc(toXMLWithError:) public func toXML() throws -> String { return try toXMLDocument().xml } // MARK: - Internal /** Creates and returns an XML document representing the current state of this workspace. - returns: An XML document. - throws: `BlocklyError`: Thrown if there was an error serializing any of the blocks in the workspace. */ internal func toXMLDocument() throws -> AEXMLDocument { let xmlDoc = AEXMLDocument() let rootXML = xmlDoc.addChild(name: "xml", value: nil, attributes: ["xmlns": "http://www.w3.org/1999/xhtml"]) for block in topLevelBlocks() { rootXML.addChild(try block.toXMLElement()) } return xmlDoc } }
true
2731fdcff1f4805be84d21845c16b3f2f4b8da4d
Swift
rjbritt/Curiosity
/Curiosity/Character.swift
UTF-8
7,213
3.375
3
[]
no_license
// // Character.swift // Characters designed to be used to play Curiosity. // Curiosity // // Created by Ryan Britt on 12/8/14. // Copyright (c) 2014 Ryan Britt. All rights reserved. // import UIKit class Character: SKSpriteNode { enum XDirection { case Right, Left, None } //Ideas: enum for valid characters, listening var to determine what character is currently in play // Allow for double jump //MARK: Private Properties private let leftVelocityMovementThreshold:CGFloat = -0.1 // m/s that determines if the character is moving to the left. private let rightVelocityMovementThreshold:CGFloat = 0.1 // m/s that determines if the character is moving to the right. //MARK: Public Properties var jumpXMovementConstant:Double = 0 //Determines the amount of movement allowed midair while jumping var torqueConstant:Double = 0 //Determines the amount of torque applied during movement var jumpConstant:CGFloat = 0 //Determines the amount of vertical impulse applied during a jump var jumpVelocityThreshold:CGFloat = 50 //character must be ascending with more velocity than this threshold var fallingVelocityThreshold:CGFloat = -30 //character must be descending with more velocity than this threshold. var accelerationX:Double = 0 var accelerationY:Double = 0 var canJump = true //MARK: Computed Properties var isFalling:Bool { if self.physicsBody?.velocity.dy < fallingVelocityThreshold { return true } return false } var isJumping:Bool // Computed property to tell whether the character is jumping or not. { if ((self.physicsBody?.velocity.dy > jumpVelocityThreshold)) { return true } return false } var direction:XDirection //Computed property to tell the direction of the character { if (self.physicsBody?.velocity.dx > rightVelocityMovementThreshold) { return .Right } else if (self.physicsBody?.velocity.dx < leftVelocityMovementThreshold) { return .Left } return .None } //MARK: Class Methods /** Returns a character configured in a particular way from the CharacterInformation plist file. Returns a nil Character if there isn't a definition for that character name This factory method configures many different aspects of a character: name, size, physics body, jumpXMovementConstant, torqueConstant, friction, categoryBitMask, and jumpConstant. It does not set the character's default position. :param: name The name of the predefined character :returns: An optional representing the character if there are presets for one, or a nil value if there are not. */ class func presetCharacter(name:String) -> Character? { var charSprite:Character? // Initialize preset characters with their unique "personality" which will affect their playstyle. // All presets are temporarily set to the same as that of Curiosity. let path = NSBundle.mainBundle().pathForResource("CharacterInformation", ofType: "plist") var presetCharacters:NSArray? if let validPath = path { presetCharacters = NSArray(contentsOfFile: validPath) } if let allCharacters = presetCharacters { for characterEntry in allCharacters { let character = characterEntry as NSDictionary if let thisName = character.valueForKey("name") as? String { if (thisName == name) { let charImage = UIImage(named: name) if let image = charImage { charSprite = Character(texture: SKTexture(image: image)) } charSprite?.name = name charSprite?.physicsBody = SKPhysicsBody(circleOfRadius: charSprite!.size.height/2)//SKPhysicsBody(texture: charSprite!.texture, alphaThreshold: 0.8, size: charSprite!.size) charSprite?.physicsBody?.mass = CGFloat((character.valueForKey("mass") as NSNumber).doubleValue) charSprite?.jumpXMovementConstant = (character.valueForKey("jumpXMovementConstant") as NSNumber).doubleValue charSprite?.torqueConstant = (character.valueForKey("torqueConstant") as NSNumber).doubleValue charSprite?.jumpConstant = CGFloat((character.valueForKey("jumpConstant") as NSNumber).doubleValue) } } } } charSprite?.physicsBody?.affectedByGravity = true charSprite?.physicsBody?.allowsRotation = true charSprite?.physicsBody?.categoryBitMask = PhysicsCategory.Character.rawValue charSprite?.physicsBody?.friction = 1.0 return charSprite } //MARK: Instance Methods /** Commands the character to perform the physics related to a jump */ func jump() { //resets the Y velocity so the current velocity has no impact on net jump height. self.physicsBody?.velocity.dy = 0 self.physicsBody?.applyImpulse(CGVectorMake(0, jumpConstant)) } /** Approximation of a torque curve for characters. Doubles the torque applied within the first 90 m/s of their X velocity :param: velocity The full velocity vector of the character :returns: An appropriate torque depending on the character's X velocity and the tilt of the device. */ func torqueToApplyForCharacterWithVelocity(velocity:CGVector) -> CGFloat { var torque:CGFloat = CGFloat(-accelerationX / torqueConstant) //If velocity is below a certain threshold, apply double the torque to get the character moving faster if fabs(velocity.dx) < 90.0 { torque *= 2 } //If acceleration is in the opposite direction as velocity, double the torque again to change directions if(CGFloat(accelerationX) * velocity.dx < 0) { torque *= 2 } return torque } /** Commands the character to move for one frame. As the applied effects are part of the physics engine, these effects are not guaranteed to only last for the length of one frame. */ func move() { let deltaX = CGFloat(accelerationX * jumpXMovementConstant) let torqueX = torqueToApplyForCharacterWithVelocity(physicsBody!.velocity) // Determines any side motion in air if (isJumping) { physicsBody?.applyImpulse(CGVectorMake(deltaX, 0)) } // Defaults to determining side motion on an area marked as solid else if !isJumping { physicsBody?.applyTorque(torqueX) } } }
true
850b6e4d4c8c50230d1c1181411a356a72a5c2fe
Swift
brownfosman5000/DatFace
/DatFace/Trainer.swift
UTF-8
3,343
2.65625
3
[]
no_license
// // Trainer.swift // DatFace // // Created by Foster Brown on 4/28/18. // Copyright © 2018 N. All rights reserved. // import AVKit import algorithmia class Trainer{ var client: AlgorithmiaClient! var datFaceCollection: String! var photos: [[String:String]] = [[:]] var photoInfo: [String:String] = [:] init(){ client = Algorithmia.client(simpleKey: APIkey) datFaceCollection = "data://brownfosman5000/DatFace/" } func getImages()->[[String:String]]{ let image_dir = client.dir(datFaceCollection) image_dir.forEach(file: { (file) in self.photoInfo["url"] = file?.path self.photos.append(self.photoInfo) }) { (error) in print(error) } print(self.photos) // predict() return self.photos } // func trainImages() { // datFaceCollection.file(name: text_file).exists() { exists, error in // if (error == nil) { // // Check if file exists // let local_file = URL(string: "/your_local_path_to_file/jack_london.txt") // if (exists == false) { // nlp_directory.put(file: local_file!) { error in // if (error == nil){ // print("File Uploaded Succesfully") // } else { // print(error) // } // } // } // // Add this to download contents of file // else { // // Download contents of file as a string // nlp_directory.file(name: text_file).getString { text, error in // if (error == nil) { // let input = text // // Add the call to the Summarizer algorithm // let summarizer = client.algo(algoUri: "nlp/Summarizer/0.1.3") // summarizer.pipe(text: input) { resp, error in // if (error == nil) { // print(resp.getText()) // } else { // print(error) // } // } // } else { // print(error) // } // } // } // } // } // } // } // func predict(){ // photos.remove(at: 0) // let json: [String:Any] = [ // "action" : "predict", // "name_space": "datFace", // "data_collection": "datFace", // "images": // [ // "url": "data://brownfosman5000/DatFace/download.png", // "output": "data://brownfosman5000/DatFace/h.k.1.jpeg" // ] // ] // // print(JSONSerialization.isValidJSONObject(json)) // // client = Algorithmia.client(simpleKey: APIkey) // let algo = client.algo(algoUri: "cv/FaceRecognition/0.2.2") // // algo.pipe(json: json) { (resp, error) in // print(resp.getJson()) // } // } }
true
664c427eb33f9ec1f4439a42e1d53f377ffcd439
Swift
mleiv/MEGameTracker
/MEGameTracker/Models/CoreData/CoreDataMigrations/CoreDataEliminateDuplicates.swift
UTF-8
1,062
2.75
3
[ "MIT" ]
permissive
// // CoreDataEliminateDuplicates.swift // MEGameTracker // // Created by Emily Ivie on 12/31/17. // Copyright © 2017 Emily Ivie. All rights reserved. // import Foundation public struct CoreDataEliminateDuplicates: CoreDataMigrationType { public func run() { deleteDuplicates(type: DataDecision.self) deleteDuplicates(type: DataEvent.self) deleteDuplicates(type: DataItem.self) deleteDuplicates(type: DataMap.self) deleteDuplicates(type: DataMission.self) deleteDuplicates(type: DataPerson.self) } private func deleteDuplicates<T: DataRowStorable>(type: T.Type) { T.getAllIds() .reduce([String: Int]()) { var l = $0; l[$1, default: 0] += 1; return l } .filter { $0.1 > 1 } .forEach { let rows = T.getAll(ids: [$0.0]) for index in 1..<rows.count { var row = rows[index] print("Deleted duplicate row \($0.0)") _ = row.delete() } } } }
true
d3a3485c3a8f9ce506624c553d68d21330819915
Swift
t-ae/vectorizate
/Tests/VectorizateTests/ExponentialTests.swift
UTF-8
2,754
2.609375
3
[ "MIT" ]
permissive
import XCTest import Vectorizate class ExponentialTests: XCTestCase { let count = 100 func runTest<F: BinaryFloatingPoint>( type: F.Type, func1: (UnsafePointer<F>, UnsafeMutablePointer<F>, Int)->Void, func2: (UnsafePointer<F>, UnsafeMutablePointer<F>, Int)->Void, range: Range<F> = 0..<1, accuracy: F = 0, file: StaticString = #file, line: UInt = #line) where F.RawSignificand: FixedWidthInteger { let x: [F] = randomArray(count: count, in: range) var ans1 = [F](repeating: 0, count: count) var ans2 = [F](repeating: 0, count: count) func1(x, &ans1, count) func2(x, &ans2, count) XCTAssertEqual(ans1, ans2, accuracy: accuracy, file: file, line: line) } func testVExp() { runTest(type: Float.self, func1: VecOps.vexp, func2: VecOpsNoAccelerate.vexp, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vexp, func2: VecOpsNoAccelerate.vexp, accuracy: 1e-12) } func testVExp2() { runTest(type: Float.self, func1: VecOps.vexp2, func2: VecOpsNoAccelerate.vexp2, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vexp2, func2: VecOpsNoAccelerate.vexp2, accuracy: 1e-12) } func testVExpm1() { runTest(type: Float.self, func1: VecOps.vexpm1, func2: VecOpsNoAccelerate.vexpm1, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vexpm1, func2: VecOpsNoAccelerate.vexpm1, accuracy: 1e-12) } func testVLog() { runTest(type: Float.self, func1: VecOps.vlog, func2: VecOpsNoAccelerate.vlog, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vlog, func2: VecOpsNoAccelerate.vlog, accuracy: 1e-12) } func testVLog1p() { runTest(type: Float.self, func1: VecOps.vlog1p, func2: VecOpsNoAccelerate.vlog1p, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vlog1p, func2: VecOpsNoAccelerate.vlog1p, accuracy: 1e-12) } func testVLog2() { runTest(type: Float.self, func1: VecOps.vlog2, func2: VecOpsNoAccelerate.vlog2, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vlog2, func2: VecOpsNoAccelerate.vlog2, accuracy: 1e-12) } func testVLog10() { runTest(type: Float.self, func1: VecOps.vlog10, func2: VecOpsNoAccelerate.vlog10, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vlog10, func2: VecOpsNoAccelerate.vlog10, accuracy: 1e-12) } func testVLogb() { runTest(type: Float.self, func1: VecOps.vlogb, func2: VecOpsNoAccelerate.vlogb, accuracy: 1e-6) runTest(type: Double.self, func1: VecOps.vlogb, func2: VecOpsNoAccelerate.vlogb, accuracy: 1e-12) } }
true
b3e316c2005fa6fb46d447c400603735f7429ea1
Swift
apbaca06/Vibe
/i-Chat/AudioCall/IncomingCallViewController.swift
UTF-8
2,423
2.515625
3
[]
no_license
// // IncomingCallViewController.swift // i-Chat // // Created by cindy on 2017/12/14. // Copyright © 2017年 Jui-hsin.Chen. All rights reserved. // import Foundation import UIKit import AVFoundation import Nuke import Crashlytics class IncomingCallViewController: UIViewController { var userInfo: [String: String]? @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var backgroundView: UIImageView! @IBOutlet weak var callDescription: UILabel! @IBOutlet weak var name: UILabel! @IBOutlet weak var acceptButton: UIButton! @IBOutlet weak var rejectButton: UIButton! @IBAction func rejectButton(_ sender: UIButton) { RingtoneManager.shared.ringPlayer.stop() print("***Did reject") CallManager.shared.session?.rejectCall(nil) print("****\(CallManager.shared.session)") CallManager.shared.session = nil self.callDescription.text = NSLocalizedString("Reject Call", comment: "") self.dismiss(animated: true, completion: nil) } @IBAction func acceptButton(_ sender: UIButton) { print("Did accept") RingtoneManager.shared.ringPlayer.stop() CallManager.shared.session?.acceptCall(nil) } override func viewDidLoad() { super.viewDidLoad() RingtoneManager.shared.playRingtone() let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.regular) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = backgroundView.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundView.addSubview(blurEffectView) guard let dict = userInfo, let name = dict["Name"], let urlString = dict["profileImgURL"], let url = URL(string: urlString) else { return } self.name.text = name Manager.shared.loadImage(with: url, into: profileImageView) // Manager.shared.loadImage(with: url, into: backgroundView) } override func viewWillLayoutSubviews() { setUpShape() } func setUpShape() { rejectButton.layer.cornerRadius = rejectButton.frame.width/2 acceptButton.layer.cornerRadius = acceptButton.frame.width/2 profileImageView.layer.cornerRadius = profileImageView.bounds.width/2 self.profileImageView.clipsToBounds = true } }
true
ae9d04bfe6d4ceab19648aacb58160c623b9d68a
Swift
jkreller/o-fish-ios
/o-fish-ios/Views/Components/WrappedShadowView.swift
UTF-8
615
2.640625
3
[ "Apache-2.0" ]
permissive
// // WrappedShadowView.swift // // Created on 03/03/2020. // Copyright © 2020 WildAid. All rights reserved. // import SwiftUI func wrappedShadowView<Content: View> (@ViewBuilder view: () -> Content) -> some View { let horizontalPadding: CGFloat = 16.0 return view() .padding(.horizontal, horizontalPadding) .background(Color.white) .compositingGroup() .defaultShadow() } struct WrappedShadowView_Previews: PreviewProvider { static var previews: some View { wrappedShadowView { Text("Shadow...") } } }
true
28802fa39054329aa840cf2e675a185cedc545d2
Swift
SerjKultenko/SmashtagPopularity
/Smashtag/BusinessLogicLayer/TweetInfoModel/TweetInfoModel.swift
UTF-8
6,024
2.765625
3
[ "MIT" ]
permissive
// // TweetInfoModel.swift // Smashtag // // Created by Sergei Kultenko on 02/10/2017. // Copyright © 2017 Stanford University. All rights reserved. // import Foundation import Twitter struct TweetInfoModel { private let tweet: Twitter.Tweet private var sections: [TweetInfoSection] = [] var sectionsNumber: Int { get { return sections.count } } var title: String { return tweet.user.name } func numberOfRows(inSection section: Int) -> Int { guard sections.count > section else { return 0 } return sections[section].numberOfRows } func title(forSection section: Int) -> String { guard sections.count > section else { return "" } return sections[section].sectionTitle } func type(forSection section: Int) -> TweetInfoSectionType? { guard sections.count > section else { return nil } return sections[section].sectionType } func title(forRow row: Int, inSection section: Int) -> String { guard sections.count > section, sections[section].numberOfRows > row else { return "" } return sections[section].title(forRow: row) } func object(forRow row: Int, inSection section: Int) -> Any? { guard sections.count > section, sections[section].numberOfRows > row else { return nil } return sections[section].object(forRow: row) } init(for tweet: Twitter.Tweet) { self.tweet = tweet sections = getSections(for: tweet) } private func getSections(for tweet: Twitter.Tweet) -> [TweetInfoSection] { var sections: [TweetInfoSection] = [] if tweet.media.count>0 { let section = TweetInfoSection(title: "Media", type: .MediaSection, rowsNumber: tweet.media.count, titleForRowProvider: { (row: Int) -> String in guard tweet.media.count > row else { return "" } return tweet.media[row].description }, objectForRowProvider: { (row: Int) -> Any? in guard tweet.media.count > row else { return nil } return tweet.media[row] }) sections.append(section) } if tweet.hashtags.count>0 { let section = TweetInfoSection(title: "Hash tags", type: .HashTagsSection, rowsNumber: tweet.hashtags.count, titleForRowProvider: { (row: Int) -> String in guard tweet.hashtags.count > row else { return "" } return tweet.hashtags[row].keyword }, objectForRowProvider: { (row: Int) -> Any? in guard tweet.hashtags.count > row else { return nil } return tweet.hashtags[row] }) sections.append(section) } if tweet.urls.count>0 { let section = TweetInfoSection(title: "URLs", type: .URLsSection, rowsNumber: tweet.urls.count, titleForRowProvider: { (row: Int) -> String in guard tweet.urls.count > row else { return "" } return tweet.urls[row].keyword }, objectForRowProvider: { (row: Int) -> Any? in guard tweet.urls.count > row else { return nil } return tweet.urls[row] }) sections.append(section) } // UserMentions let titleForRowProvider = { (row: Int) -> String in if row == 0 { return "@" + tweet.user.screenName } let userMentionsIndex = row - 1 guard tweet.userMentions.count > userMentionsIndex else { return "" } return tweet.userMentions[userMentionsIndex].keyword } let objectForRowProvider = { (row: Int) -> Any? in if row == 0 { return "@" + tweet.user.screenName } let userMentionsIndex = row - 1 guard tweet.userMentions.count > userMentionsIndex else { return nil } return tweet.userMentions[userMentionsIndex] } let section = TweetInfoSection(title: "Users", type: .UserMentionsSection, rowsNumber: tweet.userMentions.count + 1, titleForRowProvider: titleForRowProvider, objectForRowProvider: objectForRowProvider) sections.append(section) return sections } }
true
c50a72174f4fac883825126a9011831a901c4e63
Swift
hite/YanxuanHD
/YanxuanHD/ChildrenView/FeatureBanner/BannerImageModel.swift
UTF-8
1,841
2.640625
3
[]
no_license
// // BannerImage.swift // YanxuanHD // // Created by liang on 2019/6/20. // Copyright © 2019 liang. All rights reserved. // import SwiftUI import UIKit class BannerImageModel: Identifiable { static func == (lhs: BannerImageModel, rhs: BannerImageModel) -> Bool { return lhs.id == rhs.id } var id: Int var imageURL: String var destinationURL: String init(id: Int, imageURL: String, destinationURL: String) { self.id = id self.imageURL = imageURL self.destinationURL = destinationURL } init(from: Dictionary<String, Any>) { kIdSeed += 1 self.id = from["id"] as! Int self.destinationURL = from["targetUrl"] as! String self.imageURL = from["picUrl"] as! String } } struct BannerImage : View { @EnvironmentObject var userData: BannerImageData var body: some View { VStack(spacing: 0) { if self.userData.imgData != nil { self.RenderImage() } else { Image("home-banner-sample") } } } func RenderImage() -> some View { return Image(uiImage: self.userData.imgData!) .aspectRatio(1, contentMode: .fit) .scaledToFit() // .frame(width: self.width, height: self.height, alignment: .center) .clipped() } } #if DEBUG struct BannerImage_Previews : PreviewProvider { static let sampe = BannerImageModel.init(id: 1, imageURL: "https://yanxuan.nosdn.127.net/6d83b8e30b1d0a0874dbb068dfc2503a.jpg?imageView&quality=95&thumbnail=1090x310", destinationURL: "https://act.you.163.com/act/pub/nDFLuzkE7Q.html?_stat_referer=index&_stat_area=banner_5") static var previews: some View { BannerImage().environmentObject(BannerImageData(sampe)) } } #endif
true
84364f7a393246343038814fd6ca1b0b2c9f6eef
Swift
alexanderhendel/VirtualTourist
/VirtualTourist/FLICKRClient.swift
UTF-8
10,927
2.921875
3
[]
no_license
// // FLICKRClient.swift // VirtualTourist // // Created by Hiro on 14.08.15. // Copyright © 2015 alexhendel. All rights reserved. // import Foundation import UIKit import CoreData class FLICKRClient: NSObject { // MARK: - variable declarations var session: NSURLSession /// the last page of photos retrieved / downloaded var lastPage: Int /// the number of pages returned var maxPage: Int /// describes each flick (photo) and contains: /// - title /// - url /// - local path struct flick { var title: String var url_m: String var path: String init() { title = "" url_m = "" path = "" } } // MARK: - initializer override init() { // my own setup session = NSURLSession.sharedSession() lastPage = 1 maxPage = 1 // super init super.init() } // MARK: - functions /** Reset the last retrieved page and number of pages. */ func refresh() { lastPage = 1 maxPage = 1 } /** Given a URL try to donwload the photo behind it. Result is handled by a completionHandler. :param: imageurl The URL of the image. :param: completionHandler Will return <NSError, UIImage> optionals. */ func downloadPhotoWithURL(imageurl imageurl: NSURL, completionHandler: ((NSError?, UIImage?) -> Void)) { // get ready for the NSURL request var request: NSURLRequest! request = NSURLRequest(URL: imageurl) // search photos by location if (request != nil) { let task = session.dataTaskWithRequest(request!, completionHandler: {(data, response, downloadError) -> Void in // handle download error if let error = downloadError { print("couldnt finish download request: \(error.localizedDescription)") return completionHandler(error, nil) } else { // parse the response the Swift 2.0 way if (data != nil) { if let image = UIImage(data: data!) { return completionHandler(nil, image) } else { let error = NSError(domain: "download.error", code: 100, userInfo: ["localizedDescription": "conversion to image failed."]) return completionHandler(error, nil) } } else { let error = NSError(domain: "download.error", code: 200, userInfo: ["localizedDescription": "data download failed."]) return completionHandler(error, nil) } } }) task.resume() } } func photosSearchByLocationTask(latitude latitude: Double, longitude: Double, offset: Int, completionHandler: ((NSError?, [flick]?) -> Void)) { // get ready for the NSURL request var urlArgs = [ "method": methods.flickrPhotosSearch, "api_key": constants.apiKey, "bbox": createBoundingBox(latitude: latitude, longitude: longitude), "safe_search": constants.extras.safeSearch, "extras": constants.extras.urlM, "format": constants.dataFormat.json, "nojsoncallback": constants.extras.noJsonCallback, "per_page": constants.extras.perPage ] if (offset > 0) { let newPage = lastPage + offset lastPage++ if (newPage < maxPage) { urlArgs["page"] = String(newPage) } else { urlArgs["page"] = String(maxPage) } // print("maxPages: \(maxPage), newPage: \(newPage), lastPage: \(lastPage)") } let urlString = constants.baseURLSecure + escapedParameters(parameters: urlArgs) let url = NSURL(string: urlString) var request: NSURLRequest! if (url != nil) { request = NSURLRequest(URL: url!) } // search photos by location if (request != nil) { let task = session.dataTaskWithRequest(request!, completionHandler: {(data, response, downloadError) -> Void in // handle download error if let error = downloadError { print("couldnt finish download request: \(error)") } else { // parse the response the Swift 2.0 way do { let parsedResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary if let photosDictionary = parsedResult.valueForKey("photos") as? [String: AnyObject] { // get the photos var totalPhotosVal = 0 if let totalPhotos = photosDictionary["total"] as? String { totalPhotosVal = (totalPhotos as NSString).integerValue } if let totalPages = photosDictionary["pages"] { self.maxPage = totalPages as! Int } if totalPhotosVal > 0 { if let photosArray = photosDictionary["photo"] as? [[String: AnyObject]] { var photos = [flick]() for photo in photosArray { let photoDict = photo as [String: AnyObject] // get photo details var pic = flick() if let photoTitle = photoDict["title"] as? String { pic.title = photoTitle } if let photoUrl = photoDict["url_m"] as? String { pic.url_m = photoUrl } photos.append(pic) } if (photos.count > 0) { return completionHandler(nil, photos) } else { let err = NSError(domain: "error.parse", code: 100, userInfo: ["localizedDescription": "No photos found."]) return completionHandler(err, nil) } } else { let err = NSError(domain: "error.parse", code: 101, userInfo: ["localizedDescription": "No 'photo' keys found in \(photosDictionary)."]) return completionHandler(err, nil) } } else { let err = NSError(domain: "error.parse", code: 102, userInfo: ["localizedDescription": "No 'pages' key found in \(photosDictionary)."]) return completionHandler(err, nil) } } else { let err = NSError(domain: "error.parse", code: 103, userInfo: ["localizedDescription": "No 'photos' key found in \(parsedResult)."]) return completionHandler(err, nil) } } catch let error as NSError { print("parse error: \(error.description)") return completionHandler(error, nil) } catch { print("generic URLtask error") } } }) task.resume() } } // MARK: - private helper functions /** Creates a bounding box string from latitude & logitude values. :param: latitude Latitude of the map location. :param: longitude Longitude of the map location. */ private func createBoundingBox(latitude latitude: Double, longitude: Double) -> String { let bottomLeftLon = max(longitude - constants.boundingBox.halfWidth, constants.boundingBox.longitudeMin) let bottomLeftLat = max(latitude - constants.boundingBox.halfHeigt, constants.boundingBox.latitudeMin) let topRightLon = min(longitude + constants.boundingBox.halfWidth, constants.boundingBox.longitudeMax) let topRightLat = min(latitude + constants.boundingBox.halfHeigt, constants.boundingBox.latitudeMax) // return the string return "\(bottomLeftLon),\(bottomLeftLat),\(topRightLon),\(topRightLat)" } /** Create escaped parameter string from dictionary. :param: parameters A [String: AnyObject] dictionary with the parametrs to be escaped. */ private func escapedParameters(parameters parameters: [String:AnyObject]) -> String { var urlVars = [String]() for (key, value) in parameters { let stringValue = "\(value)" let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) urlVars += [key + "=" + "\(escapedValue!)"] } return (!urlVars.isEmpty ? "?" : "") + urlVars.joinWithSeparator("&") } }
true
19105a3f6bf82d6e6b1e83839f5fe097b3d09401
Swift
Le0nX/TheMovieDB
/TheMovieDBApp/TheMovieDBApp/Presentation/Favorites/FavoritesLoader.swift
UTF-8
1,754
2.796875
3
[]
no_license
// // FavoritesLoader.swift // TheMovieDBApp // // Created by Denis Nefedov on 02.04.2020. // Copyright © 2020 Den4ik's Team. All rights reserved. // import Foundation protocol FavoritesLoader { /// Метод получения фаворитов func getFavorites() } /// Лоадер-фасад экрана фаворитов, /// который скрывает за собой работу других сервисов final class FavoritesLoaderImpl: FavoritesLoader { // MARK: - Private Properties private let favoriteService: FavoritesService private let accessService: AccessCredentialsService private var userData: FavoriteServiceModel? private let view: SearchViewInput // MARK: - Initializers init(_ view: SearchViewInput, favoriteService: FavoritesService, accessService: AccessCredentialsService ) { self.view = view self.favoriteService = favoriteService self.accessService = accessService } // MARK: - Public methods func getFavorites() { // TODO: - пагинация let model = FavoriteServiceModel(sessionId: accessService.credentials?.session ?? "", profileId: accessService.credentials?.accountId ?? 0, page: 1) favoriteService.getFavorites(for: model) { [weak self] result in switch result { case .success(let movies): self?.view.setMoviesData(movies: movies) case .failure(let error): self?.view.showError(error: error) self?.view.setMoviesData(movies: []) } } } }
true
04092c9d4353215480c3aa1fb853615dcd3b1c87
Swift
willyelns/TipCalculator
/TipCalculator/TipCalculatorViewModel.swift
UTF-8
1,412
2.9375
3
[]
no_license
// // TipCalculatorViewModel.swift // TipCalculator // // Created by Will Germano on 16/10/21. // import Foundation final class TipCalculatorViewModel: ObservableObject { @Published var checkAmount = "" @Published var numberOfPeople = 2 @Published var tipPercentage = 2 let tipPercentages = [10, 15, 20, 25, 0] var subTotal: Double { Double(checkAmount) ?? 0} var subTotalPerPerson: Double { let peopleCount = Double(numberOfPeople) let orderAmount = Double(checkAmount) ?? 0 return orderAmount / peopleCount } var tipValue: Double { let tipSelection = Double(tipPercentages[tipPercentage]) let orderAmount = Double(checkAmount) ?? 0 return orderAmount / 100 * tipSelection } var tipValuePerPerson: Double { tipValue / Double(numberOfPeople) } var totalAmountWithTip: Double { let tipSelection = Double(tipPercentages[tipPercentage]) let orderAmount = Double(checkAmount) ?? 0 let tipValue = orderAmount / 100 * tipSelection let grandTotal = orderAmount + tipValue return grandTotal } var totalPerPerson: Double { let peopleCount = Double(numberOfPeople) let amountPerPerson = totalAmountWithTip / peopleCount return amountPerPerson } }
true
5926ea4d25a7e1221fc4ece13024e27e0a454129
Swift
FruitAddict/CapitalsApp
/CityBrowser/CityBrowser/Controllers/City details/Presenter/CityDetailsPresenterImpl.swift
UTF-8
3,668
2.71875
3
[]
no_license
// // CityDetailsPresenterImpl.swift // CityBrowser // // Created by Mateusz Popiało on 04/08/2020. // Copyright © 2020 Mateusz Popiało. All rights reserved. // import Foundation final class CityDetailsPresenterImpl: CityDetailsPresenter { //MARK: - Services & Dependencies struct Dependencies { let flowController : CityBrowserFlowController let city: CityWrapper let detailsService: FetchCityDetailsService let favoriteCityService: FavoriteCityService } fileprivate weak var view : CityDetailsView? fileprivate let flowController : CityBrowserFlowController fileprivate let detailsService: FetchCityDetailsService fileprivate let favoriteCityService: FavoriteCityService fileprivate let city: CityWrapper //MARK: - Initialization init(with dependencies: Dependencies) { self.city = dependencies.city self.flowController = dependencies.flowController self.detailsService = dependencies.detailsService self.favoriteCityService = dependencies.favoriteCityService } //MARK: - Service calls fileprivate func fetchCityDetailsIfNeeded() { updateView() guard case .fetched(_) = city.cityDetailsState else { fetchCityDetails() return } } private func fetchCityDetails() { detailsService.fetchCityDetails(forCity: city.city.capital) { result in switch result { case .success(let details): self.city.cityDetailsState = .fetched(details) self.updateView() case .failure(_): self.city.cityDetailsState = .error } } } //MARK: - Updating view private func updateView() { let viewModel: CityDetailsViewModel switch city.cityDetailsState { case .initial: viewModel = CityDetailsViewModel( country: city.city.name, cityName: city.city.capital, imageBase64: city.imageBase64String, numberOfVisitors: .loading, rating: .loading, isFavorite: city.isFavorite ) case .error: viewModel = CityDetailsViewModel( country: city.city.name, cityName: city.city.capital, imageBase64: city.imageBase64String, numberOfVisitors: .error, rating: .error, isFavorite: city.isFavorite ) case .fetched(let details): viewModel = CityDetailsViewModel( country: city.city.name, cityName: city.city.capital, imageBase64: city.imageBase64String, numberOfVisitors: .loaded("\(details.visitorList.visitors.count)"), rating: .loaded(details.rating.rating), isFavorite: city.isFavorite ) } view?.setViewModel(viewModel) } } //MARK: - Events emitted from view extension CityDetailsPresenterImpl { func attach(view: CityDetailsView) { self.view = view } func handleViewIsReady() { view?.setTitle("Details") fetchCityDetailsIfNeeded() } func handleFavoriteFlagChanged(_ newState: Bool) { self.favoriteCityService.setFavoriteCity(name: city.city.capital, isFavorite: newState) self.city.isFavorite = newState updateView() } }
true
bd57585a1abdc0b843aa43c9c44a2d1dad249c40
Swift
iOSDevGarg/iBeacons
/iBeacons/BeaconCreator/BeaconCreator/ViewController.swift
UTF-8
1,617
2.84375
3
[]
no_license
// // ViewController.swift // BeaconCreator // // Created by Peyman on 8/26/19. // Copyright © 2019 iOSDeveloper. All rights reserved. // import UIKit import CoreBluetooth class ViewController: UIViewController { /// UUID Label @IBOutlet weak var uuidLabel: UILabel! /// Device Name Label @IBOutlet weak var deviceNameLabel: UILabel! /// Bluetooth CLass var bleManager: AppBLEManager! @IBAction func startRegion(_ sender: UIButton) { guard let beaconClass = bleManager else { return } beaconClass.startBeaconSpreading(success: { (success) in self.deviceNameLabel.text = "Beacon is transmitting" print("Success") }) { (error) in print("Error: \(error.localizedDescription)") self.deviceNameLabel.text = nil } } @IBAction func stopRegion(_ sender: UIButton) { guard let beaconClass = bleManager else { return } beaconClass.stopLocalBeacon() self.deviceNameLabel.text = "Beacon not transmitting" } } //MARK:- View Life Cycles extension ViewController { //MARK: Did Load override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. bleManager = AppBLEManager() bleManager.delegate = self } } extension ViewController: AppBLEManagerDelegate { func bluetoothStateIssue(Error error: Error) { } func beaconStartedToTransmit() { self.deviceNameLabel.text = "Beacon is transmitting" } }
true
0156f284c2e99bc7c943913d9e40fc8dbe0ebe3a
Swift
oo20/ios-directory-listing-swift-realm-objectmapper-alamofire
/DirectoryListing/Extensions/UITextFieldExtension.swift
UTF-8
665
2.671875
3
[]
no_license
// // UITextFieldExtension.swift // DirectoryListing // // Created by Michael Steele on 5/16/17. // Copyright © 2017 Michael Steele. All rights reserved. // import UIKit extension UITextField { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ func editing(_ editingAllowed: Bool) { self.borderStyle = editingAllowed == true ? .roundedRect : .none self.isEnabled = true } func disabled() { self.borderStyle = .none self.isEnabled = false } }
true
a73804c01a6a5dc144fc2a9cad93292e086020ea
Swift
KNU-CSE-APP/iOS
/KNU_CSE/KNU_CSE/View/Main/Classroom Reservation/Reservation/SeatPicView.swift
UTF-8
1,421
2.703125
3
[ "MIT" ]
permissive
// // SeatPicView.swift // KNU_CSE // // Created by junseok on 2021/07/20. // import UIKit import SnapKit class SeatPicView : UIViewController, ViewProtocol{ var imageView:UIImageView!{ didSet{ self.view.backgroundColor = UIColor.black.withAlphaComponent(0.2) let gesture : UIGestureRecognizer = UIGestureRecognizer(target: self, action: #selector(dismissView)) self.view.addGestureRecognizer(gesture) imageView.backgroundColor = .green imageView.image = UIImage(named: "testImage.jpeg") } } override func viewDidLoad() { initUI() addView() setUpConstraints() } func initUI() { imageView = UIImageView() } func addView() { self.view.addSubview(imageView) } func setUpConstraints() { let top_margin = self.view.frame.height * 0.3 let left_margin = 10 let right_margin = -left_margin imageView.snp.makeConstraints{ make in make.left.equalToSuperview().offset(left_margin) make.right.equalToSuperview().offset(right_margin) make.top.equalToSuperview().offset(top_margin) make.bottom.equalToSuperview().offset(-top_margin) } } @objc func dismissView(){ self.dismiss(animated: true, completion: nil) } }
true
cad544d5a70d9af30491447fc82eb731c9df8f02
Swift
sloik/SwiftPlayground
/contents/swift_from_zero_to_hero.playground/Pages/11_01_generics.xcplaygroundpage/Contents.swift
UTF-8
12,069
4.4375
4
[]
no_license
//:[ToC](00-00_toc) | [Tips and Tricks](900-00-tips_and_tricks) | [Previous](@previous) | [Next](@next) //: ## [Generyki](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html) import Foundation /*: W Swift każda stała lub zmienna mają zadeklarowany typ. Dzięku temu zawsze (prawie zawsze) wiemy z jakiego _typu_ obiektem mamy do czynienia. Gdy potrzebujemy nieco rozluźnić "więzy" możemy zadeklarować zmienną jako _Any_ lub _AnyObject_. Dodatkowo mając protokoły znamy interfejs danego typu i możemy bezpiecznie wywoływać na nim metody. Jeżeli natomiast mamy potrzebę sprawdzenia z jakim konkretnie typem teraz pracujemy możemy zkastować na odpowiedni typ (oczywiście wymaga to sprawdzenia czy instancja z którą teraz pracujemy jest tego typu). **Generyki** pozwalają nam zachować "gwarancje typu" i pozwalają nam pracować bezpośrednio z instancją bez wymogu kastowania (ang. cast). Kilka przykładów: */ let strings: Array<String> = [] type(of: strings) let ints: Array<Int> = [] type(of: ints) struct 💩 { var id: Int } //: 💡: Zobacz jak zadeklarowana jest tablica w standardowej bibliotece (cmd + double click) let 💩s: Array<💩> = [] type(of: 💩s) /*: Wygląda na to, że już zupełnie niechcący generyki były wykorzystywane na potęgę i nawet o tym nie wiedzieliśmy! */ let dictionaryOfStringInt: Dictionary<String, Int> = [:] //💡: Więcej jak jeden typ (argument) generyczny type(of: dictionaryOfStringInt) let setOfStrings: Set<String> = [] type(of: setOfStrings) let maybeQuote: Optional<String> = .none /*: Generyki można też definiować w funkcjach. Poniżej przykład z funkcją `swap` dostępną w bibliotece standardowej Swift. */ run("🤽‍♂️ swap"){ var foo = 4 ; var bar = 2 var floatFoo = 4.2; var floatBar = 6.9 print("Przed", foo, bar, floatFoo, floatBar) swap(&foo , &bar ) swap(&floatFoo, &floatBar) print(" Po", foo, bar, floatFoo, floatBar) } /*: Funkcje generyczne to inny rodzaj polimorfizmu. Trudny i straszny wyraz. Może kilka przykładów aby _poczuć_ o co chodzi. **Chciałbym napisać funkcję, która zwróci mi przekazany argument**. Taka funkcja wydaje się mało użyteczna, co jest nie prawdą. Jest bardzo użyteczna i potrzebna! */ func identityInt (_ a: Int ) -> Int { a } func identityString(_ a: String) -> String { a } /*: Łatwo sobie wyobrazić więcej takich funkcji. Jednak jest z tym kilka problemów. Po pierwsze duplikuje kod i muszę go pisać dla każdego typu jaki jest. Inaczej nie mogę zawołać tej funkcji z instancją tego typu. Kolejny problem to, że w implementacji nie wykorzystuję żadnej wiedzy o tym konkretnym typie. Na sam koniec widać gołym okiem, że ten kod jest identyczny! Różni się tylko typem na wejściu i wyjściu, który jest taki sam! # Definiowanie Funkcji Generycznych Jedyną różnicą między zwykłą funkcją a funkcją generyczną jest podanie listy generyków w nawiasach `<>` między nazwą a listą argumentów. Zobaczmy... */ func identity<A>(_ a: A) -> A { a } run("🆔 identity"){ print( identity(42), identity("wow") ) } /*: Funkcja `identity` ma jeden typ generyczny o nazwie `A`. Przyjmuje jako argument instancję typu `A`. Ta sama implementacja działa dla `Int` i dla `String`. Zadziała również i dla każdego innego typu, który powstanie w przyszłości. To wszystko bez potrzeby rekompilowania kodu! Wisienką na torcie jest to, że ponieważ nic nie wiemy o typie `A` to nie możemy wywołać na nim żadnej metody. Sprawdzić żadnego property! Dzięki temu można pisać bardziej ogólne algorytmy. Napisać testy dla tych generycznych algorytmów i spokojnie reużywać! Unikać niepotrzebnych powtórzeń w kodzie. Parametrów generycznych może być więcej. */ func tupleSwap<A,B>(_ tuple: (A, B)) -> (B, A) { (tuple.1, tuple.0) } run("🐶 tupleSwap"){ print( tupleSwap( ( 42, "wow") ) ) print( tupleSwap( ("🧩", "🎈" ) ) ) } /*: W pierwszym przykładzie typy `A` i `B` były różne. W drugim takie same! Wynika z tego, że **jeżeli jest więcej typów generycznych to mogą być one takie same**. Nie ma przymusu aby były inne! ## Własne Typy Generyczne Do definiowania własnych typów, które są generyczne wykorzystujemy składnię `<Token>` (tyczy się to typów i funkcji/metod). Gdzie `Token` jest dowolnym string-iem po którym się odwołujemy do konkretnego i zawsze tego samego typu. Array używa nazwy `Element`, Optional `Wrapped` etc. Często też można się spotkać z jedno literowymi oznaczeniami `T`, `U` itd. */ run("🧩 custom") { final class Wrapper< Wrapped > { var wrap: [Wrapped] init(wrap: [Wrapped]) { self.wrap = wrap } var random: Wrapped { wrap.randomElement()! } } let numbers = [4, 2, 6, 9] let strings = ["Można", "pić", "bez", "obawień"] let numberWrapper = Wrapper(wrap: numbers) let stringsWrapper = Wrapper(wrap: strings) print( numberWrapper.random, type(of: numberWrapper.random) ) print( stringsWrapper.random, type(of: stringsWrapper.random) ) } /*: Wrapper przechowuje _coś_ typu `Wrapped`. Nie wiemy co to jest. Nie można zawołać na tym żadnej metody czy sprawdzić property. Wiemy tylko tyle _że jest_. Jeżeli byłoby więcej typów generycznych to by były zdefiniowane po przecinku np. `class Wrapper <X,Y,Z>`. W tym przykładzie są trzy typy generyczne. Każdy z nich pozwala wstawić inny konkretny typ np. `Wrapper<Int, String, Float>`. Nie musi tak być, ta sama definicja (X,Y,Z) zadziała dla `Wrapper<Int, Int, Int>`. Jedyne co to mówi to, że jest taka możliwość a nie obowiązek. ## Ograniczanie Generyków Mając typ o którym nic nie wiemy i nic z nim nie możemy zrobić może być plusem a może czasem wiązać ręce. Czasem chcemy pracować z instancją czegoś co ma jakieś właściwości i/lub metody lub konformuje do protokołu. Istnieje składnia, która pozwala na nałożenie dodatkowych ograniczeń co do typu. */ protocol Jumpable {} protocol Singable {} /*: Chcę stworzyć taką klasę, która będzie kontenerem ale tylko dla takich typów, które konformują do `Jumpable` i `Singable`. */ run("👀 generic constraint") { final class Wrapper< Wrapped > where Wrapped: Jumpable, Wrapped: Singable { var wrap: [Wrapped] init(wrap: [Wrapped]) { self.wrap = wrap } var random: Wrapped { wrap.randomElement()! } } struct Jumper : Jumpable {} struct Singer : Singable {} struct JumpingSinger: Jumpable, Singable {} // 👍🏻 let jumpers = [Jumper(), Jumper()] print(type(of: jumpers)) let singers = [Singer(), Singer()] print(type(of: singers)) let artists = [JumpingSinger(), JumpingSinger()] // 💥 Generic class 'Wrapper' requires that 'Jumper' conform to 'Singable' // Wrapper(wrap: jumpers) // 💥 Generic class 'Wrapper' requires that 'Singer' conform to 'Jumpable' // Wrapper(wrap: singers) let wrapper = Wrapper(wrap: artists) let mysteryItem = wrapper.random print( "What is it:", type(of: mysteryItem) ) } /*: Składnię ze słowem kluczowym `where` można zastąpić `Wrapper< Wrapped: Jumpable, Singable >`. Czasem czytelniej jest umieścić ograniczenia za a czasem wewnątrz. # [Generyki w Protokołach / Associated Types](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-ID189) Teraz połączymy świat protokołów i generyków. */ protocol Wrappable { associatedtype WrappedType // aby ograniczyć typ używamy składni ``: Jumpable`` var howManyWrapped: Int { get } mutating func wrap(element: WrappedType) } /*: Słowo kluczowe `associatedtype` występujące w definicji protokołu jest placeholderem na typ. Czyli jest generykiem! Mówimy tym protokołem, że będziemy owijać jakiś konkretny typ `WrappedType`. W czasie definiowania protokołu jeszcze nie wiemy jaki. Ktoś jak będzie do niego konformować będzie musiał to powiedzieć. Reszta jest dość standardowa. Jedno property i jedna metoda. */ class Wrapper< IWrapThisType >: Wrappable { typealias WrappedType = IWrapThisType var wraps: [IWrapThisType] = [] init(wraps: IWrapThisType...) { self.wraps = wraps } var howManyWrapped: Int { wraps.count } func wrap(element: IWrapThisType) { wraps.append(element) } } /*: Linijka `typealias WrappedType = IWrapThisType` mówi dla kompilatora, że tym typem który owijam jest mój generyk. Tu jest troszeczkę gęsto ponieważ sam wrapper posiada typ generyczny. Po prostu przekazujemy go dalej. Jeżeli by go nie miał to dla _zawijacza_ intów można by było napisać np. tak: `typealias WrappedType = Int`. Jednak nie chcemy pisać 500 różnych wersji i dlatego łączymy te dwa światy. */ run("🦆 associated type") { let intsWrapper = Wrapper(wraps: 4) print("intsWrapper jest typu:", type(of: intsWrapper) ) intsWrapper.wrap(element: 2) intsWrapper.howManyWrapped intsWrapper.wraps let intsWrapperFirst = intsWrapper.wraps.first! print("Owijany element to:", intsWrapperFirst, "typu", type(of: intsWrapperFirst) ) __ let stringsWrapper = Wrapper(wraps: "Można") print("stringsWrapper jest typu:", type(of: stringsWrapper) ) stringsWrapper.wrap(element: "pić") stringsWrapper.wrap(element: "bez") stringsWrapper.wrap(element: "obawień") stringsWrapper.howManyWrapped stringsWrapper.wraps let stringsWrapperFirst = stringsWrapper.wraps.first! print("Owijany element to:", stringsWrapperFirst, "typu", type(of: stringsWrapperFirst) ) } /*: Okazuje się, że jeżeli kompilator jest w stanie wydedukować typ to to zrobi. Dzięki czemu nie musimy definiować tego aliasu. Jednak z własnego doświadczenia polecam to zrobić. Nie zawsze to co dostaniemy może być tym czego chcemy (szczególnie gdy framework z którego korzystamy ma wiele generyków). Ewentualnie zawsze można dodać go potem ;) */ protocol Rememberable { associatedtype RememberedType mutating func remember(something: RememberedType) var something: RememberedType? { get } } struct Mnemo< GMO >: Rememberable { var gmos: [GMO] = [] init(_ gmo: GMO) { remember(something: gmo) } mutating func remember(something: GMO) { gmos.append(something) } var something: GMO? { gmos.last } } /*: Tym razem nie napisałem typealiasu aby wskazać jaki jest generyk. Kompilator jest w stanie to wyinferować na podstawie typu metody `remember(something:..)`. Zobaczmy jak to działa... */ run("🐡 nemo") { var intsMnemo = Mnemo(4) intsMnemo.remember(something: 4) intsMnemo.remember(something: 2) intsMnemo.gmos print("intsMnemo ma typ:", type(of: intsMnemo), "i zawiera", intsMnemo.gmos ) __ var stringsMnemo = Mnemo("można") type(of: stringsMnemo) stringsMnemo.remember(something: "pić") stringsMnemo.remember(something: "bez") stringsMnemo.remember(something: "obawień") stringsMnemo.gmos print("stringsMnemo ma typ:", type(of: stringsMnemo), "i zawiera", stringsMnemo.gmos ) } /*: W tym momencie powiedzieliśmy sobie bardzo dużo ale nie wszystko o generykach. Najtrudniej jest zacząć, ale uważaj! Niech to nie będzie wielki młotek, który rozwiązuje każdy problem. Generyki występują często, łatwo je spotkać i są użyteczne. Zacznij powoli od unikania duplikacji w kodzie. Potem dorzuć jeszcze ograniczenia (generics constraints) aby w pełni wykorzystać ich moc. */ print("🦄") //:[ToC](00-00_toc) | [Tips and Tricks](900-00-tips_and_tricks) | [Previous](@previous) | [Next](@next)
true
36d49c7694b5682b06a7b39010388e01e56fb6de
Swift
taosiyu/RainSQLiteDB
/TSYCatogorysBytaosiyu/imageUpload/ImageUploadManager.swift
UTF-8
1,288
2.625
3
[]
no_license
// // ImageUploadManager.swift // TSYCatogorysBytaosiyu // // Created by ncm on 2017/3/13. // Copyright © 2017年 ncm. All rights reserved. // import UIKit class ImageUploadManager: NSObject { lazy var queue = OperationQueue() lazy var operationCache = [String:ImageUploadOperation]() static func sharedManager()->ImageUploadManager{ struct share { static let manager = ImageUploadManager() } return share.manager } //全局管理 func uploadWithURLString(urlString:String,index:Int,success:@escaping ((Int)->())){ if self.operationCache[urlString] != nil { return } //上传图片 let op = ImageUploadOperation.uploaderOperationWithURLString(index: index, urlString: urlString) { (num) in success(index) self.operationCache.removeValue(forKey: urlString) } self.queue.addOperation(op) self.operationCache[urlString] = op } func cancelOperation(urlString:String){ if urlString=="" { return; } self.operationCache[urlString]?.cancel() self.operationCache.removeValue(forKey: urlString) } }
true
ba8e5ec1767516ad3a6731d46b506fec36d8e0cf
Swift
yeyuxx/Wisnuc-iOS-Swift
/Wisnuc-iOS-Swift/Extension/PHAssetExtension.swift
UTF-8
11,303
2.53125
3
[]
no_license
// // PHAssetExtension.swift // Wisnuc-iOS-Swift // // Created by wisnuc-imac on 2018/7/6. // Copyright © 2018年 wisnuc-imac. All rights reserved. // import Foundation import Photos extension PHAsset{ class func latestAsset() -> PHAsset? { // 获取所有资源的集合,并按资源的创建时间排序 let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let assetsFetchResults = PHAsset.fetchAssets(with: options) return assetsFetchResults.firstObject } class func latestVideoAsset() -> PHAsset? { // 获取所有资源的集合,并按资源的创建时间排序 let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let assetsFetchResults = PHAsset.fetchAssets(with: .video, options: options) return assetsFetchResults.firstObject } func getWSAssetType() -> WSAssetType{ return self.isGif() ? WSAssetType.GIF : self.isLivePhoto() ? WSAssetType.LivePhoto : self.isVideo() ? WSAssetType.Video : self.isAudio() ? WSAssetType.Audio : self.isImage() ? WSAssetType.Image : WSAssetType.Unknown } func getDurationString() -> String? { if self.mediaType != PHAssetMediaType.video {return nil} let duration:Int64 = Int64(round(self.duration)) if duration < 60{ return String.init(format: "00:%02ld", duration) }else if duration < 3600 { return String.init(format: "%02ld:%02ld", duration / 60, duration % 60) } let h:Int64 = duration / 3600; let m:Int64 = (duration % 3600) / 60 let s:Int64 = duration % 60 return String.init(format: "%02ld:%02ld:%02ld", h, m,s) } func isGif() -> Bool{ return (self.mediaType == PHAssetMediaType.image) && (self.value(forKey: "filename") as! NSString).hasSuffix("GIF") } func isLivePhoto()-> Bool{ if #available(iOS 9.1, *) { return (self.mediaType == PHAssetMediaType.image) && (self.mediaSubtypes == PHAssetMediaSubtype.photoLive || self.mediaSubtypes.rawValue == 10) } else { return false } } func isVideo() -> Bool{ return self.mediaType == PHAssetMediaType.video } func isAudio() -> Bool{ return self.mediaType == PHAssetMediaType.audio } func isImage() -> Bool{ return (self.mediaType == PHAssetMediaType.image) && !self.isGif() && !self.isLivePhoto() } func isLocal() -> Bool{ let option = PHImageRequestOptions.init() option.isNetworkAccessAllowed = false option.isSynchronous = true var isInLocalAblum = true PHCachingImageManager.default().requestImageData(for: self, options: option) { (imageData, dataUTI, orientation, info) in isInLocalAblum = imageData != nil ? true : false } return isInLocalAblum; } func getName() -> String? { let name = (PHAssetResource.assetResources(for:self ))[0].originalFilename return name } func getSizeString() -> String? { let option = PHImageRequestOptions.init() option.isNetworkAccessAllowed = false option.isSynchronous = true var size = "" PHImageManager.default().requestImageData(for: self, options: option, resultHandler: { imageData, dataUTI, orientation, info in // var imageSize = Float((imageData?.count ?? 0)) //convert to Megabytes // imageSize = imageSize / (1024 * 1024.0) size = sizeString(Int64(imageData?.count ?? 0)) }) return size } func getAssetPath() -> URL? { let option = PHImageRequestOptions.init() option.isNetworkAccessAllowed = true option.isSynchronous = true var path:URL? if self.mediaType == .video{ let videoOptions = PHVideoRequestOptions.init() videoOptions.version = PHVideoRequestOptionsVersion.current videoOptions.deliveryMode = PHVideoRequestOptionsDeliveryMode.automatic PHImageManager.default().requestAVAsset(forVideo: self, options: nil) { (avurlAsset, audioMix, dict) in if let newObj = avurlAsset as? AVURLAsset{ path = newObj.url print(path as Any) } } }else if self.mediaType == .image{ PHImageManager.default().requestImageData(for: self, options: option, resultHandler: { imageData, dataUTI, orientation, info in path = info!["PHImageFileURLKey"] as? URL }) } return path } // : "PHImageFileURLKey" // - value : file:///var/mobile/Media/DCIM/104APPLE/IMG_4887.PNG func getTmpPath() -> String { let mgr = FileManager.default let tmp = JY_TMP_Folder if !(mgr.fileExists(atPath: tmp!)){ do { try mgr.createDirectory(atPath: tmp!, withIntermediateDirectories: true, attributes: nil) } catch { } } return tmp! } func getSha256(callback:@escaping (_ error:Error?, _ sha256:String?)->()) ->PHImageRequestID{ return self.getFile(callBack: { (requestError, filePath) in if requestError != nil { return callback(requestError, nil) } do { let beforeDate = try (FileManager.default.attributesOfItem(atPath: filePath!))[FileAttributeKey.creationDate] as! Date let hashStr = FileHash.sha256HashOfFile(atPath: filePath!) do { let afterDate = try (FileManager.default.attributesOfItem(atPath: filePath!))[FileAttributeKey.creationDate] as! Date if beforeDate != afterDate { return callback(BaseError(localizedDescription:ErrorLocalizedDescription.Asset.CreateTimeMismatch , code: ErrorCode.Asset.CreateTimeMismatch), nil) }else{ if hashStr == nil || hashStr?.count == 0{ return callback(BaseError(localizedDescription: ErrorLocalizedDescription.Asset.HashError, code: ErrorCode.Asset.HashError), nil) } do { try FileManager.default.removeItem(atPath: filePath!) } catch { return callback(error, nil); } return callback(nil, hashStr) } } catch { return callback(error, nil); } } catch { return callback(error, nil); } }) } func getFile(callBack:@escaping (_ error:Error?, _ filePath:String?)->()) -> PHImageRequestID { let fileName = "tmp_\(Date.init().timeIntervalSince1970)_\(UIDevice.current.identifierForVendor!.uuidString)" var filePath = self.getTmpPath().appendingPathComponent(fileName) //TODO: do something for livephoto if(!self.isVideo()) { return PHPhotoLibrary.requestHighImageDataSync(for: self, completion: { (error, imageData, info) in if(imageData != nil) { if( UIDevice.current.systemVersion.floatValue < 9.0 && info!["PHImageFileURLKey"] != nil){ filePath = self.getTmpPath().appendingPathComponent("PHImageFileURLKey").lastPathComponent } do { try imageData?.write(to: URL(fileURLWithPath: filePath), options: .atomic) } catch { print(error) } return callBack(nil, filePath) }else{ return callBack(error, nil); } }) } else { // video // // less then iOS9 if(UIDevice.current.systemVersion.floatValue < 9.0) { let opt = PHVideoRequestOptions.init() opt.isNetworkAccessAllowed = true// TODO ?? opt.deliveryMode = PHVideoRequestOptionsDeliveryMode.highQualityFormat return PHImageManager.default().requestExportSession(forVideo: self, options: opt, exportPreset: AVAssetExportPresetHighestQuality, resultHandler: { (exportSession, info) in if exportSession == nil{ return callBack(BaseError(localizedDescription: ErrorLocalizedDescription.Asset.AssetNotFound, code:ErrorCode.Asset.AssetNotFound), nil) }else{ //输出URL exportSession?.outputURL = URL.init(fileURLWithPath: filePath) //优化网络 exportSession?.shouldOptimizeForNetworkUse = true // //转换后的格式 // exportSession.outputFileType = AVFileTypeMPEG4; //异步导出 exportSession?.exportAsynchronously { if exportSession?.error != nil { return callBack(exportSession!.error, nil); } if(exportSession?.status == AVAssetExportSessionStatus.failed) { return callBack(BaseError(localizedDescription: ErrorLocalizedDescription.Asset.AVAssetExportSessionStatusFailed, code:ErrorCode.Asset.AVAssetExportSessionStatusFailed), nil) } if(exportSession?.status == AVAssetExportSessionStatus.cancelled) { return callBack(BaseError(localizedDescription: ErrorLocalizedDescription.Asset.AVAssetExportSessionStatusCancelled, code:ErrorCode.Asset.AVAssetExportSessionStatusCancelled), nil) } // 如果导出的状态为完成 if (exportSession?.status == AVAssetExportSessionStatus.completed) { // [self saveVideo:[NSURL fileURLWithPath:path]]; // prin("压缩完毕,压缩后大小 %f MB",[self fileSize:[NSURL fileURLWithPath:filePath]]); return callBack(nil, filePath) }else{ // NSLog("当前压缩进度:%f",exportSession.progress); } } } }) // return false }else{ PHPhotoLibrary.requestVideoPath(from: self, filePath: filePath) { (error, filePath) in if error != nil { return callBack(error, nil) } return callBack(nil, filePath) } return 0 } } } }
true
e2776aabd8feed2291f935408e9b0bc5885358e1
Swift
AnanomousCat/NumericAnnex
/Tests/NumericAnnexTests/RootExtractionTests.swift
UTF-8
2,434
2.71875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import XCTest @testable import NumericAnnex class RootExtractionTests : XCTestCase { func testSqrt() { XCTAssertEqual(Int.sqrt(0), 0) XCTAssertEqual(Int.sqrt(25), 5) XCTAssertEqual(Int.sqrt(27), 5) XCTAssertEqual(Int.sqrt(256), 16) XCTAssertEqual(Int.sqrt(512), 22) XCTAssertEqual(Int.sqrt(1 << 32) * .sqrt(1 << 32), 1 << 32) XCTAssertEqual(Int.sqrt(1 << 48) * .sqrt(1 << 48), 1 << 48) XCTAssertEqual(Int.sqrt(1 << 50) * .sqrt(1 << 50), 1 << 50) XCTAssertEqual(Int.sqrt(1 << 60) * .sqrt(1 << 60), 1 << 60) XCTAssertEqual(Int.sqrt(1 << 62) * .sqrt(1 << 62), 1 << 62) XCTAssertLessThanOrEqual(Int.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int8.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int16.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int32.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(Int64.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt8.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt16.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt32.sqrt(.max) * .sqrt(.max), .max) XCTAssertLessThanOrEqual(UInt64.sqrt(.max) * .sqrt(.max), .max) } func testCbrt() { XCTAssertEqual(UInt.cbrt(0), 0) XCTAssertEqual(UInt.cbrt(25), 2) XCTAssertEqual(UInt.cbrt(27), 3) XCTAssertEqual(UInt.cbrt(256), 6) XCTAssertEqual(UInt.cbrt(512), 8) XCTAssertLessThanOrEqual(UInt.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt8.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt16.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt32.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(UInt64.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertEqual(Int.cbrt(-27), -3) XCTAssertLessThanOrEqual(Int.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int8.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int16.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int32.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) XCTAssertLessThanOrEqual(Int64.cbrt(.max) * .cbrt(.max) * .cbrt(.max), .max) } static var allTests = [ ("testSqrt", testSqrt), ("testCbrt", testCbrt), ] }
true
5cd91ffb40c9fa4c45ffe086f77105c0a8b3b578
Swift
AryanShrivastava-11/managED
/managED/View/HeaderView.swift
UTF-8
1,045
2.765625
3
[]
no_license
// // HeaderView.swift // managED // // Created by Aryan Shrivastava on 22/07/21. // import SwiftUI struct HeaderView: View { var body: some View { VStack(alignment: .leading, spacing: 10){ Text("New Bakery Town") .font(.title) .fontWeight(.bold) Text("Veg . NonVeg . Chinese") .font(.caption) HStack(spacing: 8){ Image(systemName: "clock") .font(.caption) Text("Delivered in 10 mins") .font(.caption) Text("4.91") .font(.caption) Image(systemName: "star.fill") .font(.caption) } .frame(maxWidth: .infinity, alignment: .leading) } .padding(.horizontal) .frame(height: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/) .background(Color.white) } } struct HeaderView_Previews: PreviewProvider { static var previews: some View { Home() } }
true
98d2d82c0bf6546dfffa88ac0c523afce45e1e6e
Swift
BobDeKort/DocumentManager
/DocumentManager/ImagesTableViewCell.swift
UTF-8
814
2.53125
3
[]
no_license
// // ImagesTableViewCell.swift // DocumentManager // // Created by Bob De Kort on 2/5/18. // Copyright © 2018 Bob De Kort. All rights reserved. // import UIKit class ImagesTableViewCell: UITableViewCell { var imageurl: URL? { didSet{ if let url = imageurl { let data = try! Data(contentsOf: url) let image = UIImage(data: data) self.mainImageView.image = image } } } @IBOutlet weak var mainImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
true
257662122b46c31cdd3850ce09685bb12f3da193
Swift
tagmoment/IOS
/TagMoment/TagMoment/Utils/InAppPurchaseRepo.swift
UTF-8
1,108
2.65625
3
[]
no_license
// // InAppServerRepo.swift // TagMoment // // Created by Tomer Hershkowitz on 05/11/2015. // Copyright © 2015 TagMoment. All rights reserved. // import UIKit let PurchasedItemsKey = "PurchasedItemsKey" class InAppPurchaseRepo: NSObject { class func addProductId(productId : String) { var savedObject : [String]? if let productIds = getProductsIds() { savedObject = productIds } else { savedObject = [String]() } savedObject?.append(productId) NSUserDefaults.standardUserDefaults().setObject(savedObject, forKey: PurchasedItemsKey) NSUserDefaults.standardUserDefaults().synchronize() } class func getProductsIds() -> [String]? { if let productsIds = NSUserDefaults.standardUserDefaults().objectForKey(PurchasedItemsKey) { return productsIds as? [String] } return nil } class func isProductBought(productId : String) -> Bool { guard let productIds = getProductsIds() else { return false } return productIds.contains(productId) } class func clear() { NSUserDefaults.standardUserDefaults().removeObjectForKey(PurchasedItemsKey) } }
true
0bf93ae7e3e729b552c418a84abe7d17f4faf339
Swift
alemak1/ZombiesAtLarge
/Zombies At Large/GameScene.swift
UTF-8
7,434
2.546875
3
[]
no_license
// // GameScene.swift // Zombies At Large // // Created by Aleksander Makedonski on 9/1/17. // Copyright © 2017 Aleksander Makedonski. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { var player: Player! /** **/ var overlayNode: SKNode! /** Control buttons **/ var controlButton: SKSpriteNode! /** var leftButton: SKSpriteNode! var rightButton: SKSpriteNode! var upButton: SKSpriteNode! var downButton: SKSpriteNode! **/ private var buttonsAreLoaded: Bool = false var bgNode: SKAudioNode! override func didMove(to view: SKView) { self.backgroundColor = SKColor.cyan self.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.overlayNode = SKNode() self.overlayNode.position = CGPoint(x: 0.00, y: 0.00) addChild(overlayNode) player = Player(playerType: .hitman1, scale: 1.50) player.position = CGPoint(x: 0.00, y: 0.00) self.addChild(player) let xPosControls = UIScreen.main.bounds.width*0.3 let yPosControls = -UIScreen.main.bounds.height*0.3 loadControls(atPosition: CGPoint(x: xPosControls, y: yPosControls)) } func touchDown(atPoint pos : CGPoint) { } func touchMoved(toPoint pos : CGPoint) { } func touchUp(atPoint pos : CGPoint) { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } print("You touched the screen") let overlayNodeLocation = touch.location(in: overlayNode) print("Screen touched at position x: \(overlayNodeLocation.x), y: \(overlayNodeLocation.y)") if buttonsAreLoaded{ print("Buttons have been loaded already...") if controlButton.contains(overlayNodeLocation){ print("You touched the control button...") } for node in self.overlayNode.nodes(at: overlayNodeLocation){ if node.name == "ControlButton", let node = node as? SKSpriteNode{ print("Adjusting player rotation...") let controlPos = touch.location(in: node) var zRotation: CGFloat = 0.00 if(controlPos.x > 0){ zRotation = (controlPos.y > 0) ? atan(controlPos.y/controlPos.x) : (2*CGFloat.pi + (atan(controlPos.y/controlPos.x))) } else { zRotation = (controlPos.y > 0) ? (CGFloat.pi + atan(controlPos.y/controlPos.x)) : (atan(controlPos.y/controlPos.x) + CGFloat.pi) } print("The zRotation is: \(zRotation)") if(zRotation <= CGFloat.pi*2){ player.compassDirection = CompassDirection(zRotation: zRotation) player.applyMovementImpulse(withMagnitudeOf: 1.0) } } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { } override func update(_ currentTime: TimeInterval) { // Called before each frame is rendered } func loadControls(atPosition position: CGPoint){ /** Load the control set **/ guard let user_interface = SKScene(fileNamed: "user_interface") else { fatalError("Error: User Interface SKSCene file could not be found or failed to load") } guard let controlButton = user_interface.childNode(withName: "RoundControl_flatDark")?.childNode(withName: "ControlButton") as? SKSpriteNode else { fatalError("Error: Control Buttons from user_interface SKScene file either could not be found or failed to load") } self.controlButton = controlButton controlButton.anchorPoint = CGPoint(x: 0.5, y: 0.5) controlButton.position = position controlButton.move(toParent: overlayNode) buttonsAreLoaded = true } } /** guard let controlSet = user_interface.childNode(withName: "ControlSet_flatDark") else { fatalError("Error: Control Buttons from user_interface SKScene file either could not be found or failed to load") } controlSet.position = position controlSet.move(toParent: overlayNode) /** Load the control buttons **/ guard let leftButton = controlSet.childNode(withName: "left") as? SKSpriteNode, let rightButton = controlSet.childNode(withName: "right") as? SKSpriteNode, let upButton = controlSet.childNode(withName: "up") as? SKSpriteNode, let downButton = controlSet.childNode(withName: "down") as? SKSpriteNode else { fatalError("Error: One of the control buttons either could not be found or failed to load") } self.leftButton = leftButton self.rightButton = rightButton self.upButton = upButton self.downButton = downButton buttonsAreLoaded = true print("buttons successfully loaded!") **/ /** func addSwipeGestureRecognizers(){ var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeRight.direction = .right self.view?.addGestureRecognizer(swipeRight) var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeLeft.direction = .left self.view?.addGestureRecognizer(swipeLeft) var swipeDown = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeLeft.direction = .down self.view?.addGestureRecognizer(swipeDown) var swipeUp = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeLeft.direction = .up self.view?.addGestureRecognizer(swipeUp) } func respondToSwipeGesture(gesture: UIGestureRecognizer){ if let swipeGesture = gesture as? UISwipeGestureRecognizer{ switch swipeGesture.direction{ case UISwipeGestureRecognizerDirection.right: break case UISwipeGestureRecognizerDirection.left: break case UISwipeGestureRecognizerDirection.down: break case UISwipeGestureRecognizerDirection.up: break default: break; } } **/
true
9df4da68aefca5c709f894f7d29ffbd8495ae562
Swift
Brayden-Paley/Winnipeg-Specials
/WinnipegSpecials/Models/Category.swift
UTF-8
576
2.953125
3
[]
no_license
// // Category.swift // WinnipegSpecials // // Created by Brayden Paley on 2021-01-26. // import Foundation struct Category: Identifiable { var id = UUID() var name: String var restaurants: [Restaurant] var imageName: String { return name } } var categoryList = [ Category(name: "Drinks", restaurants: drinkList), Category(name: "Mexican", restaurants: mexicanList), Category(name: "Pizza", restaurants: pizzaList), Category(name: "Pasta",restaurants: pastaList), Category(name: "Subs & Sandwiches", restaurants: subAndSandwichList) ]
true
37c05325785b4d0d457ab7c0694cd24bf2185771
Swift
iq3addLi/swift-vapor-layered-realworld-example-app
/Sources/Domain/Model/JWT/VerifiedUser.swift
UTF-8
2,524
2.8125
3
[ "MIT" ]
permissive
// // AuthedUser.swift // Domain // // Created by iq3AddLi on 2019/10/07. // /// Authenticated user information. /// /// APIs that require the logged-in user's own information to complete the process automatically query the user information through Middleware and relay the information to the controller. /// @see AuthenticateThenSearchUserMiddleware for detail. /// ### Note /// User is a struct and has no id. This class was prepared because I wanted to use it without changing the swagger definition. public final class VerifiedUser { // MARK: Properties /// Same as `User`s id. public var id: Int /// Same as `User`s email. public var email: String /// JWT used for authentication. public var token: String /// Same as `User`s username. public var username: String /// Same as `User`s bio. public var bio: String /// Same as `User`s image. public var image: String // MARK: Initalizer /// Default initalizer. /// - Parameters: /// - id: `User`s Id. /// - email: `User`s email. /// - token: Verified JWT. /// - username: `User`s username. /// - bio: `User`s bio. /// - image: `User`s image. public init(id: Int = 0, email: String = "", token: String = "", username: String = "", bio: String = "", image: String = "") { self.id = id self.email = email self.token = token self.username = username self.bio = bio self.image = image } } // MARK: Export to User extension VerifiedUser { /// Export to `User`. public var user: User { return User(email: email, token: token, username: username, bio: bio, image: image) } } import Vapor // MARK: Storageable extension VerifiedUser { public struct Key: StorageKey{ public typealias Value = VerifiedUser } } // MARK: Implementation as ServiceType /// Implementation as ServiceType. /// /// ### Extras /// When you want to relay a variable from Middleware to Request, you cannot make it a struct. To create a copy. /// Do not try to do the same with Service. To continue using the memory address registered with register(). //extension VerifiedUser: ServiceType { // // /// See `ServiceType`. // /// - throws: // /// Conforms to protocol. It does not happen logically. // /// - returns: // /// Instance with no value. // public static func makeService(for container: Container) throws -> Self { // return .init() // } //}
true
4401173980ae447a62c851eff48e69908e519c0b
Swift
latifatcii/News
/News/Persistence/PersistenceError.swift
UTF-8
344
2.734375
3
[]
no_license
// // PersistenceError.swift // News // // Created by Latif Atci on 1/28/21. // import Foundation enum PersistanceError: String, Error { case savingError = "Data couldn't be saved" case removingError = "Data couldn't be removed" case fetchingError = "Data couldn't be fetched" case checkingError = "Data couldn't be checked" }
true
f905a26036293e62ce481ddf2577d526b93cf814
Swift
marcocapano/Editor
/Editor/Controllers/ShapesViewController.swift
UTF-8
4,161
3.234375
3
[]
no_license
import UIKit class ShapesViewController: UIViewController { typealias ShapeInfo = (view: UIImageView, type: Shape) ///Keeps track of added shapes var shapes = [ShapeInfo]() ///Keeps track of consecutive positions of a shape, so that undo is possible even after multiple draggings var consecutivePositions = [UIView: [CGPoint]]() override func viewDidLoad() { view.backgroundColor = .white } /// Adds a shape to the editor and registers the related undo operation. /// /// - Parameter shape: The shape to be added func add(_ shape: ShapeInfo) { view.addSubview(shape.view) shapes.append(shape) shape.view.frame.size = CGSize(width: 44, height: 44) shape.view.center = view.center shape.view.isUserInteractionEnabled = true let draggingRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handle(_:))) shape.view.addGestureRecognizer(draggingRecognizer) //Register the undo operation, which should remove the added shape undoManager?.registerUndo(withTarget: self, handler: { [weak self] (editor) in self?.remove(shape) }) let deleteRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(promptDeletion(_:))) shape.view.addGestureRecognizer(deleteRecognizer) } /// Removes a shape from the editor. /// /// - Parameter shape: The shape to be removed. func remove(_ shape: ShapeInfo?) { shapes.removeAll(where: { $0.view === shape?.view }) shape?.view.removeFromSuperview() } ///Prompts the user about deleting the long-pressed shape. @objc private func promptDeletion(_ recognizer: UILongPressGestureRecognizer) { guard let tappedView = recognizer.view else { return } let alert = UIAlertController(title: "Do you want do delete this shape?", message: "The action can be undone later", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { [weak self] _ in guard let self = self, let shape = self.shapes.first(where: { $0.view === tappedView }) else { return } //Remove and register the undo operation self.remove(shape) self.undoManager?.registerUndo(withTarget: self, handler: { (editor) in editor.add(shape) }) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } ///Handles the dragging of shapes. When the gesture begins it stores the original position ///to make undo possible. Then it moves the shape around and registers an undo operation ///when dragging ends. @objc func handle(_ gesture: UIPanGestureRecognizer) { guard let draggedView = gesture.view else { return } switch gesture.state { case .began: if consecutivePositions[draggedView] == nil { consecutivePositions[draggedView] = [draggedView.center] } else { consecutivePositions[draggedView]?.append(draggedView.center) } case .changed: //Making sure the view is visible view.bringSubviewToFront(draggedView) //Move the view accordingly let translation = gesture.translation(in: view) draggedView.center = CGPoint(x: draggedView.center.x + translation.x, y: draggedView.center.y + translation.y) gesture.setTranslation(CGPoint.zero, in: view) case .ended: guard var positions = consecutivePositions[draggedView] else { return } let lastPosition = positions.removeLast() //Register undo operation to bring the shape back into position undoManager?.registerUndo(withTarget: self, handler: { (editor) in draggedView.center = lastPosition }) default: break } } }
true
95783e98dba85f28f19b2042874fd724f9dceed6
Swift
hiralee/FallingWords
/FallingWordsApp/FallingWordsApp/Network/HTTPClient.swift
UTF-8
1,016
3.515625
4
[]
no_license
import Foundation public enum HTTPClientResult { case success(Data, HTTPURLResponse) case failure(Error) } public protocol HTTPClientProtocol { func get(from url: URL, completion: @escaping (HTTPClientResult) -> Void) } public class HTTPClient: HTTPClientProtocol { private let session: URLSession private struct UnexpectedValuesRepresentation: Error {} @objc public init(session: URLSession = .shared) { self.session = session } public func get(from url: URL, completion: @escaping (HTTPClientResult) -> Void) { session.dataTask(with: url) { (data, response, error) in if let error = error { completion(.failure(error)) } else if let data = data, let response = response as? HTTPURLResponse { completion(.success(data, response)) } else { completion(.failure(UnexpectedValuesRepresentation())) } }.resume() } }
true
424f5a57670e0427ea80c9ba9f7a123600e3520b
Swift
Kysiek/MemeMe
/MemeMe/PersistencyManager.swift
UTF-8
1,246
2.984375
3
[]
no_license
// // PersistencyManager.swift // MemeMe // // Created by Krzysztof Maciążek on 22/03/16. // Copyright © 2016 kysieksoftware. All rights reserved. // import Foundation import UIKit class PersistencyManager { static let FONT_KEY = "fontKey" private var memes: [Meme]! init() { memes = [Meme]() } func saveMeme(meme: Meme) { if !checkMemeAlreadyContained(meme) { memes.append(meme) } } func deleteMeme(memeToDelete: Meme) { for i in 0..<memes.count { if memes[i] === memeToDelete { memes.removeAtIndex(i) return } } } func loadSavedMemes() -> [Meme] { return memes } func loadFont() -> String? { let variable = NSUserDefaults().objectForKey(PersistencyManager.FONT_KEY) as! String? return variable } func saveFont(font: String) { NSUserDefaults().setObject(font, forKey: PersistencyManager.FONT_KEY) } private func checkMemeAlreadyContained(meme: Meme) -> Bool { for i in 0..<memes.count { if memes[i] === meme { return true } } return false } }
true