text
stringlengths
8
1.32M
// // UpdateTimeEntryInteractorProtocol.swift // MyTime // // Created by Anibal Ferreira on 23/04/2017. // Copyright © 2017 Anibal Ferreira. All rights reserved. // public protocol UpdateTimeEntryInteractorProtocol { weak var delegate: UpdateTimeEntryInteractorDelegate? { get set } func doUpdateTimeEntry(timeEntry: TimeEntry) }
import Foundation import XcodeProj import XCTest class PBXSourcesBuildPhaseTests: XCTestCase { func test_itHasTheCorrectIsa() { XCTAssertEqual(PBXSourcesBuildPhase.isa, "PBXSourcesBuildPhase") } }
// // ContentView.swift // ArtOfStateObserving // // Created by Nestor Hernandez on 12/03/22. // import SwiftUI struct Item { var title: String var color: Color //var id: Int mutating func updateTitle(_ title: String){ self.title = title } } class Items: ObservableObject { @Published var item1: Item var item2: Item var item3: Item init(item1:Item, item2:Item, item3: Item) { self.item1 = item1 self.item2 = item2 self.item3 = item3 } } struct ContentView: View { // @State var item1 = Item(title: "one", color: Color.red, id: 1) // @State var item2 = Item(title: "two", color: Color.green, id: 2) // @State var item3 = Item(title: "three", color: Color.blue, id: 3) // @ObservedObject var item1 = Item(title: "one", color: Color.red, id: 1) // @ObservedObject var item2 = Item(title: "two", color: Color.green, id: 2) // @ObservedObject var item3 = Item(title: "three", color: Color.blue, id: 3) @ObservedObject var items:Items = Items(item1: Item(title: "one", color: Color.red), item2: Item(title: "two", color: Color.green), item3: Item(title: "three", color: Color.blue)) var body: some View { VStack(){ Text("Item List") .padding() HStack{ Text("\(items.item1.title)") Rectangle().fill(items.item1.color) //Text("\(items.item1.id)") } HStack{ Text("\(items.item2.title)") Rectangle().fill(items.item2.color) //Text("\(items.item2.id)") } HStack{ Text("\(items.item3.title)") Rectangle().fill(items.item3.color) //Text("\(items.item3.id)") } }.onAppear{ DispatchQueue.main.asyncAfter(deadline: .now() + 2) { // With a Class (reference type) //self.item1 = Item(title: "one+", color: Color.red, id: 1) //self.items.item2 = Item(title: "one+", color: Color.red, id: 1) self.items.item1.color = Color.orange } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // mapView.swift // West Campus // // Created by jared weinstein on 11/13/15. // Copyright © 2015 ENAS118. All rights reserved. // import Foundation import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! var projectsToBeDisplayed = [Project]() //This is the array containing a list of all the projects we want to display pins for. Use projectsToBeDisplayed[i].gpslatitude / longitude override func viewDidLoad() { super.viewDidLoad() map.delegate = self setUpMap() } func setUpMap(){ map.mapType = MKMapType.Satellite map.zoomEnabled = true map.scrollEnabled = true map.showsUserLocation = true let initialLocation = CLLocationCoordinate2D(latitude: 41.251938,longitude: -72.994110) map.setCenterCoordinate(initialLocation, animated: true) let regionRadius: CLLocationDistance = 1000 func centerMapOnLocation(location: CLLocationCoordinate2D) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location, regionRadius * 2.0, regionRadius * 2.0) map.setRegion(coordinateRegion, animated: true) } centerMapOnLocation(initialLocation) addOverlay() } func addOverlay(){ var borderPoints = [CLLocationCoordinate2D]() //Add or remove from this list to change the displayed border borderPoints.append(CLLocationCoordinate2DMake(41.253511, -72.995858))//update this to be the border of our project borderPoints.append(CLLocationCoordinate2DMake(41.253973, -72.995858)) borderPoints.append(CLLocationCoordinate2DMake(41.254014, -72.995654)) borderPoints.append(CLLocationCoordinate2DMake(41.254136, -72.995460)) borderPoints.append(CLLocationCoordinate2DMake(41.254337, -72.995460)) borderPoints.append(CLLocationCoordinate2DMake(41.254410, -72.995298)) borderPoints.append(CLLocationCoordinate2DMake(41.254469, -72.995104)) borderPoints.append(CLLocationCoordinate2DMake(41.254396, -72.994856)) borderPoints.append(CLLocationCoordinate2DMake(41.254291, -72.994640)) //borderPoints.append(CLLocationCoordinate2DMake(41.254154, -72.994478)) //borderPoints.append(CLLocationCoordinate2DMake(41.254089, -72.994208)) borderPoints.append(CLLocationCoordinate2DMake(41.254462, -72.992643)) borderPoints.append(CLLocationCoordinate2DMake(41.255055, -72.992016)) borderPoints.append(CLLocationCoordinate2DMake(41.255430, -72.991248)) borderPoints.append(CLLocationCoordinate2DMake(41.255515, -72.990804)) borderPoints.append(CLLocationCoordinate2DMake(41.255186, -72.990421)) borderPoints.append(CLLocationCoordinate2DMake(41.254727, -72.991137)) borderPoints.append(CLLocationCoordinate2DMake(41.254631, -72.991370)) borderPoints.append(CLLocationCoordinate2DMake(41.254331, -72.991190)) borderPoints.append(CLLocationCoordinate2DMake(41.253541, -72.992092)) borderPoints.append(CLLocationCoordinate2DMake(41.253250, -72.991971)) borderPoints.append(CLLocationCoordinate2DMake(41.253395, -72.991580)) borderPoints.append(CLLocationCoordinate2DMake(41.253223, -72.991079)) borderPoints.append(CLLocationCoordinate2DMake(41.253059, -72.990815)) borderPoints.append(CLLocationCoordinate2DMake(41.252768, -72.990738)) borderPoints.append(CLLocationCoordinate2DMake(41.250098, -72.994147)) borderPoints.append(CLLocationCoordinate2DMake(41.250819, -72.995286)) borderPoints.append(CLLocationCoordinate2DMake(41.250259, -72.996424)) borderPoints.append(CLLocationCoordinate2DMake(41.250713, -72.998038)) borderPoints.append(CLLocationCoordinate2DMake(41.251562, -72.998182)) borderPoints.append(CLLocationCoordinate2DMake(41.251472, -72.995602)) borderPoints.append(CLLocationCoordinate2DMake(41.252980, -72.995525)) borderPoints.append(CLLocationCoordinate2DMake(41.253511, -72.995858)) let border : MKPolygon! = MKPolygon.init(coordinates: &borderPoints, count: borderPoints.count) border.title = "Border" map.addOverlay(border) //border var pathPoints = [CLLocationCoordinate2D]() //Add or remove from this list to change the displayed border pathPoints.append(CLLocationCoordinate2DMake(41.253459, -72.995824))//bright green pathPoints.append(CLLocationCoordinate2DMake(41.253471, -72.995650)) pathPoints.append(CLLocationCoordinate2DMake(41.253447, -72.995554)) pathPoints.append(CLLocationCoordinate2DMake(41.253416, -72.995455)) pathPoints.append(CLLocationCoordinate2DMake(41.253376, -72.995144)) pathPoints.append(CLLocationCoordinate2DMake(41.253331, -72.994992)) pathPoints.append(CLLocationCoordinate2DMake(41.253241, -72.994955)) pathPoints.append(CLLocationCoordinate2DMake(41.253073, -72.994990)) pathPoints.append(CLLocationCoordinate2DMake(41.253015, -72.995011)) pathPoints.append(CLLocationCoordinate2DMake(41.252991, -72.995167)) pathPoints.append(CLLocationCoordinate2DMake(41.253007, -72.995323)) pathPoints.append(CLLocationCoordinate2DMake(41.253000, -72.995851)) pathPoints.append(CLLocationCoordinate2DMake(41.253459, -72.995824)) var path : MKPolyline = MKPolyline.init(coordinates: &pathPoints, count: pathPoints.count) path.title = "path" map.addOverlay(path) //Add or remove from this list to change the displayed paths pathPoints = [CLLocationCoordinate2D]() pathPoints.append(CLLocationCoordinate2DMake(41.253331, -72.994992)) pathPoints.append(CLLocationCoordinate2DMake(41.253352, -72.994870)) pathPoints.append(CLLocationCoordinate2DMake(41.253367, -72.994742)) pathPoints.append(CLLocationCoordinate2DMake(41.253462, -72.994660)) pathPoints.append(CLLocationCoordinate2DMake(41.253494, -72.994494)) pathPoints.append(CLLocationCoordinate2DMake(41.253559, -72.994359)) pathPoints.append(CLLocationCoordinate2DMake(41.253551, -72.994126)) pathPoints.append(CLLocationCoordinate2DMake(41.253622, -72.993871)) pathPoints.append(CLLocationCoordinate2DMake(41.253682, -72.993723)) pathPoints.append(CLLocationCoordinate2DMake(41.253651, -72.993647)) pathPoints.append(CLLocationCoordinate2DMake(41.253546, -72.993609)) pathPoints.append(CLLocationCoordinate2DMake(41.253469, -72.993514)) pathPoints.append(CLLocationCoordinate2DMake(41.253384, -72.993456)) pathPoints.append(CLLocationCoordinate2DMake(41.253226, -72.993479)) pathPoints.append(CLLocationCoordinate2DMake(41.252928, -72.993645)) pathPoints.append(CLLocationCoordinate2DMake(41.252881, -72.993584)) pathPoints.append(CLLocationCoordinate2DMake(41.252814, -72.993494)) pathPoints.append(CLLocationCoordinate2DMake(41.252714, -72.993436)) pathPoints.append(CLLocationCoordinate2DMake(41.252606, -72.993336)) pathPoints.append(CLLocationCoordinate2DMake(41.252568, -72.993329)) pathPoints.append(CLLocationCoordinate2DMake(41.252486, -72.993316)) pathPoints.append(CLLocationCoordinate2DMake(41.252379, -72.993352)) pathPoints.append(CLLocationCoordinate2DMake(41.252286, -72.993355)) pathPoints.append(CLLocationCoordinate2DMake(41.252307, -72.993447)) pathPoints.append(CLLocationCoordinate2DMake(41.252339, -72.993493)) pathPoints.append(CLLocationCoordinate2DMake(41.252793, -72.993897)) pathPoints.append(CLLocationCoordinate2DMake(41.252825, -72.993949)) pathPoints.append(CLLocationCoordinate2DMake(41.252851, -72.994036)) pathPoints.append(CLLocationCoordinate2DMake(41.252850, -72.994254)) //pathPoints.append(CLLocationCoordinate2DMake(41.252872, -72.994372)) //pathPoints.append(CLLocationCoordinate2DMake(41.252855, -72.994380)) pathPoints.append(CLLocationCoordinate2DMake(41.252840, -72.994353)) pathPoints.append(CLLocationCoordinate2DMake(41.253009, -72.994532)) pathPoints.append(CLLocationCoordinate2DMake(41.253015, -72.995011)) path = MKPolyline.init(coordinates: &pathPoints, count: pathPoints.count) path.title = "path2" map.addOverlay(path) //----------------------------------------------------------------- pathPoints = [CLLocationCoordinate2D]() pathPoints.append(CLLocationCoordinate2DMake(41.253471, -72.995650)) pathPoints.append(CLLocationCoordinate2DMake(41.253585, -72.995683)) pathPoints.append(CLLocationCoordinate2DMake(41.253813, -72.995596)) pathPoints.append(CLLocationCoordinate2DMake(41.253941, -72.995306)) pathPoints.append(CLLocationCoordinate2DMake(41.253965, -72.995176)) pathPoints.append(CLLocationCoordinate2DMake(41.254030, -72.995127)) pathPoints.append(CLLocationCoordinate2DMake(41.254031, -72.995136)) pathPoints.append(CLLocationCoordinate2DMake(41.254106, -72.995103)) pathPoints.append(CLLocationCoordinate2DMake(41.254134, -72.995033)) pathPoints.append(CLLocationCoordinate2DMake(41.254118, -72.994998)) pathPoints.append(CLLocationCoordinate2DMake(41.254158, -72.994853)) pathPoints.append(CLLocationCoordinate2DMake(41.254180, -72.994709)) pathPoints.append(CLLocationCoordinate2DMake(41.254189, -72.994525)) pathPoints.append(CLLocationCoordinate2DMake(41.254223, -72.994377)) path = MKPolyline.init(coordinates: &pathPoints, count: pathPoints.count) path.title = "path3" map.addOverlay(path) //----------------------------------------------------------------- pathPoints = [CLLocationCoordinate2D]() pathPoints.append(CLLocationCoordinate2DMake(41.253110, -72.993536)) pathPoints.append(CLLocationCoordinate2DMake(41.253107, -72.993633)) pathPoints.append(CLLocationCoordinate2DMake(41.253232, -72.993673)) pathPoints.append(CLLocationCoordinate2DMake(41.253290, -72.993743)) pathPoints.append(CLLocationCoordinate2DMake(41.253275, -72.993866)) pathPoints.append(CLLocationCoordinate2DMake(41.253252, -72.993961)) pathPoints.append(CLLocationCoordinate2DMake(41.253182, -72.994092)) pathPoints.append(CLLocationCoordinate2DMake(41.253231, -72.994159)) pathPoints.append(CLLocationCoordinate2DMake(41.253205, -72.994332)) pathPoints.append(CLLocationCoordinate2DMake(41.253225, -72.994464)) pathPoints.append(CLLocationCoordinate2DMake(41.253186, -72.994514)) pathPoints.append(CLLocationCoordinate2DMake(41.253178, -72.994550)) pathPoints.append(CLLocationCoordinate2DMake(41.253199, -72.994626)) pathPoints.append(CLLocationCoordinate2DMake(41.253145, -72.994955)) path = MKPolyline.init(coordinates: &pathPoints, count: pathPoints.count) path.title = "path4" map.addOverlay(path) pathPoints = [CLLocationCoordinate2D]() //----------------------------------------------------------------- pathPoints = [CLLocationCoordinate2D]() pathPoints.append(CLLocationCoordinate2DMake(41.253965, -72.995176)) pathPoints.append(CLLocationCoordinate2DMake(41.253962, -72.995084)) pathPoints.append(CLLocationCoordinate2DMake(41.253896, -72.995046)) /*pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake()) pathPoints.append(CLLocationCoordinate2DMake())*/ path = MKPolyline.init(coordinates: &pathPoints, count: pathPoints.count) path.title = "path5" map.addOverlay(path) pathPoints = [CLLocationCoordinate2D]() //iterate through the projectsToBeDisplayed array list, [i].longitude, latitude for var i = 0; i < projectsToBeDisplayed.count; i++ { let lat = projectsToBeDisplayed[i].gpsLatitude let long = projectsToBeDisplayed[i].gpsLongitude let loc : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat, longitude: long) let annotation = MKPointAnnotation.init() annotation.coordinate = loc annotation.title = projectsToBeDisplayed[i].title //annotation.subtitle = "subtitle" map.addAnnotation(annotation) } } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKPolygon { //These are the settings for our outer border let polygonRender = MKPolygonRenderer(overlay: overlay) polygonRender.strokeColor = UIColor.whiteColor() polygonRender.lineWidth = 1 polygonRender.fillColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2) return polygonRender }else if overlay is MKPolyline{ //These are the settings for our path lines let polylineRender = MKPolylineRenderer(overlay: overlay) polylineRender.strokeColor = UIColor(red:0.00, green: 0.40, blue: 0.00, alpha: 1.0) polylineRender.lineWidth = 2 polylineRender.fillColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) return polylineRender } NSLog("Error: mapView in mapViewController got passed an overlay that wasn't properly handled") let polygonRender = MKPolygonRenderer(overlay: overlay) return polygonRender } //MKAnnotation Customization ------NONE OF THIS IS GETTING CALLED --------------- //This needs to get called when every annotation is rendered but it isn't for some reason func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { NSLog("CALLED VIEWFORANNOTATION") if annotation is MKUserLocation { //return nil so map view draws "blue dot" for standard user location return nil } let reuseId = "myPin" let pinView = map.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView == nil { NSLog("annotation set up") let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin") pinAnnotationView.pinTintColor = UIColor.purpleColor() pinAnnotationView.canShowCallout = true let moreButton = UIButton.init(type: UIButtonType.Custom) as UIButton moreButton.frame.size.width = 44 moreButton.frame.size.height = 44 moreButton.backgroundColor = UIColor.purpleColor() moreButton.setImage(UIImage(named: "home"), forState: .Normal) pinAnnotationView.rightCalloutAccessoryView = moreButton return pinAnnotationView } return nil } //None of these are getting called. Possible issue where the delegate is not set correctly. func mapView(mapView: MKMapView, didAddAnnotationViews views: [MKAnnotationView]) { NSLog("hello") } func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { NSLog("HELLO") } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { NSLog("COOL") } }
// // HybridViewController.swift // AESwiftWorking_Example // // Created by Adam on 2022/9/9. // Copyright © 2022 CocoaPods. All rights reserved. // 原生捕获webview的input的内容 import UIKit import WebKit class HybridViewController: BaseViewController { private var webView: WKWebView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func configEvent() { super.configEvent() } override func configUI() { super.configUI() // 设置webView的配置 let config = WKWebViewConfiguration.init() // 注入名字 config.userContentController.add(self, name: "JSBridge") //创建webView webView = WKWebView.init(frame: self.view.bounds, configuration: config) //导航代理 webView?.navigationDelegate = self //交互代理 webView?.uiDelegate = self //加载网页 let filePath = Bundle.main.path(forResource: "index", ofType: "html") ?? "" //获取代码 let pathURL = URL(fileURLWithPath: filePath) let request = URLRequest.init(url: pathURL) //webView.allowsBackForwardNavigationGestures = true webView?.load(request) view.addSubview(webView!) } } extension HybridViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { //接收到js发送的消息 //判断消息名字 if message.name == "JSBridge" { guard let body = message.body as? [String : AnyObject] else{ return } if body["id"] as! String == "sumit" { let value = body["value"] as! String //弹窗控制器 let alertVC = UIAlertController.init(title: "提示", message: value, preferredStyle: UIAlertController.Style.alert) let canclelBtn = UIAlertAction.init(title: "ok", style: UIAlertAction.Style.cancel, handler: nil) alertVC.addAction(canclelBtn) self.present(alertVC, animated: true, completion: nil) } if body["id"] as! String == "searchKey" { let searchKey = body["value"] as! String print("输入中:\(searchKey)") } } } } extension HybridViewController: WKNavigationDelegate { //网页加载完成 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { //注入监听输入框改变的方法和点击button的方法 //获取js代码存放路径 let filePath = Bundle.main.path(forResource: "bridge", ofType: "js") ?? "" //获取代码 guard var jsString = try? String(contentsOfFile:filePath ) else { // 沒有讀取出來則不執行注入 return } //在bridge.js文件里给输入框赋值是临时的,这里可以替换 jsString = jsString.replacingOccurrences(of: "Placeholder_searchKey", with: "这里可以更换值") //获取到的代码 注入到web webView.evaluateJavaScript(jsString, completionHandler: { _, _ in print("代码注入成功") }) } } extension HybridViewController: WKUIDelegate { }
// Try with and without whole module optimization // RUN: %target-build-swift %S/library.swift %S/main.swift // RUN: %target-build-swift -whole-module-optimization %S/library.swift %S/main.swift // REQUIRES: executable_test // FIXME: Fails on iPhone simulator target due to possible MC-JIT bug // REQUIRES: disabled extension NuclearMeltdown : ErrorProtocol {}
// // SectionHeaderCell.swift // OrgTech // // Created by Maksym Balukhtin on 28.04.2020. // Copyright © 2020 Maksym Balukhtin. All rights reserved. // import UIKit typealias SectionType = (title: String, isAccessoryVisible: Bool) enum SectionHeaderCellEvent { case onAccessoryAction } final class SectionHeaderCell: BuildableTableViewCell<SectionHeaderCellView, SectionType> { var eventHandler: EventHandler<SectionHeaderCellEvent>? override func config(with object: SectionType) { mainView.titleLabel.text = object.title mainView.accessoryButton.isHidden = !object.isAccessoryVisible setupActions() } } private extension SectionHeaderCell { func setupActions() { mainView.accessoryButton.addAction(for: .touchUpInside) { [unowned self] in self.eventHandler?(.onAccessoryAction) } } }
// // ViewController.swift // NewProduct // // Created by Greg MacEachern on 2017-03-10. // Copyright © 2017 Greg MacEachern. All rights reserved. // //CODE FOR MAIN PROFILE import UIKit import Firebase import FirebaseAuth import CoreLocation import Photos class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextFieldDelegate, CLLocationManagerDelegate { @IBOutlet weak var lblName: UILabel! @IBOutlet weak var imgMain: UIImageView! //@IBOutlet weak var Logout: UIButton! @IBOutlet weak var Loader: UIActivityIndicatorView! @IBOutlet var tap: UITapGestureRecognizer! @IBOutlet var longpress: UILongPressGestureRecognizer! @IBOutlet weak var btnSave: UIButton! @IBOutlet var longLabel: UILongPressGestureRecognizer! @IBOutlet weak var tbAbout: UITextField! @IBOutlet weak var tabBar: UITabBarItem! @IBOutlet weak var lblEmail: UILabel! //declarations for about section @IBOutlet weak var lblLoc: UILabel! @IBOutlet weak var lblBirth: UILabel! @IBOutlet weak var lblGend: UILabel! @IBOutlet weak var lblID: UILabel! @IBOutlet weak var btnEdit: UIButton! let NameRef = FIRDatabase.database().reference() let storageRef = FIRStorage.storage().reference() var upload = false var ableToSwitch = false //giving these values of nothing var loc = "" var birth = "" var gend = "" var skills = "" var email:String! var imagePicker = UIImagePickerController() var state = false var artistCreate = false let user = FIRAuth.auth()?.currentUser //I was being lazy and made variables for these references let NameLoad = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("Name") let aboutLoad = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("About") let manager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestWhenInUseAuthorization() lblName.isUserInteractionEnabled = true btnSave.layer.mask?.cornerRadius = 5 //if user is logged out if FIRAuth.auth()?.currentUser?.uid == nil { LogoutSeq() //this removes every saved thing UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!) } //set profile qualities setupProfile() //allow the profile pic to be clicked self.imgMain.isUserInteractionEnabled = true } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations[0] NameRef.child("users").child(self.user!.uid).child("location(LL)").setValue("\(location.coordinate.latitude),\(location.coordinate.longitude)") // print(manager.location!) if manager.location != nil { manager.stopUpdatingLocation() } } //when save button is clicked @IBAction func SaveChanges(_ sender: Any) { self.manager.startUpdatingLocation() // saveChange() print(artistCreate) //"upload" is if the image has been changed. If not (false), then the image isn't reuploaded which saves data, memory and database storage if upload == true{ saveChange() upload = false } else{ self.NameRef.child("users").child(self.user!.uid).child("Name").setValue(lblName.text) btnSave.isHidden=true if loc == ""{ } else{ self.NameRef.child("users").child(self.user!.uid).child("Location").setValue(loc) } if birth == ""{ } else{ self.NameRef.child("users").child(self.user!.uid).child("Birthday").setValue(birth) } if gend == ""{ } else{ self.NameRef.child("users").child(self.user!.uid).child("Gender").setValue(gend) } if skills == ""{ } else { self.NameRef.child("users").child(self.user!.uid).child("Skills").setValue(skills) } if artistCreate == true { if skills == ""{ } else { self.NameRef.child("artistProfiles").child(self.user!.uid).child("Skills").setValue(skills) } self.NameRef.child("artistProfiles").child(self.user!.uid).child("Name").setValue(lblName.text) } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //SETTING UP THE PROFILE func setupProfile(){ // self.NameRef.child("artistProfiles").child(self.user!.uid).child("token").observe(.value){ // (snap: FIRDataSnapshot) in if UserDefaults.standard.bool(forKey: "artistCreate") == true { self.artistCreate = true } else { self.artistCreate = false } imgMain.layer.cornerRadius = 4 imgMain.clipsToBounds = true btnSave.layer.cornerRadius = 5 btnSave.clipsToBounds = true self.Loader.startAnimating() //loading image from database into view. Found this online. Not as efficient as I would have liked but it works if UserDefaults.standard.object(forKey: "savedImage") != nil { let imgdata2 = UserDefaults.standard.object(forKey: "savedImage") as! NSData imgMain.image = UIImage(data: imgdata2 as Data) self.Loader.stopAnimating() } else { let uid = FIRAuth.auth()?.currentUser?.uid NameRef.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in if let dict = snapshot.value as? [String: AnyObject] { if let profileImageURL = dict["pic"] as? String { let url = URL(string: profileImageURL) URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in if error != nil{ // print(error!) return } DispatchQueue.main.async { if data == nil { self.Loader.stopAnimating() } else { self.imgMain?.image = UIImage(data: data!) UserDefaults.standard.set(data!, forKey: "savedImage") self.ableToSwitch = true self.Loader.stopAnimating() } } }).resume() } else{ self.Loader.stopAnimating() } } }) self.Loader.stopAnimating() } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Loading all the default value NameLoad.observe(.value){ (snap: FIRDataSnapshot) in self.lblName.text = snap.value as? String } NameRef.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("Location").observe(.value){ (snap: FIRDataSnapshot) in if let temp1 = snap.value as? String{ self.loc = temp1 self.lblLoc.text = "Location: \(temp1)" } } NameRef.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("Email").observe(.value){ (snap: FIRDataSnapshot) in if let temp1 = snap.value as? String{ self.email = temp1 self.lblEmail.text = temp1 } } NameRef.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("Birthday").observe(.value){ (snap: FIRDataSnapshot) in if let temp2 = snap.value as? String{ self.birth = temp2 self.lblBirth.text = "Birthday: \(temp2)" } } NameRef.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("Gender").observe(.value){ (snap: FIRDataSnapshot) in if let temp3 = snap.value as? String{ self.gend = temp3 self.lblGend.text = "Gender: \(temp3)" } } NameRef.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("Skills").observe(.value){ (snap: FIRDataSnapshot) in if let temp4 = snap.value as? String{ self.skills = temp4 self.lblID.text = "Skills: \(temp4)" } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //image picker func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { //btnSave.isHidden = false //Seeting the image equal to the profile picture. If the image was edited (cropped) it will upload that instead var selectedImage:UIImage? if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage { selectedImage = editedImage } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { selectedImage = originalImage } if let selectedImage2 = selectedImage { Loader.startAnimating() imgMain.image = selectedImage2 upload = true saveChange() Loader.stopAnimating() } dismiss(animated: true, completion: nil) } //if persons presses cancel func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //SAVING CHANGES func saveChange(){ Loader.startAnimating() let imageName = NSUUID().uuidString let storedImage = storageRef.child("imgMain").child(imageName) // let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext // let task = Task(context: context) // Link Task & Context // //task.name = taskTextField.text! // // // Save the data to coredata // (UIApplication.shared.delegate as! AppDelegate).saveContext() //also found this online if let uploadData = UIImagePNGRepresentation(self.imgMain.image!) { storedImage.put(uploadData, metadata: nil, completion: { ( metadata, error) in if error != nil { //print(error!) return } storedImage.downloadURL(completion: { (url,error) in if error != nil { //print(error!) return } if let urlText = url?.absoluteString{ self.NameRef.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).updateChildValues(["pic" : urlText], withCompletionBlock: { (error,ref) in if error != nil { // print(error!) return } self.Loader.stopAnimating() self.ableToSwitch = true self.btnSave.isHidden = true let imgData = UIImagePNGRepresentation(self.imgMain.image!)! as NSData UserDefaults.standard.set(imgData, forKey: "savedImage") }) if self.artistCreate == true { self.NameRef.child("artistProfiles").child((FIRAuth.auth()?.currentUser?.uid)!).updateChildValues(["pic" : urlText], withCompletionBlock: { (error,ref) in if error != nil { // print(error!) return } self.Loader.stopAnimating() self.ableToSwitch = true self.btnSave.isHidden = true }) } } }) }) } } //what happens when logout is clicked func LogoutSeq(){ let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let loginVC: UIViewController = storyboard.instantiateViewController(withIdentifier: "login") if UserDefaults.standard.object(forKey: "savedImage") != nil{ UserDefaults.standard.removeObject(forKey: "savedImage") } UserDefaults.standard.removeObject(forKey: "artistOn") self.present(loginVC, animated: true, completion: nil) } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //When user taps profile picture @IBAction func Tapped(_ sender: UITapGestureRecognizer) { //this method opens a little menu at the bottom with the options; View Picture, Photos and Camera let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true picker.sourceType = UIImagePickerControllerSourceType.photoLibrary let myActionSheet = UIAlertController(title: "Profile Picture", message: "Select", preferredStyle: UIAlertControllerStyle.actionSheet) let viewPicture = UIAlertAction(title: "View Picture", style: UIAlertActionStyle.default) { (action) in //Put code for what happens when the button is clicked let imageView = sender.view as! UIImageView let newImageView = UIImageView(image: imageView.image) newImageView.frame = self.view.frame newImageView.backgroundColor = UIColor.black newImageView.contentMode = .scaleAspectFit newImageView.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target:self,action:#selector(self.dismissFullScreenImage)) newImageView.addGestureRecognizer(tap) self.view.addSubview(newImageView) } let photoGallery = UIAlertAction(title: "Photos", style: UIAlertActionStyle.default) { (action) in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum) { //Not sure why i have to set the imagepickers delegate to self. Thats the only way it worked tho self.imagePicker.delegate = self self.imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum self.imagePicker.allowsEditing = true self.state = false self.present(self.imagePicker, animated: true, completion: nil) } } let camera = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default) { (action) in if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { //This was a pain in the ass to get to work. In the in GoogleService-Info.plist you HAVE to add the camera permission (for future projects obvi) self.imagePicker.delegate = self self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera self.imagePicker.allowsEditing = true self.state = false self.present(self.imagePicker, animated: true, completion: nil) } } myActionSheet.addAction(viewPicture) myActionSheet.addAction(photoGallery) myActionSheet.addAction(camera) myActionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)) self.present(myActionSheet, animated: true, completion: nil) } // This func just dismisses the view when the user tappen "View Picture" func dismissFullScreenImage(_sender:UITapGestureRecognizer){ _sender.view?.removeFromSuperview() } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //long press for cover photo (Not being used) @IBAction func LongPress(_ sender: UILongPressGestureRecognizer) { } @IBAction func longPressLabel(_ sender: UILongPressGestureRecognizer) { //When the label with the name stored in it is long pressed, this occurs //Allows me to edit the name in the database. I don't like the look of it but it will suffice for now let alertController = UIAlertController(title: "Edit Name", message: "", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in let firstTextField = alertController.textFields![0] as UITextField if firstTextField.text == "" { } else { //print("firstName \(firstTextField.text)") self.lblName.text = firstTextField.text // self.btnSave.isHidden = false } }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in self.Loader.stopAnimating() }) alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Enter First and Last Name" } alertController.addAction(saveAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { tbAbout.resignFirstResponder() return true } @IBAction func tbEditBeing(_ sender: Any) { // btnSave.isHidden = false } //////////////////////////////////////////////////////////////////////////////////////////////////////// @IBAction func editClick(_ sender: Any) { // This brings up the dialogue for changing the about field let alertController = UIAlertController(title: "Edit Information", message: "", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in let firstTextField = alertController.textFields![0] as UITextField firstTextField.placeholder = "Please enter a location (City/State/Country)" if firstTextField.text != "" { //print("firstName \(firstTextField.text)") if let temp1 = firstTextField.text{ self.lblLoc.text = "Location: \(temp1)" self.loc = temp1 //self.btnSave.isHidden = false self.NameRef.child("users").child(self.user!.uid).child("Location").setValue(temp1) print(UserDefaults.standard.bool(forKey: "artistCreate")) print(self.artistCreate) print(UserDefaults.standard.bool(forKey: "artistOn")) if self.artistCreate == true{ self.NameRef.child("artistProfiles").child(self.user!.uid).child("Location").setValue(temp1) } } } let secondTextField = alertController.textFields![1] as UITextField secondTextField.placeholder = "Please enter a birthday(dd/mm/yy)" if secondTextField.text == "" { } else { //print("firstName \(firstTextField.text)") if let temp2 = secondTextField.text{ self.lblBirth.text = "Birthday: \(temp2)" self.birth = temp2 //self.btnSave.isHidden = false self.NameRef.child("users").child(self.user!.uid).child("Birthday").setValue(temp2) if self.artistCreate == true{ self.NameRef.child("artistProfiles").child(self.user!.uid).child("Birthday").setValue(temp2) } } } let thirdTextField = alertController.textFields![2] as UITextField thirdTextField.placeholder = "Please enter a gender" if thirdTextField.text == "" { } else { if let temp3 = thirdTextField.text{ self.lblGend.text = "Gender: \(temp3)" self.gend = temp3 //self.btnSave.isHidden = false self.NameRef.child("users").child(self.user!.uid).child("Gender").setValue(temp3) if self.artistCreate == true{ self.NameRef.child("artistProfiles").child(self.user!.uid).child("Gender").setValue(temp3) } } } let fourthTextField = alertController.textFields![3] as UITextField fourthTextField.placeholder = "Please enter some skills" if fourthTextField.text == "" { } else { //print("firstName \(firstTextField.text)") if let temp4 = fourthTextField.text{ self.lblID.text = "Skills: \(temp4)" self.skills = temp4 //self.btnSave.isHidden = false self.NameRef.child("users").child(self.user!.uid).child("Skills").setValue(temp4) if self.artistCreate == true{ self.NameRef.child("artistProfiles").child(self.user!.uid).child("Skills").setValue(temp4) } } } }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in self.Loader.stopAnimating() }) alertController.addTextField { (firstTextField : UITextField!) -> Void in if (self.lblLoc.text == "Location: Not Declared" || self.lblLoc.text == "Location:") { firstTextField.placeholder = "Please enter a location (City/State/Country)" } else { firstTextField.text = self.loc } } alertController.addTextField { (secondTextField : UITextField!) -> Void in if (self.lblBirth.text == "Birthday: Not Declared" || self.lblBirth.text == "Birthday:") { secondTextField.placeholder = "Please enter a birthday (dd/mm/yyyy)" } else { secondTextField.text = self.birth } } alertController.addTextField { (thirdTextField : UITextField!) -> Void in if (self.lblGend.text == "Gender: Not Declared" || self.lblGend.text == "Gender:") { thirdTextField.placeholder = "Please enter a gender" } else { thirdTextField.text = self.gend } } alertController.addTextField { (fourthTextField : UITextField!) -> Void in if (self.lblID.text == "Skills: Not Declared" || self.lblID.text == "Skills:") { fourthTextField.placeholder = "Please enter your skills (necessary for artist account)" } else { fourthTextField.text = self.skills } } alertController.addAction(saveAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } @IBAction func btnMoreAction(_ sender: Any) { let myActionSheet = UIAlertController(title: "Options", message: "Select", preferredStyle: UIAlertControllerStyle.actionSheet) let Logout = UIAlertAction(title: "Logout", style: UIAlertActionStyle.default) { (action) in self.setupProfile() try! FIRAuth.auth()?.signOut() self.LogoutSeq() } let sentInquires = UIAlertAction(title: "Sent Inquires", style: UIAlertActionStyle.default) { (action) in let myVC = self.storyboard?.instantiateViewController(withIdentifier: "sentInquire") as! sentInquireViewController self.present(myVC, animated: true) } // let createArtist = UIAlertAction(title: alertTitle, style: UIAlertActionStyle.default) { (action) in // // // // if self.artistCreate == true // { // // // // } // else{ // if self.skills == "" // { // let alertContoller = UIAlertController(title: "Oops!", message: "Add a set of skills to procede", preferredStyle: .alert) // // let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) // alertContoller.addAction(defaultAction) // self.present(alertContoller, animated: true) // } // else{ // // // self.NameRef.child("artistProfiles").child(self.user!.uid).child("Name").setValue(self.lblName.text) // // self.NameRef.child("artistProfiles").child(self.user!.uid).child("token").setValue(self.user!.uid) // // // self.NameRef.child("artistProfiles").child(self.user!.uid).child("skills").setValue(self.skills) // // self.NameRef.child("artistProfiles").child(self.user!.uid).child("Email").setValue(self.email) // // self.NameRef.child("users").child(self.user!.uid).child("pic").observe(.value){ // (snap: FIRDataSnapshot) in // // if snap.exists() == true // { // self.NameRef.child("artistProfiles").child(self.user!.uid).child("pic").setValue(snap.value as! String) // } // else{ // self.NameRef.child("artistProfiles").child(self.user!.uid).child("pic").setValue("default.ca") // } // let myVC = self.storyboard?.instantiateViewController(withIdentifier: "Artist") as! ArtistViewController // // myVC.token = self.user!.uid // // self.present(myVC, animated: true) // } // // } // } // // } //myActionSheet.addAction(createArtist) myActionSheet.addAction(sentInquires) myActionSheet.addAction(Logout) myActionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)) self.present(myActionSheet, animated: true, completion: nil) } @IBAction func backClick(_ sender: Any) { self.dismiss(animated: true, completion: nil) } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }
// // DataMapViewController.swift // RoambeeDemo // // Created by Nidhi Joshi on 26/09/2021. // import Foundation import UIKit import MapKit import CoreLocation class DataMapViewController: UIViewController,MKMapViewDelegate { // MARK: - Outlets @IBOutlet weak var secondLabel: UILabel! @IBOutlet weak var mapView: MKMapView! // MARK: - Properties var objectAnnotation = MKPointAnnotation() var viewModel: DataMapViewModel? // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() viewModel?.viewDidLoad() showMapData() } func showMapData() { let latitude = viewModel?.latitude ?? 0.0 let longitude = viewModel?.longitude ?? 0.0 let theSpan:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latitude, longitudeDelta: longitude) let pointLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let region:MKCoordinateRegion = MKCoordinateRegion(center: pointLocation, span: theSpan) mapView?.setRegion(region, animated: true) let pinLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) //CLLocationCoordinate2D(latitude: viewModel?.latitude, longitude: viewModel?.longitude) objectAnnotation.coordinate = pinLocation objectAnnotation.title = Constant.pinTitle self.mapView?.addAnnotation(objectAnnotation) } }
// // Encounter+CoreDataProperties.swift // CovidCare // // Copyright © 2020 Australian Government. All rights reserved. // // import Foundation import CoreData import UIKit import CoreBluetooth extension Encounter { enum CodingKeys: String, CodingKey { case timestamp case msg case modelC case modelP case rssi case txPower case org case v } @nonobjc public class func fetchRequest() -> NSFetchRequest<Encounter> { return NSFetchRequest<Encounter>(entityName: "Encounter") } @nonobjc public class func fetchRequestForRecords() -> NSFetchRequest<Encounter> { let fetchRequest = NSFetchRequest<Encounter>(entityName: "Encounter") let predicateString = Encounter.Event .allCases .map { "msg != '\($0.rawValue)'" } .joined(separator: " and ") fetchRequest.predicate = NSPredicate(format: predicateString) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)] return fetchRequest } @nonobjc public class func fetchRequestForEvents() -> NSFetchRequest<Encounter> { let fetchRequest = NSFetchRequest<Encounter>(entityName: "Encounter") let predicateString = Encounter.Event .allCases .map { "msg = '\($0.rawValue)'" } .joined(separator: " or ") fetchRequest.predicate = NSPredicate(format: predicateString) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)] return fetchRequest } // Fetch encounters older than 21 days from today. @nonobjc public class func fetchOldEncounters() -> NSFetchRequest<NSFetchRequestResult>? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Encounter") // Get the current calendar with local time zone var calendar = Calendar.current calendar.timeZone = NSTimeZone.local // Get date 21 days ago let today = calendar.startOfDay(for: Date()) guard let dateTo = calendar.date(byAdding: .day, value: -21, to: today) else { return nil } // Set predicate as date older than 21 days ago fetchRequest.predicate = NSPredicate(format: "timestamp <= %@", dateTo as NSDate) return fetchRequest } @NSManaged public var timestamp: Date? @NSManaged public var msg: String? @NSManaged public var modelC: String? @NSManaged public var modelP: String? @NSManaged public var rssi: NSNumber? @NSManaged public var txPower: NSNumber? @NSManaged public var org: String? @NSManaged public var v: NSNumber? func set(encounterStruct: EncounterRecord) { setValue(encounterStruct.timestamp, forKeyPath: "timestamp") setValue(encounterStruct.msg, forKeyPath: "msg") setValue(encounterStruct.modelC, forKeyPath: "modelC") setValue(encounterStruct.modelP, forKeyPath: "modelP") setValue(encounterStruct.rssi, forKeyPath: "rssi") setValue(encounterStruct.txPower, forKeyPath: "txPower") setValue(encounterStruct.org, forKeyPath: "org") setValue(encounterStruct.v, forKeyPath: "v") } // MARK: - Encodable public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(Int(timestamp!.timeIntervalSince1970), forKey: .timestamp) try container.encode(msg, forKey: .msg) if let modelC = modelC, let modelP = modelP { try container.encode(modelC, forKey: .modelC) try container.encode(modelP, forKey: .modelP) try container.encode(rssi?.doubleValue, forKey: .rssi) try container.encode(txPower?.doubleValue, forKey: .txPower) try container.encode(org, forKey: .org) try container.encode(v?.intValue, forKey: .v) } } }
// // File.swift // ReaderTranslator // // Created by Viktor Kushnerov on 26/10/19. // Copyright © 2019 Viktor Kushnerov. All rights reserved. // import SwiftUI private var stack = Stack<TranslateAction>() @MainActor enum TranslateAction: Equatable { case none(text: String) case speak(text: String) case merriamWebster(text: String) case stackExchange(text: String) case reverso(text: String) case gTranslator(text: String) case deepL(text: String) case yTranslator(text: String) case longman(text: String) case macmillan(text: String) case collins(text: String) case cambridge(text: String) case wikipedia(text: String) case bookmarks(text: String) case chatGPT(text: String) init() { self = .none(text: "") } @MainActor func getText() -> String { switch self { case let .none(text), let .speak(text), let .merriamWebster(text), let .stackExchange(text), let .reverso(text), let .gTranslator(text), let .deepL(text), let .yTranslator(text), let .longman(text), let .macmillan(text), let .collins(text), let .cambridge(text), let .bookmarks(text), let .wikipedia(text), let .chatGPT(text): return text .trimmingCharacters(in: .whitespaces) } } mutating func add(_ actions: [TranslateAction], isSpeaking: Bool = true) { guard Store.shared.enabledClipboard else { return } let isEmpty = stack.count == 0 ? true : false for action in actions { if case .none = action { continue } stack.push(action) } if isSpeaking { stack.push(.speak(text: actions.first?.getText() ?? "")) } if isEmpty { next() } } mutating func add(_ action: TranslateAction, isSpeaking: Bool = true) { guard Store.shared.enabledClipboard else { return } add([action], isSpeaking: isSpeaking) } mutating func addAll(text: String, except: AvailableView? = nil, isSpeaking: Bool = true) { guard Store.shared.enabledClipboard else { return } let actions = ViewsStore.shared.enabledViews .filter { guard $0 != except else { return false } let count = text.split(separator: " ").count switch $0 { case .collins, .cambridge, .merriamWebster, .stackExchange, .longman, .macmillan, .wikipedia: if count < 4 { return true } case .reverso: if count < 10 { return true } case .gTranslator, .deepL, .yTranslator, .bookmarks, .chatGPT: return true case .audioToText, .pdf, .web, .safari: return false } return false } .map { $0.getAction(text: text) } add(actions, isSpeaking: isSpeaking) } @discardableResult mutating func next() -> TranslateAction { if let action = stack.pop() { self = action } else { self = .none(text: getText()) } return self } }
// // CoordinateChecker+Validator.swift // CoordinateCalculator // // Created by BLU on 2019. 5. 13.. // Copyright © 2019년 Codesquad Inc. All rights reserved. // import Foundation protocol Validator { func isValid(_ input: String) -> Bool } struct CoordinateChecker: Validator { func isValid(_ input: String) -> Bool { let regex = "\\(-?[\\d]+,-?[\\d]+\\)" return input.matches(regex) } }
// // SearchBarHelper.swift // homeCheif // // Created by Mohamed Abdu on 4/19/18. // Copyright © 2018 Atiaf. All rights reserved. // import Foundation import UIKit private var searchImagePrivate: UIImage? private var cancelImagePrivate: UIImage? extension UISearchBar { /// SwifterSwift: Border width of view; also inspectable from Storyboard. @IBInspectable public var searchImage: UIImage { get { return self.searchImage } set { searchImagePrivate = newValue } } /// SwifterSwift: Border width of view; also inspectable from Storyboard. @IBInspectable public var cancelImage: UIImage { get { return self.cancelImage } set { cancelImagePrivate = newValue } } func initSearchBar() { self.tintColor = .white self.translatesAutoresizingMaskIntoConstraints = false self.setValue("cancel.lan".localized, forKey: "_cancelButtonText") var searchImageIcon = UIImage() var cancelImageIcon = UIImage() if Localizer.current == "ar" { self.semanticContentAttribute = .forceRightToLeft } else { self.semanticContentAttribute = .forceLeftToRight } if searchImagePrivate != nil { searchImageIcon = searchImagePrivate! } if cancelImagePrivate != nil { cancelImageIcon = cancelImagePrivate! } self.setImage(searchImageIcon, for: .search, state: .normal) self.setImage(cancelImageIcon, for: .clear, state: .normal) for subView in self.subviews { for case let textField as UITextField in subView.subviews { textField.backgroundColor = UIColor.black.withAlphaComponent(0.1) let attributeDict = [NSAttributedString.Key.foregroundColor: UIColor.white] textField.attributedPlaceholder = NSAttributedString(string: "search.lan".localized, attributes: attributeDict) textField.textColor = .white } for innerSubViews in subView.subviews { if let cancelButton = innerSubViews as? UIButton { cancelButton.setTitleColor(UIColor.white, for: .normal) cancelButton.setTitle("cancel.lan".localized, for: .normal) } } } self.enablesReturnKeyAutomatically = false self.returnKeyType = .done } }
// // ZXCategoryCCVCell.swift // YDY_GJ_3_5 // // Created by screson on 2017/5/16. // Copyright © 2017年 screson. All rights reserved. // import UIKit /// 药品分类-子标签 class ZXCategoryCCVCell: UICollectionViewCell { @IBOutlet weak var imgvIcon: UIImageView! @IBOutlet weak var lbName: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code contentView.backgroundColor = .clear self.imgvIcon.backgroundColor = .clear self.lbName.text = "" self.lbName.font = UIFont.zx_bodyFont(13) self.lbName.textColor = UIColor.zx_textColorBody } }
// // Polygon.swift // Pods // // Created by Michael Borgmann on 24/02/2017. // // import GameplayKit public class Polygon { public let points: [float2] public var graphNodes: [GKGraphNode2D] = [] public init(points: [float2]) { self.points = points } public func contains(_ point: float2) -> Bool { var contains = false var j = points.count - 1 for i in 0..<points.count { if ((points[i].y > point.y) != (points[j].y > point.y)) && (point.x < (points[j].x - points[i].x) * (point.y - points[i].y) / (points[j].y - points[i].y) + points[i].x) { contains = !contains } j = i + 1 } return contains } }
import Foundation public let SwiftyHttp = SwiftyHttpManager() open class SwiftyHttpManager: NSObject { //MARK: - POST Method /** Sends POST request to server SwiftyHttp.POST("http://www.sample.com/api/method", params: params, contentType: contentType, headers: headers, withParseKeys: ["firstKey", "secondKey", ...], completion: { (request, data, response) in }, failure: { (request, error, response) in } ) - parameter URL: String value of API method. - parameter params: Dictionary where the key is a server parameter and value is the parameter that should be sent. - parameter contentType: There are three content types supported: * application/json (.JSON) * application/x-www-form-urlencoded (.URLENCODED) * multipart/form-data (.MULTIPART_FORM_DATA) - parameter headers: Dictionary with HTTP Headers. - parameter withParseKeys: String array of keys to parse server response with nested objects. For example server returns data in object with key "data": { "data" : { "name": "userName", "age": "userAge" } } for getting needed data you need to set withParseKeys: ["data"] - parameter completion: Closure is called when server has responded successfully. Returns: * request: *SHRequest* * data: *Data?* * response: *SHResponse?* - parameter failure: Closure is called when request is failed or server has responded with an error. Returns: * request: *SHRequest* * error: *Error?* * response: *SHResponse?* - returns: Instance of URLSessionDataTask. */ @discardableResult open func POST (URL: String, params: [String: AnyObject]?, contentType: ContentType, headers: [String: String]? = nil, withParseKeys parseKeys: [String]? = nil, completion: SuccessHTTPCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDataTask { let request = SHRequest(URL: URL, method: .post, params: params, contentType: contentType, headers: headers, parseKeys: parseKeys) let dataTask = SHDataTaskManager.createDataTaskWithRequest(request: request, completion: completion, failure: failure) dataTask.resume() return dataTask } //MARK: - GET Method /** Sends GET request to server SwiftyHttp.GET("http://www.sample.com/api/method", params: params, headers: headers, withParseKeys: ["firstKey", "secondKey", ...], completion: { (request, data, response) in }, failure: { (request, error, response) in } ) - parameter URL: String value of API method. - parameter params: Dictionary where the key is a server parameter and value is the parameter that should be sent. - parameter headers: Dictionary with HTTP Headers. - parameter withParseKeys: String array of keys to parse server response with nested objects. For example server returns data in object with key "data": { "data" : { "name": "userName", "age": "userAge" } } for getting needed data you need to set withParseKeys: ["data"] - parameter completion: Closure is called when server has responded successfully. Returns: * request: *SHRequest* * data: *Data?* * response: *SHResponse?* - parameter failure: Closure is called when request is failed or server has responded with an error. Returns: * request: *SHRequest* * error: *Error?* * response: *SHResponse?* - returns: Instance of URLSessionDataTask. */ @discardableResult open func GET (URL: String, params: [String: AnyObject]? = nil, headers: [String: String]? = nil, withParseKeys parseKeys: [String]? = nil, completion: SuccessHTTPCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDataTask { let request = SHRequest(URL: URL, method: .get, params: params, headers: headers, parseKeys: parseKeys) let dataTask = SHDataTaskManager.createDataTaskWithRequest(request: request, completion: completion, failure: failure) dataTask.resume() return dataTask } //MARK: - PUT Methods /** Sends PUT request to server SwiftyHttp.PUT("http://www.sample.com/api/method", params: params, contentType: .JSON, headers:headers, withParseKeys: ["firstKey", "secondKey", ...], completion: { (request, data, response) in }, failure: { (request, error, response) in } ) - parameter URL: String value of API method. - parameter params: Dictionary where the key is a server parameter and value is the parameter that should be sent. - parameter contentType: There are three content types supported: * application/json (.JSON) * application/x-www-form-urlencoded (.URLENCODED) * multipart/form-data (.MULTIPART_FORM_DATA) - parameter headers: Dictionary with HTTP Headers. - parameter withParseKeys: String array of keys to parse server response with nested objects. For example server returns data in object with key "data": { "data" : { "name": "userName", "age": "userAge" } } for getting needed data you need to set withParseKeys: ["data"] - parameter completion: Closure is called when server has responded successfully. Returns: * request: *SHRequest* * data: *Data?* * response: *SHResponse?* - parameter failure: Closure is called when request is failed or server has responded with an error. Returns: * request: *SHRequest* * error: *Error?* * response: *SHResponse?* - returns: Instance of URLSessionDataTask. */ @discardableResult open func PUT (URL: String, params: [String: AnyObject]?, contentType: ContentType, headers: [String: String]? = nil, withParseKeys parseKeys: [String]? = nil, completion: SuccessHTTPCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDataTask { let request = SHRequest(URL: URL, method: .put, params: params, contentType: contentType, headers: headers, parseKeys: parseKeys) let dataTask = SHDataTaskManager.createDataTaskWithRequest(request: request, completion: completion, failure: failure) dataTask.resume() return dataTask } //MARK: - DELETE Method /** Sends DELETE request to server SwiftyHttp.DELETE("http://www.sample.com/api/method", params: params, headers: headers, withParseKeys: ["firstKey", "secondKey", ...], completion: { (request, data, response) in }, failure: { (request, error, response) in } ) - parameter URL: String value of API method. - parameter params: Dictionary where the key is a server parameter and value is the parameter that should be sent. - parameter headers: Dictionary with HTTP Headers. - parameter withParseKeys: String array of keys to parse server response with nested objects. For example server returns data in object with key "data": { "data" : { "name": "userName", "age": "userAge" } } for getting needed data you need to set withParseKeys: ["data"] - parameter completion: Closure is called when server has responded successfully. Returns: * request: *SHRequest* * data: *Data?* * response: *SHResponse?* - parameter failure: Closure is called when request is failed or server has responded with an error. Returns: * request: *SHRequest* * error: *Error?* * response: *SHResponse?* - returns: Instance of URLSessionDataTask. */ @discardableResult open func DELETE (URL: String, params: [String: AnyObject]? = nil, headers: [String: String]? = nil, withParseKeys parseKeys: [String]? = nil, completion: SuccessHTTPCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDataTask { let request = SHRequest(URL: URL, method: .delete, params: params, headers: headers, parseKeys: parseKeys) let dataTask = SHDataTaskManager.createDataTaskWithRequest(request: request, completion: completion, failure: failure) dataTask.resume() return dataTask } //MARK: - PATCH Method @discardableResult open func PATCH (URL: String, params: [String: AnyObject]?, contentType: ContentType, headers: [String: String]? = nil, withParseKeys parseKeys: [String]? = nil, completion: SuccessHTTPCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDataTask { let request = SHRequest(URL: URL, method: .patch, params: params, contentType: contentType, headers: headers, parseKeys: parseKeys) let dataTask = SHDataTaskManager.createDataTaskWithRequest(request: request, completion: completion, failure: failure) dataTask.resume() return dataTask } //MARK: - Sending SHDataRequest @discardableResult open func send (dataRequest: SHDataRequest, completion: SuccessHTTPCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDataTask { dataRequest.configureRequest() let dataTask = SHDataTaskManager.createDataTaskWithRequest(request: dataRequest, completion: completion, failure: failure) dataTask.resume() return dataTask } //MARK: - Upload process @discardableResult open func upload (request: SHUploadRequest, success: UploadCompletion? = nil, progress: ProgressCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionUploadTask { request.configureRequest() var successCallback = request.success var progressCallback = request.progress var failureCallback = request.failure if let success = success { successCallback = success } if let progress = progress { progressCallback = progress } if let failure = failure { failureCallback = failure } let uploadTask = SHDataTaskManager.createUploadTaskWithRequest(request: request, completion: successCallback, progress: progressCallback, failure: failureCallback) uploadTask.resume() return uploadTask } @discardableResult open func upload (URL: String, method: SHMethod, contentType: ContentType = .multipart_form_data, params: [String: AnyObject]? = nil, headers: [String: String]? = nil, completion: UploadCompletion? = nil, progress: ProgressCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionUploadTask { let request = SHRequest(URL: URL, method: method, params: params, contentType: contentType, headers: headers) let uploadTask = SHDataTaskManager.createUploadTaskWithRequest(request: request, completion: completion, progress: progress, failure: failure) uploadTask.resume() return uploadTask } //MARK: - Download process @discardableResult open func download (request: SHDownloadRequest, success: DownloadCompletion? = nil, progress: ProgressCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDownloadTask { request.configureRequest() var successCallback = request.success var progressCallback = request.progress var failureCallback = request.failure if let success = success { successCallback = success } if let progress = progress { progressCallback = progress } if let failure = failure { failureCallback = failure } let downloadTask = SHDataTaskManager.createDownloadTaskWithRequest(request: request, completion: successCallback, progress: progressCallback, failure: failureCallback) downloadTask.resume() return downloadTask } @discardableResult open func download (URL: String, method: SHMethod, contentType: ContentType = .multipart_form_data, params: [String: AnyObject]? = nil, headers: [String: String]? = nil, completion: DownloadCompletion? = nil, progress: ProgressCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionDownloadTask { let request = SHRequest(URL: URL, method: method, params: params, contentType: contentType, headers: headers) let downloadTask = SHDataTaskManager.createDownloadTaskWithRequest(request: request, completion: completion, progress: progress, failure: failure) downloadTask.resume() return downloadTask } }
// // UITableViewCell+Extension.swift // FBSnapshotTestCase // // Created by JH on 2019/3/10. // import UIKit public extension UITableViewCell { static var iden: String { return self.description().components(separatedBy: ".").last! } }
// // AppCenter.swift // MovieListDemo // // Created by GevinChen on 2019/12/30. // Copyright © 2019 GevinChen. All rights reserved. // import UIKit import Realm import RealmSwift class AppCenter { let apiClient: APIClient let realm: Realm let movieInteractor: MovieInteractor let imageInteractor: ImageInteractor private static var _instance: AppCenter? static func initial( apiClient: APIClient, realm: Realm ) { let instance = AppCenter( apiClient: apiClient, realm: realm) _instance = instance } static let shared: AppCenter = { return _instance! }() private init( apiClient: APIClient, realm: Realm ) { self.apiClient = apiClient self.realm = realm self.movieInteractor = MovieInteractor(apiClient: self.apiClient, realm: self.realm) self.imageInteractor = ImageInteractor(apiClient: self.apiClient, realm: self.realm) } }
// // Post_DetailVC.swift // Surface // // Created by Nandini Yadav on 23/03/18. // Copyright © 2018 Appinventiv. All rights reserved. // import UIKit import AVFoundation import AVKit class Post_DetailVC: BaseSurfaceVC { //MARK:- Properties // properties when edit post var postData: Featured_List? weak var delegate : editPostProtocol? var videoAsset : AVAsset? var videoUrl: URL? var player: AVPlayer! var avpController = AVPlayerViewController() //MARK:- @IBOutlets @IBOutlet weak var coverImage: UIImageView! @IBOutlet weak var overLayView: UIView! @IBOutlet weak var post_descLabel: UILabel! @IBOutlet weak var viewCountButton: UIButton! @IBOutlet weak var commentCountButton: UIButton! @IBOutlet weak var shareButton: UIButton! @IBOutlet weak var navigationBarView: UIView! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var sideMenuOption: UIButton! @IBOutlet weak var videoPreview: UIView! @IBOutlet weak var playVideoButton: UIButton! //MARK:- View Life Cycle override func viewDidLoad() { super.viewDidLoad() self.initialSetup() overLayView.isUserInteractionEnabled = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.overLayView.vertical_Gradient_Color(colors: [#colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.3769263698).cgColor , #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor , #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.4138484589).cgColor], locations: [0.0 , 0.50 , 0.90]) self.profileImage.cornerRadius(radius: profileImage.h/2) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil) } //MARK:- Private Methods private func initialSetup(){ if let postData = self.postData , let mediaData = postData.media_arr.first{ self.post_descLabel.text = postData.desc commentCountButton.setTitle("\(postData.comments_count)", for: .normal) viewCountButton.setTitle("\(postData.views_count)", for: .normal) userName.text = postData.user_name.capitalizedFirst() profileImage.kf.setImage(with: URL(string:mediaData.media_thumbnail)) if mediaData.media_type == "1"{ self.coverImage.contentMode = .scaleAspectFit self.coverImage.kf.setImage(with: URL(string:mediaData.media_thumbnail)) self.videoPreview.isHidden = true self.playVideoButton.isHidden = true }else{ self.coverImage.isHidden = true videoUrl = URL(string: mediaData.media_url) let asset = AVAsset(url: videoUrl!) videoAsset = asset // Add Player view Global.print_Debug(" filter_video URl:- \(videoUrl?.absoluteString ?? "")") self.avpController = AVPlayerViewController() avpController.view.frame = self.videoPreview.frame self.addChildViewController(avpController) self.videoPreview.addSubview(avpController.view) self.playVideo() NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player.currentItem) } } } fileprivate func playVideo() { guard let avAsset = self.videoAsset else {return} let item = AVPlayerItem(asset: avAsset) self.player = AVPlayer(playerItem: item) self.avpController.player = self.player self.player.play() self.playVideoButton.isSelected = true } @objc private func playerDidFinishPlaying(_ note: NSNotification) { Global.print_Debug("Video Finished") //self.playVideoButton.isSelected = false self.player.play() self.player.seek(to: CMTime(seconds: 0.0, preferredTimescale: 1)) self.view.layoutIfNeeded() } //MARK:- @IBActions & Methods @IBAction func playVideoButtonTapped(_ sender: UIButton) { if self.player != nil , !self.playVideoButton.isSelected{ self.player.play() self.playVideoButton.isSelected = true }else{ self.player.pause() self.playVideoButton.isSelected = false } } @IBAction func viewButtonTapped(_ sender: UIButton) { Global.showToast(msg: "Under Development") } @IBAction func commentButtonTapped(_ sender: UIButton) { let storyboard: UIStoryboard = UIStoryboard(name: "Comments", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "CommentViewController") as! CommentViewController if let id = self.postData?.featured_id{ print(id) vc.postId = Int(id)! } self.navigationController?.pushViewController(vc, animated: true) } @IBAction func shareButtonTapped(_ sender: UIButton) { Global.showToast(msg: "Under Development") } @IBAction func closeButtonTapped(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } @IBAction func sideMenuOptionButtonTapped(_ sender: UIButton) { Global.showToast(msg: "Under Development") } }
// // GenericProvidableKeyTests.swift // EasyInject // // Created by Valentin Knabel on 20.10.16. // // import XCTest @testable import EasyInject class GenericProvidableKeyTests: XCTestCase, LinuxTestCase { static var allTests = [ ("testName", testName), ("testEqual", testEqual), ("testStringLiteral", testStringLiteral), ("testExtendedGraphemeClusterLiteral", testExtendedGraphemeClusterLiteral), ("testUnicodeScalarLiteral", testUnicodeScalarLiteral) ] func testName() { let key = GenericProvidableKey<Any>(name: "key") XCTAssertEqual(key.name, "key") } func testEqual() { let key0 = GenericProvidableKey<Any>(name: "key") let key1 = GenericProvidableKey<Any>(name: "key") XCTAssertEqual(key0, key1) } func testStringLiteral() { let literal: GenericProvidableKey<Any> = "key" let manual = GenericProvidableKey<Any>(name: "key") XCTAssertEqual(literal, manual) } func testExtendedGraphemeClusterLiteral() { let key0 = GenericProvidableKey<Any>(name: "key") let key1 = GenericProvidableKey<Any>(extendedGraphemeClusterLiteral: "key") XCTAssertEqual(key0, key1) } func testUnicodeScalarLiteral() { let key0 = GenericProvidableKey<Any>(name: "key") let key1 = GenericProvidableKey<Any>(unicodeScalarLiteral: "key") XCTAssertEqual(key0, key1) } }
// // ProfileViewController.swift // InstagramLab // // Created by Brendon Cecilio on 3/5/20. // Copyright © 2020 Brendon Cecilio. All rights reserved. // import UIKit import FirebaseAuth import FirebaseFirestore import Kingfisher class ProfileViewController: UIViewController { @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! private lazy var imagePickerController: UIImagePickerController = { let ip = UIImagePickerController() ip.delegate = self return ip }() private var selectedImage: UIImage? { didSet { profileImage.image = selectedImage } } private var items = [Item]() { didSet { collectionView.reloadData() } } private var listener: ListenerRegistration? private let storageService = StorageService() override func viewDidLoad() { super.viewDidLoad() profileImage.layer.cornerRadius = profileImage.frame.size.height / 2 collectionView.delegate = self collectionView.dataSource = self collectionView.register(UINib(nibName: "ProfileCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "profileCell") updateUI() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) listener = Firestore.firestore().collection(DatabaseService.postCollection).addSnapshotListener({ [weak self] (snapshot, error) in if let error = error { DispatchQueue.main.async { self?.showAlert(title: "Try again later", message: "firestore error: \(error)") } } else if let snapshot = snapshot { // this is the data in our firebase database let items = snapshot.documents.map { Item($0.data()) } self?.items = items } }) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) listener?.remove() } private func updateUI() { guard let user = Auth.auth().currentUser else { return } usernameLabel.text = user.email profileImage.kf.setImage(with: user.photoURL) } @IBAction func editButtonPressed(_ sender: UIButton) { let alertController = UIAlertController(title: "Add Profile Picture", message: nil, preferredStyle: .actionSheet) let camerAction = UIAlertAction(title: "Camera", style: .default) { alertAction in self.imagePickerController.sourceType = .camera self.present(self.imagePickerController, animated: true) } let photoLibrary = UIAlertAction(title: "Choose from Library", style: .default) { alertAction in self.imagePickerController.sourceType = .photoLibrary self.present(self.imagePickerController, animated: true) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) if UIImagePickerController.isSourceTypeAvailable(.camera) { alertController.addAction(camerAction) } alertController.addAction(photoLibrary) alertController.addAction(cancelAction) present(alertController, animated: true) } @IBAction func updateProfileButtonPressed(_ sender: UIButton) { guard let selectedImage = selectedImage else { print("missing fields") return } guard let user = Auth.auth().currentUser else {return} let resizeImage = UIImage.resizeImage(originalImage: selectedImage, rect: profileImage.bounds) print("original image size: \(selectedImage.size)") print("original image size: \(resizeImage)") storageService.uploadPhoto(userId: user.uid, image: resizeImage) { [weak self] (result) in switch result { case .failure(let error): DispatchQueue.main.async { self?.showAlert(title: "Error", message: "Error uploading photo: \(error.localizedDescription)") } case .success(let url): let request = Auth.auth().currentUser?.createProfileChangeRequest() request?.photoURL = url request?.commitChanges(completion: { [unowned self] (error) in if let error = error { DispatchQueue.main.async { self?.showAlert(title: "Could not change display name", message: "Error changing display name: \(error.localizedDescription)") } } else { DispatchQueue.main.async { self?.showAlert(title: "Success!", message: "Your display name has changed successfully.") } } }) } } } @IBAction func signOutButtonPressed(_ sender: UIButton) { do { try Auth.auth().signOut() UIViewController.showViewController(storyboardName: "Login", viewControllerId: "LoginViewController") } catch { DispatchQueue.main.async { self.showAlert(title: "Error signing out", message: "\(error.localizedDescription)") } } } } extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return } selectedImage = image dismiss(animated: true) } } extension ProfileViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "profileCell", for: indexPath) as? ProfileCollectionCell else { fatalError() } let itemCell = items[indexPath.row] cell.layer.borderColor = UIColor.blue.cgColor cell.layer.borderWidth = 1 cell.layer.cornerRadius = 30 cell.updateUI(for: itemCell) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let maxSize: CGSize = UIScreen.main.bounds.size let spacingBetweenItems: CGFloat = 11 let numberOfItems: CGFloat = 1 let totalSpacing: CGFloat = (1.2 * spacingBetweenItems) + (numberOfItems - 1) * numberOfItems let itemWidth: CGFloat = (maxSize.width - totalSpacing) / numberOfItems let itemHeight: CGFloat = maxSize.height * 0.50 return CGSize(width: itemWidth, height: itemHeight) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } }
// Copyright (c) 2020-2022 InSeven Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Combine import SwiftUI public struct ManagerEnvironmentKey: EnvironmentKey { public static var defaultValue = BookmarksManager() } public extension EnvironmentValues { var manager: BookmarksManager { get { self[ManagerEnvironmentKey.self] } set { self[ManagerEnvironmentKey.self] = newValue } } } public class BookmarksManager: ObservableObject { public enum State { case idle case unauthorized } @Published public var state: State = .idle // TODO: Explore whether it's possible make some of the BookmarksManager properties private #266 // https://github.com/inseven/bookmarks/issues/266 public var imageCache: ImageCache! public var thumbnailManager: ThumbnailManager public var settings = Settings() public var tagsView: TagsView public var cache: NSCache = NSCache<NSString, SafeImage>() public var database: Database private var documentsUrl: URL private var downloadManager: DownloadManager private var updater: Updater public init() { documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! try! FileManager.default.createDirectory(at: documentsUrl, withIntermediateDirectories: true, attributes: nil) // TODO: Handle database initialisation errors #143 // https://github.com/inseven/bookmarks/issues/143 database = try! Database(path: documentsUrl.appendingPathComponent("store.db")) imageCache = FileImageCache(path: documentsUrl.appendingPathComponent("thumbnails")) downloadManager = DownloadManager(limit: settings.maximumConcurrentThumbnailDownloads) thumbnailManager = ThumbnailManager(imageCache: imageCache, downloadManager: downloadManager) updater = Updater(database: database, settings: settings) tagsView = TagsView(database: database) updater.delegate = self updater.start() tagsView.start() #if os(macOS) let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(nsApplicationDidBecomeActive), name: NSNotification.Name("NSApplicationDidBecomeActiveNotification"), object: nil) #endif } public var user: String? { return updater.user } public func authenticate(username: String, password: String, completion: @escaping (Result<Void, Error>) -> Void) { let completion = DispatchQueue.global().asyncClosure(completion) updater.authenticate(username: username, password: password) { result in DispatchQueue.main.async { switch result { case .success(): self.state = .idle completion(.success(())) case .failure(let error): completion(.failure(error)) } } } } public func logout(completion: @escaping (Result<Void, Error>) -> Void) { dispatchPrecondition(condition: .onQueue(.main)) let completion = DispatchQueue.global().asyncClosure(completion) updater.logout { result in DispatchQueue.main.async { switch result { case .success(): self.state = .unauthorized completion(.success(())) case .failure(let error): completion(.failure(error)) } } } } public func refresh() { updater.update(force: true) } public func deleteBookmarks(_ bookmarks: [Bookmark], completion: @escaping (Result<Void, Error>) -> Void) { updater.deleteBookmarks(bookmarks, completion: completion) } public func deleteBookmarks(_ bookmarks: Set<Bookmark>, completion: @escaping (Result<Void, Error>) -> Void) { updater.deleteBookmarks(Array(bookmarks), completion: completion) } public func deleteBookmarks(_ bookmarks: [Bookmark]) async throws { return try await withCheckedThrowingContinuation { continuation in updater.deleteBookmarks(bookmarks) { result in switch result { case .success: continuation.resume() case .failure(let error): continuation.resume(throwing: error) } } } } public func updateBookmarks(_ bookmarks: [Bookmark], completion: @escaping (Result<Void, Error>) -> Void) { updater.updateBookmarks(bookmarks, completion: completion) } public func updateBookmarks(_ bookmarks: Set<Bookmark>, completion: @escaping (Result<Void, Error>) -> Void) { updater.updateBookmarks(Array(bookmarks), completion: completion) } public func updateBookmarks(_ bookmarks: [Bookmark]) async throws { return try await withCheckedThrowingContinuation { continuation in updater.updateBookmarks(bookmarks) { result in switch result { case .success: continuation.resume() case .failure(let error): continuation.resume(throwing: error) } } } } public func renameTag(_ old: String, to new: String, completion: @escaping (Result<Void, Error>) -> Void) { updater.renameTag(old, to: new, completion: completion) } public func deleteTag(_ tag: String, completion: @escaping (Result<Void, Error>) -> Void) { updater.deleteTag(tag, completion: completion) } public func openBookmarks(_ bookmarks: Set<Bookmark>, location: Bookmark.Location = .web, completion: @escaping (Result<Void, Error>) -> Void) { openBookmarks(Array(bookmarks), location: location, completion: completion) } public func openBookmarks(_ bookmarks: [Bookmark], location: Bookmark.Location = .web, completion: @escaping (Result<Void, Error>) -> Void) { let completion = DispatchQueue.main.asyncClosure(completion) do { let many = open(urls: try bookmarks.map { try $0.url(location) }) _ = many.sink { result in switch result { case .finished: completion(.success(())) case .failure(let error): completion(.failure(error)) } } receiveValue: { _ in } } catch { completion(.failure(error)) } } fileprivate func open(urls: [URL]) -> Publishers.MergeMany<Future<Void, Error>> { let openers = urls.map { self.open(url: $0) } let many = Publishers.MergeMany(openers) return many } fileprivate func open(url: URL) -> Future<Void, Error> { return Future() { promise in self.open(url: url) { success in if success { promise(.success(())) } else { promise(.failure(BookmarksError.openFailure)) } } } } public func open(url: URL, completion: ((Bool) -> Void)? = nil) { let completion = DispatchQueue.main.asyncClosure(completion) #if os(macOS) NSWorkspace.shared.open(url) guard let completion = completion else { return } completion(true) #else UIApplication.shared.open(url, options: [:], completionHandler: completion) #endif } @objc func nsApplicationDidBecomeActive() { self.updater.update() } } extension BookmarksManager: UpdaterDelegate { func updaterDidStart(_ updater: Updater) { } func updaterDidFinish(_ updater: Updater) { } func updater(_ updater: Updater, didFailWithError error: Error) { print("Failed to update bookmarks with error \(error)") switch error { case BookmarksError.httpError(.unauthorized), BookmarksError.unauthorized: DispatchQueue.main.async { self.state = .unauthorized } default: print("Ignoring error \(error)...") } } }
// // UILabel+Utility.swift // AlbumRSS // // Created by Gavin Li on 8/14/20. // Copyright © 2020 Gavin Li. All rights reserved. // import UIKit extension UILabel { // a simplistic style common to all the UILabels in the app func configureStyle(fontSize: CGFloat = 13, textColor: UIColor = .black) { numberOfLines = 0 lineBreakMode = .byTruncatingTail font = UIFont(name: "HelveticaNeue", size: fontSize) self.textColor = textColor textAlignment = .left translatesAutoresizingMaskIntoConstraints = false } class func newSimpleLabel(with fontSize: CGFloat = 13, textColor: UIColor = .black) -> UILabel { let label = self.init(frame: .zero) label.configureStyle(fontSize: fontSize, textColor: textColor) return label } convenience init(with fontSize: CGFloat, textColor: UIColor) { self.init(frame: .zero) configureStyle(fontSize: fontSize, textColor: textColor) } }
// // ShipItemStorageUnitTests.swift // SailingThroughHistoryTests // // Created by henry on 13/4/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // // swiftlint:disable function_body_length import XCTest @testable import SailingThroughHistory class ShipItemStorageUnitTests: XCTestCase { static let itemParameters = [ItemParameter.opium, ItemParameter.food] var node = NodeStub(name: "testNode", identifier: 0) var items = ShipItemStorageUnitTests.itemParameters.map { GenericItemStub(name: $0.rawValue, itemParameter: $0, quantity: 1) } let portWithItems = PortStub(buyValueOfAllItems: 100, sellValueOfAllItems: 100, itemParameters: ShipItemStorageUnitTests.itemParameters) let portWithoutItems = PortStub(buyValueOfAllItems: 100, sellValueOfAllItems: 100, itemParameters: []) let itemStorage = ShipItemManager() var map = Map(map: "testMap", bounds: Rect(originX: 0, originY: 0, height: 0, width: 0)) override func setUp() { super.setUp() node = NodeStub(name: "testNode", identifier: 0) map = Map(map: "testMap", bounds: Rect(originX: 0, originY: 0, height: 0, width: 0)) map.addNode(node) map.addNode(portWithItems) map.addNode(portWithoutItems) } override class func tearDown() { Node.nextID = 0 Node.reuseID.removeAll() } override func tearDown() { for node in map.nodes.value { map.removeNode(node) } } func testGetPurchasableItemTypes() { let ship1 = Ship(node: portWithItems, itemsConsumed: []) ship1.isDocked = true ship1.map = map let itemParameters1 = itemStorage.getPurchasableItemParameters(ship: ship1) XCTAssertEqual(Set(itemParameters1), Set(ShipItemStorageUnitTests.itemParameters)) let ship2 = Ship(node: node, itemsConsumed: []) ship2.isDocked = true ship2.map = map let itemParameters2 = itemStorage.getPurchasableItemParameters(ship: ship2) XCTAssertEqual(itemParameters2, [ItemParameter]()) } func testGetMaxPurchaseAmount() { guard let itemParameter = ShipItemStorageUnitTests.itemParameters.first else { XCTFail("No item parameters defined for ItemStorage tests") return } let ship1 = Ship(node: portWithItems, itemsConsumed: []) ship1.map = map ship1.isDocked = true ship1.weightCapacity = 100000 let owner1 = GenericPlayerStub() owner1.money.value = 1000 ship1.owner = owner1 let amount1 = itemStorage.getMaxPurchaseAmount(ship: ship1, itemParameter: itemParameter) guard let portValue1 = portWithItems.getBuyValue(of: itemParameter) else { XCTFail("Item not sold at port!") return } XCTAssertEqual(amount1, owner1.money.value / portValue1) let ship2 = Ship(node: portWithItems, itemsConsumed: []) ship2.map = map ship2.isDocked = true ship2.weightCapacity = 1000 let owner2 = GenericPlayerStub() owner2.money.value = 100000 ship2.owner = owner2 let amount2 = itemStorage.getMaxPurchaseAmount(ship: ship2, itemParameter: itemParameter) XCTAssertEqual(amount2, ship2.weightCapacity / itemParameter.unitWeight) let ship3 = Ship(node: node, itemsConsumed: []) ship3.map = map ship3.isDocked = true ship3.weightCapacity = 100000 let owner3 = GenericPlayerStub() owner3.money.value = 100000 ship3.owner = owner3 let amount3 = itemStorage.getMaxPurchaseAmount(ship: ship3, itemParameter: itemParameter) XCTAssertEqual(amount3, 0) let ship4 = Ship(node: node, itemsConsumed: []) ship4.map = map ship4.isDocked = true ship4.weightCapacity = 100000 let amount4 = itemStorage.getMaxPurchaseAmount(ship: ship4, itemParameter: itemParameter) XCTAssertEqual(amount4, 0) } func testBuyItem() throws { guard let itemParameter = ShipItemStorageUnitTests.itemParameters.first else { XCTFail("No item parameters defined for ItemStorage tests") return } guard let itemValue = portWithItems.getBuyValue(of: itemParameter) else { XCTFail("Item not available at port!") return } for quantity in 1...3 { let ship1 = Ship(node: node, itemsConsumed: []) ship1.weightCapacity = 100000 ship1.map = map ship1.isDocked = true let owner1 = GenericPlayerStub() owner1.money.value = 100000 ship1.owner = owner1 XCTAssertThrowsError(try itemStorage.buyItem(ship: ship1, itemParameter: itemParameter, quantity: quantity)) { error in guard let notDockedError = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(notDockedError.getMessage(), TradeItemError.notDocked.getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship1.items.value, [GenericItem]())) let ship2 = Ship(node: portWithoutItems, itemsConsumed: []) ship2.weightCapacity = 100000 ship2.map = map ship2.isDocked = true let owner2 = GenericPlayerStub() owner2.money.value = 100000 ship2.owner = owner2 XCTAssertThrowsError(try itemStorage.buyItem(ship: ship2, itemParameter: itemParameter, quantity: quantity)) { error in guard let itemNotAvailableError = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(itemNotAvailableError.getMessage(), TradeItemError.itemNotAvailable.getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship2.items.value, [GenericItem]())) let ship3 = Ship(node: portWithItems, itemsConsumed: []) ship3.weightCapacity = 100000 ship3.map = map ship3.isDocked = true let owner3 = GenericPlayerStub() owner3.money.value = 0 ship3.owner = owner3 XCTAssertThrowsError(try itemStorage.buyItem(ship: ship3, itemParameter: itemParameter, quantity: quantity)) { error in guard let insufficientFunds = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(insufficientFunds.getMessage(), TradeItemError.insufficientFunds(shortOf: itemValue * quantity - owner3.money.value).getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship3.items.value, [GenericItem]())) } } func testBuyItem2() throws { guard let itemParameter = ShipItemStorageUnitTests.itemParameters.first else { XCTFail("No item parameters defined for ItemStorage tests") return } guard let itemValue = portWithItems.getBuyValue(of: itemParameter) else { XCTFail("Item not available at port!") return } let item = Item(itemParameter: itemParameter, quantity: 1) for quantity in 1...3 { let ship4 = Ship(node: portWithItems, itemsConsumed: []) ship4.weightCapacity = 100000 ship4.isDocked = true ship4.map = map XCTAssertThrowsError(try itemStorage.buyItem(ship: ship4, itemParameter: itemParameter, quantity: quantity)) { error in guard let insufficientFunds = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(insufficientFunds.getMessage(), TradeItemError.insufficientFunds(shortOf: itemValue * quantity).getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship4.items.value, [GenericItem]())) let ship5 = Ship(node: portWithItems, itemsConsumed: []) ship5.weightCapacity = itemParameter.unitWeight * quantity - 1 ship5.isDocked = true ship5.map = map let owner5 = GenericPlayerStub() owner5.money.value = 100000 ship5.owner = owner5 XCTAssertThrowsError(try itemStorage.buyItem(ship: ship5, itemParameter: itemParameter, quantity: quantity)) { error in guard let insufficientCapacity = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(insufficientCapacity.getMessage(), TradeItemError .insufficientCapacity(shortOf: itemParameter.unitWeight * quantity - ship5.weightCapacity) .getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship5.items.value, [GenericItem]())) let ship6 = Ship(node: portWithItems, itemsConsumed: []) ship6.weightCapacity = itemParameter.unitWeight * quantity ship6.isDocked = true ship6.map = map ship6.items.value = [item.copy()] let owner6 = GenericPlayerStub() owner6.money.value = 100000 ship6.owner = owner6 XCTAssertThrowsError(try itemStorage.buyItem(ship: ship6, itemParameter: itemParameter, quantity: quantity)) { error in guard let insufficientCapacity = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(insufficientCapacity.getMessage(), TradeItemError .insufficientCapacity(shortOf: -itemParameter.unitWeight * quantity + ship6.weightCapacity + item.weight) .getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship6.items.value, [item])) let ship7 = Ship(node: portWithItems, itemsConsumed: []) ship7.weightCapacity = 100000 ship7.isDocked = true ship7.map = map ship7.items.value = [item.copy()] let owner7 = GenericPlayerStub() owner7.money.value = 100000 ship7.owner = owner7 try itemStorage.buyItem(ship: ship7, itemParameter: itemParameter, quantity: quantity) let combinedItem = Item(itemParameter: itemParameter, quantity: quantity + item.quantity) XCTAssertTrue(testTwoGenericItemArray(ship7.items.value, [combinedItem])) XCTAssertEqual(owner7.money.value, 100000 - quantity * itemValue) } } func testSellItem() throws { guard let itemParameter = ShipItemStorageUnitTests.itemParameters.first else { XCTFail("No item parameters defined for ItemStorage tests") return } guard let itemValue = portWithItems.getBuyValue(of: itemParameter) else { XCTFail("Item not available at port!") return } let item = Item(itemParameter: itemParameter, quantity: 1) let quantity = item.quantity + 1 //func sellItem(item: GenericItem) throws let ship1 = Ship(node: node, itemsConsumed: []) ship1.weightCapacity = 100000 ship1.map = map ship1.items.value = [item.copy()] ship1.isDocked = true let owner1 = GenericPlayerStub() owner1.money.value = 0 ship1.owner = owner1 XCTAssertThrowsError(try itemStorage.sell(ship: ship1, itemParameter: itemParameter, quantity: item.quantity)) { error in guard let notDockedError = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(notDockedError.getMessage(), TradeItemError.notDocked.getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship1.items.value, [item])) let ship2 = Ship(node: portWithoutItems, itemsConsumed: []) ship2.weightCapacity = 100000 ship2.map = map ship2.items.value = [item.copy()] ship2.isDocked = true let owner2 = GenericPlayerStub() owner2.money.value = 0 ship2.owner = owner2 XCTAssertThrowsError(try itemStorage.sell(ship: ship2, itemParameter: itemParameter, quantity: item.quantity)) { error in guard let itemNotAvailable = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(itemNotAvailable.getMessage(), TradeItemError.itemNotAvailable.getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship2.items.value, [item])) let ship3 = Ship(node: portWithItems, itemsConsumed: []) ship3.weightCapacity = 100000 ship3.map = map ship3.items.value = [item.copy()] ship3.isDocked = true let owner3 = GenericPlayerStub() owner3.money.value = 0 ship3.owner = owner3 try itemStorage.sell(ship: ship3, itemParameter: itemParameter, quantity: item.quantity) XCTAssertTrue(testTwoGenericItemArray(ship3.items.value, [GenericItem]())) XCTAssertEqual(owner3.money.value, item.quantity * itemValue) let ship4 = Ship(node: portWithItems, itemsConsumed: []) ship4.weightCapacity = 100000 ship4.map = map ship4.items.value = [item.copy()] ship4.isDocked = true let owner4 = GenericPlayerStub() owner4.money.value = 0 ship4.owner = owner4 XCTAssertThrowsError(try itemStorage.sell(ship: ship4, itemParameter: itemParameter, quantity: quantity)) { error in guard let insufficientItems = error as? TradeItemError else { XCTFail("Error was not correct type") return } XCTAssertEqual(insufficientItems.getMessage(), TradeItemError.insufficientItems(shortOf: quantity - item.quantity, sold: item.quantity).getMessage()) } XCTAssertTrue(testTwoGenericItemArray(ship4.items.value, [GenericItem]())) XCTAssertEqual(owner4.money.value, item.quantity * itemValue) } func testRemoveItem() { guard let itemParameter1 = ShipItemStorageUnitTests.itemParameters.first, let itemParameter2 = ShipItemStorageUnitTests.itemParameters.last, itemParameter1 != itemParameter2 else { XCTFail("One or less item parameters defined for ItemStorage tests") return } let item1 = Item(itemParameter: itemParameter1, quantity: 1) let item1More = Item(itemParameter: itemParameter1, quantity: 2) let ship1 = Ship(node: node, itemsConsumed: []) ship1.items.value = [item1.copy()] XCTAssertEqual(itemStorage.removeItem(ship: ship1, by: itemParameter2, with: 1), 1) XCTAssertTrue(testTwoGenericItemArray(ship1.items.value, [item1])) let ship2 = Ship(node: node, itemsConsumed: []) ship2.items.value = [item1.copy()] XCTAssertEqual(itemStorage.removeItem(ship: ship2, by: itemParameter1, with: 1), 0) XCTAssertTrue(testTwoGenericItemArray(ship2.items.value, [GenericItemStub]())) let ship3 = Ship(node: node, itemsConsumed: []) ship3.items.value = [item1More.copy()] XCTAssertEqual(itemStorage.removeItem(ship: ship3, by: itemParameter1, with: 1), 0) XCTAssertTrue(testTwoGenericItemArray(ship3.items.value, [item1])) let ship4 = Ship(node: node, itemsConsumed: []) ship4.items.value = [item1.copy()] XCTAssertEqual(itemStorage.removeItem(ship: ship4, by: itemParameter1, with: 2), 1) XCTAssertTrue(testTwoGenericItemArray(ship4.items.value, [GenericItemStub]())) let ship5 = Ship(node: node, itemsConsumed: []) ship5.items.value = [item1.copy(), item1.copy()] XCTAssertEqual(itemStorage.removeItem(ship: ship5, by: itemParameter1, with: 2), 0) XCTAssertTrue(testTwoGenericItemArray(ship5.items.value, [GenericItemStub]())) } private func testTwoGenericItemArray(_ array1: [GenericItem], _ array2: [GenericItem]) -> Bool { guard array1.count == array2.count else { return false } for (item1, item2) in zip(array1, array2) { guard item1 == item2 else { return false } } return true } } // swiftlint:enable function_body_length
// // ShopTableViewCell.swift // SkillupPractice12 // // Created by k_motoyama on 2017/04/22. // Copyright © 2017年 k_moto. All rights reserved. // import UIKit class ShopTableView: NSObject, UITableViewDataSource { var shopList: [ShopItem] = [] func add(shopList: [ShopItem]){ self.shopList = shopList } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shopList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellID = ShopTableViewCell.identifier let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ShopTableViewCell let shopItem = shopList[indexPath.row] cell.shopItem = shopItem return cell } }
// // DateUtil.swift // TemplateSwiftAPP // // Created by wenhua on 2018/9/18. // Copyright © 2018年 wenhua yu. All rights reserved. // import Foundation /// 时间相关 class DateUtil: NSObject { /// 时间戳转化成日期:yyyy-MM-dd HH:mm:ss static func timeStampToDate(timeStamp: TimeInterval) -> String { return String.timeStampToDate(timeStamp: timeStamp) } /// 时间戳转化成日期:MM-dd HH:mm static func timeStampToString(timeStamp: TimeInterval) -> String { // 时间戳为毫秒级要 / 1000, 秒就不用除1000,参数带没带000 let date = NSDate(timeIntervalSince1970: timeStamp) let dfmatter = DateFormatter() // yyyy-MM-dd HH:mm:ss dfmatter.dateFormat="MM-dd HH:mm" return dfmatter.string(from: date as Date) } }
// // ViewController.swift // Yelp // // Created by Timothy Lee on 9/19/14. // Copyright (c) 2014 Timothy Lee. All rights reserved. // import UIKit class ViewController: UITableViewController, UISearchBarDelegate { var client: YelpClient! var dataArray: NSArray? var networkError: Bool = false var searchTerm: String = "" // You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys let yelpConsumerKey = "_0ZgjQ3ruYuw213HuXaqMw"//"vxKwwcR_NMQ7WaEiQBK_CA" let yelpConsumerSecret = "DMBkUNH01MH9sFNTSNA_gq_xENk"//"33QCvh5bIF5jIHR5klQr7RtBDhQ" let yelpToken = "Oxf8V9ZUljfHB01-FqKRzx0OkZfYEked"//"uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV" let yelpTokenSecret = "lqfHcRBCKZzGVIG3r8SUou-Kvrc"//"mqtKIxMIR4iBtBPZCmCLEb-Dz3Y" var webView: WebViewController! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Set status bar to white UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) // Do any additional setup after loading the view, typically from a nib. client = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret) // Search bar let searchBar = UISearchBar() self.navigationItem.titleView = searchBar searchBar.delegate = self // Resize rows self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = 90.0; reload() } func reload() { println("Reloading") showActivity() if activeOperation != nil { activeOperation.cancel() } activeOperation = client.searchWithTerm(searchTerm, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in self.dataArray = response["businesses"] as? NSArray self.networkError = false self.hideActivity() self.tableView.reloadData() }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in if !operation.cancelled { println(error) self.networkError = true self.hideActivity() self.tableView.reloadData() } } } var activeOperation: AFHTTPRequestOperation! override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (networkError) { return 1; } if (dataArray != nil) { var i:Int? = dataArray?.count as Int? println("\(i!) cells") return i! } println("0 cells"); return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if ( !networkError ) { let index:Int = indexPath.row let cell = tableView.dequeueReusableCellWithIdentifier("yelpCell") as YelpTableViewCell; if (dataArray?.count >= index) { let data: NSDictionary = self.dataArray?[index] as NSDictionary; cell.setData(data, index: index+1) } return cell; } else { let cell = tableView.dequeueReusableCellWithIdentifier("networkErrorCell") as UITableViewCell; return cell; } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if ( !networkError ) { let index:Int = indexPath.row if (dataArray?.count >= index) { if let data: NSDictionary = self.dataArray?[index] as? NSDictionary { if let urlStr = data["mobile_url"] as? String { // Web View webView = self.storyboard?.instantiateViewControllerWithIdentifier("webView") as WebViewController webView.bizUrlStr = urlStr self.showViewController(webView, sender: webView) } } } } else { reload() } } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { self.searchTerm = searchText reload() } @IBAction func filterPressed(sender: AnyObject) { let filterView: FilterViewController! = self.storyboard?.instantiateViewControllerWithIdentifier("filterView") as FilterViewController filterView.filter = client.filter self.showViewController(filterView, sender: filterView) } func showActivity() { if actInd == nil { actInd = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView actInd?.center = self.view.center actInd?.hidesWhenStopped = true actInd?.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray view.addSubview(actInd!) actInd?.startAnimating() } } func hideActivity() { actInd?.stopAnimating() actInd?.removeFromSuperview() actInd = nil } var actInd: UIActivityIndicatorView? func TestGeoDistance() { let geo1 = GeoCoordinate(latitude: 37.770706, longitude: -122.403511) let geo2 = GeoCoordinate(latitude: 37.770649, longitude: -122.402799) println("distance in km: \(geo1.Distance(geo2))") println("distance in mi: \(geo1.DistanceInMiles(geo2))") } }
// // main.swift // FourSum // // Created by cyzone on 2020/11/27. // import Foundation /// 454. 四数相加 II /// /// 给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。 /// 为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。 /// 首先求出 A 和 B 任意两数之和 sumAB,以 sumAB 为 key,sumAB 出现的次数为 value,存入 hashmap 中。 /// 然后计算 C 和 D 中任意两数之和的相反数 sumCD,在 hashmap 中查找是否存在 key 为 sumCD。 /// 算法时间复杂度为 O(n2)。 /// - Returns: func fourSumCount(_ A: [Int], _ B: [Int], _ C: [Int], _ D: [Int]) -> Int { if A.isEmpty { return 0 } //两个数组的和 : 个数 var map:[Int : Int] = [:] var count = 0 //O n^2 for i in 0..<A.count{ for j in 0..<B.count{ let sumAB = A[i] + B[j] map[sumAB] = (map[sumAB] ?? 0 ) + 1 } } //O n^2 for i in 0..<C.count{ for j in 0..<D.count{ let sumCD = -(C[i] + D[j]) //取反 if let x = map[sumCD]{ count += x } } } // O(2*N^2) return count } print(fourSumCount([1,2], [-2,-1], [-1,2], [0,2])) //-1 0 0 1
// // MarginLabel.swift // Plan // // Created by sta bari on 5/30/18. // Copyright © 2018 tom. All rights reserved. // import UIKit class MarginLabel: UILabel { @IBInspectable var marginLeft: CGFloat = 5 @IBInspectable var marginRight: CGFloat = 5 @IBInspectable var marginTop: CGFloat = 5 @IBInspectable var marginBottom: CGFloat = 5 override func drawText(in rect: CGRect) { let margin = UIEdgeInsets(top: marginTop, left: marginLeft, bottom: marginBottom, right: marginRight) super.drawText(in: rect.inset(by: margin)) } }
// // NewUserViewController.swift // DatabasesProject // // Created by Tahia Emran on 12/7/17. // Copyright © 2017 Tahia Emran. All rights reserved. // import UIKit import Firebase import FirebaseDatabase import FirebaseAuth class NewUserViewController: UIViewController { let darkPurple = UIColor(red: 17.0/255.0, green: 29.0/255.0, blue: 68.0/255.0, alpha: 1.0) let lightPurple = UIColor(red: 48.0/255.0, green: 59.0/255.0, blue: 116.0/255.0, alpha: 1.0) let lightPurple1 = UIColor(red: 75.0/255.0, green: 102.0/255.0, blue: 160.0/255.0, alpha: 1.0) let middle = UIColor(red: 90.0/255.0, green: 132.0/255.0, blue: 182.0/255.0, alpha: 1.0) let blue1 = UIColor(red: 103.0/255.0, green: 159.0/255.0, blue: 202.0/255.0, alpha: 1.0) let darkBlue = UIColor(red: 125.0/255.0, green: 203.0/255.0, blue: 232.0/255.0, alpha: 1.0) @IBOutlet weak var createNewUser: UIButton! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var zipCodeTextField: UITextField! fileprivate var name: String! fileprivate var email: String! fileprivate var pass: String! fileprivate var zip: String! var ref: DatabaseReference! @IBAction func createNewUser(_ sender: UIButton) { guard let email = emailTextField.text, !email.isEmpty else {print("No email entered"); return} guard let password = passwordTextField.text, !password.isEmpty else {print("No pass entered"); return} guard let zip = zipCodeTextField.text, !zip.isEmpty else {print("No zip entered"); return} Auth.auth().createUser(withEmail: email, password: password) { (user, error) in if error == nil { }else{ print("didnt work") print(error!) //registration failure } } var i = 1 while (true){ i += 1 if i == 1500000000{ break } } let zipRef = Database.database().reference().child("UserZips") let userID = Auth.auth().currentUser?.uid print("uid", userID, "zip", zip) let keyValue = [userID! : String(zip)] zipRef.updateChildValues(keyValue) } func doStuff(text:String) -> Bool{ return true } override func viewDidLoad() { super.viewDidLoad() let newLayer = CAGradientLayer() newLayer.colors = [darkPurple.cgColor, lightPurple.cgColor, lightPurple1.cgColor, middle.cgColor ,blue1.cgColor ,darkBlue.cgColor] newLayer.frame = self.view.frame view.layer.insertSublayer(newLayer, at: 0) zipCodeTextField.delegate = self //passwordTextField.delegate = self ref = Database.database().reference() // set placeholder self.emailTextField.attributedPlaceholder = getPlaceHolderText(text: "Email Address") self.nameTextField.attributedPlaceholder = getPlaceHolderText(text: "Name") self.passwordTextField.attributedPlaceholder = getPlaceHolderText(text: "Password") self.zipCodeTextField.attributedPlaceholder = getPlaceHolderText(text: "Zip Code") } fileprivate func getPlaceHolderText(text:String) -> NSAttributedString{ let attrPlaceholder = NSMutableAttributedString(string: text) attrPlaceholder.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(0, text.count)) let placholderTxt = NSAttributedString(attributedString: attrPlaceholder) return placholderTxt } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension NewUserViewController: UITextFieldDelegate{ func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { self.becomeFirstResponder() return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.email = emailTextField.text! self.name = nameTextField.text! self.pass = passwordTextField.text! self.zip = zipCodeTextField.text! self.resignFirstResponder() // self.performSegue(withIdentifier: "login", sender: self.Any?) return true } func textFieldDidEndEditing(_ textField: UITextField) { self.email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) self.name = nameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) self.pass = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) self.zip = zipCodeTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) self.resignFirstResponder() } }
// // Character.swift // Assessment // // Created by Flavius Bortas on 10/29/18. // Copyright © 2018 Flavius Bortas. All rights reserved. // import Foundation class Films: Codable { var characters: [String] } class HomeWorld: Codable { let name: String } class Species: Codable { let name: String } struct Character: Codable { let name: String let birthYear: String let gender: String let homeWorldURL: String let speciesURL: [String] enum CodingKeys: String, CodingKey { case name, gender case birthYear = "birth_year" case homeWorldURL = "homeworld" case speciesURL = "species" } }
import UIKit class ViewController: UIViewController, SpeechRecognitionModalDelegate { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var micButton: UIButton! let speechObject: SpeechRecognitionModal = SpeechRecognitionModal() override func viewDidLoad() { super.viewDidLoad() speechObject.delegate = self speechObject.customInit() } @IBAction func micButtonPressed(_ sender: UIButton) { speechObject.micButtonPressedFunc() } func didPrepareSpeech(finalString: String, isMicButtonEnabled: Bool) { self.titleLabel.text = finalString self.micButton.isEnabled = isMicButtonEnabled if isMicButtonEnabled { self.view.backgroundColor = UIColor.lightGray } else { self.view.backgroundColor = UIColor.green } } }
import Flutter import UIKit import UserNotifications /// `RestartAppPlugin` class provides a method to restart a Flutter application in iOS. /// /// It uses the Flutter platform channels to communicate with the Flutter code. /// Specifically, it uses a `FlutterMethodChannel` named 'restart' for this communication. /// /// The main functionality is provided by the `handle` method. public class RestartAppPlugin: NSObject, FlutterPlugin { /// Registers the plugin with the given `registrar`. /// /// This function is called when the plugin is registered with Flutter. /// It creates a `FlutterMethodChannel` named 'restart', and sets this plugin instance as /// the delegate for method calls from Flutter. public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "restart", binaryMessenger: registrar.messenger()) let instance: RestartAppPlugin = RestartAppPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } /// Handles method calls from the Flutter code. /// /// If the method call is 'restartApp', it requests notification permissions and then sends a /// notification. Finally, it exits the app. public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if call.method == "restartApp" { self.requestNotificationPermissions { granted in if granted { self.sendNotification() } exit(0) } } } /// Requests notification permissions. /// /// This function gets the current notification center and then requests alert notification /// permissions. If the permissions are granted, or if there's an error, it calls the given /// `completion` handler with the appropriate value. private func requestNotificationPermissions(completion: @escaping (Bool) -> Void) { let current = UNUserNotificationCenter.current() current.requestAuthorization(options: [.alert]) { granted, error in if let error = error { print("Error requesting notification permissions: \(error)") completion(false) } else { completion(granted) } } } /// Sends a notification. /// /// This function sets up the notification content and trigger, creates a notification request, /// and then adds the request to the notification center. private func sendNotification() { let content = UNMutableNotificationContent() content.title = "Tap to open the app!" content.sound = nil let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let request = UNNotificationRequest(identifier: "RestartApp", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } }
// // OngDetailViewController.swift // SuCasa // // Created by Arthur Rodrigues on 27/11/19. // Copyright © 2019 João Victor Batista. All rights reserved. // import UIKit import SDWebImage class OngDetailViewController: UIViewController { var ong: Ong! var placeHolderImage = UIImage(named: "waiting") @IBOutlet weak var ongImage: UIImageView! @IBOutlet weak var ongName: UILabel! @IBOutlet weak var location: UILabel! @IBOutlet weak var email: UILabel! @IBOutlet weak var phone: UILabel! override func viewDidLoad() { super.viewDidLoad() setInformations() self.navigationController?.navigationBar.tintColor = Colors.buttonColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.tabBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) tabBarController?.tabBar.isHidden = false } private func setInformations() { ongName.text = ong.name for i in 0 ..< self.ong.url.count { let imageUrl = URL(string: ong.url[i]) ongImage.sd_setImage(with: imageUrl, placeholderImage: placeHolderImage, options: SDWebImageOptions.lowPriority, context: nil, progress: nil) { (downloadedImage, error, cacheType, downloadURL) in if let error = error { print("Error downloading the ong image: \(error.localizedDescription)") } else { print("Successfully downloaded ong image: \(String(describing: downloadURL?.absoluteString))") } } } } }
// // toggleView.swift // Group8Application WatchKit Extension // // Created by roblof-8 on 2021-03-07. // import Foundation import SwiftUI struct ToggleView : View { @State var isChecked: Bool private var firstClick : prepLoad var connection: Connection? let name: String? let id : Int? init(connection : Connection, name : String, id : Int, status : Bool){ self.connection = connection self.name = name self.id = id self.firstClick = prepLoad() if status { _isChecked = State(initialValue: true) } else { _isChecked = State(initialValue: false) } } var body: some View{ Toggle(isOn: $isChecked) { HStack{ Image(systemName: "lightbulb.fill").padding() Text("\(name!)") if isChecked { Text("\(self.turnOn(node: self.id!))") } else{ Text("\(self.turnOff(node: self.id!))") } } } .onAppear(){ self.firstClick.setFinishedLoading() } } //Turn on func func turnOn(node : Int) -> String { if self.firstClick.getLoaded(){ print("ON") sendMsgToPhone(onOff: 1, node: node) return "" } return "" } //Turn off func turnOff(node : Int) -> String { if self.firstClick.getLoaded(){ print("Off") sendMsgToPhone(onOff: 0, node: node) return "" } return "" } func sendMsgToPhone(onOff : Int, node : Int){ guard let connection = connection else {return} var dic = [String : Any]() dic["FIBARO"] = true dic["CODE"] = onOff dic["NODE"] = node connection.send(msg: dic) print("vi är i sendmsg to phone func") } } /* class prepLoad{ var prep: Bool = false func setFinishedLoading() -> String{ self.prep = true print("den e \(self.prep) nu") return "" } func getLoaded() -> Bool{ return self.prep } } */
// // ObjectFile.swift // ARServer // // Created by Denis Zubkov on 11.02.2020. // import Foundation import LoggerAPI import SwiftKuery import SwiftKueryORM struct ObjectFile: Codable { var filename: String? var fileData: Data? var thumbnailData: Data? }
// // SortViewController.swift // property-finder // // Created by iOS Developer on 4/1/19. // Copyright © 2019 Property Finder. All rights reserved. // import UIKit enum SortOption: String { case priceDescending, priceAscending, bedsDescending, bedsAscending var toStringParameter: String { switch self { case .priceDescending: return "pd" case .priceAscending: return "pa" case .bedsDescending: return "bd" case .bedsAscending: return "ba" } } } protocol SortViewControllerDelegate { func didSelectSortOption(sort: SortOption) } final class SortViewController: UIViewController { private var currentChoice: String? var delegate: SortViewControllerDelegate? // MARK: - Buttons actions @IBAction func priceDescendingDidTap() { guard let delegate = delegate else { return } delegate.didSelectSortOption(sort: .priceDescending) } @IBAction func priceAscendingDidTap() { guard let delegate = delegate else { return } delegate.didSelectSortOption(sort: .priceAscending) } @IBAction func bedsDescendingDidTap() { guard let delegate = delegate else { return } delegate.didSelectSortOption(sort: .bedsDescending) } @IBAction func bedsAscendingDidTap() { guard let delegate = delegate else { return } delegate.didSelectSortOption(sort: .bedsAscending) } }
//: [Previous](@previous) import Foundation import UIKit struct animal { } class Person: NSObject { var name = "" var age = 0 required override init() {} } //let xiaoming = Person(name: "小明", age: 10) //let re = Mirror(reflecting: xiaoming) //print(re.children.count) //for (i, item) in re.children.enumerated() { // if let name = item.label, name == "name" { // print(item.value) // // } // if let key = item.label { // print(dict[key]) // } //} extension Dictionary { func convert<D: Person>(to: D) -> D { let model = D.init() let mirror = Mirror(reflecting: model) for (_, item) in mirror.children.enumerated() { if let key = item.label { model.setValue([key], forKey: key) } } return model } } let dict: [String: Any] = ["name": "xiaohong", "age": 20]
// // APIRequest.swift // AstroTest // // Created by Thanh-Tam Le on 9/22/17. // Copyright © 2017 Tam. All rights reserved. // import UIKit class APIRequest: NSObject { private static func dataTask(request: URLRequest, completion: @escaping (_ error: Error?, _ data: Data?) -> ()) { let session = URLSession(configuration: URLSessionConfiguration.default) session.dataTask(with: request) { (data, _, error) -> Void in completion(error, data) }.resume() } static func request(request: URLRequest, completion: @escaping (_ error: Error?, _ data: Data?) -> ()) { dataTask(request: request, completion: completion) } }
// // CoinGlanceInterfaceController.swift // CoinTracker // // Created by Jonathan Crossley on 5/30/15. // Copyright (c) 2015 Razeware LLC. All rights reserved. // import Foundation import WatchKit import CoinKit class CoinGlanceInterfaceController: WKInterfaceController { // 1 @IBOutlet weak var coinImage: WKInterfaceImage! @IBOutlet weak var nameLabel: WKInterfaceLabel! @IBOutlet weak var priceLabel: WKInterfaceLabel! // 2 let helper = CoinHelper() let defaults = NSUserDefaults.standardUserDefaults() override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // 3 let favoriteCoin = defaults.stringForKey("favoriteCoin") ?? "DOGE" // 4 let coins = helper.cachedPrices() for coin in coins { // 5 if coin.name == favoriteCoin { coinImage.setImageNamed(coin.name) nameLabel.setText(coin.name) priceLabel.setText("\(coin.price)") updateUserActivity("com.razeware.CoinTracker.glance", userInfo: ["coin": coin.name], webpageURL: nil) break } } } }
// // TrackTableViewCell.swift // itunes-demo-test // // Created by Ostrenkiy on 12.07.2020. // Copyright © 2020 Ostrenkiy. All rights reserved. // import UIKit import Nuke class TrackTableViewCell: UITableViewCell { @IBOutlet weak var coverImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var artistLabel: 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 setupWith(track: Track) { if let url = URL(string: track.imagePath) { Nuke.loadImage(with: url, into: coverImageView) } titleLabel.text = track.title artistLabel.text = track.artist } }
import XCTest import LayoutConstraintHelpers final class PublicAPITests: XCTestCase { func inits() { #if canImport(UIKit) let view = UIView() #elseif canImport(AppKit) let view = NSView() #endif _ = NSLayoutConstraint(setting: .width, of: view, to: 5) _ = NSLayoutConstraint(setting: .width, of: view, to: 5, relation: .equal) _ = NSLayoutConstraint(setting: .width, of: view, to: 5, multiplier: 1) _ = NSLayoutConstraint(setting: .width, of: view, to: 5, relation: .equal, multiplier: 1) _ = NSLayoutConstraint(for: .width, of: view, matching: view) _ = NSLayoutConstraint(for: .width, of: view, matching: view, relation: .equal) _ = NSLayoutConstraint(for: .width, of: view, matching: view, multiplier: 1) _ = NSLayoutConstraint(for: .width, of: view, matching: view, relation: .equal, multiplier: 1) _ = NSLayoutConstraint(for: .width, of: view, matching: view, relation: .equal, constant: 0) _ = NSLayoutConstraint(for: .width, of: view, matching: view, multiplier: 1, constant: 0) _ = NSLayoutConstraint(for: .width, of: view, matching: view, relation: .equal, multiplier: 1, constant: 0) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view, constant: 0) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view, multiplier: 1) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view, relation: .equal) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view, relation: .equal, constant: 0) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view, relation: .equal, multiplier: 1) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view, multiplier: 1, constant: 0) _ = NSLayoutConstraint(linking: .width, of: view, to: .height, of: view, relation: .equal, multiplier: 1, constant: 0) } func viewExtensions() { #if canImport(UIKit) let view = UIView() #elseif canImport(AppKit) let view = NSView() #endif let size = CGSize(width: 1, height: 2) view.addConstraints(view.constraints(for: size)) view.addConstraints([ view.constraintForAspectRatio(size), view.constraintForAspectRatio(width: 1, height: 2), view.constraint(setting: .width, to: 5), view.constraint(setting: .width, to: 5, relation: .equal), view.constraint(setting: .width, to: 5, multiplier: 1), view.constraint(setting: .width, to: 5, relation: .equal, multiplier: 1), view.constraint(for: .width, matching: view), view.constraint(for: .width, matching: view, relation: .equal), view.constraint(for: .width, matching: view, multiplier: 1), view.constraint(for: .width, matching: view, relation: .equal, multiplier: 1), view.constraint(for: .width, matching: view, relation: .equal, constant: 0), view.constraint(for: .width, matching: view, multiplier: 1, constant: 0), view.constraint(for: .width, matching: view, relation: .equal, multiplier: 1, constant: 0), view.constraint(linking: .width, to: .height, of: view), view.constraint(linking: .width, to: .height, of: view, constant: 0), view.constraint(linking: .width, to: .height, of: view, multiplier: 1), view.constraint(linking: .width, to: .height, of: view, relation: .equal), view.constraint(linking: .width, to: .height, of: view, relation: .equal, constant: 0), view.constraint(linking: .width, to: .height, of: view, relation: .equal, multiplier: 1), view.constraint(linking: .width, to: .height, of: view, multiplier: 1, constant: 0), view.constraint(linking: .width, to: .height, of: view, relation: .equal, multiplier: 1, constant: 0), ]) } static var allTests = [ ("inits", inits), ("viewExtensions", viewExtensions), ] }
// // LoginViewController.swift // ETBAROON // // Created by imac on 8/20/17. // Copyright © 2017 IAS. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class LoginViewController: UIViewController,UITextFieldDelegate,UITextViewDelegate { var user = [User]() @IBOutlet weak var txtEmail: UITextField! @IBOutlet weak var txtPassword: UITextField! override func viewDidLoad() { super.viewDidLoad() // let x = helper.getUserDetail() // print(x ?? "0m") //when click screan let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard)) view.addGestureRecognizer(tap) // Do any additional setup after loading the view. } func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } @IBAction func btnLogin(_ sender: Any) { guard let email = txtEmail.text , !email.isEmpty,let password = txtPassword.text, !password.isEmpty else { let alertController = UIAlertController(title: "Error", message: "ادخل الايميل", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) return } if (!(self.validateEmail(enteredEmail: email)==true)){ let alertController = UIAlertController(title: "Error", message: "الايميل غير صحيح", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil ) return } API.login(fldAppUserEmail: email, fldAppUserPassword: password) { (error: Error?, success: Bool,user:[User]?) in if success { if let user = user { self.user = user let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SWRevealViewController") self.present(viewController, animated: false, completion: nil) let attributedString = NSAttributedString(string: "تم الارسال بنجاح", attributes: [ NSFontAttributeName : UIFont.systemFont(ofSize: 15), //your font here NSForegroundColorAttributeName : UIColor.green ]) let alert = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.alert) alert.setValue(attributedString, forKey: "attributedTitle") alert.addAction(UIAlertAction(title: "موافق", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } else{ let attributedString = NSAttributedString(string: "error in email or password", attributes: [ NSFontAttributeName : UIFont.systemFont(ofSize: 15), //your font here NSForegroundColorAttributeName : UIColor.red ]) let alert = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.alert) alert.setValue(attributedString, forKey: "attributedTitle") alert.addAction(UIAlertAction(title: "موافق", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } }} func validateEmail(enteredEmail:String) -> Bool { let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat) return emailPredicate.evaluate(with: enteredEmail) } //click return func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() //textField.returnKeyType = UIReturnKeyType.done return true } }
/* Copyright 2011-present Samuel GRAU 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. */ // // FluableView : UpdatableTableViewCell.swift // import Foundation /** - author: Samuel GRAU, 16-03-02 22:03:47 The protocol for a cell that could be updated. Cells that implement this protocol are given the object that implemented the AVNICellObject protocol and returned this cell's class name in @link AVNICellObject::cellClass cellClass@endlink. */ public protocol UpdatableTableViewCell { /** Called when a cell is created and reused. Implement this method to customize the cell's properties for display using the given object. - parameter object: the object model used to update the view - parameter indexPath: the location of that cell in the tableview - returns: `true` if the update is needed, otherwise returns `false` */ func shouldUpdateCellWithObject(object: TableCellObject, indexPath: NSIndexPath) -> Bool /** Called when a cell is created and reused. Implement this method to customize the cell's properties for display using the given object. - parameter object: the object model used to update the viez - parameter indexPath: the location of that cell in the tableview - returns: `true` if the update is needed, otherwise returns `false` */ func updateCellWithObject(object: TableCellObject, indexPath: NSIndexPath) /** Asks the receiver whether the mapped object class should be appended to the reuse identifier in order to create a unique cell.object identifier key. This is useful when you have a cell that is intended to be used by a variety of different objects. - returns: `true` if the reuse identifier should be appended by the class name, otherwise returns `false`. */ static func shouldAppendObjectClassToReuseIdentifier() -> Bool /** Asks the receiver to calculate its height. - parameter object: the object model used to update the view - parameter indexPath: the index path of the object - parameter tableView: the table view targeted by the height computation - returns: the height in points */ static func heightForObject(object: TableCellObject, atIndexPath indexPath: NSIndexPath, tableView: UITableView) -> CGFloat }
// // CCTBorderButton.swift // EFI // // Created by LUIS ENRIQUE MEDINA GALVAN on 7/24/18. // Copyright © 2018 LUIS ENRIQUE MEDINA GALVAN. All rights reserved. // import AsyncDisplayKit class CCTBorderButtonNode:ASButtonNode { init(fontSize:Float,textColor:UIColor,with text:String) { super.init() setTitle(text, with: UIFont.boldSystemFont(ofSize: CGFloat(fontSize)), with: textColor, for: .normal) cornerRadius = 10 clipsToBounds = true contentEdgeInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) } }
// // KeyedEncodingContainer+DateFormat.swift // // // Created by Vladislav Fitc on 29/05/2020. // import Foundation extension KeyedEncodingContainer { mutating func encode(_ date: Date, forKey key: K, dateFormat: String) throws { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat let rawDate = dateFormatter.string(from: date) try encode(rawDate, forKey: key) } mutating func encodeIfPresent(_ date: Date?, forKey key: K, dateFormat: String) throws { guard let date = date else { return } let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat let rawDate = dateFormatter.string(from: date) try encode(rawDate, forKey: key) } }
// // BabyModeViewController.swift // Alarm For Children // // Created by Huijing on 25/01/2017. // Copyright © 2017 Huijing. All rights reserved. // import UIKit import MASSDK class BabyModeViewController: BaseViewController { @IBOutlet weak var btnBabyModeStatus: UIButton! @IBOutlet weak var btnBack: UIButton! @IBOutlet weak var imvBack: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var suggestionLabel: UILabel! @IBOutlet weak var suggestionDetailLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. titleLabel.text = NSLocalizedString("Baby Mode", comment: "") suggestionLabel.text = NSLocalizedString("Suggestion", comment: "") suggestionDetailLabel.text = NSLocalizedString("To reduce the possibility of interruption, it is recommended to enable Airplane Mode.\n\nIf you press the start button, you will be redirected to the System Settings", comment: "") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { if self.navigationController?.viewControllers.count == 1 { btnBack.isHidden = true imvBack.isHidden = true self.navigationController?.isNavigationBarHidden = false } else{ self.navigationController?.isNavigationBarHidden = true btnBack.isHidden = false imvBack.isHidden = false imvBack.setImageWith(color: UIColor.white) } setButtonStatus() } override func appDidEnterForeground() { setButtonStatus() } @IBAction func backButtonTapped(_ sender: Any) { _ = self.navigationController?.popViewController(animated: true) } @IBAction func babyModeStatusButtonTapped(_ sender: Any) { UIApplication.shared.openURL(URL(string:UIApplicationOpenSettingsURLString)!) } func setButtonStatus() { if (Settings.getAirplaneStatus()){ btnBabyModeStatus.backgroundColor = UIColor(colorLiteralRed: 173.0 / 255.0, green: 37.0 / 255.0 , blue: 36.0 / 255.0, alpha: 1) btnBabyModeStatus.setTitle(NSLocalizedString("STOP", comment: ""), for: .normal) } else{ btnBabyModeStatus.backgroundColor = UIColor(colorLiteralRed: 72.0 / 255.0, green: 142.0 / 255.0 , blue: 42.0 / 255.0, alpha: 1) btnBabyModeStatus.setTitle(NSLocalizedString("START", comment: ""), for: .normal) } } }
// // settingCell.swift // 闲鱼界面搭建 // // Created by tusm on 2016/11/7. // Copyright © 2016年 cleven. All rights reserved. // import UIKit class settingCell: UITableViewCell { public var item:[String:AnyObject]?{ didSet{ guard let item = item else { return } self.textLabel?.text = item["title"] as? String self.textLabel?.textColor = UIColor.blue if ((item["icon"]) != nil) { self.imageView?.image = UIImage(named: item["icon"] as! String) } if ((item["details"]) != nil) { self.detailTextLabel?.text = item["details"] as? String self.detailTextLabel?.textColor = UIColor.red } //判断这个类是不是UIimageView if (item["accessory"] as! String == "UIImageView") { let imageView = UIImageView.init() imageView.image = UIImage(named: item["accessory_img"] as! String) imageView.sizeToFit() accessoryView = imageView }else if (item["accessory"] as! String == "UISwitch"){ let swc = UISwitch.init() swc.addTarget(self, action: #selector(clickSwitch(swc:)), for: .valueChanged) accessoryView = swc } } } @objc private func clickSwitch(swc:UISwitch){ print(swc.isOn) } } extension settingCell { //MARK: 创建cell的方法 public class func setCellWithTableView(tableView:UITableView,item:[String:AnyObject])->UITableViewCell{ var cell = tableView.dequeueReusableCell(withIdentifier: "set_cell") if cell == nil { cell = settingCell.init(style: cellStyleWithText(cellStyle: item["cell_style"] as! String), reuseIdentifier: "set_cell") } if ((item["is_highlighted"]) != nil) { cell?.detailTextLabel?.textColor = UIColor.red } return cell! } //MARK: 按照plist加载cell样式 fileprivate class func cellStyleWithText(cellStyle:String)->UITableViewCellStyle{ if cellStyle == "UITableViewCellStyleDefault"{ return .default }else if cellStyle == "UITableViewCellStyleValue1"{ return .value1 }else if cellStyle == "UITableViewCellStyleValue2"{ return .value2 }else{ return .subtitle } } }
// // MNTitle.swift // Moon // // Created by YKing on 16/5/21. // Copyright © 2016年 YKing. All rights reserved. // import Foundation class MNTitle: NSObject { var title:String? var enable:Bool = false class func initWithTitle(_ title:String) -> MNTitle { let mntitle = MNTitle() mntitle.title = title return mntitle } }
// // View2Controller.swift // SnapkitTest // // Created by kangsik choi on 2017. 6. 18.. // Copyright (c) 2017 choiks14. All rights reserved. // import Foundation import Foundation import UIKit class View2Controller: UIViewController { var didSetupConstraints = false let redView: UIView = { let view = UIView() view.backgroundColor = UIColor.red return view }() let blueView: UIView = { let view = UIView() view.backgroundColor = UIColor.blue return view }() let greenView: UIView = { let view = UIView() view.backgroundColor = UIColor.green return view }() let blackView: UIView = { let view = UIView() view.backgroundColor = UIColor.black return view }() override func viewDidLoad() { super.viewDidLoad() self.initUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } static func instance() -> View2Controller { let vc = View2Controller() return vc } } //snapkit extension View2Controller { func initUI() { self.view.backgroundColor = .white self.view.addSubview(self.redView) self.view.addSubview(self.greenView) self.view.addSubview(self.blackView) self.view.addSubview(self.blueView) view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if (!didSetupConstraints) { /* red | blue green | black */ redView.snp.makeConstraints { (make) in let multipler = 1.0 / 2.0 make.width.equalTo(self.view).multipliedBy(multipler) make.height.equalTo(self.view).multipliedBy(multipler) make.top.equalTo(self.view) make.left.equalTo(self.view) } blueView.snp.makeConstraints { (make) in let multipler = 1.0 / 2.0 make.width.equalTo(self.view).multipliedBy(multipler) make.height.equalTo(self.view).multipliedBy(multipler) make.top.equalTo(self.view) make.right.equalTo(self.view) } greenView.snp.makeConstraints { (make) in let multipler = 1.0 / 2.0 make.width.equalTo(self.view).multipliedBy(multipler) make.height.equalTo(self.view).multipliedBy(multipler) make.bottom.equalTo(self.view) make.right.equalTo(self.view) } blackView.snp.makeConstraints { (make) in let multipler = 1.0 / 2.0 make.width.equalTo(self.view).multipliedBy(multipler) make.height.equalTo(self.view).multipliedBy(multipler) make.bottom.equalTo(self.view) make.left.equalTo(self.view) } didSetupConstraints = true } super.updateViewConstraints() } }
import MapKit final class Map: MKMapView { }
// // SettingLiveTests.swift // Tests // // Created by Mederic Petit on 10/11/2017. // Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved. // import OmiseGO import XCTest class SettingLiveTests: LiveClientTestCase { func testGetSettings() { let expectation = self.expectation(description: "Setting result") let request = Setting.get(using: self.testClient) { result in defer { expectation.fulfill() } switch result { case let .success(setting): XCTAssert(!setting.tokens.isEmpty) case let .fail(error): XCTFail("\(error)") } } XCTAssertNotNil(request) waitForExpectations(timeout: 15.0, handler: nil) } }
// // ScreenMeet.swift // ScreenMeetSDK // // Created by Vasyl Morarash on 26.08.2020. // import Foundation // MARK: Main /// Main class to work with ScreenMeet SDK public final class ScreenMeet { private var presenter: SessionPresenterIn private lazy var lifecycleListeners = [WeakLifecycleListener]() private lazy var sessionEventListeners = [WeakSessionEventListener]() private var isSessionPaused: Bool = false private init() { let presenter = SessionPresenter() self.presenter = presenter let interactor = SessionInteractor() presenter.interactor = interactor interactor.presenter = presenter UIDevice.current.isBatteryMonitoringEnabled = true NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil) } @objc private func applicationDidEnterBackground() { isSessionPaused = session?.lifecycleState == .pause session?.pause() } @objc private func applicationWillEnterForeground() { guard isSessionPaused == false else { return } session?.resume() } /// Returns singleton instance of ScreenMeet public static let shared = ScreenMeet() /// Allow to configure ScreenMeet framework public let config = Config() /// Implement ScreenMeetUI protocol to use own UI elements public var interface: ScreenMeetUIProtocol { get { presenter as! ScreenMeetUIProtocol } set { presenter.interface = newValue } } /// Local video source public var localVideoSource: LocalVideoSource = AppStreamVideoSource() /// Allow to manage session public var session: Session? /// Starts ScreenMeet session. No code specified, user will be asked to enter code value /// - Parameter code: Identify session created by agent /// - Parameter completion: Session if success. Error if fails (see `ScreenMeet.Session.SessionError`) public func connect(code: String, completion: @escaping (Result<Session, Session.SessionError>) -> Void) { if let session = session { completion(.success(session)) return } let session = Session() self.session = session presenter.connectSession(sessionCode: code, success: { session.lifecycleState = .streaming completion(.success(session)) }, failure: { [weak self] (error) in self?.session = nil completion(.failure(error)) }) } /// Stops ScreenMeet session. public func disconnect() { presenter.disconnectSession() } /// Allow to register lifecycle listener public func registerLifecycleListener<T: LifecycleListener>(_ lifecycleListener: T) { guard self.lifecycleListeners.contains(where: { $0.value?.lid == lifecycleListener.lid }) == false else { return } self.lifecycleListeners.append(WeakLifecycleListener(lifecycleListener)) } /// Allow to unregister lifecycle listener public func unregisterLifecycleListener<T: LifecycleListener>(_ lifecycleListener: T) { guard let index = self.lifecycleListeners.firstIndex(where: { $0.value?.lid == lifecycleListener.lid }) else { return } self.lifecycleListeners.remove(at: index) } /// Allow to register session event listener public func registerSessionEventListener<T: SessionEventListener>(_ sessionEventListener: T) { guard self.sessionEventListeners.contains(where: { $0.value?.sid == sessionEventListener.sid }) == false else { return } self.sessionEventListeners.append(WeakSessionEventListener(sessionEventListener)) } /// Allow to unregister session event listener public func unregisterSessionEventListener<T: SessionEventListener>(_ sessionEventListener: T) { guard let index = self.sessionEventListeners.firstIndex(where: { $0.value?.sid == sessionEventListener.sid }) else { return } self.sessionEventListeners.remove(at: index) } } // MARK: Session extension ScreenMeet { /// Represents a session with the ScreenMeet backend services. public final class Session { fileprivate init() { } /// Retrieve the current state of the session. public var lifecycleState: State = .inactive /// The owner of this session. The owner may or may not ultimately join this session as a participant. public var ownerName: String? /// Return the set of other participants in this session. public var participants = [Participant]() /// Pauses any streaming on the current session public func pause() { guard lifecycleState == .streaming else { return } ScreenMeet.shared.presenter.pauseStream() } /// Resumes streaming on the current session public func resume() { guard lifecycleState == .pause else { return } ScreenMeet.shared.presenter.resumeStream() } /// Represents the state of a session public enum State { case streaming /// Session stream is acvive case inactive /// Session stream is not started or already stopped case pause /// Session is active but stream is paused public enum StreamingReason { case sessionResumed } public enum InactiveReason { case terminatedLocal case terminatedServer } public enum PauseReason { case sessionPaused } } /// Describes session participant public struct Participant: Equatable { /// UID of participant public var id: String /// Participant name public var name: String /// Equatable by participant UID public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.id == rhs.id } } /// The actions that may happen for a participant public enum ParticipantAction { /// The participant was added case added /// The participant was removed case removed /// The audio was muted for the participant case audioMuted /// The audio was unmuted for the participant case audioUnmuted } /// Describes reason why session can't be started public enum SessionError: Error { /// Incorrect session code or expired session code case incorrectSessionCode /// Can't connect to server case connectionTimeout /// Incorrect session code or expired session code case sessionNotFound /// Session with specified code already started case sessionAlreadyConnected /// Wrong organization key (mobileKey) value case incorrectOrganizationKey /// Can't start capturing or user disallowed screen capturing case captureFailed } } } /// ScreenMeet Configuration extension ScreenMeet { /// ScreenMeet Configuration open class Config { /// Organization key to access API open var organizationKey: String? = nil /// Initial connection endpoint/port open var endpoint: URL = URL(string: "https://api-v3.screenmeet.com/v3/")! /// Additional parameters to configure framework open var parameters: [String: Any] = [:] /// Represent the severity and importance of log messages ouput (`.info`, `.debug`, `.error`, see `LogLevel`) open var loggingLevel: LogLevel = .error { didSet { switch loggingLevel { case .info: Logger.log.level = .info case .debug: Logger.log.level = .debug case .error: Logger.log.level = .error } } } /// Represent the severity and importance of any particular log message. public enum LogLevel { /// Information that may be helpful, but isn’t essential, for troubleshooting errors case info /// Verbose information that may be useful during development or while troubleshooting a specific problem case debug /// Designates error events that might still allow the application to continue running case error } /// HTTP connection timeout. Provided in seconds. Default 30s. open var httpTimeout: TimeInterval = 30 { didSet { if httpTimeout < 0 { httpTimeout = 30 } } } /// HTTP connection retry number. Default 5 retries. open var httpNumRetry: Int = 5 { didSet { if httpNumRetry < 0 { httpNumRetry = 5 } } } /// Socket connection timeout. Provided in seconds. Default 20s. open var socketConnectionTimeout: TimeInterval = 20 { didSet { if socketConnectionTimeout < 0 { socketConnectionTimeout = 20 } } } /// Socket connection retry number. Default 5 retries. open var socketConnectionNumRetries: Int = 5 { didSet { if socketConnectionNumRetries < 0 { socketConnectionNumRetries = 5 } } } /// Socket reconnection retry number. Default unlimited retries. For unlimited set -1. open var socketReconnectNumRetries: Int = -1 { didSet { if socketReconnectNumRetries < -1 { socketReconnectNumRetries = -1 } } } /// Socket reconnection delay. Provided in seconds. Default 0s. open var socketReconnectDelay: TimeInterval = 0 { didSet { if socketReconnectDelay < 0 { socketReconnectDelay = 0 } } } /// WebRTC connection timeout. Provided in seconds. Default 60s. open var webRtcTimeout: TimeInterval = 60 { didSet { if webRtcTimeout < 0 { webRtcTimeout = 60 } } } /// WebRTC connection retry number. Default 5 retries. open var webRtcNumRetries: Int = 5 { didSet { if webRtcNumRetries < 0 { webRtcNumRetries = 5 } } } } } // MARK: Events extension ScreenMeet { func disconnectStreamEvent() { self.lifecycleListeners.networkDisconnect() } func reconnectStreamEvent() { self.lifecycleListeners.networkReconnect() } func pauseStreamEvent() { guard let session = session else { return } self.lifecycleListeners.onPause(oldState: session.lifecycleState, pauseReason: .sessionPaused) self.session?.lifecycleState = .pause } func resumeStreamEvent() { guard let session = session else { return } self.lifecycleListeners.onStreaming(oldState: session.lifecycleState, streamingReason: .sessionResumed) self.session?.lifecycleState = .streaming } func terminatedLocalEvent() { guard let session = session else { return } self.lifecycleListeners.onInactive(oldState: session.lifecycleState, inactiveReason: .terminatedLocal) self.session = nil } func terminateEvent() { guard let session = session else { return } self.lifecycleListeners.onInactive(oldState: session.lifecycleState, inactiveReason: .terminatedServer) self.session = nil } func joinParticipantEvent(participant: Session.Participant) { self.session?.participants.removeAll(where: { $0.id == participant.id }) self.session?.participants.append(participant) self.sessionEventListeners.onParticipantAction(participant: participant, participantAction: .added) } func leftParticipantEvent(participant: Session.Participant) { self.session?.participants.removeAll(where: { $0.id == participant.id }) self.sessionEventListeners.onParticipantAction(participant: participant, participantAction: .removed) } } // MARK: Static methods extension ScreenMeet { /// ScreenMeet SDK version /// - Returns: ScreenMeet SDK version public static func version() -> String { let bundle = Bundle(identifier: "org.cocoapods.ScreenMeetSDK") let version = bundle?.infoDictionary?["CFBundleShortVersionString"] ?? "" let build = bundle?.infoDictionary?["CFBundleVersion"] ?? "" return "\(version) (\(build))" } }
import SwiftUI struct Home: View { @EnvironmentObject var appState: AppState @EnvironmentObject var homeViewModel: HomeViewModel @EnvironmentObject var filterViewModel: FilterViewModel @State private var currentPost: Int = 0 @Binding var showNav : Bool @State private var offset: CGSize = .zero @State private var didJustSwipe = false var body: some View { ZStack(alignment: .topLeading) { PagerView(showNav: $showNav,currentPost: self.$currentPost).environmentObject(homeViewModel).edgesIgnoringSafeArea(.all).environmentObject(filterViewModel) //SwiperView(posts: self.posts, currentPost: self.$currentPost) .edgesIgnoringSafeArea(.all) Rectangle() .fill(LinearGradient(gradient: Gradient(colors: [Color.black.opacity(0.7), Color.black.opacity(0.0)]), startPoint: .top, endPoint: .bottom)) .frame(height: 140) .edgesIgnoringSafeArea(.top) CarouselView().padding(.top,50) } } }
// // CalculateBitDifference.swift // BitManipulation // // Created by Preet on 2019-04-15. // Copyright © 2019 Preetinder Marok. All rights reserved. // import Foundation struct Calculate { func bitSwapCount(x: Int, y: Int) -> Int { // Find different bits let signedDifferentBits = x ^ y // Bitcast Int to UInt to allow the algorithm work correctly also for negative numbers. var differentBits: UInt = UInt(bitPattern: signedDifferentBits) // Count the bits var count = 0 // Until there are some bits set to '1' in differentBits. while differentBits > 0 { // Mask differentBits with number 1 aka 00000001. // By doing this, we set all bits of differentBits // but the last one to zero. let maskedBits = differentBits & 1 // If the last bit is not zero, if maskedBits != 0 { // increment the counter. count += 1 } // Shift bits in differentBits to the right. differentBits = differentBits >> 1 } // return the number of 1s we've found. return count } }
// // HeapTests.swift // DataStructures // // Created by Yuri Gorokhov on 11/14/14. // Copyright (c) 2014 Yuri Gorokhov. All rights reserved. // import Cocoa import XCTest class HeapTests: XCTestCase { func Heap_peek_returns_nil_when_empty() { // Arrange let h = MinHeap<Int>() // Assert XCTAssertNil(h.Peek(), "peek should have returned nil") } func Heap_peek_returns_minimum() { // Arrange let h = MinHeap<Int>(fromArray: [4,3,2,1]) // Assert XCTAssertEqual(1, h.Peek()!, "peek should have returned 1") } }
import UIKit import GrouviActionSheet class SendConfirmationAlertModel: BaseAlertModel { private let viewItem: SendConfirmationViewItem private let titleItem: SendTitleItem private let amountItem: SendConfirmationAmounItem private let addressItem: SendConfirmationAddressItem private let feeItem: SendConfirmationValueItem private let totalItem: SendConfirmationValueItem private let sendButtonItem: SendButtonItem var onCopyAddress: (() -> ())? init(viewItem: SendConfirmationViewItem) { self.viewItem = viewItem titleItem = SendTitleItem(tag: 0) amountItem = SendConfirmationAmounItem(viewItem: viewItem, tag: 1) addressItem = SendConfirmationAddressItem(address: viewItem.address, tag: 2) feeItem = SendConfirmationValueItem(title: "send.fee".localized, amountInfo: viewItem.feeInfo, tag: 3) totalItem = SendConfirmationValueItem(title: "send.total".localized, amountInfo: viewItem.totalInfo, tag: 4) sendButtonItem = SendButtonItem(buttonTitle: "alert.confirm".localized, tag: 5) super.init() hideInBackground = false addItemView(titleItem) addItemView(amountItem) addressItem.onHashTap = { [weak self] in self?.onCopyAddress?() } addItemView(addressItem) addItemView(feeItem) addItemView(totalItem) sendButtonItem.onClicked = { [weak self] in self?.dismiss?(true) } addItemView(sendButtonItem) } override func viewWillAppear(_ animated: Bool) { titleItem.bindCoin?(viewItem.coin) } }
// // FullTableScan.swift // epiphanyquickpicker // // Created by Yaniv Silberman on 2016-02-11. // Copyright © 2016 Yaniv Silberman. All rights reserved. // // EQ = Equal // LE = Less than or equal // LT = Less than // GE = Greater than or Equal // GT = Greater than // BEGINS_WITH = checks for prefix // BETWEEN = between or equal to one of two values import Foundation import AWSCore import AWSDynamoDB import Bolts import GameKit import FLAnimatedImage import SVProgressHUD import Async class FullTableScan { // INPUT: "String" of UserId that isn't you // OUTPUT: Looks for gifs you placed in the OnHoldTable and returns them var scanCond = AWSDynamoDBCondition() var scanV1 = AWSDynamoDBAttributeValue() var scanExp = AWSDynamoDBScanExpression() init(chiefId: String){ scanV1.S = chiefId scanCond.comparisonOperator = AWSDynamoDBComparisonOperator.BeginsWith scanCond.attributeValueList = [ scanV1 ] scanExp.scanFilter = [ "chiefId" : scanCond ] } func scan(expression : AWSDynamoDBScanExpression) -> AWSTask! { let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper() return mapper.scan(AWSGif.self, expression: expression) } } func scanTheFuckingTable(gifView: FLAnimatedImageView){ // INPUT: gifView, Cognito ID "String", chiefId.otherChiefs, TableScan Class // OUTPUT: Scans OnHold, if Found - Queries found ID, sets as newAWSGif // if Not Found - Updates Tables and Submit Mode, Runs GetGiphyAPI Function let RN = GKRandomSource.sharedRandom().nextIntWithUpperBound(thisChief.otherChiefs.count) newGifTables.update(.OnHoldTable) UIApplication.sharedApplication().networkActivityIndicatorVisible = true let newTableScan: FullTableScan = FullTableScan(chiefId: thisChief.otherChiefs[RN]) newTableScan.scan(newTableScan.scanExp).continueWithSuccessBlock({ (task: AWSTask!) -> AWSTask! in NSLog("Scan multiple values - success") UIApplication.sharedApplication().networkActivityIndicatorVisible = false let results = task.result as! AWSDynamoDBPaginatedOutput if (results.items.isEmpty == true){ NSLog("Getting Gif from Giphy") newGifSubmitMode.update(.onHoldMode) newGifTables.update(.OnHoldTable) getGiphyAPI(gifView) } else { let r = results.items[0] //for r in results.items { NSLog("Getting Gif from OnHold for Gifs Table") let newGif = r as? AWSGif newAWSGif = newGif! NSLog(newAWSGif.gifId!) newGifSubmitMode.update(.inputMode) newGifTables.update(.OnHoldTable) Async.main{ loadGifView(newAWSGif, gifView: gifView) newGifSubmitMode.update(.inputMode) } } //} return nil }) }
// // LoadController.swift // Seeing-Behind-Alpha // // Created by lyjtour on 4/1/18. // Copyright © 2018 lyjtour. All rights reserved. // import UIKit import NVActivityIndicatorView class LoadController: UIViewController{ //@IBOutlet weak var indicator: NVActivityIndicatorView! //@IBOutlet weak var indicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() //Loading Animation let frame = CGRect(x: 107, y: 249, width: 128, height: 128) let indicator = NVActivityIndicatorView(frame: frame, type: NVActivityIndicatorType(rawValue: 12)!) indicator.color = UIColor(red: CGFloat(237 / 255.0), green: CGFloat(85 / 255.0), blue: CGFloat(101 / 255.0), alpha: 1) view.addSubview(indicator) indicator.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true indicator.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true indicator.startAnimating() print(indicator.isAnimating) DispatchQueue.main.async { var session: NMSSHSession = NMSSHSession (host:host_url, andUsername:username) session.connect() if (session.isConnected) { session.authenticate(byPassword: password) if (session.isAuthorized) { NSLog("Authentication succeeded"); } } else{ print("error") } var error: NSError? = nil var response: String! = session.channel.execute("sudo motion", error: &error, timeout: 10) //var response: String! = session.channel.execute("mkdir", error: &error, timeout: nil) print("List of my sites: ", response) //var BOOL success = [session.channel uploadFile:@"~/index.html" to:@"/var/www/9muses.se/"]; session.disconnect() print("give Pi time to sudo motion") usleep(2000000) print("done with starting") indicator.stopAnimating() self.performSegue(withIdentifier: "autoShowMenu", sender: self) } print("jump") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ }
// // WorkoutSchema.swift // Workout Tracker // // Created by Sam Paterson on 16/01/21. // import Foundation class Workout{ var id: Int; var name: String; var seqNo: Int; //var exercises: [Exercise] init(id: Int){ //call database to load schema from id self.id = id; self.name = ""; //temp self.seqNo = 0; //temp //self.exercises = self.LoadExercises(workoutId: id); } // func LoadExercises(workoutId: Int) -> [Exercise]{ // //load all exerises from link table // } }
// // Request.swift // // // Created by Alejandro Castillejo on 9/16/17. // // import Foundation enum RequestNeed: Int { case nineOneOne = 0 case FIRSTAID = 1 case EVACUATION = 2 case WATER = 3 case FOOD = 4 case PHONECHARGE = 5 case LIGHTS = 6 case MEDICATION = 7 case CLOTHING = 8 var description: String { switch self { case .nineOneOne: return "🍴" case .FIRSTAID: return "⛑" case .EVACUATION: return "🚁" case .WATER: return "💧" case .FOOD: return "🍴" case .PHONECHARGE: return "🔋" case .LIGHTS: return "🔦" case .MEDICATION: return "💊" case .CLOTHING: return "👖" } } var longDescription: String { switch self { case .nineOneOne: return "Food" case .FIRSTAID: return "First Aid" case .EVACUATION: return "Evacuation" case .WATER: return "Water" case .FOOD: return "🍴" case .PHONECHARGE: return "Phone Charge" case .LIGHTS: return "Lights" case .MEDICATION: return "Medication" case .CLOTHING: return "Clothing" } } } enum RequestStatus: Int { case Available = 0 case Claimed = 1 case Completed = 2 // var description: String { // switch self { // case .RequestEmoji0: // return "🤗" // case .RequestEmoji1: // return "👍" // } // } } class Request:NSObject { let id:Int let latitude:Float let longitude:Float let name:String let dateCreated:Date let needs:[RequestNeed] let status: RequestStatus let personDescription: String init(id:Int, latitude:Float, longitude:Float, name:String, dateCreated:Date, needs:[RequestNeed], status:RequestStatus, personDescription:String) { self.id = id self.latitude = latitude self.longitude = longitude self.name = name self.dateCreated = dateCreated self.needs = needs self.status = status self.personDescription = personDescription } static func serialize(dictionary:Dictionary<String,Any>) -> Request? { // print(sessionDictionary) if let id = dictionary["pk"] as? Int { if let longitude = dictionary["longitude"] as? Float { if let latitude = dictionary["latitude"] as? Float { if let name = dictionary["name"] as? String { if let dateString = dictionary["created_on"] as? String { let date = Date() if let personDescription = dictionary["message"] as? String { if let status = dictionary["status"] as? Int { let requestStatus = RequestStatus.init(rawValue: status) var needsArray:[RequestNeed] = [] if let needs = dictionary["needs"] as? Array<Any> { for need in needs { if let need = need as? Dictionary<String, Int> { needsArray.append(RequestNeed.init(rawValue: need["need"]!)!) // print(need) } } } return Request(id: id, latitude: latitude, longitude: longitude, name: name, dateCreated: date, needs:needsArray, status:requestStatus!, personDescription:personDescription) } } } } } } } return nil } }
// // ViewController.swift // stackViewPractice // // Created by Jeewoo Chung on 7/9/19. // Copyright © 2019 Jeewoo Chung. All rights reserved. // import UIKit class ViewController: UIViewController { let imageView11: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView12: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView13: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView21: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView22: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView23: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView31: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView32: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() let imageView33: UIImageView = { let main = UIImageView(image: UIImage(named: "Carbon")) main.translatesAutoresizingMaskIntoConstraints = false main.contentMode = .scaleAspectFit return main }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.addSubview(imageView11) view.addSubview(imageView12) view.addSubview(imageView13) let stackView1 = UIStackView(arrangedSubviews: [ imageView11, imageView12, imageView13 ]) stackView1.translatesAutoresizingMaskIntoConstraints = false stackView1.axis = .horizontal stackView1.alignment = .center stackView1.spacing = 10 stackView1.distribution = .fillEqually view.addSubview(stackView1) view.addSubview(imageView21) view.addSubview(imageView22) view.addSubview(imageView23) let stackView2 = UIStackView(arrangedSubviews: [ imageView21, imageView22, imageView23 ]) stackView2.translatesAutoresizingMaskIntoConstraints = false stackView2.axis = .horizontal stackView2.alignment = .center stackView2.spacing = 10 stackView2.distribution = .fillEqually view.addSubview(stackView2) view.addSubview(imageView31) view.addSubview(imageView32) view.addSubview(imageView33) let stackView3 = UIStackView(arrangedSubviews: [ imageView31, imageView32, imageView33 ]) stackView3.translatesAutoresizingMaskIntoConstraints = false stackView3.axis = .horizontal stackView3.alignment = .center stackView3.spacing = 10 stackView3.distribution = .fillEqually view.addSubview(stackView3) let masterStackView = UIStackView(arrangedSubviews: [ stackView1, stackView2, stackView3 ]) masterStackView.translatesAutoresizingMaskIntoConstraints = false masterStackView.axis = .vertical masterStackView.alignment = .center masterStackView.spacing = 10 masterStackView.distribution = .fillEqually view.addSubview(masterStackView) NSLayoutConstraint(item: masterStackView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: masterStackView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: masterStackView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 0.8, constant: 0).isActive = true NSLayoutConstraint(item: masterStackView, attribute: .height, relatedBy: .equal, toItem: masterStackView, attribute: .width, multiplier: 1, constant: 0).isActive = true } }
// Add your code below 👇 // Add your code above 👆 /*: #### Make the following code compile Don't edit the following code block or wrap it in a comment block /\* *\/ 😉 --- */ func raw<T: RawRepresentable>(t: T) -> T.RawValue { return t.rawValue } let array : [E] = [.A(true), .B(1), .C("C")] array.map(raw) if case .C(let s?)? = array.first {} // Bonus: for elem in array { switch elem { case .C(_): print("C!") } } /*: --- After making the previous code block compile, the syntax highlighting (Dusk Theme) should match this picture: ![Picture](Picture.png) */
// // WatchFace.swift // Nightscouter // // Created by Peter Ina on 6/25/15. // Copyright (c) 2015 Peter Ina. All rights reserved. // import Foundation extension EntryPropertyKey { static let statusKey = "status" static let nowKey = "now" static let bgsKey = "bgs" static let bgdeltaKey = "bgdelta" static let trendKey = "trend" static let datetimeKey = "datetime" static let batteryKey = "battery" static let iob = "iob" // Not implmented yet. } public class WatchEntry: Entry, CustomStringConvertible { public var now: NSDate public var bgdelta: Double public let battery: Int public var batteryString: String { get{ // Convert int from JSON into a proper precentge. let percentage = Float(battery)/100 let numberFormatter: NSNumberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .PercentStyle numberFormatter.zeroSymbol = "---%" return numberFormatter.stringFromNumber(percentage)! } } public var batteryColorState: DesiredColorState { if battery < 50 && battery > 20 { return DesiredColorState.Warning } else if battery <= 20 && battery > 1 { return DesiredColorState.Alert } return DesiredColorState.Neutral } public var raw: Double? { if let sgValue:SensorGlucoseValue = self.sgv, calValue = self.cal { let raw: Double = sgValue.rawIsigToRawBg(calValue) return sgValue.sgv.isInteger ? round(raw) : raw } return nil } public var description: String { return "WatchEntry: { \(dictionary.description) }" } public init(identifier: String, date: NSDate, device: Device, now: NSDate, bgdelta: Double, battery: Int) { self.now = now self.bgdelta = bgdelta self.battery = battery super.init(identifier: identifier, date: date, device: device) } } public extension WatchEntry { public convenience init(watchEntryDictionary: [String : AnyObject]) { let rootDictionary: NSMutableDictionary = NSMutableDictionary() let device = Device.WatchFace for (key, obj) in watchEntryDictionary { if let array = obj as? [AnyObject] { if let objDict: NSDictionary = array.first as? NSDictionary { rootDictionary["\(key)"] = objDict } } } var nowDouble: Double = 0 if let statusDictionary = rootDictionary[EntryPropertyKey.statusKey] as? NSDictionary, now = statusDictionary[EntryPropertyKey.nowKey] as? Double { nowDouble = now } // Blood glucose object var direction = Direction.None var sgv: Double = 0 var filtered = 0 var unfiltlered = 0 var noise: Noise = .None var bgdelta: Double = 0 var batteryInt: Int = 0 var datetime: Double = 0 if let bgsDictionary = rootDictionary[EntryPropertyKey.bgsKey] as? NSDictionary { if let directionString = bgsDictionary[EntryPropertyKey.directionKey] as? String, directionType = Direction(rawValue: directionString), sgvString = bgsDictionary[EntryPropertyKey.sgvKey] as? String { direction = directionType if let sgvDouble = sgvString.toDouble { sgv = sgvDouble } } if let opFiltered = bgsDictionary[EntryPropertyKey.filteredKey] as? Int, opUnfiltlered = bgsDictionary[EntryPropertyKey.unfilteredKey] as? Int { filtered = opFiltered unfiltlered = opUnfiltlered } if let opNoiseInt = bgsDictionary[EntryPropertyKey.noiseKey] as? Int, opNoise = Noise(rawValue: opNoiseInt) { noise = opNoise } if let bgdeltaString = bgsDictionary[EntryPropertyKey.bgdeltaKey] as? String { bgdelta = bgdeltaString.toDouble! } if let bgdeltaNumber = bgsDictionary[EntryPropertyKey.bgdeltaKey] as? Double { bgdelta = bgdeltaNumber } if let batteryString = bgsDictionary[EntryPropertyKey.batteryKey] as? String { if let batInt = Int(batteryString) { batteryInt = batInt } } if let datetimeDouble = bgsDictionary[EntryPropertyKey.datetimeKey] as? Double { datetime = datetimeDouble } } // cals object var cals: NSDictionary = NSDictionary() if let opCals: NSDictionary = rootDictionary[EntryPropertyKey.calsKey] as? NSDictionary { cals = opCals } guard let slope = cals[EntryPropertyKey.slopeKey] as? Double, intercept = cals[EntryPropertyKey.interceptKey] as? Double, scale = cals[EntryPropertyKey.scaleKey] as? Double else { self.init(identifier: NSUUID().UUIDString, date: datetime.toDateUsingSeconds(), device: device, now: nowDouble.toDateUsingSeconds(), bgdelta: bgdelta, battery: batteryInt) self.sgv = SensorGlucoseValue(sgv: sgv, direction: direction, filtered: filtered, unfiltered: unfiltlered, rssi: 0, noise: noise) return } self.init(identifier: NSUUID().UUIDString, date: datetime.toDateUsingSeconds(), device: device, now: nowDouble.toDateUsingSeconds(), bgdelta: bgdelta, battery: batteryInt) self.sgv = SensorGlucoseValue(sgv: sgv, direction: direction, filtered: filtered, unfiltered: unfiltlered, rssi: 0, noise: noise) self.cal = Calibration(slope: slope, scale: scale, intercept: intercept, date: date) } }
// // KeystoreCipherparamsModel.swift // MMWallet // // Created by Dmitry Muravev on 16.09.2018. // Copyright © 2018 micromoney. All rights reserved. // import Foundation import RealmSwift import ObjectMapper class KeystoreCipherparamsModel: Object, Mappable { @objc dynamic var iv = "" required convenience init?(map: Map) { self.init() } func mapping(map: Map) { iv <- map["iv"] } }
// // PagedListLayoutTests.swift // ListableUI-Unit-Tests // // Created by Kyle Van Essen on 6/6/20. // import XCTest import Snapshot @testable import ListableUI class PagedListLayoutTests : XCTestCase { func test_layout_vertical() { let listView = self.list(for: .vertical) let snapshot = Snapshot(for: SizedViewIteration(size: listView.contentSize), input: listView) snapshot.test(output: ViewImageSnapshot.self) snapshot.test(output: LayoutAttributesSnapshot.self) } func test_layout_horizontal() { let listView = self.list(for: .horizontal) let snapshot = Snapshot(for: SizedViewIteration(size: listView.contentSize), input: listView) snapshot.test(output: ViewImageSnapshot.self) snapshot.test(output: LayoutAttributesSnapshot.self) } func list(for direction : LayoutDirection) -> ListView { let listView = ListView(frame: CGRect(origin: .zero, size: CGSize(width: 200.0, height: 200.0))) listView.configure { list in list.layout = .paged { $0.direction = direction $0.pagingSize = .fixed(50.0) $0.itemInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) } list.content.header = HeaderFooter(TestingHeaderFooterContent(color: .blue)) list.content.footer = HeaderFooter(TestingHeaderFooterContent(color: .green)) list += Section("first") { section in section.header = HeaderFooter(TestingHeaderFooterContent(color: .purple)) section.footer = HeaderFooter(TestingHeaderFooterContent(color: .red)) section += TestingItemContent(color: .init(white: 0.0, alpha: 0.3)) section += TestingItemContent(color: .init(white: 0.0, alpha: 0.4)) section += TestingItemContent(color: .init(white: 0.0, alpha: 0.5)) } list += Section("second") { section in section.header = HeaderFooter(TestingHeaderFooterContent(color: .purple)) section.footer = HeaderFooter(TestingHeaderFooterContent(color: .red)) section += TestingItemContent(color: .init(white: 0.0, alpha: 0.6)) section += TestingItemContent(color: .init(white: 0.0, alpha: 0.7)) } } return listView } } class PagedAppearanceTests : XCTestCase { func test_init() { let appearance = PagedAppearance() XCTAssertEqual(appearance.direction, .vertical) XCTAssertEqual(appearance.showsScrollIndicators, false) XCTAssertEqual(appearance.itemInsets, .zero) } } class PagedAppearance_PagingSize_Tests : XCTestCase { func test_size() { let size = CGSize(width: 30.0, height: 50.0) XCTAssertEqual(PagedAppearance.PagingSize.view.size(for: size, direction: .vertical), CGSize(width: 30.0, height: 50.0)) XCTAssertEqual(PagedAppearance.PagingSize.view.size(for: size, direction: .horizontal), CGSize(width: 30.0, height: 50.0)) XCTAssertEqual(PagedAppearance.PagingSize.fixed(100).size(for: size, direction: .vertical), CGSize(width: 30.0, height: 100.0)) XCTAssertEqual(PagedAppearance.PagingSize.fixed(100).size(for: size, direction: .horizontal), CGSize(width: 100.0, height: 50.0)) } } fileprivate struct TestingHeaderFooterContent : HeaderFooterContent { var color : UIColor func apply( to views: HeaderFooterContentViews<TestingHeaderFooterContent>, for reason: ApplyReason, with info: ApplyHeaderFooterContentInfo ) { views.content.backgroundColor = self.color } func isEquivalent(to other: TestingHeaderFooterContent) -> Bool { false } typealias ContentView = UIView static func createReusableContentView(frame: CGRect) -> UIView { UIView(frame: frame) } } fileprivate struct TestingItemContent : ItemContent { var color : UIColor var identifierValue: String { "" } func apply(to views: ItemContentViews<Self>, for reason: ApplyReason, with info: ApplyItemContentInfo) { views.content.backgroundColor = self.color } func isEquivalent(to other: TestingItemContent) -> Bool { false } typealias ContentView = UIView static func createReusableContentView(frame: CGRect) -> UIView { UIView(frame: frame) } }
func time() -> Double { // Returns Unix epoch time return Date().timeIntervalSince1970 } func testSetFunc<BenchMap: Map> (_ map: inout BenchMap, _ filter: Set<Int>, _ iters: Int) -> Dictionary<Int,Double> where BenchMap.Key == Int, BenchMap.Value == Int { var results = Dictionary<Int, Double>() for _ in 1...iters { for i in 1...filter.max()! { var startTime = time() map.set(i, i+1) // Use dummy data, in this case simply the index:index+1 var elapsed = time()-startTime if filter.contains(i) { results[i-1] = Double(elapsed)/Double(iters) } } map.clear() } return results } func testSetFunc<BenchMap: Map> (_ map: inout BenchMap, _ length: Int, _ iters: Int) -> [Double] where BenchMap.Key == Int, BenchMap.Value == Int { // The final dataset. Index is the number of items (n) and // the value is the average time it took to perform a set operation // over [iters] iterations. var results = Array<Double>(repeating: 0, count: length) for _ in 1...iters { for i in 1...length { var startTime = time() map.set(i, i+1) // Use dummy data, in this case simply the index:index+1 var elapsed = time()-startTime results[i] = Double(elapsed)/Double(iters) } map.clear() } return results } let fileManager = FileManager.default let path = fileManager.currentDirectoryPath "oofer".writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding) // let benchMarker = BenchMarker() // benchMarker.filedTest3Maps(100, 1000, at:path) // benchMarker.filedTest3Maps(1000, 1000, at:path) // benchMarker.filedTest3Maps(10000, 1000, at:path) // benchMarker.filedTest3Maps(100000, 1000, at:path) // benchMarker.filedTest3Maps(1000000, 1000, at:path)
// // Utilities.swift // VacationPlanner // // Created by Cem Atilgan on 2019-03-14. // Copyright © 2019 Cem Atilgan. All rights reserved. // import UIKit class Utilities{ private init() { } static func getOpeningHours(workingDays: [String]) -> String { var openingHours = "" let currentDay: Int = { let date = Date() let calendar = Calendar(identifier: .gregorian) let today = calendar.component(.weekday, from: date) return today }() let dayOfTheWeek = Constants.WeekDays.daysOfTheWeek[currentDay]! for day in workingDays { if day.contains(dayOfTheWeek){ openingHours = day } } return openingHours } static func getAttributedString(for ratingText: String, with ratingSize: Double, textSize: Double) -> NSMutableAttributedString { let ratingAttributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.foregroundColor : UIColor(red: 1, green: 0.6705882353, blue: 0, alpha: 1), NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: CGFloat(ratingSize)) ] let textAttributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.foregroundColor : UIColor.lightGray, NSAttributedString.Key.font : UIFont.systemFont(ofSize: CGFloat(textSize)) ] // The range of the number of user ratings part of the text let textLength: Int = ratingText.count - 4 let range = NSRange(location: 4, length: textLength) let attributedString = NSMutableAttributedString(string: ratingText, attributes: ratingAttributes) attributedString.addAttributes(textAttributes, range: range) return attributedString } static func editStringForPlaceTypes(text: String) -> String{ let newString = text.replacingOccurrences(of: "_", with: " ") return newString.firstUppercased } } extension StringProtocol { var firstUppercased: String { return prefix(1).uppercased() + dropFirst() } }
// // Date+Extension.swift // AwesomeBlogs // // Created by wade.hawk on 2017. 8. 20.. // Copyright © 2017년 wade.hawk. All rights reserved. // import Foundation import SwiftDate extension Date { static public func == (lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == .orderedSame } static public func < (lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == .orderedAscending } static public func > (lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == .orderedDescending } func colloquial() -> String { return (try? self.colloquial(to: Date()).colloquial) ?? "" } }
// // ProductCollectionCell.swift // collexapp // // Created by Lex on 15/8/20. // Copyright © 2020 Lex. All rights reserved. // import UIKit import SnapKit class ProductGridCell: UICollectionViewCell { override func awakeFromNib() { super.awakeFromNib() } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(white: 1, alpha: 0.1) addSubview(productImageView) productImageView.snp.makeConstraints { (make) in make.top.bottom.centerX.centerY.equalTo(self) make.left.right.lessThanOrEqualTo(self) } productImageView.addSubview(priceLabel) priceLabel.snp.makeConstraints{ (make) in make.bottom.equalTo(productImageView).inset(10) make.left.right.lessThanOrEqualTo(productImageView) make.height.equalTo(25) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var productImageView: UIImageView = { let imageView = UIImageView() imageView.layer.cornerRadius = 5 imageView.layer.borderWidth = 1 imageView.layer.borderColor = UIColor.collexapp.mainLightGrey.cgColor imageView.backgroundColor = UIColor.collexapp.mainLightWhite imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill return imageView }() let priceLabel: UILabel = { let label = PaddingLabel() label.text = "4,000 Baht" label.textColor = UIColor.collexapp.mainBlack label.layer.backgroundColor = UIColor.white.withAlphaComponent(0.95).cgColor label.layer.cornerRadius = 5 label.font = UIFont(name: "FiraSans-Bold", size: 17) label.textAlignment = .left label.lineBreakMode = NSLineBreakMode.byTruncatingTail label.numberOfLines = 1 label.padding(0, 10, 0, 10) return label }() }
import UIKit class PhotoCollectionViewCell: UICollectionViewCell, Reusable { private(set) lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.accessibilityIdentifier = "PhotoCollectionViewCell.imageView" return imageView }() override init(frame: CGRect) { super.init(frame: frame) setUp() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUp() } override func prepareForReuse() { super.prepareForReuse() imageView.image = nil } // MARK: - Private methods private func setUp() { backgroundColor = UIColor(displayP3Red: 229 / 255, green: 229 / 255, blue: 234 / 255, alpha: 1) // systemGray5 in iOS13 layer.cornerRadius = 20 clipsToBounds = true addImageView() } private func addImageView() { contentView.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true imageView.widthAnchor.constraint(equalTo: contentView.widthAnchor).isActive = true imageView.heightAnchor.constraint(equalTo: contentView.heightAnchor).isActive = true } }
import Foundation public struct AutostatMeasureValue: Codable { public let name: AutostatMeasure public let value: String }
// // EventDetailViewController.swift // Eventful // // Created by Amy Chin Siu Huang on 5/12/20. // Copyright © 2020 Amy Chin Siu Huang. All rights reserved. // import UIKit import EventKit import EventKitUI class EventDetailViewController: UIViewController { weak var delegate: EventDetailProtocol? var eventSelected: Event? init(delegate: EventDetailProtocol, eventSelected: Event) { super.init(nibName: nil, bundle: nil) self.delegate = delegate self.eventSelected = eventSelected } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } var scrollView: UIScrollView! var eventName: UILabel! var eventLocation: UILabel! var eventLocationDetailed: UILabel! var eventDate: UILabel! var eventTime: UILabel! var eventDescription: UITextView! var eventTags: UILabel! var eventImage: UIImageView! var locationIcon: UIImageView! var dateIcon: UIImageView! var addToCalendarButton: UIBarButtonItem! var dateObject: Date! var color = UIColor.black var labelSize: CGFloat = 16 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white self.navigationItem.largeTitleDisplayMode = .never self.navigationItem.title = "Event Details" makeDateObject() scrollView = UIScrollView() scrollView.backgroundColor = .white scrollView.contentSize.width = view.bounds.width scrollView.contentSize.height = view.bounds.height + 700 scrollView.isUserInteractionEnabled = true view.addSubview(scrollView) eventName = UILabel() eventName.text = eventSelected?.eventName eventName.numberOfLines = 0 eventName.textColor = color eventName.font = UIFont.systemFont(ofSize: 28, weight: .bold) scrollView.addSubview(eventName) eventLocation = UILabel() eventLocation.text = eventSelected?.eventLocation eventName.numberOfLines = 0 eventLocation.textColor = color eventLocation.font = UIFont.systemFont(ofSize: labelSize, weight: .regular) scrollView.addSubview(eventLocation) eventLocationDetailed = UILabel() eventLocationDetailed.text = eventSelected?.eventLocationDetailed eventName.numberOfLines = 0 eventLocationDetailed.textColor = .darkGray eventLocationDetailed.font = UIFont.systemFont(ofSize: labelSize, weight: .regular) scrollView.addSubview(eventLocationDetailed) eventDate = UILabel() eventDate.text = eventSelected?.eventDate eventName.numberOfLines = 0 eventDate.textColor = color eventDate.font = UIFont.systemFont(ofSize: labelSize, weight: .regular) scrollView.addSubview(eventDate) eventTime = UILabel() eventTime.text = "from \(eventSelected!.eventStartTime) to \(eventSelected!.eventEndTime)" eventName.numberOfLines = 0 eventTime.textColor = color eventTime.font = UIFont.systemFont(ofSize: labelSize, weight: .regular) scrollView.addSubview(eventTime) addToCalendarButton = UIBarButtonItem(image: UIImage(named: "addtocalendarbutton"), style: .plain, target: self, action: #selector(addToCalendar)) self.navigationItem.rightBarButtonItem = addToCalendarButton eventTags = UILabel() if let eventTagList = eventSelected?.eventTags { var eventTagText = "Tags: " for tag in eventTagList { eventTagText = eventTagText + " #\(tag)" } eventTags.text = eventTagText } eventName.numberOfLines = 0 eventTags.textColor = color eventTags.font = UIFont.systemFont(ofSize: labelSize, weight: .medium) scrollView.addSubview(eventTags) eventImage = UIImageView() eventImage.contentMode = .scaleAspectFill eventImage.clipsToBounds = true eventImage.layer.masksToBounds = true eventImage.image = eventSelected?.eventImage scrollView.addSubview(eventImage) locationIcon = UIImageView() locationIcon.image = UIImage(named: "locationicon") locationIcon.contentMode = .scaleAspectFit scrollView.addSubview(locationIcon) dateIcon = UIImageView() dateIcon.image = UIImage(named: "dateicon") dateIcon.contentMode = .scaleAspectFit scrollView.addSubview(dateIcon) eventDescription = UITextView() eventDescription.font = UIFont.systemFont(ofSize: labelSize, weight: .regular) eventDescription.text = eventSelected?.eventDescription eventDescription.isEditable = false eventDescription.isUserInteractionEnabled = true scrollView.addSubview(eventDescription) setUpConstraints() } func makeDateObject() { let monthDictionary:[String: Int] = ["January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12] if let date = eventSelected?.eventDate { let datearray = date.components(separatedBy: " ") var month = datearray[0] var day = datearray[1] if let i = day.firstIndex(of: ",") { day.remove(at: i) } var year = datearray[2] day = day.trimmingCharacters(in: .whitespacesAndNewlines) month = month.trimmingCharacters(in: .whitespacesAndNewlines) year = year.trimmingCharacters(in: .whitespacesAndNewlines) if let dateMonth = monthDictionary[month], let dateYear = Int(year), let dateDay = Int(day) { let calendar = Calendar.current let dateComponents = DateComponents(calendar: calendar, year: dateYear, month: dateMonth, day: dateDay) dateObject = calendar.date(from: dateComponents) } } } func alert() { let alert = UIAlertController(title: "Success!", message: "Event Successfully Added To Your Calendar", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Okay", style: .cancel)) self.present(alert, animated: true, completion: nil) } @objc func addToCalendar() { makeDateObject() let eventStore: EKEventStore = EKEventStore() eventStore.requestAccess(to: .event) { (granted, error) in if (granted) && (error == nil) { let eventCreated: EKEvent = EKEvent(eventStore: eventStore) eventCreated.title = self.eventSelected?.eventName eventCreated.startDate = self.dateObject! eventCreated.endDate = self.dateObject! eventCreated.location = self.eventSelected?.eventLocation eventCreated.notes = self.eventSelected?.eventDescription eventCreated.calendar = eventStore.defaultCalendarForNewEvents do { try eventStore.save(eventCreated, span: .thisEvent) } catch let error as NSError { print(error.localizedDescription) } } else { print("There was an error adding your event to the calendar") } } self.alert() } func setUpConstraints() { let verticalPadding: CGFloat = 15 let horizontalPadding: CGFloat = 25 let iconSize: CGFloat = 22 scrollView.snp.makeConstraints { (make) in make.left.equalTo(view.snp.left) make.right.equalTo(view.snp.right) make.top.equalTo(view.snp.top) make.bottom.equalTo(view.snp.bottom) } eventImage.snp.makeConstraints { (make) in make.top.equalTo(scrollView.snp.top) make.left.equalTo(scrollView.snp.left) make.right.equalTo(scrollView.snp.right) make.width.equalTo(scrollView.snp.width) make.height.equalTo(280) } eventName.snp.makeConstraints { (make) in make.top.equalTo(eventImage.snp.bottom).offset(verticalPadding) make.centerX.equalTo(scrollView.snp.centerX) let width = view.bounds.width - 50 make.width.equalTo(width) } locationIcon.snp.makeConstraints { (make) in make.left.equalTo(scrollView.snp.left).offset(horizontalPadding) make.top.equalTo(eventName.snp.bottom).offset(verticalPadding) make.width.height.equalTo(iconSize) } eventLocation.snp.makeConstraints { (make) in make.top.equalTo(eventName.snp.bottom).offset(verticalPadding) make.left.equalTo(locationIcon.snp.right).offset(10) } eventLocationDetailed.snp.makeConstraints { (make) in make.top.equalTo(eventLocation.snp.bottom).offset(6) make.left.equalTo(eventLocation.snp.left) } dateIcon.snp.makeConstraints { (make) in make.left.equalTo(scrollView.snp.left).offset(horizontalPadding) make.top.equalTo(eventLocationDetailed.snp.bottom).offset(verticalPadding) make.width.height.equalTo(iconSize) } eventDate.snp.makeConstraints { (make) in make.left.equalTo(eventLocation.snp.left) make.top.equalTo(eventLocationDetailed.snp.bottom).offset(verticalPadding) } eventTime.snp.makeConstraints { (make) in make.left.equalTo(eventDate.snp.left) make.top.equalTo(eventDate.snp.bottom).offset(6) } eventTags.snp.makeConstraints { (make) in make.left.equalTo(scrollView.snp.left).offset(horizontalPadding) make.top.equalTo(eventTime.snp.bottom).offset(verticalPadding) } eventDescription.snp.makeConstraints { (make) in make.left.equalTo(scrollView.snp.left).offset(horizontalPadding) make.right.equalTo(scrollView.snp.right).offset(-horizontalPadding) make.height.equalTo(200) make.top.equalTo(eventTags.snp.bottom).offset(verticalPadding) } } }
// // NotificationsView.swift // Tile // // Created by Jerry Turcios on 1/5/20. // Copyright © 2020 Jerry Turcios. All rights reserved. // import SwiftUI struct NotificationsView: View { @State private var notifications = [String]() var body: some View { VStack { AppBarView() if notifications.count == 0 { Spacer() Text("No new notifications").padding(.bottom, 100) Spacer() } else { Text("YEAHHHHHH") } } } } #if DEBUG struct NotificationsViewPreviews: PreviewProvider { static var previews: some View { ZStack { NotificationsView() VStack { Spacer() VStack { HorizontalLine(color: AppColor.navBorder, height: 2) TabBarView(viewSelected: .constant(.notifications)) }.background(Color.white) } } } } #endif
// // Calendar.swift // PillReminder // // Created by Dumitru Tabara on 1/3/20. // Copyright © 2020 Dumitru Tabara. All rights reserved. // import Foundation class CalendarModel { let Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] let DaysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] var DaysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] let date = Date() let calendar = Calendar.current var day = Int() var weekday = Int() var weekOfMonth = Int() var month = Int() var year = Int() var numberOfEmptyBox = 0 var nextNumberOfEmptyBox = Int() var previousNumberOfEmptyBox = 0 var direction = 0 var positionIndex = 0 var currentMonth: String { return Months[month] } var currentMonthDays: Int { return DaysInMonths[month] } init() { day = calendar.component(.day, from: date) weekday = calendar.component(.weekday, from: date) weekOfMonth = calendar.component(.weekOfMonth, from: date) month = calendar.component(.month, from: date) - 1 year = calendar.component(.year, from: date) numberOfEmptyBox = (7 * weekOfMonth) - (7 - weekday) - day positionIndex = numberOfEmptyBox changeFebruaryNumberOfDays() } func getCurrentMonthAndYear() -> String { return "\(currentMonth) \(year)" } func getPreviousMonth() { switch currentMonth { case "January": month = 11 year -= 1 changeFebruaryNumberOfDays() direction = -1 getStartDateDayPosition() default: month -= 1 direction = -1 getStartDateDayPosition() } } func getNextMonth() { switch currentMonth { case "December": month = 0 year += 1 changeFebruaryNumberOfDays() direction = 1 getStartDateDayPosition() default: direction = 1 getStartDateDayPosition() month += 1 } } func getStartDateDayPosition() { switch direction { case 0: switch day { case 1...7: numberOfEmptyBox = weekday - day case 8...14: numberOfEmptyBox = weekday - day - 7 case 15...21: numberOfEmptyBox = weekday - day - 14 case 22...28: numberOfEmptyBox = weekday - day - 21 case 29...31: numberOfEmptyBox = weekday - day - 28 default: break } positionIndex = numberOfEmptyBox case 1...: nextNumberOfEmptyBox = (positionIndex + DaysInMonths[month]) % 7 positionIndex = nextNumberOfEmptyBox case -1: previousNumberOfEmptyBox = 7 - (DaysInMonths[month] - positionIndex) % 7 if previousNumberOfEmptyBox == 7 { previousNumberOfEmptyBox = 0 } positionIndex = previousNumberOfEmptyBox default: fatalError() } } func getCurrentMonthDays() -> Int { switch direction { case 0: return DaysInMonths[month] + numberOfEmptyBox case 1...: return DaysInMonths[month] + nextNumberOfEmptyBox case -1: return DaysInMonths[month] + previousNumberOfEmptyBox default: fatalError() } } func getCurrentDay(indexPathRow: Int) -> Int { switch direction { case 0: return indexPathRow + 1 - numberOfEmptyBox case 1: return indexPathRow + 1 - nextNumberOfEmptyBox case -1: return indexPathRow + 1 - previousNumberOfEmptyBox default: fatalError() } } func isLeapYear(_ year: Int) -> Bool { return ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) } func changeFebruaryNumberOfDays() { DaysInMonths[1] = isLeapYear(year) ? 29 : 28; } func getCurrentDateAsString(indexPathRow: Int) -> String { let currentDay = getCurrentDay(indexPathRow: indexPathRow) let currentMonth = month + 1 let currentYear = year return ("\(currentDay)-\(currentMonth)-\(currentYear)") } func createDateFromDay(dateToConvert: String) -> Date { let dateFormatter = DateFormatter() let format = "d-m-yyyy" dateFormatter.dateFormat = format return dateFormatter.date(from: dateToConvert)! } }
// // NumberingTimerAction.swift // Domain // // Created by 이광용 on 24/05/2019. // Copyright © 2019 GwangYongLee. All rights reserved. // import Foundation public class NumberingTimerAction: TimerAction { public var identifier: TimerXIdentifier { return .numberingTimerAction } public weak var owner: Action? public let uuid: String public let title: String public let goal: Int public let interval: TimeInterval public let countingType: CountingType public init(uuid: String = UUID().uuidString, title: String = "", goal: Int = 5, interval: TimeInterval = 1.0, countingType: CountingType = .up) { self.uuid = uuid self.title = title self.goal = goal self.interval = interval self.countingType = countingType } private enum CodingKeys: CodingKey { case uuid case title case goal case interval case countingType } }
/* Copyright Airship and Contributors */ import XCTest @testable import AirshipCore class ContactAPIClientTest: XCTestCase { var config: RuntimeConfig! var localeManager: LocaleManager! var session: TestRequestSession! var contactAPIClient: ContactAPIClient! override func setUpWithError() throws { let airshipConfig = Config() airshipConfig.requireInitialRemoteConfigEnabled = false self.config = RuntimeConfig(config: airshipConfig, dataStore: PreferenceDataStore(appKey: UUID().uuidString)) self.localeManager = LocaleManager(dataStore: PreferenceDataStore(appKey: config.appKey)) self.session = TestRequestSession.init() self.session.response = HTTPURLResponse(url: URL(string: "https://contacts_test")!, statusCode: 200, httpVersion: "", headerFields: [String: String]()) self.contactAPIClient = ContactAPIClient.init(config: self.config, session: self.session) } func testIdentify() throws { self.session.data = """ { "contact_id": "56779" } """.data(using: .utf8) let expectation = XCTestExpectation(description: "callback called") contactAPIClient.identify(channelID: "test_channel", namedUserID: "contact", contactID: nil) { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertNotNil(response?.contactID) XCTAssertNotNil(response?.isAnonymous) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } func testResolve() throws { self.session.data = """ { "contact_id": "56779", "is_anonymous": true } """.data(using: .utf8) let expectation = XCTestExpectation(description: "callback called") contactAPIClient.resolve(channelID: "test_channel") { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertNotNil(response?.contactID) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } func testReset() throws { self.session.data = """ { "contact_id": "56779", } """.data(using: .utf8) let expectation = XCTestExpectation(description: "callback called") contactAPIClient.reset(channelID: "test_channel") { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertNotNil(response?.contactID) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } func testRegisterEmail() throws { self.session.data = """ { "channel_id": "some-channel", } """.data(using: .utf8) let date = Date() let expectation = XCTestExpectation(description: "callback called") contactAPIClient.registerEmail(identifier: "some-contact-id", address: "ua@airship.com", options: EmailRegistrationOptions.options(transactionalOptedIn:date, properties: ["interests" : "newsletter"], doubleOptIn: true)) { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertEqual("some-channel", response?.channel?.channelID) XCTAssertEqual(.email, response?.channel?.channelType) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) let previousRequest = self.session.previousRequest! XCTAssertNotNil(previousRequest) XCTAssertEqual("https://device-api.urbanairship.com/api/channels/restricted/email", previousRequest.url!.absoluteString) let previousBody = try JSONSerialization.jsonObject(with: previousRequest.body!, options: []) let currentLocale = self.localeManager.currentLocale let formatter = Utils.isoDateFormatterUTCWithDelimiter() let previousExpectedBody : Any = [ "channel" : [ "type" : "email", "address" : "ua@airship.com", "timezone" : TimeZone.current.identifier, "locale_country" : currentLocale.regionCode ?? "", "locale_language" : currentLocale.languageCode ?? "", "transactional_opted_in" : formatter.string(from:date) ], "opt_in_mode" : "double", "properties" : [ "interests" : "newsletter" ] ] XCTAssertEqual(previousBody as! NSDictionary, previousExpectedBody as! NSDictionary) let lastRequest = self.session.lastRequest! XCTAssertEqual("https://device-api.urbanairship.com/api/contacts/some-contact-id", lastRequest.url!.absoluteString) let lastBody = try JSONSerialization.jsonObject(with: lastRequest.body!, options: []) let lastExpectedBody : Any = [ "associate" : [ [ "device_type" : "email", "channel_id" : "some-channel" ] ] ] XCTAssertEqual(lastBody as! NSDictionary, lastExpectedBody as! NSDictionary) } func testRegisterSMS() throws { self.session.data = """ { "channel_id": "some-channel", } """.data(using: .utf8) let expectation = XCTestExpectation(description: "callback called") contactAPIClient.registerSMS(identifier: "some-contact-id", msisdn: "15035556789", options: SMSRegistrationOptions.optIn(senderID: "28855")) { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertEqual("some-channel", response?.channel?.channelID) XCTAssertEqual(.sms, response?.channel?.channelType) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) let previousRequest = self.session.previousRequest! XCTAssertNotNil(previousRequest) XCTAssertEqual("https://device-api.urbanairship.com/api/channels/restricted/sms", previousRequest.url!.absoluteString) let previousBody = try JSONSerialization.jsonObject(with: previousRequest.body!, options: []) let currentLocale = self.localeManager.currentLocale let previousExpectedBody : Any = [ "msisdn" : "15035556789", "sender" : "28855", "timezone" : TimeZone.current.identifier, "locale_country" : currentLocale.regionCode ?? "", "locale_language" : currentLocale.languageCode ?? "" ] XCTAssertEqual(previousBody as! NSDictionary, previousExpectedBody as! NSDictionary) let lastRequest = self.session.lastRequest! XCTAssertEqual("https://device-api.urbanairship.com/api/contacts/some-contact-id", lastRequest.url!.absoluteString) let lastBody = try JSONSerialization.jsonObject(with: lastRequest.body!, options: []) let lastExpectedBody : Any = [ "associate" : [ [ "device_type" : "sms", "channel_id" : "some-channel" ] ] ] XCTAssertEqual(lastBody as! NSDictionary, lastExpectedBody as! NSDictionary) } func testRegisterOpen() throws { self.session.data = """ { "channel_id": "some-channel", } """.data(using: .utf8) let expectation = XCTestExpectation(description: "callback called") contactAPIClient.registerOpen(identifier: "some-contact-id", address: "open_address", options: OpenRegistrationOptions.optIn(platformName: "my_platform", identifiers: ["model":"4", "category":"1"])) { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertEqual("some-channel", response?.channel?.channelID) XCTAssertEqual(.open, response?.channel?.channelType) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) let previousRequest = self.session.previousRequest! XCTAssertNotNil(previousRequest) XCTAssertEqual("https://device-api.urbanairship.com/api/channels/restricted/open", previousRequest.url!.absoluteString) let previousBody = try JSONSerialization.jsonObject(with: previousRequest.body!, options: []) let currentLocale = self.localeManager.currentLocale let previousExpectedBody : Any = [ "channel" : [ "type" : "open", "address" : "open_address", "timezone" : TimeZone.current.identifier, "locale_country" : currentLocale.regionCode ?? "", "locale_language" : currentLocale.languageCode ?? "", "opt_in" : true, "open" : [ "open_platform_name" : "my_platform", "identifiers" : [ "model" : "4", "category" : "1" ] ] ] ] XCTAssertEqual(previousBody as! NSDictionary, previousExpectedBody as! NSDictionary) let lastRequest = self.session.lastRequest! XCTAssertEqual("https://device-api.urbanairship.com/api/contacts/some-contact-id", lastRequest.url!.absoluteString) let lastBody = try JSONSerialization.jsonObject(with: lastRequest.body!, options: []) let lastExpectedBody : Any = [ "associate" : [ [ "device_type" : "open", "channel_id" : "some-channel" ] ] ] XCTAssertEqual(lastBody as! NSDictionary, lastExpectedBody as! NSDictionary) } func testAssociateChannel() throws { let expectation = XCTestExpectation(description: "callback called") contactAPIClient.associateChannel(identifier: "some-contact-id", channelID: "some-channel", channelType: .sms) { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertEqual("some-channel", response?.channel?.channelID) XCTAssertEqual(.sms, response?.channel?.channelType) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) let request = self.session.lastRequest! XCTAssertEqual("https://device-api.urbanairship.com/api/contacts/some-contact-id", request.url!.absoluteString) let body = try JSONSerialization.jsonObject(with: request.body!, options: []) let expectedBody : Any = [ "associate" : [ [ "device_type" : "sms", "channel_id" : "some-channel" ] ] ] XCTAssertEqual(body as! NSDictionary, expectedBody as! NSDictionary) } func testUpdate() throws { let tagUpdates = [ TagGroupUpdate(group: "tag-set", tags: [], type: .set), TagGroupUpdate(group: "tag-add", tags: ["add tag"], type: .add), TagGroupUpdate(group: "tag-other-add", tags: ["other tag"], type: .add), TagGroupUpdate(group: "tag-remove", tags: ["remove tag"], type: .remove) ] let date = Date() let attributeUpdates = [ AttributeUpdate.set(attribute: "some-string", value: "Hello", date: date), AttributeUpdate.set(attribute: "some-number", value: 32.0, date: date), AttributeUpdate.remove(attribute: "some-remove", date: date) ] let listUpdates = [ ScopedSubscriptionListUpdate(listId: "bar", type: .subscribe, scope: .web, date: date), ScopedSubscriptionListUpdate(listId: "foo", type: .unsubscribe, scope: .app, date: date) ] let expectation = XCTestExpectation(description: "callback called") contactAPIClient.update(identifier: "some-contact-id", tagGroupUpdates: tagUpdates, attributeUpdates: attributeUpdates, subscriptionListUpdates: listUpdates) { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) let request = self.session.lastRequest! XCTAssertEqual("https://device-api.urbanairship.com/api/contacts/some-contact-id", request.url!.absoluteString) let body = try JSONSerialization.jsonObject(with: request.body!, options: []) let formattedDate = Utils.isoDateFormatterUTCWithDelimiter().string(from: date) let expectedBody : Any = [ "attributes" : [ [ "action" : "set", "key" : "some-string", "timestamp" : formattedDate, "value" : "Hello" ], [ "action" : "set", "key" : "some-number", "timestamp" : formattedDate, "value" : 32 ], [ "action" : "remove", "key" : "some-remove", "timestamp" : formattedDate, ], ], "tags": [ "add": [ "tag-add": [ "add tag" ], "tag-other-add": [ "other tag" ] ], "remove": [ "tag-remove": [ "remove tag" ] ], "set": [ "tag-set": [ ] ] ], "subscription_lists": [ [ "action": "subscribe", "list_id": "bar", "scope": "web", "timestamp" : formattedDate, ], [ "action": "unsubscribe", "list_id": "foo", "scope": "app", "timestamp" : formattedDate, ] ] ] XCTAssertEqual(body as! NSDictionary, expectedBody as! NSDictionary) } func testUpdateMixValidInvalidAttributes() throws { let date = Date() let attributeUpdates = [ AttributeUpdate(attribute: "some-string", type: .set, value: nil, date: date), AttributeUpdate.set(attribute: "some-string", value: "Hello", date: date), ] let expectation = XCTestExpectation(description: "callback called") contactAPIClient.update(identifier: "some-contact-id", tagGroupUpdates: [], attributeUpdates: attributeUpdates, subscriptionListUpdates: nil) { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) let request = self.session.lastRequest! XCTAssertEqual("https://device-api.urbanairship.com/api/contacts/some-contact-id", request.url!.absoluteString) let body = try JSONSerialization.jsonObject(with: request.body!, options: []) let formattedDate = Utils.isoDateFormatterUTCWithDelimiter().string(from: date) let expectedBody : Any = [ "attributes" : [ [ "action" : "set", "key" : "some-string", "timestamp" : formattedDate, "value" : "Hello" ], ] ] XCTAssertEqual(body as! NSDictionary, expectedBody as! NSDictionary) } func testGetContactLists() throws { let responseBody = """ { "ok" : true, "subscription_lists": [ { "list_ids": ["example_listId-1", "example_listId-3"], "scope": "email" }, { "list_ids": ["example_listId-2", "example_listId-4"], "scope": "app" }, { "list_ids": ["example_listId-2"], "scope": "web" } ], } """ self.session.response = HTTPURLResponse(url: URL(string: "https://neat")!, statusCode: 200, httpVersion: "", headerFields: [String: String]()) self.session.data = responseBody.data(using: .utf8) let expectation = XCTestExpectation(description: "callback called") let expected: [String: [ChannelScope]] = [ "example_listId-1": [.email], "example_listId-2": [.app, .web], "example_listId-3": [.email], "example_listId-4": [.app], ] self.contactAPIClient.fetchSubscriptionLists("some-contact") { response, error in XCTAssertEqual(response?.status, 200) XCTAssertNil(error) XCTAssertEqual(expected, response?.result) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) XCTAssertEqual("GET", self.session.lastRequest?.method) XCTAssertEqual("https://device-api.urbanairship.com/api/subscription_lists/contacts/some-contact", self.session.lastRequest?.url?.absoluteString) } func testGetContactListParseError() throws { let responseBody = "What?" self.session.response = HTTPURLResponse(url: URL(string: "https://neat")!, statusCode: 200, httpVersion: "", headerFields: [String: String]()) self.session.data = responseBody.data(using: .utf8) let expectation = XCTestExpectation(description: "callback called") self.contactAPIClient.fetchSubscriptionLists("some-contact") { response, error in XCTAssertNotNil(error) XCTAssertNil(response) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } func testGetContactListError() throws { let sessionError = AirshipErrors.error("error!") self.session.error = sessionError let expectation = XCTestExpectation(description: "callback called") self.contactAPIClient.fetchSubscriptionLists("some-contact") { response, error in XCTAssertNotNil(error) XCTAssertNil(response) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } }
/** * Copyright IBM Corporation 2017 * * 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 SwiftyJSON struct Tag: Codable { let label: String let confidence: Double } struct PopularTag: Codable { let key: String let value: Int var rev: String? } extension PopularTag: JSONConvertible { static func convert(document: JSON, hasDocs: Bool = false, decoder: JSONDecoder) throws -> [PopularTag] { return try decoder.decode([PopularTag].self, from: document["rows"].rawData()) } }
// // AlamofireXML.swift // TestAlamofireXML // // Created by _Genesis_ on 8/26/16. // Copyright © 2016 _Genesis_. All rights reserved. // import UIKit import Alamofire extension Manager{ public func requestXML(method:Alamofire.Method, _ URLString: URLStringConvertible, parameters:String?, headers:[String: String]?) -> Request{ let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) mutableURLRequest.HTTPMethod = method.rawValue mutableURLRequest.setValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type") if let xmlParams = parameters { mutableURLRequest.setValue("\(xmlParams.characters.count)", forHTTPHeaderField: "Content-Length") } if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } let encodedURLRequest = encodingXML(mutableURLRequest, parametersXML: parameters).0 return request(encodedURLRequest) } public func encodingXML(URLRequest: URLRequestConvertible, parametersXML:String?) -> (NSMutableURLRequest,NSError?){ let mutableURLRequest = URLRequest.URLRequest guard let parameters = parametersXML else { return (mutableURLRequest, nil) } let encodingError:NSError? = nil mutableURLRequest.HTTPBody = parameters.dataUsingEncoding(NSUTF8StringEncoding) return (mutableURLRequest, encodingError) } } class AlamofireXML:Manager{ static func request( method: Alamofire.Method, _ URLString: URLStringConvertible, parameters: String?, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.requestXML( method, URLString, parameters: parameters, headers: headers ) } }
// // PageViewController.swift // UIPageViewTestProject // // Created by Md Sazzad Islam on 1/12/17. // Copyright © 2017 lynas. All rights reserved. // import UIKit class PageViewController: UIPageViewController, UIPageViewControllerDataSource { let imageNames = ["dog0","dog1","dog2","dog3"] var imgPos = 0 override func viewDidLoad() { super.viewDidLoad() imgPos = 0 self.dataSource = self let eachView = self.storyboard?.instantiateViewController(withIdentifier: "imageScroller") as! ViewController eachView.imageName = imageNames[imgPos] let viewControllers = [eachView] setViewControllers(viewControllers, direction: .forward, animated: true, completion: nil) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if imgPos == (imageNames.count - 1) { return nil } let eachView = self.storyboard?.instantiateViewController(withIdentifier: "imageScroller") as! ViewController imgPos = imgPos + 1 eachView.imageName = imageNames[imgPos] return eachView } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if imgPos == 0 { return nil } let eachView = self.storyboard?.instantiateViewController(withIdentifier: "imageScroller") as! ViewController imgPos = imgPos - 1 eachView.imageName = imageNames[imgPos] return eachView } }
// // EncounterExpanded.swift // MC3 // // Created by Aghawidya Adipatria on 28/07/20. // Copyright © 2020 Aghawidya Adipatria. All rights reserved. // import SwiftUI struct EncounterExpanded: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @EnvironmentObject var moduleInfo: ModuleInfo var body: some View { VStack(spacing: 0) { ModuleHeader(action: {self.presentationMode.wrappedValue.dismiss()}) ZStack { BackgroundCard() EncounterSectionList() } } .navigationBarTitle("") .navigationBarHidden(true) .navigationBarBackButtonHidden(true) } } struct EncounterSectionList: View { @EnvironmentObject var moduleInfo: ModuleInfo @State var encounter: Encounter = Encounter(name: "", location: "") var body: some View { VStack(spacing: 0) { HStack { Text(encounter.name) .padding(.top, 20) .padding(.leading, 30) .font(.system(size: 23, weight: .medium, design: .rounded)) Spacer() } .padding(.bottom, 30) Rectangle() .fill(Color.separator) .frame(width: UIScreen.main.bounds.width, height: 2) ScrollView { VStack(spacing: 0) { ForEach(EncounterSection.allCases, id: \.self) {(sections) in self.getLink(section: sections) } } } } .background(Color.white) .cornerRadius(10) .frame(minWidth: UIScreen.main.bounds.width, idealHeight: UIScreen.main.bounds.height) .padding(.top, 32) .onAppear(perform: { self.encounter = self.moduleInfo.currentModule.content.encounters[self.moduleInfo.encounterIndex] }) } func getLink(section: EncounterSection) -> some View { let index = self.moduleInfo.encounterIndex let encounter = self.moduleInfo.currentModule.content.encounters[index] var destination: AnyView var isEmpty: Bool switch section { case .Environment: destination = AnyView(EncounterEnvironment()) isEmpty = (encounter.environment == nil) case .Traps: destination = AnyView(EncounterTraps()) isEmpty = (encounter.traps == nil) case .Maps: destination = AnyView(EncounterMaps()) isEmpty = (encounter.maps == nil) case .POI: destination = AnyView(EncounterPOI()) isEmpty = (encounter.pois == nil) case .NPC: destination = AnyView(EncounterNPC()) isEmpty = (encounter.npcs == nil) case .Monsters: destination = AnyView(EncounterMonsters()) isEmpty = (encounter.monsters == nil) case .ReadAloudText: destination = AnyView(EncounterRAT()) isEmpty = (encounter.readAloudText == nil) case .Treasure: destination = AnyView(EncounterTreasure()) isEmpty = (encounter.treasure == nil) case .Notes: destination = AnyView(EncounterNotes()) isEmpty = (encounter.notes == nil) } return NavigationLink(destination: destination) { EncounterSectionCard(isEmpty: isEmpty, section: section) }.buttonStyle(PlainButtonStyle()) } } struct EncounterExpanded_Preview: PreviewProvider { static var previews: some View { //EncounterExpanded(encounter: ModulesStub.modulContent.last?.encounters[0] ?? Encounter(name: "Title", location: "Desc")).environmentObject(ModuleInfo()) EncounterExpanded().environmentObject(ModuleInfo()) //EncounterNotification() } } //circle system blue 24 //! rounded bold 17
// // EpisodeViewModel.swift // ScreenLifeMaze // // Created by Felipe Lobo on 19/09/21. // import Foundation import Combine final class EpisodeViewModel { @Published var episode: Episode init(episode: Episode) { self.episode = episode } }
// // UIColor.swift // NYC_JOBS_DATA_FINAL // // Created by Jonathan Cravotta on 5/29/18. // Copyright © 2018 Jonathan Cravotta. All rights reserved. // import Foundation import UIKit extension UIColor { public static var customBlue: UIColor { return UIColor.color(withRed: 72, green: 66, blue: 244) } public static var customPink: UIColor { return UIColor.color(withRed: 244, green: 66, blue: 136) } fileprivate static func color(withRed red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat = 1) -> UIColor { return UIColor(red:red/255.0, green:green/255.0, blue: blue/255.0, alpha:alpha) } }
// // ViewController.swift // RLPSwiftExample // // Created by Aleph Retamal on 1/2/18. // Copyright © 2018 Lalacode. All rights reserved. // import UIKit import RLPSwift class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() do { let encoded = try RLP.encode("dog") print("Success: \(encoded)") } catch { print("Error: \(error.localizedDescription)") } } }
// // main.swift // tts // // Created by Muhammad Hilmi Asyrofi on 21/1/20. // Copyright © 2020 Muhammad Hilmi Asyrofi. All rights reserved. // // Text-to-Speech on OSX import Foundation import AppKit import Cocoa // File path (change this). let path = "/Users/mhilmiasyrofi/Documents/test-case-generation/corpus-sentence.txt" // Read an entire text file into an NSString. let contents = try NSString(contentsOfFile: path, encoding: String.Encoding.ascii.rawValue) let synth = NSSpeechSynthesizer() let voices = NSSpeechSynthesizer.availableVoices.map { v in (v, NSSpeechSynthesizer.attributes(forVoice: v)[NSSpeechSynthesizer.VoiceAttributeKey.localeIdentifier] as! String) }.sorted { ($0.1, $0.0.rawValue) < ($1.1, $1.0.rawValue) } for (k, v) in voices { if (v.contains("en")) { if (v.contains("US") && k.rawValue.contains("Alex")) { let voice_id = k.rawValue // let accent_id = v // let directory = String("/Users/mhilmiasyrofi/Documents/test-case-generation/tts_apple/aiff_generated_speech/") synth.setVoice(NSSpeechSynthesizer.VoiceName(rawValue: voice_id)) // Process each lines var i = 0 contents.enumerateLines({ (line, stop) -> () in i = i + 1 let output_file = String(format:"/Users/mhilmiasyrofi/Documents/test-case-generation/tts_apple/aiff_generated_speech/audio_%d.aiff", i) let url = Foundation.URL.init(fileURLWithPath: output_file) let skill_executor = "" let skill_command = line let command = skill_executor + skill_command synth.startSpeaking(command, to: url) print("Generated: " + command) }) } } }
// // ImageCollectionViewCell.swift // photopizza // // Created by Gary Cheng on 7/12/16. // Copyright © 2016 Gary Cheng. All rights reserved. // import UIKit class ImageCollectionViewCell: UICollectionViewCell { @IBOutlet weak var designatedPic: UIImageView! }
// // TimerViewController.swift // Planning // // Created by Winter Lavigne on 30/05/15. // Copyright (c) 2015 Ziekelingskes. All rights reserved. // import UIKit class TimerViewController: UIViewController { // MARK: Actions func setTitle(){ let formatter = NSDateFormatter() formatter.timeStyle = NSDateFormatterStyle.ShortStyle self.title = formatter.stringFromDate( NSDate()) } // MARK: Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { self.setTitle() if segue.identifier == "PickTaskSegue" { } } // MARK: Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() self.setColorSchema() } override func prefersStatusBarHidden() -> Bool { return true } override func awakeFromNib() { self.title = Constants.TimerViewControllerConstants.title } }
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -enable-resilience -emit-silgen -parse-as-library -I %t %s | FileCheck %s import resilient_class func doFoo(_ f: () -> ()) { f() } public class Parent { public init() {} public func method() {} public final func finalMethod() {} public class func classMethod() {} public final class func finalClassMethod() {} } public class GenericParent<A> { let a: A public init(a: A) { self.a = a } public func method() {} public final func finalMethod() {} public class func classMethod() {} public final class func finalClassMethod() {} } class Child : Parent { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super5Child6methodfT_T_ : $@convention(method) (@guaranteed Child) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TTdFC19partial_apply_super6Parent6methodFT_T_ : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super5Child11classMethodfT_T_ : $@convention(method) (@thick Child.Type) -> () { // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TTdZFC19partial_apply_super6Parent11classMethodFT_T_ : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } // CHECK-LABEL: sil hidden @_TFC19partial_apply_super5Child20callFinalSuperMethodfT_T_ : $@convention(method) (@guaranteed Child) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC19partial_apply_super6Parent11finalMethodFT_T_ : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> () // CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> () // CHECK: apply [[DOFOO]]([[APPLIED_SELF]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () func callFinalSuperMethod() { doFoo(super.finalMethod) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super5Child25callFinalSuperClassMethodfT_T_ : $@convention(method) (@thick Child.Type) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TZFC19partial_apply_super6Parent16finalClassMethodFT_T_ : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> () // CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> () // CHECK: apply [[DOFOO]]([[APPLIED_SELF]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () class func callFinalSuperClassMethod() { doFoo(super.finalClassMethod) } } class GenericChild<A> : GenericParent<A> { override init(a: A) { super.init(a: a) } // CHECK-LABEL: sil hidden @_TFC19partial_apply_super12GenericChild6methodfT_T_ : $@convention(method) <A> (@guaranteed GenericChild<A>) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $GenericChild<A> to $GenericParent<A> // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TTdFC19partial_apply_super13GenericParent6methodFT_T_ : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_owned () -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_owned () -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super12GenericChild11classMethodfT_T_ : $@convention(method) <A> (@thick GenericChild<A>.Type) -> () // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChild<A>.Type to $@thick GenericParent<A>.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TTdZFC19partial_apply_super13GenericParent11classMethodFT_T_ : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_owned () -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply %4<A>(%3) : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_owned () -> () // CHECK: apply %2(%5) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } } class ChildToFixedOutsideParent : OutsideParent { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super25ChildToFixedOutsideParent6methodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $ChildToFixedOutsideParent to $OutsideParent // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $ChildToFixedOutsideParent, #OutsideParent.method!1 : (OutsideParent) -> () -> () , $@convention(method) (@guaranteed OutsideParent) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@guaranteed OutsideParent) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super25ChildToFixedOutsideParent11classMethodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToFixedOutsideParent.Type to $@thick OutsideParent.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToFixedOutsideParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> () , $@convention(method) (@thick OutsideParent.Type) -> (){{.*}} // user: %5 // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick OutsideParent.Type) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } } class ChildToResilientOutsideParent : ResilientOutsideParent { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super29ChildToResilientOutsideParent6methodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $ChildToResilientOutsideParent to $ResilientOutsideParent // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $ChildToResilientOutsideParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> () , $@convention(method) (@guaranteed ResilientOutsideParent) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@guaranteed ResilientOutsideParent) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super29ChildToResilientOutsideParent11classMethodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToResilientOutsideParent.Type to $@thick ResilientOutsideParent.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToResilientOutsideParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> () , $@convention(method) (@thick ResilientOutsideParent.Type) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideParent.Type) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } } class GrandchildToFixedOutsideChild : OutsideChild { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super29GrandchildToFixedOutsideChild6methodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $GrandchildToFixedOutsideChild to $OutsideChild // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $GrandchildToFixedOutsideChild, #OutsideChild.method!1 : (OutsideChild) -> () -> () , $@convention(method) (@guaranteed OutsideChild) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply %5(%4) : $@convention(method) (@guaranteed OutsideChild) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super29GrandchildToFixedOutsideChild11classMethodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToFixedOutsideChild.Type to $@thick OutsideChild.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToFixedOutsideChild.Type, #OutsideChild.classMethod!1 : (OutsideChild.Type) -> () -> () , $@convention(method) (@thick OutsideChild.Type) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply %4(%3) : $@convention(method) (@thick OutsideChild.Type) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } } class GrandchildToResilientOutsideChild : ResilientOutsideChild { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super33GrandchildToResilientOutsideChild6methodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $GrandchildToResilientOutsideChild to $ResilientOutsideChild // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $GrandchildToResilientOutsideChild, #ResilientOutsideChild.method!1 : (ResilientOutsideChild) -> () -> () , $@convention(method) (@guaranteed ResilientOutsideChild) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@guaranteed ResilientOutsideChild) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super33GrandchildToResilientOutsideChild11classMethodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToResilientOutsideChild.Type to $@thick ResilientOutsideChild.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToResilientOutsideChild.Type, #ResilientOutsideChild.classMethod!1 : (ResilientOutsideChild.Type) -> () -> () , $@convention(method) (@thick ResilientOutsideChild.Type) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideChild.Type) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } } class GenericChildToFixedGenericOutsideParent<A> : GenericOutsideParent<A> { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super39GenericChildToFixedGenericOutsideParent6methodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $GenericChildToFixedGenericOutsideParent<A> to $GenericOutsideParent<A> // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $GenericChildToFixedGenericOutsideParent<A>, #GenericOutsideParent.method!1 : <A> (GenericOutsideParent<A>) -> () -> () , $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super39GenericChildToFixedGenericOutsideParent11classMethodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type to $@thick GenericOutsideParent<A>.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type, #GenericOutsideParent.classMethod!1 : <A> (GenericOutsideParent<A>.Type) -> () -> () , $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } } class GenericChildToResilientGenericOutsideParent<A> : ResilientGenericOutsideParent<A> { // CHECK-LABEL: sil hidden @_TFC19partial_apply_super43GenericChildToResilientGenericOutsideParent6methodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $GenericChildToResilientGenericOutsideParent<A> to $ResilientGenericOutsideParent<A> // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $GenericChildToResilientGenericOutsideParent<A>, #ResilientGenericOutsideParent.method!1 : <A> (ResilientGenericOutsideParent<A>) -> () -> () , $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override func method() { doFoo(super.method) } // CHECK-LABEL: sil hidden @_TZFC19partial_apply_super43GenericChildToResilientGenericOutsideParent11classMethodfT_T_ // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_TF19partial_apply_super5doFooFFT_T_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> () // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type to $@thick ResilientGenericOutsideParent<A>.Type // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type, #ResilientGenericOutsideParent.classMethod!1 : <A> (ResilientGenericOutsideParent<A>.Type) -> () -> () , $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> () // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> () // CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> () override class func classMethod() { doFoo(super.classMethod) } }
// // AllUsersViewController.swift // Spoint // // Created by kalyan on 09/12/17. // Copyright © 2017 Personal. All rights reserved. // import UIKit protocol UserSelectionDelegate { func usersSelected(users:[User]) } class AllUsersViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating { @IBOutlet var tableview:UITableView! var resultSearchController = UISearchController() var searchUsers = [User]() var selectionDelegate: UserSelectionDelegate? var viewType = 0 // Chatview @IBOutlet var bgImageView:UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. bgImageView.image = kAppDelegate?.bgImage tableview.register(FriendsTableViewCell.self) self.resultSearchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() controller.searchBar.searchBarStyle = .minimal self.tableview.tableHeaderView = controller.searchBar return controller })() self.navigationController?.extendedLayoutIncludesOpaqueBars = true //self.resultSearchController.searchBar.scopeButtonTitles = [String]() //self.tableview.allowsMultipleSelection = true self.showLoaderWithMessage(message: "Loading") FireBaseContants.firebaseConstant.getAllUserObserver { DispatchQueue.main.async { self.dismissLoader() } } } func updateSearchResults(for searchController: UISearchController) { let searchtext = searchController.searchBar.text?.lowercased().description let array = FireBaseContants.firebaseConstant.allUsers.filter { (message:User) -> Bool in return message.name.lowercased().hasPrefix(searchtext!) || message.email.lowercased().hasPrefix(searchtext!) || message.phone.hasPrefix(searchtext!) } searchUsers = array self.tableview.reloadData() } @IBAction func doneButtonAction(){ self.dismiss(animated: true) { /* for user in FireBaseContants.firebaseConstant.allUsers { let values = [keys.requestStatusKey: 0, keys.recieverKey: "123",keys.seeTimelineKey:true,keys.seeLocationKey:true,keys.notificationsKey:true,keys.senderKey:UserDefaults.standard.value(forKey: UserDefaultsKey.phoneNoKey) as! String,keys.timestampKey:Int64(TimeStamp)] as [String : Any] FireBaseContants.firebaseConstant.sendRequestToUser(user.userInfo.id,param: values ) }*/ } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchUsers.count == 0{ self.showEmptyMessage(message: "No data available", tableview: tableView) return 0 }else{ tableview.backgroundView = nil return searchUsers.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsTableViewCell") as! FriendsTableViewCell cell.titleLabel?.text = searchUsers[indexPath.item].name.capitalized cell.imageview?.kf.setImage(with: searchUsers[indexPath.item].profilePic) //FireBaseContants.firebaseConstant.allUsers[indexPath.item].selected = cell.checkmarkButton.isSelected ? true : false if cell.checkmarkButton.isSelected { //cell.checkmarkButton.isSelected = true }else{ // cell.checkmarkButton.isSelected = false } cell.contentView.backgroundColor = UIColor.clear cell.backgroundColor = UIColor.clear //cell.accessoryType = cell.isSelected ? .checkmark : .none // cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.showLoaderWithMessage(message: "Loading") self.dismiss(animated: true) { self.dismissLoader() self.selectionDelegate?.usersSelected(users: [self.searchUsers[indexPath.row]]) } resultSearchController.isActive = false // let selectedCell = tableView.cellForRow(at: indexPath)! as! FriendsTableViewCell // selectedCell.checkmarkButton.isSelected = true // FireBaseContants.firebaseConstant.allUsers[indexPath.item].selected = true } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { // let deselectedCell = tableView.cellForRow(at: indexPath)! as! FriendsTableViewCell // deselectedCell.checkmarkButton.isSelected = false // FireBaseContants.firebaseConstant.allUsers[indexPath.item].selected = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ }
// // Pokemon.swift // Pokedex // // Created by Praveen Yadav on 22/02/17. // Copyright © 2017 Missing Stack. All rights reserved. // import Foundation class Pokemon { fileprivate var _name: String! fileprivate var _pokedexId: Int! var name: String { if _name == nil { _name = "" } return _name } var pokedexId: Int { if _pokedexId == nil { _pokedexId = 0 } return _pokedexId } init(name: String, pokedexId: Int) { self._name = name self._pokedexId = pokedexId } }
import Foundation import Basic public final class SwiftyConverter { private let origin: String public init(origin: String) { self.origin = origin } public func convertFromBinary() throws -> ConvertedString { if let decimal = UInt(self.origin, radix: 2) { return ConvertedString(decimal: decimal) } else { throw NSError(domain: Msg.Error.Binary, code: -1, userInfo: nil) } } public func convertFromOctal() throws -> ConvertedString { if let decimal = UInt(self.origin, radix: 8) { return ConvertedString(decimal: decimal) } else { throw NSError(domain: Msg.Error.Octal, code: -1, userInfo: nil) } } public func convertFromDecimal() throws -> ConvertedString { if let decimal = UInt(self.origin) { return ConvertedString(decimal: decimal) } else { throw NSError(domain: Msg.Error.Decimal, code: -1, userInfo: nil) } } public func convertFromHex() throws -> ConvertedString { if let decimal = UInt(self.origin, radix: 16) { return ConvertedString(decimal: decimal) } else { throw NSError(domain: Msg.Error.Hex, code: -1, userInfo: nil) } } public func convertFromColorCode() throws -> Color { if let colorCode = self.getValidColorCode(self.origin), let code = UInt(colorCode, radix: 16) { return Color(code: code) } else { throw NSError(domain: Msg.Error.Color, code: -1, userInfo: nil) } } private func getValidColorCode(_ hex: String) -> String? { var hexString = hex if let range = hexString.range(of: "#") { hexString.removeSubrange(range) } return hexString.count == 6 ? hexString : nil } public func printOutputString(_ string: ConvertedString, terminal: TerminalController) { let b = "binary".padding(toLength: 8, withPad: " ", startingAt: 0) let o = "octal".padding(toLength: 8, withPad: " ", startingAt: 0) let d = "decimal".padding(toLength: 8, withPad: " ", startingAt: 0) let x = "hex".padding(toLength: 8, withPad: " ", startingAt: 0) print(terminal.wrap("\(b): ", inColor: .yellow) + string.binary) print(terminal.wrap("\(o): ", inColor: .yellow) + string.octal) print(terminal.wrap("\(d): ", inColor: .yellow) + string.decimal) print(terminal.wrap("\(x): ", inColor: .yellow) + string.hex) } public func printOutputString(color: Color, terminal: TerminalController) { let r = terminal.wrap(String(format: "%.2f", color.red), inColor: .red) let g = terminal.wrap(String(format: "%.2f", color.green), inColor: .green) let b = terminal.wrap(String(format: "%.2f", color.blue), inColor: .cyan) print("UIColor(red:\(r), green:\(g), blue:\(b), alpha:1.0)") } }
// // RecipeBooksShelfFlowLayout.swift // RecipeManager // // Created by Anton Stamme on 10.04.20. // Copyright © 2020 Anton Stamme. All rights reserved. // import Foundation import UIKit class RecipeBooksShelfFlowLayout: UICollectionViewFlowLayout { open var maxAngle : CGFloat = CGFloat.pi / 2 open var isFlat : Bool = false fileprivate var _halfDim : CGFloat { get { return _visibleRect.width / 2 } } fileprivate var _mid : CGFloat { get { return _visibleRect.midX } } fileprivate var _visibleRect : CGRect { get { if let cv = collectionView { return CGRect(origin: cv.contentOffset, size: cv.bounds.size) } return CGRect.zero } } func initialize() { minimumLineSpacing = 0.0 scrollDirection = .horizontal } override init() { super.init() self.initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let attributes = super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes { let distance = (attributes.frame.midX - _mid) var transform = CATransform3DIdentity if distance < 500 { let scale = (1 - abs(distance / 700)) transform = CATransform3DScale(transform, scale, scale, 1) // transform = CATransform3DTranslate(transform, -(distance * 0.75), 0, -abs(distance)) // attributes.alpha = (1 - abs(distance / 1500)) } // // transform = CATransform3DTranslate(transform, -distance, 0, -_halfDim) // transform = CATransform3DRotate(transform, currentAngle, 0, 1, 0) // // transform = CATransform3DTranslate(transform, 0, 0, _halfDim) attributes.transform3D = transform // attributes.alpha = abs(currentAngle) < maxAngle ? 1.0 : 0.0 return attributes } return nil } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes = [UICollectionViewLayoutAttributes]() if self.collectionView!.numberOfSections > 0 { for i in 0 ..< self.collectionView!.numberOfItems(inSection: 0) { let indexPath = IndexPath(item: i, section: 0) attributes.append(self.layoutAttributesForItem(at: indexPath)!) } } return attributes } var snapToCenter : Bool = true override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { if let collectionViewBounds = self.collectionView?.bounds { let halfWidthOfVC = collectionViewBounds.size.width * 0.5 let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidthOfVC if let attributesForVisibleCells = self.layoutAttributesForElements(in: collectionViewBounds) { var candidateAttribute : UICollectionViewLayoutAttributes? for attributes in attributesForVisibleCells { let candAttr : UICollectionViewLayoutAttributes? = candidateAttribute if candAttr != nil { let a = attributes.center.x - proposedContentOffsetCenterX let b = candAttr!.center.x - proposedContentOffsetCenterX if abs(a) < abs(b) { candidateAttribute = attributes } } else { candidateAttribute = attributes continue } } if candidateAttribute != nil { return CGPoint(x: candidateAttribute!.center.x - halfWidthOfVC, y: proposedContentOffset.y); } } } return CGPoint.zero } }
// // ViewController.swift // Kjorelista // // Created by Sven Aanesen on 04/03/2019. // Copyright © 2019 svenway. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() } func setupNavigationBar() { let image = UIImage(named: "add") navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(addButtonHandler(_:))) } @objc private func addButtonHandler(_ sender: UIBarButtonItem) { } }
// // ColorListCollectionView.swift // GriDot // // Created by 박찬울 on 2022/03/10. // import UIKit class ColorListCollectionView: UICollectionView { var currentPalette: Palette init(frame: CGRect, palette: Palette) { self.currentPalette = palette let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.itemSize = CGSize(width: 60, height: 60) layout.scrollDirection = .horizontal super.init(frame: frame, collectionViewLayout: layout) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ColorListCollectionView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return currentPalette.colors!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "colorCell", for: indexPath) as? ColorCellAtRename else { return UICollectionViewCell() } let hex = currentPalette.colors![indexPath.row] cell.contentView.backgroundColor = hex.uicolor return cell } } extension ColorListCollectionView: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let oneSideLength = self.frame.height return CGSize(width: oneSideLength, height: oneSideLength) } } class ColorCellAtRename: UICollectionViewCell { }
// // UserPersistence.swift // FastNet // // Created by Julian Hulme on 2016/02/21. // Copyright © 2016 ArcadeSoftware. All rights reserved. // import Foundation class User: NSObject, NSCoding { var firstName:String? var email:String? required init(firstName:String?, email:String?) { self.firstName = firstName self.email = email } // MARK: - NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.firstName, forKey: "firstName") aCoder.encodeObject(self.email, forKey: "email") } required convenience init?(coder aDecoder: NSCoder) { let firstName = aDecoder.decodeObjectForKey("firstName") as? String let email = aDecoder.decodeObjectForKey("email") as? String self.init(firstName:firstName, email:email) } }
// // DaySix.swift // aoc2020 // // Created by Shawn Veader on 12/6/20. // import Foundation struct DaySix2020: AdventDay { var year = 2020 var dayNumber = 6 var dayTitle = "Custom Customs" var stars = 2 func parse(_ input: String?) -> [CustomsForm] { (input ?? "") .replacingOccurrences(of: "\n\n", with: "|") .split(separator: "|") .map(String.init) .compactMap { CustomsForm($0) } } func partOne(input: String?) -> Any { let forms = parse(input) return forms.reduce(0) { $0 + $1.yesQuestions } } func partTwo(input: String?) -> Any { let forms = parse(input) return forms.reduce(0) { $0 + $1.groupYesQuestions } } }
// // Poi.swift // MapKit0106 // // Created by Luc Derosne on 09/07/2019. // Copyright © 2019 Luc Derosne. All rights reserved. // // point d'intérêt import MapKit import UIKit struct Location { // vive la France static let trouville = Poi(title: "Trouville", subtitle: "", coordinate: CLLocationCoordinate2D(latitude: 49.367384, longitude: 0.074862), info: "Normandie", type: .playa) static let parcecrins = Poi(title: "Parc des écrins", subtitle: "", coordinate: CLLocationCoordinate2D(latitude: 44.841066, longitude: 6.281187), info: "Hautes Alpes", type: .parque) } class Poi: NSObject, MKAnnotation { enum PoiType : String { case playa = "Plage" case parque = "Parc" } let poiType : PoiType var coordinate: CLLocationCoordinate2D var title: String? var subtitle: String? var info: String init(title: String, subtitle: String, coordinate: CLLocationCoordinate2D, info: String,type: PoiType) { poiType = type self.title = title self.subtitle = subtitle self.coordinate = coordinate self.info = info } }
// // File.swift // // // Created by Noah Kamara on 30.10.20. // import Foundation extension API.Models { public struct Episode: Decodable, Playable { public let id: String public let name: String public let type: MediaType public let seasonName: String public let seasonId: String public let index: Int? public let parentIndex: Int public let overview: String? public let genres: [Genre]? public let mediaSources: [MediaSource] private var imageBlurHashes: [String: [String: String]]? public func blurHash(for imageType: ImageType) -> String? { guard let hashes = imageBlurHashes else { return nil } return hashes[imageType.rawValue]?.values.first } private let communityRatingRaw: Double? public var communityRating: Int? { if let raw = communityRatingRaw { return Int(round(raw*10)) } else { return nil } } public let userData: UserData enum CodingKeys: String, CodingKey { case name = "Name" case id = "Id" case type = "Type" case seasonName = "SeasonName" case seasonId = "SeasonId" case index = "IndexNumber" case parentIndex = "ParentIndexNumber" case mediaSources = "MediaSources" case imageBlurHashes = "ImageBlurHashes" case overview = "Overview" case genres = "GenreItems" case communityRatingRaw = "CommunityRating" case userData = "UserData" } } }
// // CSResponse.swift // COpenSSL // // Created by Georgie Ivanov on 13.11.19. // import Foundation import PerfectHTTP public struct CSResponse<T: Encodable>: Encodable { let body: T let type: CSResponseType var viewType: CSViewType } public enum CSResponseType: String, Encodable { case json case string case number case bool case jsonString } public extension HTTPResponse { func sendResponse<T: Encodable>(body b: T, responseType rt: CSResponseType, viewType vt: CSViewType = .entityView, statusCode: HTTPResponseStatus = .ok) { let response: CSResponse = CSResponse(body: b, type: rt, viewType: vt) do { try self.setBody(json: response) self.completed(status: statusCode) }catch{ self.completed(status: .internalServerError) } } }
// // SeriesSearchResponse.swift // jobsitychallenge // // Created by Rafael Freitas on 16/01/21. // import Foundation struct SeriesSearchResponse: Decodable { var score: Float var show: SerieDataResponse }