text
stringlengths
8
1.32M
// // AddNewDeviceViewController.swift // PaymentsApp // // Created by Chinmay Bapna on 29/07/20. // Copyright © 2020 Chinmay Bapna. All rights reserved. // import UIKit import Alamofire class AddNewDeviceViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var DOBTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! private var datePicker : UIDatePicker? @IBOutlet weak var addButton: UIButton! override func viewDidLoad() { super.viewDidLoad() datePicker = UIDatePicker() datePicker?.datePickerMode = .date DOBTextField.inputView = datePicker datePicker?.addTarget(self, action: #selector(dateChanged(datePicker:)), for: .valueChanged) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped)) view.addGestureRecognizer(tapGesture) nameTextField.delegate = self DOBTextField.delegate = self emailTextField.delegate = self phoneTextField.delegate = self addButton.layer.cornerRadius = 20 nameTextField.layer.cornerRadius = 10 DOBTextField.layer.cornerRadius = 10 emailTextField.layer.cornerRadius = 10 phoneTextField.layer.cornerRadius = 10 nameTextField.backgroundColor = #colorLiteral(red: 0.7373645306, green: 0.9292912483, blue: 0.7189010978, alpha: 1) DOBTextField.backgroundColor = #colorLiteral(red: 0.7373645306, green: 0.9292912483, blue: 0.7189010978, alpha: 1) emailTextField.backgroundColor = #colorLiteral(red: 0.7373645306, green: 0.9292912483, blue: 0.7189010978, alpha: 1) phoneTextField.backgroundColor = #colorLiteral(red: 0.7373645306, green: 0.9292912483, blue: 0.7189010978, alpha: 1) nameTextField.attributedPlaceholder = NSAttributedString(string: "Name", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) DOBTextField.attributedPlaceholder = NSAttributedString(string: "Date of Birth", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) emailTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) phoneTextField.attributedPlaceholder = NSAttributedString(string: "Phone Number", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == phoneTextField { let maxLength = 10 let currentString: NSString = textField.text! as NSString let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString return newString.length <= maxLength } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { view.endEditing(true) return true } @objc func viewTapped() { view.endEditing(true) } @objc func dateChanged(datePicker : UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" DOBTextField.text = dateFormatter.string(from: datePicker.date) } @IBAction func addButtonPressed() { if nameTextField.text == "", DOBTextField.text == "", emailTextField.text == "", phoneTextField.text == "" { //show error } else if phoneTextField.text!.count < 10 { //show error } else { saveNewAccountToBackend() } } func saveNewAccountToBackend() { let url = "https://paye-backend-adminpanel.herokuapp.com/api/users/register" let parameters : [String: Any] = [ "name": nameTextField.text!, "phone": "+44" + phoneTextField.text!, "pin": "0000", "role": "merchant", "userGroupId": UserDefaults.standard.string(forKey: "userGroupId")!, "details": [ "isSubAcc": true, "DOB": DOBTextField.text!, "email": emailTextField.text! ] ] AF.request(URL(string: url)!, method: .post, parameters: parameters as Parameters, encoding: JSONEncoding.default).responseString { (response) in print(response.result) switch response.result { case .success(let success): self.performSegue(withIdentifier: "device_added", sender: nil) break case .failure(let error): break } } } }
// // RTCVideoBase.swift // WebRTCDemo // // Created by Hydeguo on 24/01/2018. // Copyright © 2018 Hydeguo. All rights reserved. // import Foundation import Starscream import WebRTC enum JanusType { case Join case Listparticipants } public class RTCVideoServer: WebSocketDelegate, OMGRTCServerDelegate { open var isNewRoom: Bool = false open var initPublish = true open var maxViewer = 5000 open var display: String = "" var roomId: Int64 = 1234 var session_id: Int64 = 0 var private_id: Int64 = 0 var janusId_id_to_handle: [String: Int64] = [:] var info_from_janusId: [Int64: Publisher] = [:] open var client: RTCClient? var type: JanusType = .Join private var socket: WebSocket? private var tempRemotSdp: String? private var _aliveTimer: Timer? var myJanusId: String = "" var commandList = [BaseCommand]() /** url : handshake socket server url */ public init(url: String, client: RTCClient) { socket = WebSocket(url: URL(string: url)!, protocols: ["janus-protocol"]) socket?.delegate = self self.client = client } func setSessionId(_ id: Int64) { session_id = id _aliveTimer = Timer.scheduledTimer(timeInterval: 25, target: self, selector: #selector(senfAlive), userInfo: nil, repeats: true) } @objc func senfAlive() { sendCommand(command: KeepAliveCommand(delegate: self, handleId: 0)) } public func getHandIdForJanusId(id: String) -> Int64? { for (janusId, handleId) in janusId_id_to_handle { if janusId == id { return handleId } } return nil } public func getJanusIdFromHandId(id: Int64) -> String? { for (janusId, handleId) in janusId_id_to_handle { if handleId == id { return janusId } } return nil } public func getDisplayForJanusId(id: String) -> String? { for (janusId, publishData) in info_from_janusId { if String(janusId) == id { return publishData.display } } return nil } public func getJanusIdForDisplay(display: String) -> Int64? { for (janusId, publishData) in info_from_janusId { if publishData.display == display { return janusId } } return nil } public func getHandIdForDisplay(display: String) -> Int64? { if let janusId = getJanusIdForDisplay(display: display) { return getHandIdForJanusId(id: String(janusId)) } return nil } public func unpublishMyself() { if let myHanldId = getHandIdForJanusId(id: myJanusId) { sendCommand(command: UnpublishCommand(delegate: self, handleId: myHanldId)) } } public func publishMyself() { client?.startConnection(myJanusId, localStream: true) client?.makeOffer(myJanusId) } public func sendCommand(command: BaseCommand) { commandList.append(command) let sendText = command.getSendData() socket?.write(string: sendText) } public func websocketDidConnect(socket: WebSocketClient) { print("[websocket connected]") janusId_id_to_handle = [:] info_from_janusId = [:] self.sendCommand(command: CreateCommand(delegate: self, handleId: 0)) } public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { if let e = error { print("[websocket is disconnected: \(e.localizedDescription)]") } else { print("[websocket disconnected]") } } public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { onDataReceived(str: text) } public func websocketDidReceiveData(socket: WebSocketClient, data: Data) { // print("Received data: \(data.count)") let dataString = String(data: data, encoding: .utf8)! onDataReceived(str: dataString) } func onDataReceived(str: String) { #if DEBUG print("[Received text]:\n___start___\n \(str)\n___end___") #endif if str.contains("transaction") { for command in commandList { if str.contains(command.transaction) { command.receive(strData: str) } } } else { if str.contains("unpublished") { ReceiveUnpublishCommand(delegate: self, handleId: 0).receive(strData: str) } else if str.contains("publishers") { if (client?.getConnectActiveNum())! - 1 < maxViewer { NewJoinActiveCommand(delegate: self, handleId: 0).receive(strData: str) } } } cleanTimeOutCommad() } public func registerMeetRoom(_ roomId: Int64) { self.roomId = roomId socket?.connect() print("[registerMeetRoom]:\(roomId),clientId:\(myJanusId)") } public func disconnectMeetingById(id: String) { client?.disconnect(id) } public func disconnectMeeting() { client?.disconnectAll() socket?.disconnect() _aliveTimer?.invalidate() } deinit { _aliveTimer?.invalidate() socket?.disconnect() socket?.delegate = nil socket = nil client?.disconnectAll() client?.delegate = nil client = nil } // private func doRegister() // { // let props = ["cmd": "register", "clientid":clientId,"roomid":roomId] as [String : Any] // do { // let jsonData = try JSONSerialization.data(withJSONObject: props, // options: .prettyPrinted) // socket?.write(string:String(data: jsonData, encoding: String.Encoding.utf8)!) // print("[doRegister]:\(roomId),clientId:\(clientId)") // } catch let error { // print("error converting to json: \(error)") // } // } func sendMsg(string: String) { socket?.write(string: string) } private func returnJsonStr(data: [String: Any]) -> String { do { let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted) return (String(data: jsonData, encoding: String.Encoding.utf8))! } catch { print("error converting to json: \(error)") return "" } } private func cleanTimeOutCommad() { let now = Date().timeIntervalSince1970 var active = [BaseCommand]() for command in commandList { if now - command.time < 30 { active.append(command) } } commandList = active } }
// // UIViewController+Extension.swift // Seraph // // Created by Musa Mahmud on 4/5/19. // Copyright © 2019 Mubtasim Mahmud. All rights reserved. // import UIKit extension UIViewController { // Hide when tapped anywhere on the view // Note: note being used anymore func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } // Dismiss keyboard @objc func dismissKeyboard() { view.endEditing(true) } // Display alert and execute the custom handler passed in as an argument func displayMessage(title: String, message: String, onCompletion: @escaping () -> Void) { // display alert with the specified title and message let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) // Get alert content view let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView // change background color of alert window to dark subview.backgroundColor = UIColor(red: 35/255, green: 35/255, blue: 35/255, alpha: 1) // change font color/size for alert text alert.setValue(NSAttributedString(string: title, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17),NSAttributedString.Key.foregroundColor : UIColor.white]), forKey: "attributedTitle") alert.setValue(NSAttributedString(string: message, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor : UIColor.lightGray]), forKey: "attributedMessage") // change button text color for alert alert.view.tintColor = UIColor(red: 85/255, green: 186/255, blue: 85/255, alpha: 1) // pop current view controller on dismissing alert message alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { (_) in onCompletion() })) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.destructive, handler: nil) ) self.present(alert, animated: true, completion: nil) } }
// // WeatherTaskTests.swift // WeatherTaskTests // // Created by Riddhi Ojha on 11/28/17. // Copyright © 2017 Riddhi Ojha. All rights reserved. // import XCTest import CoreLocation @testable import WeatherTask class WeatherTaskTests: XCTestCase, WeatherDetailsDelegate, WeatherLocationDelegate{ var locationTest:FetchWeatherLocation?=nil var weatherTest:WeatherDetails?=nil override func setUp() { super.setUp() locationTest = FetchWeatherLocation(delegate: self) weatherTest = WeatherDetails(delegate: self) locationTest?.getLocation() weatherTest?.fetchWeatherInfo(city: "Dubai") // Put setup code here. This method is called before the invocation of each test method in the class. } func didGetWeather(weather: WeatherData) { print("SUCCESS") } func didNotGetWeather(error: NSError) { } func didFetchLocation(location: CLLocation) { print("SUCCESS") } func unableToFetchLocation() { } func showAlertForOpenSettings(alert: UIAlertController) { } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() locationTest = nil weatherTest = nil } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
// // MVMoviesDataSource.swift // Movies // // Created by Daniel Amaral on 07/03/18. // Copyright © 2018 Ilhasoft. All rights reserved. // import UIKit import RxSwift protocol MVMoviesDataSource: class { func getMovies(by name: String, page: Int) -> Observable<MVMovieSearch> func getImage(by path: String) -> Observable<UIImage> }
// // SavedFilesViewController.swift // Machine Details // // Created by David Sarkisyan on 19.03.2020. // Copyright © 2020 DavidS. All rights reserved. // import UIKit import Foundation import PDFKit class SavedFilesViewController: UIViewController, SavedFilesViewControllerProtocol{ var files: [(String, Data)] = [] var interactor: SavedFilesInteractorProtocol! let tableView = UITableView() override func viewDidLoad() { setupArchitecture() self.files = interactor.fetchFiles() tableView.delegate = self tableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { setupTableView() } func setupArchitecture(){ self.interactor = SavedFilesInteractor(viewController: self) } func setupTableView(){ view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true tableView.separatorInset = .zero tableView.separatorColor = .darkGray } func openPDF(index: Int){ let data = files[index].1 let viewController = PDFViewController(documentData: data, showSaveNotification: false) self.navigationController?.pushViewController(viewController, animated: true) } } extension SavedFilesViewController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return files.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = SaveFilesTableViewCell() let data = files[indexPath.row] cell.fileName = data.0 cell.setup() return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let tableViewHeight = tableView.bounds.height let filesNumber = CGFloat(files.count) return tableViewHeight / filesNumber } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { openPDF(index: indexPath.row) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ interactor.deletePDF(index: indexPath.row) tableView.reloadData() } } }
// // Constants.swift // Smack // // Created by Shalu Scaria on 2018-08-12. // Copyright © 2018 Shalu Scaria. All rights reserved. // import Foundation //segues let TO_LOGIN = "toLogin" let TO_CREATE_ACCOUNT = "toCreateAccount" let UNWIND = "unwind"
//import Vapor //import Crypto // //var userIDListener = [String]() // //public func sockets(_ websockets: NIOWebSocketServer) { // // websockets.get("echo-test") { ws, req in // print("ws connnected") // ws.onText { ws, text in // print("ws received: \(text)") // ws.send("echo - \(text)") // } // } // // websockets.get("listen", TrackingSession.parameter) { ws, req in // let session = try req.parameters.next(TrackingSession.self) // guard sessionManager.sessions[session] != nil else { // ws.close() // return // } // // print(session) // // sessionManager.add(listener: ws, to: session) // // ws.onText { ws, text in // let string = text // let data = string.data(using: .utf8)! // var a = MessageForm(time: "", content: "", roomID: 0, from: "", to: "") // // if let json = try? JSONDecoder().decode(MessageForm.self, from: data){ // a = json // let message = Message(time: a.time, content: a.content, roomID: a.roomID, from: a.from, to: a.to) // let _ = message.save(on: req) // print(a) // } //// do { //// if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any> //// { //// print("good json") //// print(jsonArray) // use the json here //// } else { //// print("bad json") //// } //// } catch let error as NSError { //// print(error) //// } // sessionManager.update(text, for: session, to: a.to) // } // } //}
// // ViewController.swift // TicTacToe // // Created by Konstantin Kostadinov on 12.11.19. // Copyright © 2019 Konstantin Kostadinov. All rights reserved. // import UIKit class GameConfigVC: UIViewController,UITextFieldDelegate { @IBOutlet weak var enterDetailsLabel: UILabel! @IBOutlet weak var playerOneNameLabel: UILabel! @IBOutlet weak var playerTwoNameLabel: UILabel! @IBOutlet weak var backgroundColorLabel: UILabel! @IBOutlet weak var playerOneTextField: UITextField! @IBOutlet weak var playerTwoTextField: UITextField! @IBOutlet weak var backgroundColorDropDown: DropDown! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "TicTacToe" setupDropDownMenu() // Do any additional setup after loading the view. } fileprivate func setupDropDownMenu(){ backgroundColorDropDown.text = "white" backgroundColorDropDown.optionArray = ["white","cyan","blue","gray"] backgroundColorDropDown.optionIds = [1,2,3,4] backgroundColorDropDown.textAlignment = .center backgroundColorDropDown.selectedRowColor = .lightGray backgroundColorDropDown.isSearchEnable = false backgroundColorDropDown.didSelect{(selectedText , index ,id) in var backgroundColor = self.backgroundColorDropDown.text backgroundColor = "\(selectedText)" if backgroundColor == "white"{ self.view.backgroundColor = .white self.navigationController?.navigationBar.barTintColor = .white } else if backgroundColor == "cyan"{ self.view.backgroundColor = .cyan self.navigationController?.navigationBar.barTintColor = .cyan }else if backgroundColor == "blue"{ self.view.backgroundColor = .blue self.navigationController?.navigationBar.barTintColor = .blue }else if backgroundColor == "gray"{ self.view.backgroundColor = .gray self.navigationController?.navigationBar.barTintColor = .gray } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func startButton(_ sender: Any) { } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destinationVC = segue.destination as! ViewController destinationVC.player1.name = playerOneTextField.text ?? "Player 1" destinationVC.player2.name = playerTwoTextField.text ?? "Player 2" destinationVC.view.backgroundColor = self.view.backgroundColor destinationVC.cellBackgroudColor = self.view.backgroundColor } }
// // File.swift // Tutorbot // // Created by student on 28/05/19. // Copyright © 2019 student. All rights reserved. // import Foundation class Disciplines{ var id: Int? var name: String? var description: String? var }
// // ViewController.swift // SwiftStretchHeaderEffect // // Created by AlexanderChen on 2019/8/7. // Copyright © 2019 AlexanderChen. All rights reserved. // import UIKit class ScrollViewController: UIViewController { @IBOutlet var scrollView:UIScrollView! @IBOutlet var headerView:UIView! @IBOutlet var avatarImage:UIImageView! private var offsetHeaderStop:CGFloat = 0 //Header上推到多少高度停止 override func viewDidLoad() { super.viewDidLoad() if navigationController != nil { let offsetGap = (navigationController?.navigationBar.frame.height)! + (UIApplication.shared.statusBarFrame.height) // navigationBar高度 (44或66)+ statusBar高度(22) offsetHeaderStop = headerView.frame.height - offsetGap }else { offsetHeaderStop = headerView.frame.height - 64 // 64為HeaderView上推後的高度 // offsetHeaderStop = headerView.frame.height - 88 //如果是XS等有瀏海的機種改用88 } navBarBgAlpha = 0 navBarTitleColor = .clear navBarBgColor = .clear isHiddenShadowImage = true avatarImage.layer.cornerRadius = 10.0 avatarImage.layer.borderColor = UIColor.white.cgColor avatarImage.layer.borderWidth = 3.0 } } extension ScrollViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // debugPrint("scrollView.contentOffset.y: \(scrollView.contentOffset.y)") // let offset = scrollView.contentOffset.y + headerView.frame.height let offset = scrollView.contentOffset.y var headerTransform = CATransform3DIdentity var avatarTransform = CATransform3DIdentity // debugPrint("scrollView.contentOffset.y: \(scrollView.contentOffset.y)") // PULL DOWN if offset < 0 { let headerScaleFactor:CGFloat = -(offset) / headerView.bounds.height // debugPrint("headerScaleFactor:\(headerScaleFactor))") let headerSizevariation = ((headerView.bounds.height * (1.0 + headerScaleFactor)) - headerView.bounds.height)/2.0 // debugPrint("headerSizevariation:\(headerSizevariation))") headerTransform = CATransform3DTranslate(headerTransform, 0, headerSizevariation, 0) headerTransform = CATransform3DScale(headerTransform, 1.0 + headerScaleFactor, 1.0 + headerScaleFactor, 0) // debugPrint("scrollView headerTransform:\(headerTransform))") } else { // SCROLL UP/DOWN ------------ // Header View ----------- headerTransform = CATransform3DTranslate(headerTransform, 0, max(-offsetHeaderStop, -offset), 0) //大頭照 ----------- let avatarScaleFactor = (min(offsetHeaderStop, offset)) / avatarImage.bounds.height / 1.4 // Slow down the animation let avatarSizeVariation = ((avatarImage.bounds.height * (1.0 + avatarScaleFactor)) - avatarImage.bounds.height) / 2.0 avatarTransform = CATransform3DTranslate(avatarTransform, 0, avatarSizeVariation, 0) avatarTransform = CATransform3DScale(avatarTransform, 1.0 - avatarScaleFactor, 1.0 - avatarScaleFactor, 0) // headerView 和 avatarImage 的 z-position 位置調動 if offset <= offsetHeaderStop { if avatarImage.layer.zPosition < headerView.layer.zPosition{ headerView.layer.zPosition = 0 } }else if avatarImage.layer.zPosition >= headerView.layer.zPosition { headerView.layer.zPosition = 2 } } // Apply Transformations headerView.layer.transform = headerTransform avatarImage.layer.transform = avatarTransform } }
// // OpenCage.swift // Dash // // Created by Yuji Nakayama on 2019/07/25. // Copyright © 2019 Yuji Nakayama. All rights reserved. // import Foundation import CoreLocation import MapKit class OpenCage { let apiKey: String init(apiKey: String) { self.apiKey = apiKey } func reverseGeocode(coordinate: CLLocationCoordinate2D, completionHandler: @escaping (Result<Place, Error>) -> Void) -> URLSessionTask { var urlComponents = URLComponents(string: "https://api.opencagedata.com/geocode/v1/json")! urlComponents.queryItems = [ URLQueryItem(name: "q", value: "\(coordinate.latitude),\(coordinate.longitude)"), URLQueryItem(name: "language", value: "native"), URLQueryItem(name: "no_annotations", value: "1"), URLQueryItem(name: "roadinfo", value: "1"), URLQueryItem(name: "key", value: apiKey) ] let task = urlSession.dataTask(with: urlComponents.url!) { (data, response, error) in if let error = error { completionHandler(.failure(error)) return } let result = Result<Place, Error>(catching: { let response = try JSONDecoder().decode(ReverseGeocodingResponse.self, from: data!) let result = response.results.first! let address = result.components let region = result.bounds let road = result.annotations.roadinfo return (address: address, region: region, road: road) }) completionHandler(result) } task.resume() return task } private lazy var urlSession = URLSession(configuration: urlSessionConfiguration) private lazy var urlSessionConfiguration: URLSessionConfiguration = { let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = 10 configuration.urlCache = nil return configuration }() } extension OpenCage { typealias Place = (address: Address, region: Region, road: Road?) struct ReverseGeocodingResponse: Decodable { let results: [ReverseGeocodingResult] } struct ReverseGeocodingResult: Decodable { enum CodingKeys: String, CodingKey { case annotations case bounds case components } let annotations: ReverseGeocodingAnnotation let bounds: Region let components: Address init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) annotations = try values.decode(ReverseGeocodingAnnotation.self, forKey: .annotations) bounds = try values.decode(Region.self, forKey: .bounds) components = try values.decode(Address.self, forKey: .components) } } struct ReverseGeocodingAnnotation: Decodable { static let nationWideRoadKeys = Set<Road.CodingKeys>([.trafficSide, .speedUnit]) enum CodingKeys: String, CodingKey { case roadinfo } let roadinfo: Road? init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let roadValues = try values.nestedContainer(keyedBy: Road.CodingKeys.self, forKey: .roadinfo) // OpenCage returns `drive_on` and `speed_in` values even in the sea if !Set(roadValues.allKeys).subtracting(Self.nationWideRoadKeys).isEmpty { roadinfo = try values.decode(Road.self, forKey: .roadinfo) } else { roadinfo = nil } } } struct Road: Decodable { enum CodingKeys: String, CodingKey { case trafficSide = "drive_on" case isOneWay = "oneway" case isTollRoad = "toll" case popularName = "road" case numberOfLanes = "lanes" case roadReference = "road_reference" case roadType = "road_type" case speedLimit = "maxspeed" case speedUnit = "speed_in" case surfaceType = "surface" } let trafficSide: TrafficSide? let isOneWay: Bool? let isTollRoad: Bool? let popularNames: [String] let numberOfLanes: Int? let routeNumber: Int? // e.g. 1 for Route 1 let identifier: String? // e.g. "E1" for Tomei Expressway let roadType: RoadType? let speedLimit: Int? let speedUnit: SpeedUnit? let surfaceType: String? init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) trafficSide = try values.decodeIfPresent(TrafficSide.self, forKey: .trafficSide) isOneWay = try values.decodeIfPresent(String.self, forKey: .isOneWay).map { $0 == "yes" } isTollRoad = try values.decodeIfPresent(String.self, forKey: .isTollRoad).map { $0 == "yes" } if let popularNameText = try values.decodeIfPresent(String.self, forKey: .popularName), popularNameText != "unnamed road" { // Some roads have popular name property containing multiple names (e.g. "目黒通り;東京都道312号白金台町等々力線") popularNames = popularNameText.split(separator: ";").map { String($0) } } else { popularNames = [] } numberOfLanes = try values.decodeIfPresent(Int.self, forKey: .numberOfLanes) if let referenceText = try? values.decodeIfPresent(String.self, forKey: .roadReference) { let references = referenceText.split(separator: ";").map({ String($0) }) routeNumber = references.first { Int($0) != nil }.map { Int($0)! } identifier = references.first { Int($0) == nil } } else { identifier = nil routeNumber = nil } roadType = try? values.decodeIfPresent(RoadType.self, forKey: .roadType) speedLimit = try values.decodeIfPresent(Int.self, forKey: .speedLimit) speedUnit = try values.decodeIfPresent(SpeedUnit.self, forKey: .speedUnit) surfaceType = try values.decodeIfPresent(String.self, forKey: .surfaceType) } } enum TrafficSide: String, Decodable { case leftHand = "left" case rightHand = "right" } // https://wiki.openstreetmap.org/wiki/JA:Key:highway // https://qiita.com/nyampire/items/7fa6efd944086aea820e enum RoadType: String, Decodable { case motorway // 高速道路 case trunk // 国道 case primary // 主要地方道 (mostly 都道府県道 but some 市道 are included such as 横浜市道環状2号; mostly 2-digits route number) case secondary // 一般都道府県道 (3-digits route number) case tertiary // Mostly 市町村道 having popular name, but some 都道府県道 are included such as 東京都道441号線, which is a 特例都道 case unclassified case residential case livingStreet = "living_street" case service case track case pedestrian } enum SpeedUnit: String, Decodable { case kilometersPerHour = "km/h" case milesPerHour = "mph" } struct Region: Decodable { static let earthCircumference: CLLocationDistance = 40000 * 1000 static let degreesPerMeter: CLLocationDistance = 360 / earthCircumference enum CodingKeys: String, CodingKey { case northeast case southwest } let northeast: CLLocationCoordinate2D let southwest: CLLocationCoordinate2D let latitudeRange: ClosedRange<CLLocationDegrees> let longitudeRange: ClosedRange<CLLocationDegrees> init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let northeast = try decodeCoordinate(from: values, forKey: .northeast) let southwest = try decodeCoordinate(from: values, forKey: .southwest) self.init(northeast: northeast, southwest: southwest) } init(northeast: CLLocationCoordinate2D, southwest: CLLocationCoordinate2D) { self.northeast = northeast self.southwest = southwest latitudeRange = southwest.latitude...northeast.latitude longitudeRange = southwest.longitude...northeast.longitude } func contains(_ coordinate: CLLocationCoordinate2D) -> Bool { return latitudeRange.contains(coordinate.latitude) && longitudeRange.contains(coordinate.longitude) } func extended(by distance: CLLocationDistance) -> Region { let newNortheast = CLLocationCoordinate2D( latitude: northeast.latitude + latitudeDelta(for: distance), longitude: northeast.longitude + longitudeDelta(for: distance, at: northeast) ) let newSouthwest = CLLocationCoordinate2D( latitude: southwest.latitude - latitudeDelta(for: distance), longitude: southwest.longitude - longitudeDelta(for: distance, at: southwest) ) return Region( northeast: newNortheast, southwest: newSouthwest ) } private func latitudeDelta(for meters: CLLocationDistance) -> CLLocationDegrees { return meters * Self.degreesPerMeter } private func longitudeDelta(for meters: CLLocationDistance, at coordinate: CLLocationCoordinate2D) -> CLLocationDegrees { return meters * Self.degreesPerMeter / cos(coordinate.latitude * .pi / 180) } } // https://github.com/OpenCageData/address-formatting/blob/c379c9f/conf/components.yaml struct Address: Decodable { let country: String? let postcode: String? let state: String? let province: String? let city: String? let city_block: String? let county: String? let town: String? let suburb: String? let neighbourhood: String? let quarter: String? // 35.63755713321449, 139.7048284895448 // "city"=>"目黒区", // "neighbourhood"=>"中目黒四丁目", // 36.05906586478792, 138.349589583782 // "county"=>"南佐久郡", // "province"=>"長野県", // "state"=>"長野県", // "town"=>"佐久穂町", // 35.628379512272765, 139.79711613490383 // "city"=>"江東区", // "city_block"=>"有明3", // "quarter"=>"有明", // 35.680786103826414, 139.75836050256484 // "city"=>"千代田区", // "neighbourhood"=>"丸の内1", // "quarter"=>"皇居外苑", // "suburb"=>"神田", // 35.533175370219716, 139.69416757984942 // "city"=>"川崎市", // "neighbourhood"=>"中幸町三丁目", // "province"=>"神奈川県", // "state"=>"神奈川県", // "suburb"=>"幸区", // https://github.com/OpenCageData/address-formatting/blob/c379c9f/conf/countries/worldwide.yaml#L1116-L1124 var components: [String] { return [ prefecture, city, county, town, [suburb, city_block, quarter].first { $0 != nil } ?? nil, neighbourhood ].compactMap { $0 } } var prefecture: String? { if let prefecture = state ?? province { return prefecture } // OpenCage doesn't return "東京都" for `state` property if let postcode = postcode, postcode.starts(with: "1") { return "東京都" } return nil } } } fileprivate func decodeCoordinate<SuperKey: CodingKey>(from superContainer: KeyedDecodingContainer<SuperKey>, forKey superKey: SuperKey) throws -> CLLocationCoordinate2D { let container = try superContainer.nestedContainer(keyedBy: CoordinateCodingKeys.self, forKey: superKey) let latitude = try container.decode(CLLocationDegrees.self, forKey: .latitude) let longitude = try container.decode(CLLocationDegrees.self, forKey: .longitude) return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } fileprivate enum CoordinateCodingKeys: String, CodingKey { case latitude = "lat" case longitude = "lng" }
import PackageDescription let package = Package( name: "VaporMongo", dependencies: [ .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1), .Package(url: "https://github.com/DanSessions/mongo-driver.git", Version(1, 0, 10)) ] )
// // Monomorphic.swift // Focus // // Created by Robert Widmann on 8/23/15. // Copyright © 2015 TypeLift. All rights reserved. // /// A `SimpleLens` is a `Lens` where the sources and targets a public struct SimpleLens<S, A> : LensType { public typealias Source = S public typealias Target = A public typealias AltSource = S public typealias AltTarget = A /// Gets the Indexed Costate Comonad Coalgebroid underlying the receiver. private let _run : S -> IxStore<A, A, S> public func run(v : S) -> IxStore<A, A, S> { return _run(v) } /// Produces a lens from an Indexed Costate Comonad Coalgebroid. public init(_ f : S -> IxStore<A, A, S>) { _run = f } /// Creates a lens from a getter/setter pair. public init(get : S -> A, set : (S, A) -> S) { self.init({ v in IxStore(get(v)) { set(v, $0) } }) } /// Creates a lens that transforms set values by a given function before they are returned. public init(get : S -> A, modify : (S, A -> A) -> S) { self.init(get: get, set: { v, x in modify(v) { _ in x } }) } } extension SimpleLens { public init<Other : LensType where S == Other.Source, A == Other.Target, S == Other.AltSource, A == Other.AltTarget> (_ other : Other) { self.init(other.run) } } extension SimpleLens : SetterType { public func over(f: A -> A) -> S -> S { return { s in self.modify(s, f) } } } public struct SimpleIso<S, A> : IsoType { public typealias Source = S public typealias Target = A public typealias AltSource = S public typealias AltTarget = A private let _get : S -> A private let _inject : A -> S /// Builds a monomorphic `Iso` from a pair of inverse functions. public init(get f : S -> A, inject g : A -> S) { _get = f _inject = g } public func get(v : S) -> A { return _get(v) } public func inject(x : A) -> S { return _inject(x) } } extension SimpleIso { public init<Other : IsoType where S == Other.Source, A == Other.Target, S == Other.AltSource, A == Other.AltTarget> (_ other : Other) { self.init(get: other.get, inject: other.inject) } } public struct SimplePrism<S, A> : PrismType { public typealias Source = S public typealias Target = A public typealias AltSource = S public typealias AltTarget = A private let _tryGet : S -> A? private let _inject : A -> S public init(tryGet f : S -> A?, inject g : A -> S) { _tryGet = f _inject = g } public func tryGet(v : Source) -> Target? { return _tryGet(v) } public func inject(x : AltTarget) -> AltSource { return _inject(x) } } extension SimplePrism { public init<Other : PrismType where S == Other.Source, A == Other.Target, S == Other.AltSource, A == Other.AltTarget> (_ other : Other) { self.init(tryGet: other.tryGet, inject: other.inject) } } extension SimplePrism : SetterType { public func over(f: A -> A) -> S -> S { return { s in self.tryModify(s, f) ?? s } } } public struct SimpleSetter<S, A> : SetterType { public typealias Source = S public typealias Target = A public typealias AltSource = S public typealias AltTarget = A private let _over : (A -> A) -> S -> S public init(over: (A -> A) -> S -> S) { self._over = over } public func over(f : A -> A) -> S -> S { return _over(f) } } extension SimpleSetter { public init<Other : SetterType where S == Other.Source, A == Other.Target, S == Other.AltSource, A == Other.AltTarget> (_ other : Other) { self.init(over: other.over) } }
// // ViewController.swift // Bookmark // // Created by 김희진 on 2021/07/23. // import UIKit protocol Search{ func onChange() } var bookLines: [BookmarkLineData] = BookmarkLineData.getBookmarkLines() var selectedProduct: BookmarkData? class ViewController: UIViewController { var delegate : Search? @IBOutlet var lblSelect: UIButton! @IBOutlet var tfSearch: UITextField! @IBOutlet var tableView: UITableView! @IBOutlet var domains: [UIButton]! @IBOutlet var editButton: UIBarButtonItem! var pickerView = UIPickerView() var selectedDomain: String = "" override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self // tableView.estimatedRowHeight = tableView.rowHeight // tableView.rowHeight = UITableView.automaticDimension // let bookCell = UINib(nibName: "TableTableViewCell" , bundle: nil) // self.tableView.register(bookCell, forCellReuseIdentifier: "bookCell") } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() } @IBAction func handleSelect(_ sender: Any) { domains.forEach{ button in UIView.animate(withDuration: 0.3, animations: { button.isHidden = !button.isHidden self.view.layoutIfNeeded() }) } } enum Domains: String { case naver = "Naver" case daum = "Daum" case kakao = "Kakao" } @IBAction func domainTapped(_ sender: UIButton) { selectedDomain = sender.titleLabel!.text! lblSelect.titleLabel!.text = sender.titleLabel!.text! domains.forEach{ button in UIView.animate(withDuration: 0.3, animations: { button.isHidden = !button.isHidden self.view.layoutIfNeeded() }) } guard let title = sender.currentTitle, let select = Domains(rawValue: title) else{ return } switch select { case .naver: print("naver") case .daum: print("daum") case .kakao: print("Kakao") } } @IBAction func searchTapped(_ sender: Any) { let data: String = tfSearch.text! let tabbar = tabBarController as! TabBarViewController if(selectedDomain != ""){ if (data != ""){ tabbar.keyword = String(data) tabbar.domain = selectedDomain tabBarController?.selectedIndex = 1 tfSearch.text = "" } else { let inputAlert = UIAlertController(title: "검색어를 입력하세요", message: "", preferredStyle: UIAlertController.Style.alert) //OK 버튼 -> 아무런 동작을 하지 않아 핸들러를 nil 로 설정 let onAction = UIAlertAction(title: "네", style: UIAlertAction.Style.default , handler: nil) //alert 만듬 inputAlert.addAction(onAction) //만든 alert를 띄움, present 메서드 이용 present(inputAlert, animated: true, completion: nil) } } else { let selectAlert = UIAlertController(title: "검색할 플랫폼을 선택하세요", message: "", preferredStyle: UIAlertController.Style.alert) //OK 버튼 -> 아무런 동작을 하지 않아 핸들러를 nil 로 설정 let onAction = UIAlertAction(title: "네", style: UIAlertAction.Style.default , handler: nil) //alert 만듬 selectAlert.addAction(onAction) //만든 alert를 띄움, present 메서드 이용 present(selectAlert, animated: true, completion: nil) } } @IBAction func btnWatch(_ sender: Any) { let miniWebTVC = storyboard?.instantiateViewController(withIdentifier: "MiniWebViewController") as! MiniWebViewController let contentView = (sender as AnyObject).superview let cell = contentView??.superview as! UITableViewCell let indexPath = tableView.indexPath(for: cell) let section = indexPath![0] let row = indexPath![1] miniWebTVC.webtoonLink = bookLines[section].bookmarks[row].link self.present(miniWebTVC, animated: true, completion: nil) } @IBAction func btnEdit(_ sender: Any) { if self.tableView.isEditing { self.tableView.isEditing = false self.editButton.title = "Edit" } else { self.tableView.isEditing = true self.editButton.title = "Done" } } } //extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource{ // // func numberOfComponents(in pickerView: UIPickerView) -> Int { // return 1 // } // func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { // return domains.count // } // func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { // return domains[row] // } // func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // tfSearch.text = domains[row] // // tfSearch.resignFirstResponder() // } extension ViewController : UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return bookLines.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookLines[section].bookmarks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath) as! ProductTableViewCell // let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath) as! TableTableViewCell let bookLine = bookLines[indexPath.section] let bookmarkList = bookLine.bookmarks let bookmark = bookmarkList[indexPath.row] // 이게 아래를 대체 cell.bookmarkList = bookmark return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let bookmarkLine = bookLines[section] return bookmarkLine.name } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let bookToMove = bookLines[sourceIndexPath.section].bookmarks[sourceIndexPath.row] bookLines[destinationIndexPath.section].bookmarks.insert(bookToMove, at: destinationIndexPath.row) bookLines[sourceIndexPath.section].bookmarks.remove(at: sourceIndexPath.row) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let bookLine = bookLines[indexPath.section] bookLine.bookmarks.remove(at: (indexPath as NSIndexPath).row) // tableView.reloadData() tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let productDetailTVC = storyboard?.instantiateViewController(withIdentifier: "ProductDetailTableViewController") as! ProductDetailTableViewController let bookLine = bookLines[indexPath.section] let bookmark = bookLine.bookmarks[indexPath.row] selectedProduct = bookmark productDetailTVC.bookmark = selectedProduct productDetailTVC.section = indexPath.section productDetailTVC.row = indexPath.row self.navigationController?.pushViewController(productDetailTVC, animated: true) } // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // // tableView.rowHeight = 80 // // // // // 셀을 가져오는데 nill 이면 셀에 UITableViewCell 을 넣어라 // // nil 방지 -> guard. nill 일때는 else 문이 리턴된다 // let cell = tableView.dequeueReusableCell(withIdentifier: "FriendCell", for: indexPath) as! FriendTableViewCell // // let friendData : FriendData = friendList[indexPath.row] // // // //위 델리게이트 메서드를 이용해 이제 cell 의 객체들이 사용될 수 있음 // //위의 배열 내용으로 초기화했음 , uiSwitch 는 false로 초기화 해도 되는데, 나는 그냥 배열 값으로 넣어줌 // //셀에 각 데이터들을 전달한다 // cell.uiName.text = friendData.name // cell.uiProfileMessage.text = friendData.profileMessage // cell.uiSwitch.isOn = friendData.isOn // cell.friend = friendData // // return cell // } }
// // APIErrors.swift // SKUAD // // Created by Virender Dall on 30/10/20. // Copyright © 2020 Virender Dall. All rights reserved. // import UIKit enum APIErrors: Error { case emptySearch case noImageFound case noMoreImagesFound } extension APIErrors { var localizedDescription: String { switch self { case .emptySearch: return "Please let's know what kind of images you want to search" case .noImageFound: return "No result found" case .noMoreImagesFound: return "No more images for the search" } } }
// // TransferViewController.swift // Adamant // // Created by Anokhov Pavel on 09.01.2018. // Copyright © 2018 Adamant. All rights reserved. // import UIKit import Eureka // MARK: - Localization extension String.adamantLocalized { struct transfer { static let addressPlaceholder = NSLocalizedString("TransferScene.Recipient.Placeholder", comment: "Transfer: recipient address placeholder") static let amountPlaceholder = NSLocalizedString("TransferScene.Amount.Placeholder", comment: "Transfer: transfer amount placeholder") static let addressValidationError = NSLocalizedString("TransferScene.Error.InvalidAddress", comment: "Transfer: Address validation error") static let amountZeroError = NSLocalizedString("TransferScene.Error.TooLittleMoney", comment: "Transfer: Amount is zero, or even negative notification") static let amountTooHigh = NSLocalizedString("TransferScene.Error.NotEnoughtMoney", comment: "Transfer: Amount is hiegher that user's total money notification") static let accountNotFound = NSLocalizedString("TransferScene.Error.AddressNotFound", comment: "Transfer: Address not found error") static let transferProcessingMessage = NSLocalizedString("TransferScene.SendingFundsProgress", comment: "Transfer: Processing message") static let transferSuccess = NSLocalizedString("TransferScene.TransferSuccessMessage", comment: "Transfer: Tokens transfered successfully message") private init() { } } } fileprivate extension String.adamantLocalized.alert { static let confirmSendMessageFormat = NSLocalizedString("TransferScene.SendConfirmFormat", comment: "Transfer: Confirm transfer %1$@ tokens to %2$@ message. Note two variables: at runtime %1$@ will be amount (with ADM suffix), and %2$@ will be recipient address. You can use address before amount with this so called 'position tokens'.") static let send = NSLocalizedString("TransferScene.Send", comment: "Transfer: Confirm transfer alert: Send tokens button") } // MARK: - class TransferViewController: FormViewController { // MARK: - Rows private enum Row { case balance case amount case maxToTransfer case address case fee case total case sendButton var tag: String { switch self { case .balance: return "balance" case .amount: return "amount" case .maxToTransfer: return "max" case .address: return "recipient" case .fee: return "fee" case .total: return "total" case .sendButton: return "send" } } var localized: String { switch self { case .balance: return NSLocalizedString("TransferScene.Row.Balance", comment: "Transfer: logged user balance.") case .amount: return NSLocalizedString("TransferScene.Row.Amount", comment: "Transfer: amount of adamant to transfer.") case .maxToTransfer: return NSLocalizedString("TransferScene.Row.MaxToTransfer", comment: "Transfer: maximum amount to transfer: available account money substracting transfer fee.") case .address: return NSLocalizedString("TransferScene.Row.Recipient", comment: "Transfer: recipient address") case .fee: return NSLocalizedString("TransferScene.Row.TransactionFee", comment: "Transfer: transfer fee") case .total: return NSLocalizedString("TransferScene.Row.Total", comment: "Transfer: total amount of transaction: money to transfer adding fee") case .sendButton: return NSLocalizedString("TransferScene.Row.Send", comment: "Transfer: Send button") } } } private enum Sections { case wallet case transferInfo var localized: String { switch self { case .wallet: return NSLocalizedString("TransferScene.Section.YourWallet", comment: "Transfer: 'Your wallet' section") case .transferInfo: return NSLocalizedString("TransferScene.Section.TransferInfo", comment: "Transfer: 'Transfer info' section") } } } // MARK: - Dependencies var apiService: ApiService! var accountService: AccountService! var dialogService: DialogService! private(set) var maxToTransfer: Double = 0.0 // MARK: - Properties let defaultFee = 0.5 var account: Account? private(set) var totalAmount: Double? = nil // MARK: - IBOutlets @IBOutlet weak var sendButton: UIBarButtonItem! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // MARK: - Wallet section if let account = account { sendButton.isEnabled = maxToTransfer > 0.0 let balance = (account.balance as NSDecimalNumber).doubleValue maxToTransfer = balance - defaultFee > 0 ? balance - defaultFee : 0.0 form +++ Section(Sections.wallet.localized) <<< DecimalRow() { $0.title = Row.balance.localized $0.value = balance $0.tag = Row.balance.tag $0.disabled = true $0.formatter = AdamantUtilities.currencyFormatter } <<< DecimalRow() { $0.title = Row.maxToTransfer.localized $0.value = maxToTransfer $0.tag = Row.maxToTransfer.tag $0.disabled = true $0.formatter = AdamantUtilities.currencyFormatter } } else { sendButton.isEnabled = false } // MARK: - Transfer section form +++ Section(Sections.transferInfo.localized) <<< TextRow() { $0.title = Row.address.localized $0.placeholder = String.adamantLocalized.transfer.addressPlaceholder $0.tag = Row.address.tag $0.add(rule: RuleClosure<String>(closure: { value -> ValidationError? in guard let value = value?.uppercased() else { return ValidationError(msg: String.adamantLocalized.transfer.addressValidationError) } switch AdamantUtilities.validateAdamantAddress(address: value) { case .valid: return nil case .system, .invalid: return ValidationError(msg: String.adamantLocalized.transfer.addressValidationError) } })) $0.validationOptions = .validatesOnBlur }.cellUpdate({ (cell, row) in cell.titleLabel?.textColor = row.isValid ? .black : .red }) <<< DecimalRow() { $0.title = Row.amount.localized $0.placeholder = String.adamantLocalized.transfer.amountPlaceholder $0.tag = Row.amount.tag $0.formatter = AdamantUtilities.currencyFormatter // $0.add(rule: RuleSmallerOrEqualThan<Double>(max: maxToTransfer)) // $0.validationOptions = .validatesOnChange }.onChange(amountChanged) <<< DecimalRow() { $0.title = Row.fee.localized $0.value = defaultFee $0.tag = Row.fee.tag $0.disabled = true $0.formatter = AdamantUtilities.currencyFormatter } <<< DecimalRow() { $0.title = Row.total.localized $0.value = nil $0.tag = Row.total.tag $0.disabled = true $0.formatter = AdamantUtilities.currencyFormatter } <<< ButtonRow() { $0.title = Row.sendButton.localized $0.tag = Row.sendButton.tag $0.disabled = Condition.function([Row.total.tag], { [weak self] form -> Bool in guard let row: DecimalRow = form.rowBy(tag: Row.amount.tag), let amount = row.value, amount > 0, AdamantUtilities.validateAmount(amount: Decimal(amount)), let maxToTransfer = self?.maxToTransfer else { return true } return amount > maxToTransfer }) }.onCellSelection({ [weak self] (cell, row) in self?.sendFunds(row) }) // MARK: - UI navigationAccessoryView.tintColor = UIColor.adamantPrimary for row in form.allRows { row.baseCell?.textLabel?.font = UIFont.adamantPrimary(size: 17) row.baseCell?.textLabel?.textColor = UIColor.adamantPrimary row.baseCell?.tintColor = UIColor.adamantPrimary // TODO: Not working. Somehow font get's dropped at runtime. // if let cell = row.baseCell as? TextFieldCell { // cell.textField.font = font // cell.textField.textColor = color // } } let button: ButtonRow? = form.rowBy(tag: Row.sendButton.tag) button?.evaluateDisabled() } // MARK: - Form Events private func amountChanged(row: DecimalRow) { guard let totalRow: DecimalRow = form.rowBy(tag: Row.total.tag), let account = account else { return } guard let amount = row.value else { totalAmount = nil sendButton.isEnabled = false row.cell.titleLabel?.textColor = .black return } totalAmount = amount + defaultFee totalRow.evaluateDisabled() totalRow.value = totalAmount totalRow.evaluateDisabled() if let totalAmount = totalAmount { if amount > 0, AdamantUtilities.validateAmount(amount: Decimal(amount)), totalAmount > 0.0 && totalAmount < (account.balance as NSDecimalNumber).doubleValue { sendButton.isEnabled = true row.cell.titleLabel?.textColor = .black } else { sendButton.isEnabled = false row.cell.titleLabel?.textColor = .red } } else { sendButton.isEnabled = false row.cell.titleLabel?.textColor = .black } } // MARK: - IBActions @IBAction func sendFunds(_ sender: Any) { guard let dialogService = self.dialogService, let apiService = self.apiService else { fatalError("Dependecies fatal error") } guard let account = accountService.account, let keypair = accountService.keypair else { return } guard let recipientRow = form.rowBy(tag: Row.address.tag) as? TextRow, let recipient = recipientRow.value, let amountRow = form.rowBy(tag: Row.amount.tag) as? DecimalRow, let raw = amountRow.value else { return } let amount = Decimal(raw) guard AdamantUtilities.validateAmount(amount: amount) else { dialogService.showWarning(withMessage: String.adamantLocalized.transfer.amountZeroError) return } switch AdamantUtilities.validateAdamantAddress(address: recipient) { case .valid: break case .system, .invalid: dialogService.showWarning(withMessage: String.adamantLocalized.transfer.addressValidationError) return } guard amount <= Decimal(maxToTransfer) else { dialogService.showWarning(withMessage: String.adamantLocalized.transfer.amountTooHigh) return } let alert = UIAlertController(title: String.localizedStringWithFormat(String.adamantLocalized.alert.confirmSendMessageFormat, "\(amount) \(AdamantUtilities.currencyCode)", recipient), message: "You can't undo this action.", preferredStyle: .alert) let cancelAction = UIAlertAction(title: String.adamantLocalized.alert.cancel , style: .cancel, handler: nil) let sendAction = UIAlertAction(title: String.adamantLocalized.alert.send, style: .default, handler: { _ in dialogService.showProgress(withMessage: String.adamantLocalized.transfer.transferProcessingMessage, userInteractionEnable: false) // Check if address is valid apiService.getPublicKey(byAddress: recipient) { result in switch result { case .success(_): apiService.transferFunds(sender: account.address, recipient: recipient, amount: amount, keypair: keypair) { [weak self] result in switch result { case .success(_): DispatchQueue.main.async { dialogService.showSuccess(withMessage: String.adamantLocalized.transfer.transferSuccess) self?.accountService.update() if let nav = self?.navigationController { nav.popViewController(animated: true) } else { self?.dismiss(animated: true, completion: nil) } } case .failure(let error): dialogService.showError(withMessage: error.localized, error: error) } } case .failure(let error): dialogService.showError(withMessage: String.adamantLocalized.transfer.accountNotFound, error: error) } } }) alert.addAction(cancelAction) alert.addAction(sendAction) present(alert, animated: true, completion: nil) } }
// // TransformerAttributeView.swift // Transformers // // Created by Willian Rodrigues on 16/02/21. // import UIKit protocol TransformerAttributeViewDelegate: class { func didUpdate(type: TransformerViewCardModels.PropertieType, value: Int) } final class TransformerAttributeView: UIView { // MARK: - Delegate weak var delegate: TransformerAttributeViewDelegate? // MARK: - Variables var type: TransformerViewCardModels.PropertieType // MARK: - Views private lazy var nameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = .boldSystemFont(ofSize: 14) label.text = "\(type.name):" label.addAccessibility() return label }() private lazy var textField: UITextField = { let textf = UITextField() textf.translatesAutoresizingMaskIntoConstraints = false textf.backgroundColor = UIColor.blue.withAlphaComponent(0.5) textf.layer.cornerRadius = 13 textf.isUserInteractionEnabled = false textf.keyboardType = .numberPad textf.text = "0" textf.textAlignment = .center textf.font = .boldSystemFont(ofSize: 14) textf.addAccessibility() return textf }() private lazy var controlOptions = TransformerViewAttributedButtons(delegate: self) // MARK: - Life Cycle init(type: TransformerViewCardModels.PropertieType, delegate: TransformerAttributeViewDelegate?) { self.type = type self.delegate = delegate super.init(frame: .zero) self.setupViews() } required convenience init?(coder: NSCoder) { self.init(type: .courage, delegate: nil) } // MARK: - Layout Functions private func setupViews() { translatesAutoresizingMaskIntoConstraints = false backgroundColor = .lightGray layer.cornerRadius = 10 addComponents() addComponentsConstraints() } private func addComponents() { addSubview(nameLabel) addSubview(textField) addSubview(controlOptions) } private func addComponentsConstraints() { addNameLabelConstraints() addTextFieldConstraints() addControlOptionsConstraints() } private func addNameLabelConstraints() { nameLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true nameLabel.centerYAnchor.constraint(equalTo: textField.centerYAnchor).isActive = true } private func addTextFieldConstraints() { textField.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true textField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5).isActive = true textField.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: 8).isActive = true textField.widthAnchor.constraint(equalToConstant: 26).isActive = true textField.heightAnchor.constraint(equalToConstant: 26).isActive = true } private func addControlOptionsConstraints() { controlOptions.topAnchor.constraint(equalTo: topAnchor).isActive = true controlOptions.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true controlOptions.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true controlOptions.widthAnchor.constraint(equalToConstant: 80).isActive = true } // MARK: - Public Functions public func setup(value: Int) { textField.text = String(value) textField.addAccessibility() } public func setup(color: UIColor) { nameLabel.textColor = color } public func setEditingMode(_ isEditing: Bool) { controlOptions.isHidden = !isEditing } } extension TransformerAttributeView: TransformerViewAttributedButtonsDelegate { func didTapIncrease() { let currentValue = Int(textField.text ?? "0") ?? 1 let nextValue = currentValue + 1 delegate?.didUpdate(type: type, value: nextValue) } func didTapDescrease() { let currentValue = Int(textField.text ?? "0") ?? 1 let nextValue = currentValue - 1 delegate?.didUpdate(type: type, value: nextValue) } }
// // EmojiCollectionViewCell.swift // EmojiArt // // Created by Chang Hyun Choi on 2019. 8. 25.. // Copyright © 2019년 IOHC. All rights reserved. // import UIKit class EmojiCollectionViewCell: UICollectionViewCell { @IBOutlet weak var label: UILabel! }
// // TableViewCellProtocol.swift // Arsenal // // Created by Zhu Shengqi on 2018/9/2. // Copyright © 2018 Zhu Shengqi. All rights reserved. // #if os(iOS) import UIKit public protocol TableViewCellProtocol: UITableViewCell & ViewModelViewProtocol & TableViewReusableViewSizingProtocol where ViewModel: TableViewCellModelProtocol { } #endif
// // WeatherForecastRxTests.swift // WeatherForecastRxTests // // Created by 愤怒大葱鸭 on 9/13/19. // Copyright © 2019 愤怒大葱鸭. All rights reserved. // import XCTest @testable import WeatherForecastRx class WeatherForecastRxTests: XCTestCase { override func setUp() { } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testAPIcall() { let nm = WeatherViewModel() // nm.setupWeather(lat: 50, lon: 50).subscribe(onNext: { (weather) in // // }).disposed(by: DisposeBag) } func testTableViewExisting() { let main = UIStoryboard.init(name: "Main", bundle: nil) let vc = main.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController _ = vc.view XCTAssertNotNil(vc.tblView) } }
// // Passport.swift // aoc2020 // // Created by Shawn Veader on 12/4/20. // import Foundation struct Passport { enum Field: String, CaseIterable { case birthYear = "byr" case issueYear = "iyr" case expYear = "eyr" case height = "hgt" case hairColor = "hcl" case eyeColor = "ecl" case passportID = "pid" case countryID = "cid" } let fields: [Field: String] init?(_ input: String) { var tmpFields = [Field: String]() input.replacingOccurrences(of: "\n", with: " ") // pretend it's one long string instead of multiple lines .split(separator: " ") // String -> [String] : separate fields .map(String.init) // [Substring] -> [String] : sigh... .forEach { fieldData in let pieces = fieldData.split(separator: ":").map(String.init) guard pieces.count == 2, let field = Field(rawValue: pieces[0]) else { return } tmpFields[field] = pieces[1] } fields = tmpFields } private var requiredFields: Set<Field> { Set(Field.allCases).subtracting(Set([Field.countryID])) } /// Examine the fields in the passport to determine if it is valid var valid: Bool { let intersection = Set(fields.keys).intersection(requiredFields) return intersection == requiredFields } var fullyValid: Bool { valid && fields.map({ validate(field: $0, value: $1) }).reduce(true) { $0 && $1 } } func validate(field: Field, value: String) -> Bool { switch field { case .birthYear: guard let year = Int(value), (1920...2002).contains(year) else { return false } return true case .issueYear: guard let year = Int(value), (2010...2020).contains(year) else { return false } return true case .expYear: guard let year = Int(value), (2020...2030).contains(year) else { return false } return true case .height: guard let height = Int(value.dropLast(2)) else { return false } if value.contains("cm") { return (150...193).contains(height) } else if value.contains("in") { return (59...76).contains(height) } else { return false } case .hairColor: guard value.matching(regex: "\\#[a-f0-9]{6}") != nil else { return false } return true case .eyeColor: return ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].contains(value) case .passportID: guard let match = value.matching(regex: "[0-9]{9}") else { return false } return match.match == value case .countryID: return true } } } extension Passport: CustomDebugStringConvertible { var debugDescription: String { "<Passport: [ " + fields.map({ "\($0.rawValue):\($1)" }).joined(separator: " ") + " ]>" } }
// // FloatingTextField.swift // PocketDex // // Created by Thomas Tenzin on 7/20/20. // Copyright © 2020 Thomas Tenzin. All rights reserved. // import SwiftUI struct FloatingTextField: View { let title: String let text: Binding<String> var body: some View { ZStack(alignment: .leading) { Text(title) .foregroundColor(text.wrappedValue.isEmpty ? Color(.placeholderText) : .accentColor) .offset(y: text.wrappedValue.isEmpty ? 0 : -25) .scaleEffect(text.wrappedValue.isEmpty ? 1 : 0.75, anchor: .leading) TextField("", text: text) } .padding(.top, 15) .animation(.spring(response: 0.4, dampingFraction: 0.3)) } }
// RUN: %target-parse-verify-swift protocol P1 { subscript (i: Int) -> Int { get } // expected-note{{protocol requires subscript with type '(Int) -> Int'}} } class C1 : P1 { subscript (i: Int) -> Int { get { return i } set {} } } struct S1 : P1 { subscript (i: Int) -> Int { get { return i } set {} } } struct S1Error : P1 { // expected-error{{type 'S1Error' does not conform to protocol 'P1'}} subscript (i: Int) -> Double { // expected-note{{candidate has non-matching type '(Int) -> Double'}} get { return Double(i) } set {} } } //===----------------------------------------------------------------------===// // Get-only property requirements //===----------------------------------------------------------------------===// protocol PropertyGet { var x : Int { get } // expected-note {{protocol requires property 'x' with type 'Int'}} } class PropertyGet_Stored : PropertyGet { var x : Int = 0 // ok } class PropertyGet_Immutable : PropertyGet { let x : Int = 0 // ok. } class PropertyGet_ComputedGetSet : PropertyGet { var x : Int { get { return 0 } set {} } // ok } class PropertyGet_ComputedGet : PropertyGet { var x : Int { return 0 } // ok } struct PropertyGet_StaticVar : PropertyGet { // expected-error {{type 'PropertyGet_StaticVar' does not conform to protocol 'PropertyGet'}} static var x : Int = 42 // expected-note {{candidate operates on a type, not an instance as required}} } //===----------------------------------------------------------------------===// // Get-Set property requirements //===----------------------------------------------------------------------===// protocol PropertyGetSet { var x : Int { get set } // expected-note 2{{protocol requires property 'x' with type 'Int'}} } class PropertyGetSet_Stored : PropertyGetSet { var x : Int = 0 // ok } class PropertyGetSet_Immutable : PropertyGetSet { // expected-error {{type 'PropertyGetSet_Immutable' does not conform to protocol 'PropertyGetSet'}} let x : Int = 0 // expected-note {{candidate is not settable, but protocol requires it}} } class PropertyGetSet_ComputedGetSet : PropertyGetSet { var x : Int { get { return 42 } set {} } // ok } class PropertyGetSet_ComputedGet : PropertyGetSet { // expected-error {{type 'PropertyGetSet_ComputedGet' does not conform to protocol 'PropertyGetSet'}} var x : Int { return 42 } // expected-note {{candidate is not settable, but protocol requires it}} } //===----------------------------------------------------------------------===// // Get-only subscript requirements //===----------------------------------------------------------------------===// protocol SubscriptGet { subscript(a : Int) -> Int { get } } class SubscriptGet_Get : SubscriptGet { subscript(a : Int) -> Int { return 0 } // ok } class SubscriptGet_GetSet : SubscriptGet { subscript(a : Int) -> Int { get { return 42 } set {} } // ok } //===----------------------------------------------------------------------===// // Get-set subscript requirements //===----------------------------------------------------------------------===// protocol SubscriptGetSet { subscript(a : Int) -> Int { get set } // expected-note {{protocol requires subscript with type '(Int) -> Int'}} } class SubscriptGetSet_Get : SubscriptGetSet { // expected-error {{type 'SubscriptGetSet_Get' does not conform to protocol 'SubscriptGetSet'}} subscript(a : Int) -> Int { return 0 } // expected-note {{candidate is not settable, but protocol requires it}} } class SubscriptGetSet_GetSet : SubscriptGetSet { subscript(a : Int) -> Int { get { return 42 } set {} } // ok }
// // Gate.swift // TwinStick_Shooter // // Created by William Leet on 6/27/20. // Copyright © 2020 William Leet. All rights reserved. // // Wall subclass used to handle the gates between rooms. // Comes with additional functions to let it change its bitmask and opacity accordingly import UIKit import SpriteKit import GameplayKit class Gate: Wall{ var direction: String! var isOpen: Bool = false //For the sake of practicality, gates can only use the more specific Wall constructor //The gate will be initialized as open convenience init(sprite: String, width: CGFloat, height: CGFloat, game_world: GameScene, place: String, open: Bool){ self.init(sprite: sprite, width: width, height: height, game_world: game_world) if(open){ //Sets bitmask settings to Gate, makes sprite transparent self.physicsBody!.categoryBitMask = CollisionType.Gate.rawValue self.physicsBody!.collisionBitMask = 0x0 self.physicsBody!.contactTestBitMask = CollisionType.Player.rawValue self.alpha = 0.0 } //Denotes the gate as a north, south, east, or west gate, allowing for accurate room transitions direction = place } func setClosed(){ isOpen = false //Sets bitmask settings to Wall, makes sprite opaque self.physicsBody!.categoryBitMask = CollisionType.Wall.rawValue self.physicsBody!.collisionBitMask = CollisionType.Player_Bullet.rawValue | CollisionType.Player.rawValue self.physicsBody!.contactTestBitMask = CollisionType.Player_Bullet.rawValue | CollisionType.Enemy_Bullet.rawValue self.alpha = 1.0 } func setOpen(){ isOpen = true //Sets bitmask settings to Gate, makes sprite transparent self.physicsBody!.categoryBitMask = CollisionType.Gate.rawValue self.physicsBody!.collisionBitMask = 0x0 self.physicsBody!.contactTestBitMask = CollisionType.Player.rawValue self.alpha = 0.0 } func open(){ isOpen = true //Functionally the same as 'setOpen', but fades the gate sprite out //Sets bitmask settings to Gate, makes sprite transparent self.physicsBody!.categoryBitMask = CollisionType.Gate.rawValue self.physicsBody!.collisionBitMask = 0x0 self.physicsBody!.contactTestBitMask = CollisionType.Player.rawValue //Fades in the gate sprite self.run(SKAction.repeat((SKAction.sequence([ SKAction.wait(forDuration: 0.02), SKAction.run{ self.alpha -= 0.05 } ])), count: 20)) } func close(){ isOpen = false //Functionally the same as 'setClosed', but fades the gate sprite in self.physicsBody!.categoryBitMask = CollisionType.Wall.rawValue self.physicsBody!.collisionBitMask = CollisionType.Player_Bullet.rawValue | CollisionType.Player.rawValue self.physicsBody!.contactTestBitMask = CollisionType.Player_Bullet.rawValue | CollisionType.Enemy_Bullet.rawValue self.run(SKAction.repeat((SKAction.sequence([ SKAction.wait(forDuration: 0.02), SKAction.run{ self.alpha += 0.05 } ])), count: 20)) } }
/*Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.*/ // Answer: each node knows the min of the substack below it, so when the min pops off the min can be updated class Node { var value: Int var next: Node? var nextMin: Int? init(value: Int) { self.value = value } } struct Stack { var head: Node? var min: Int? func printOut(){ guard var node = head else{ return } while let next = node.next{ print(node.value) node = next } print(node.value) } mutating func push(_ v: Int) { let newNode = Node(value: v) guard let node = head else { head = newNode min = v // assign min for new stacks on first push of value return } if let currentMin = min, v < currentMin { node.nextMin = currentMin min = v } else { node.nextMin = subStack()?.min } newNode.next = node head = newNode } mutating func pop() { if let node = head, let currentMin = min{ if node.value == currentMin { min = subStack()?.findMin() } } head = head?.next } func findMin() -> Int?{ guard var node = head else{ return nil } var min = node.value while let next = node.next{ if next.value < min{ min = next.value } node = next } if min > node.value{ min = node.value return min } return min } func subStack() -> Stack?{ guard let node = head else{ return nil } var newStack = Stack(head: node.next, min: nil) newStack.min = newStack.findMin() return newStack } } var stack = Stack() stack.push(11) stack.push(2) stack.push(33) stack.push(4) stack.push(54) stack.pop() stack.printOut() print("Min: ",stack.min as Any)
// // ContactInfo.swift // RandomUsersDataApp // // Created by Ирина Кузнецова on 09.06.2020. // Copyright © 2020 Irina Kuznetsova. All rights reserved. // struct Person { let name: String let secondName: String let phone: String let email: String var fullName: String { "\(name) \(secondName)" } } var contactsList = [Person]() extension Person { static func getPersonsList() -> [Person] { if contactsList.count != 0 { return contactsList } let shuffledName = DataManager().nameBase.shuffled() let shuffledSecondName = DataManager().secondNameBase.shuffled() let shuffledPhone = DataManager().phoneBase.shuffled() let shuffledEmail = DataManager().emailBase.shuffled() for index in 0 ..< DataManager().nameBase.count { contactsList.append ( Person ( name: shuffledName[index], secondName: shuffledSecondName[index], phone: shuffledPhone[index], email: shuffledEmail[index]) ) } return contactsList } }
import XCTest import SwiftSphereTests var tests = [XCTestCaseEntry]() tests += SwiftSphereTests.allTests() XCTMain(tests)
// // HowToPlayScene.swift // Tai Lopez - A Quest for Knowledge // // Created by John Marcus Mabanta on 2016-05-26. // Copyright © 2016 1337GamingElite. All rights reserved. // import Foundation import SpriteKit class HowToPlayScene: SKScene{ let playGameButton = SKLabelNode(fontNamed: "LemonMilk") override func didMove(to view: SKView) { currentGameState = gameState.preGame // Background Init let bg = SKSpriteNode(imageNamed: "background2") bg.size = self.size bg.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2) bg.zPosition = 0 self.addChild(bg) // How to Play Title let tutorialLabel = SKLabelNode(fontNamed: "Lobster1.4") tutorialLabel.text = "How to Play" tutorialLabel.fontSize = 180 tutorialLabel.fontColor = SKColor.green tutorialLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.75) tutorialLabel.zPosition = 1 self.addChild(tutorialLabel) // "How to move Tai Lopez" let movementLabel = SKLabelNode(fontNamed: "LemonMilk") movementLabel.text = "To move Tai Lopez, swipe left, right, up, or down." movementLabel.fontSize = 50 movementLabel.fontColor = SKColor.green movementLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.65) movementLabel.zPosition = 1 self.addChild(movementLabel) // "How to Shoot" let shootLabel = SKLabelNode(fontNamed: "LemonMilk") shootLabel.text = "To shoot, simply tap the screen." shootLabel.fontSize = 50 shootLabel.fontColor = SKColor.green shootLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.60) shootLabel.zPosition = 1 self.addChild(shootLabel) // "Limited Bullets" let limitLabel = SKLabelNode(fontNamed: "LemonMilk") limitLabel.text = "Remember, your bullets recharge over time" limitLabel.fontSize = 50 limitLabel.fontColor = SKColor.green limitLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.55) limitLabel.zPosition = 1 self.addChild(limitLabel) // "How To Die" let deathLabel = SKLabelNode(fontNamed: "LemonMilk") deathLabel.text = "You lose lives by missing targets." deathLabel.fontSize = 50 deathLabel.fontColor = SKColor.green deathLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2) deathLabel.zPosition = 1 self.addChild(deathLabel) // "How to John Cena" let johnCenaDeathLabel = SKLabelNode(fontNamed: "LemonMilk") johnCenaDeathLabel.text = "You get instant K.O'd if you get hit by Lamborghinis." johnCenaDeathLabel.fontSize = 40 johnCenaDeathLabel.fontColor = SKColor.green johnCenaDeathLabel.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.45) johnCenaDeathLabel.zPosition = 1 self.addChild(johnCenaDeathLabel) // PLay Game Button playGameButton.text = "Next Page" playGameButton.fontSize = 70 playGameButton.fontColor = SKColor.green playGameButton.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.2) playGameButton.zPosition = 1 self.addChild(playGameButton) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch: AnyObject in touches{ let pointOfTouch = touch.location(in: self) if playGameButton.contains(pointOfTouch){ let sceneToMoveTo = HowToPlayPG2(size: self.size) sceneToMoveTo.scaleMode = self.scaleMode let myTransition = SKTransition.doorsOpenHorizontal(withDuration: 1) self.view!.presentScene(sceneToMoveTo, transition: myTransition) } } } }
// // Constants.swift // nba-teams // // Created by Carlo Zuffetti on 19/06/21. // import Foundation // // MARK: - Constants // var CachedPlayers: Players? struct Constants { // // MARK: - Date Formatters // struct DateFormatters { static let simpleDateFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" return dateFormatter }() } // // MARK: - EndpointData // struct EndpointData { let baseUrl: String = "https://free-nba.p.rapidapi.com/" let apiHostKey: String = "x-rapidapi-host" let apiHostValue: String = "free-nba.p.rapidapi.com" let apiKeyKey: String = "x-rapidapi-key" let apiKeyValue: String = "bf4986b7f6msh81554ae6a1ae7a0p11ab0djsn8fe930c453d2" } }
// // BasicTypes.swift // Weather // // Created by Alvin Ling on 4/19/19. // Copyright © 2019 iOSPlayground. All rights reserved. // import Foundation extension Double { // MARK: - Unit conversions var fahrenheit: Double { return (self * 9.0 / 5.0) + 32 } var celcius: Double { return (self - 32) * 5.0 / 9.0 } var mph: Double { return self * 2.237 } var ms: Double { return self / 2.237 } }
import XCTest @testable import framework-search-pathTestSuite XCTMain([ testCase(framework-search-pathTests.allTests), ])
// // learnerMode.swift // learnerOOP // // Created by Stefandi Glivert on 15/05/19. // Copyright © 2019 Stefandi Glivert. All rights reserved. // import Foundation class learnerModel { var name: String var age:Int var gender: String var imageProfile: String init(nameLearner: String, ageLearner: Int, genderLearner: String, imageProfileLearner: String) { self.name = nameLearner self.age = ageLearner self.gender = genderLearner self.imageProfile = imageProfileLearner } func increaseAge() { self.age += 1 } } class Lamborghini { var name: String var horsePower: Int var speed: Int init(carName: String, carHorsePower: Int, carSpeed: Int) { self.name = carName self.horsePower = carHorsePower self.speed = carSpeed } func increaseSpeed(){ self.speed += 10 } func reduceSpeed() { self.speed -= 5 } func stopCar() { self.speed -= speed } func useNOS() { self.horsePower += 50 self.speed += 30 } }
// // DeliveryConfirmViewController.swift // ThirdEye Deliver // // Created by Tanay Kothari on 12/06/16. // Copyright © 2016 Tanay Kothari. All rights reserved. // import UIKit import Parse import ParseUI import Firebase class DeliveryConfirmViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var image: PFImageView! @IBOutlet weak var name: UITextField! @IBOutlet weak var price: UITextField! @IBOutlet weak var products: UITextView! @IBOutlet weak var shop: UITextField! @IBOutlet weak var address: UILabel! var delivery: PFObject? override func viewDidAppear(animated: Bool) { price.delegate = self price.text = delivery!["price"] as? String products.text = delivery!["productList"] as? String address.text = delivery!["dropAddress"] as? String shop.text = delivery!["shopName"] as? String let user = delivery!["orderer"] as! PFUser name.text = user["name"] as? String if let media = delivery!["price"] as? PFFile { image.file = media image.loadInBackground({ (img, error) -> Void in }) } } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } let root = Firebase(url:"https://pulsedeliver.firebaseio.com/deliveries") @IBAction func yes(sender: AnyObject) { delivery!["price"] = price.text delivery!["productList"] = products.text delivery?.saveInBackground() root.childByAppendingPath(self.delivery?.objectId).setValue("Finished") self.performSegueWithIdentifier("rate", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "rate" { let dest = segue.destinationViewController as! RatingsViewController dest.delivery = self.delivery } } }
// // RedirectHandlerTests.swift // OnestapSDK // // Created by Munir Wanis on 22/09/17. // Copyright © 2017 Stone Payments. All rights reserved. // import XCTest @testable import OnestapSDK class RedirectHandlerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testRedirectHandleImplementationConfigNotFoundError() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. do { _ = try RedirectHandlerImplementation(bundle: nil) } catch { switch error { case OSTErrors.plistNotFound: XCTAssertTrue(true) default: XCTFail() } } } }
// // SolveMeFirst.swift // Datasnok // // Created by Vladimir Urbano on 6/28/16. // Copyright © 2016 Vladimir Urbano. All rights reserved. // /* Welcome to HackerRank! The purpose of this challenge is to familiarize you with reading input from stdin (the standard input stream) and writing output to stdout (the standard output stream) using our environment. Review the code provided in the editor below, then complete the solveMeFirst function so that it returns the sum of two integers read from stdin. Take some time to understand this code so you're prepared to write it yourself in future challenges. Select a language below, and start coding! Input Format Code that reads input from stdin is provided for you in the editor. There are lines of input, and each line contains a single integer. Output Format Code that prints the sum calculated and returned by solveMeFirst is provided for you in the editor. */ class SolveMeFirst { init() { // read integers line by line let a = Int(readLine()!)! let b = Int(readLine()!)! // Hint: Type print(a + b) below print(a + b) } }
// // MemeTextFieldDelegate.swift // MemeMe2.0Project // // Created by Sean Conrad on 7/28/18. // Copyright © 2018 Sean Conrad. All rights reserved. // import UIKit // TODO: // WRITE SOME TESTS!!!!!!! class MemeTextFieldDelegate: NSObject, UITextFieldDelegate { private var defaultText = "" public func setDefaultText(newDefaultText: String){ defaultText = newDefaultText } public func getDefaultText() -> String { return defaultText } func textFieldDidBeginEditing(_ textField: UITextField){ let currentText = textField.text // If the current text is the default value, clear it so the user may enter a new value if currentText == defaultText { textField.text = "" } } func textFieldDidEndEditing(_ textField: UITextField) { // if text field is blank, assign to be the default value if let currentText = textField.text { if currentText == "" { textField.text = defaultText } } // dismiss the kyeboard textField.resignFirstResponder() } }
// // EntityJsonDecoder.swift // CoreDataJsonParser // // Created by Alex Belozierov on 9/8/19. // Copyright © 2019 Alex Belozierov. All rights reserved. // import CoreData struct EntityJsonDecoder { private var entityDecoder: EntityObjectJsonDecoder init(model: EntityModel) { entityDecoder = EntityObjectJsonDecoder(entityModel: model) } var entityModel: EntityModel { get { entityDecoder.entityModel } set { isKnownUniquelyReferenced(&entityDecoder) ? (entityDecoder.entityModel = newValue) : (entityDecoder = entityDecoder.copy(entityModel: newValue)) } } @inlinable func parse(json: Json, in object: NSManagedObject) throws { try entityDecoder.objectParser.value(json, object) } @inlinable func parse(json: Json, context: NSManagedObjectContext?) throws -> NSManagedObject { try entityDecoder.byContextParser.value(json, context) } @inlinable func create(json: Json, context: NSManagedObjectContext?) throws -> NSManagedObject { try entityDecoder.byContextCreator.value(json, context) } @inlinable func parse(json: Json, context: NSManagedObjectContext, predicate: NSPredicate) throws -> NSManagedObject { try entityDecoder.byPredicateParser.value(json, context, predicate) } @inlinable func findObject(json: Json, context: NSManagedObjectContext) throws -> NSManagedObject? { try entityDecoder.byJsonSearcher.value(json, context) } @inlinable func findObject(predicate: NSPredicate, context: NSManagedObjectContext) throws -> NSManagedObject? { try entityDecoder.byPredicateSearcher.value(predicate, context) } @inlinable func predicate(json: Json) throws -> NSPredicate? { try predicateDecoder?(json) } @inlinable var predicateDecoder: EntityObjectJsonDecoder.PredicateDecoder? { entityDecoder.predicateDecoder.value } }
// // AppSettings.swift // Singleton // // Created by Manoli on 28/10/2020. // import Foundation class AppSettings { static let shared = AppSettings() /* To serialize getting and setting methods prevents crashes while AppSettings are acessed from multiple threads on concurrent queues, but they might couse performance issues. private let serialQueue = DispatchQueue(label: "serialQueue") */ private let concurrentQueue = DispatchQueue(label: "concurrentQueue", attributes: .concurrent) private var settings: [String: Any] = [ "Theme": "Dark", "MaxConcurrentDownloads": 4 ] private init() { } func string(forKey key: String) -> String? { var result: String? /* Serialized Access serialQueue.sync { result = settings[key] as? String } */ concurrentQueue.sync { result = settings[key] as? String } return result } func int(forKey key: String) -> Int? { var result: Int? concurrentQueue.sync { result = settings[key] as? Int } return result } func set(value: Any, forKey key: String) { /* Serialized Access serialQueue.sync { settings[key] = value } */ concurrentQueue.async(flags: .barrier) { self.settings[key] = value } } }
// // Observable+Ext.swift // MapBoxTest // // Created by YanQi on 2020/04/15. // Copyright © 2020 Prageeth. All rights reserved. // import Foundation import RxSwift import RxCocoa import UIKit extension ObservableType where Element == Bool { /// Boolean not operator public func not() -> Observable<Bool> { return self.map(!) } } extension SharedSequenceConvertibleType { func mapToVoid() -> SharedSequence<SharingStrategy, Void> { return map { _ in } } } extension ObservableType { func catchErrorJustComplete() -> Observable<Element> { return catchError { _ in return Observable.empty() } } func asDriverOnErrorJustComplete() -> Driver<Element> { return asDriver { error in #if DEBUG assertionFailure("Error \(error)") #endif return Driver.empty() } } func asDriverOnSkipError() -> Driver<Element> { return asDriver { error in debugPrint("asDriverOnSkipError error: \(error)") return Driver.empty() } } func mapToVoid() -> Observable<Void> { return map { _ in } } func checkAccountValidity() -> Observable<Element> { return self.do(onError: { (error) in switch error { case let RxCocoa.RxCocoaURLError.httpRequestFailed(httpResponse, _): if httpResponse.statusCode == 401, let delegate = UIApplication.shared.delegate as? AppDelegate, let naviVC = delegate.currentKeyWindow()?.rootViewController as? UINavigationController, let mapVC = naviVC.viewControllers.first(where: { $0 is MapViewController }) { naviVC.popToViewController(mapVC, animated: false) MapViewNavigator.init(with: mapVC).toLogin() } default: break } }) } }
/// Wraps a given `Injector` in order to lose type details, but keeps it mutable. /// - Todo: Replace generic `I : Injector` with a `ProvidableKey` public struct AnyInjector<K: Hashable>: InjectorDerivingFromMutableInjector { public typealias Key = K /// The internally used `Injector`. private var injector: Any private let lambdaRevoke: (inout AnyInjector, Key) -> Void private let lambdaKeys: (AnyInjector) -> [K] private let lambdaResolve: (inout AnyInjector, Key) throws -> Providable private let lambdaProvide: (inout AnyInjector, K, @escaping (inout AnyInjector) throws -> Providable) -> Void /** Initializes `AnyInjector` with a given `MutableInjector`. - Parameter injector: The `MutableInjector` that shall be wrapped. */ public init<I: MutableInjector>(injector: I) where I.Key == K { self.injector = injector self.lambdaResolve = { (this: inout AnyInjector, key: Key) in // swiftlint:disable:next force_cast var injector = this.injector as! I defer { this.injector = injector } return try injector.resolve(key: key) } self.lambdaProvide = { this, key, factory in // swiftlint:disable:next force_cast var injector = this.injector as! I defer { this.injector = injector } injector.provide( key: key, usingFactory: { inj in var any = AnyInjector(injector: inj) return try factory(&any) }) } self.lambdaRevoke = { (this: inout AnyInjector, key: Key) in // swiftlint:disable:next force_cast var injector = this.injector as! I defer { this.injector = injector } injector.revoke(key: key) } self.lambdaKeys = { this in return (this.injector as! I).providedKeys } } /** Initializes `AnyInjector` with a given `Injector`. - Parameter injector: The `Injector` that shall be wrapped. */ public init<I: Injector>(injector: I) where I.Key == K { self.injector = injector self.lambdaResolve = { (this: inout AnyInjector, key: Key) in // swiftlint:disable:next force_cast return try (this.injector as! I).resolving(key: key) } self.lambdaProvide = { this, key, factory in // swiftlint:disable:next force_cast let injector = this.injector as! I this.injector = injector.providing( key: key, usingFactory: { inj in var any = AnyInjector(injector: inj) return try factory(&any) }) } self.lambdaRevoke = { (this: inout AnyInjector, key: Key) in // swiftlint:disable:next force_cast let injector = this.injector as! I this.injector = injector.revoking(key: key) } self.lambdaKeys = { this in return (this.injector as! I).providedKeys } } /// See `MutableInjector.resolve(key:)`. public mutating func resolve(key: K) throws -> Providable { return try self.lambdaResolve(&self, key) } /// See `MutableInjector.provide(key:usingFactory:)`. public mutating func provide( key: K, usingFactory factory: @escaping (inout AnyInjector) throws -> Providable ) { self.lambdaProvide(&self, key, factory) } /// See `Injector.providedKeys`. public var providedKeys: [K] { return lambdaKeys(self) } /// See `MutableInjector.revoke(key:)`. public mutating func revoke(key: K) { lambdaRevoke(&self, key) } }
// // ArenaEnemyModel.swift // Pods // // Created by Alexander Skorulis on 2/9/18. // import GameplayKit public class ArenaEnemyModel: Codable { public var position:vector_int2 = vector_int2(0,0) public var base:CharacterModel = CharacterModel(name: "empty") public var ai:BattleAIModel = BattleAIModel() let wave:Int //Wave number that this enemy will show up on init() { wave = 0 } }
// // LearnCourse.swift // ddx0513 // // Created by jiang yongbin on 15/5/31. // Copyright (c) 2015年 jiang yongbin. All rights reserved. // import UIKit class LearnCourse: UITableViewController { //var learnArr:NSMutableArray = [] var lessonId:NSMutableArray = [] var lessonName:NSMutableArray = [] var lessonImg:NSMutableArray = [] var learnProgress:NSMutableArray = [] var sectionNum:NSMutableArray = [] var totalCount = 0 var learncourseitem:LearnCourseItem! = nil // @IBOutlet weak var learnCourseName: UILabel! override func viewDidLoad() { super.viewDidLoad() learn() // learncourseitem.lessonProgress.progressImage = UIImage(named: "进度条.png") // CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 3.0f); // progressView.transform = transform; // learncourseitem.lessonProgress. } func learn() { //var userid:Int = 1 var userid:Int = DBUtils.mem.userId var token:String = DBUtils.mem.token NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLStudying() , parameters: ["userid":userid,"token":token] , responseHandler: nil, netErrorHandler: nil, successHandler: learnlist, interErrorHandler: nil, jsonErrorHandler: nil) } func learnlist(json: JSON) { // println(json["list"][i]["lessonName"].string!) /* if let totalCount = json["totalcount"].int { println(totalCount) }*/ // println(totalcount) totalCount = json["totalcount"].int! println("aiya") println(json) // println(json["data"]) for (var i = 0;i < totalCount; i++ ) { lessonId.addObject(json["list"][i]["lessonid"].int!) lessonName.addObject(json["list"][i]["lessonname"].string!) sectionNum.addObject(json["list"][i]["sectionnum"].int!) lessonImg.addObject(json["list"][i]["imgurl"].string!) sectionNum.addObject(json["list"][i]["sectionnum"].int!) learnProgress.addObject(json["list"][i]["progress"].int!) } self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return lessonId.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var tableCell :LearnCourseItem = tableView.dequeueReusableCellWithIdentifier("LearnCourseItem") as! LearnCourseItem var s = lessonName.objectAtIndex(indexPath.row) as? String tableCell.learnCourseName.text = s; //tableCell.lessonImg.image = tableCell.lessonProgress.progressImage = UIImage(named: "进度条.png") tableCell.lessonProgress.trackImage = UIImage(named: "进度条.png") var a = learnProgress.objectAtIndex(indexPath.row) as! Float var b = sectionNum.objectAtIndex(indexPath.row) as! Float var c = a / b println(c) var transform:CGAffineTransform = CGAffineTransformMakeScale(1.0, 3.0) tableCell.lessonProgress.transform = transform tableCell.lessonProgress.layer.masksToBounds.boolValue tableCell.lessonProgress.layer.cornerRadius = 10 //tableCell.lessonProgress.maskView?.bounds //pro1.progressTintColor=[UIColor redColor]; tableCell.lessonProgress.setProgress(c, animated: true) var url:String = lessonImg.objectAtIndex(indexPath.row) as! String DBUtils.getImageFromFile(url, successHandler: { (imgUrl, img) -> Void in if (url == imgUrl) { tableCell.lessonImg.image = img } }) tableCell.accessoryType = UITableViewCellAccessoryType.None ////////////////// return tableCell as UITableViewCell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { /*tableView.deselectRowAtIndexPath(indexPath, animated: true) var allcoursedetail = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseDetail") as! AllCourseDetail NSLog("navigation13 \(rootController.navigationController) string") rootController.navigationController?.pushViewController(allcoursedetail, animated: true)*/ tableView.deselectRowAtIndexPath(indexPath, animated: true) var allcoursedetail = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseDetail") as! AllCourseDetail rootController.navigationController?.pushViewController(allcoursedetail, animated: true) var lessonid = lessonId.objectAtIndex(indexPath.row) as! Int println(lessonid) allcoursedetail.lessonId = lessonid println(allcoursedetail.lessonId) var lessonname = lessonName.objectAtIndex(indexPath.row) as? String allcoursedetail.lessonName = lessonname! } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
// // ViewController.swift // Anonymous Diary // // Created by Webcash on 2019/12/06. // Copyright © 2019 Moon. All rights reserved. // import UIKit import Firebase class LoginViewController: UIViewController { @IBOutlet weak var txtEmail: UITextField! @IBOutlet weak var txtPassWord: UITextField! @IBOutlet weak var btnLogin: UIButton! var handle: AuthStateDidChangeListenerHandle? override func viewDidLoad() { super.viewDidLoad() if Auth.auth().currentUser != nil { txtEmail.placeholder = "이미 로그인된 상태입니다." txtPassWord.placeholder = "이미 로그인된 상태입니다." btnLogin.setTitle("이미 로그인된 상태입니다.", for: .normal) } } override func viewWillAppear(_ animated: Bool) { handle = Auth.auth().addStateDidChangeListener { (auth, user) in self.navigationController?.title = user?.email } self.navigationController?.setNavigationBarHidden(true, animated: true) } override func viewWillDisappear(_ animated: Bool) { Auth.auth().removeStateDidChangeListener(handle!) } @IBAction func btnLogin(_ sender: UIButton) { Auth.auth().signIn(withEmail: txtEmail.text!, password: txtPassWord.text!, completion: { (user, error) in if user != nil { print("login success") } else { print("login fail") } }) } @IBAction func btnPushRegister(_ sender: UIButton) { self.navigationController?.pushViewController((self.storyboard?.instantiateViewController(withIdentifier: "RegisterVC"))!, animated: true) } }
// // APTabBarOverlayVC.swift // Untitled // // Created by alexeyweb11@gmail.com on 05/12/2016, using AnimaApp.com, under MIT license. // Copyright © 2016 Company Name. All rights reserved. // import UIKit public class APTabBarOverlayVC : ANViewController, ANTabBarControllerOverlay { }
// // ReceiveSDR.swift // SimpleSDR3 // // Created by Andy Hooper on 2020-02-26. // Copyright © 2020 Andy Hooper. All rights reserved. // import SimpleSDRLibrary class ReceiveSDR:ReceiveThread { let tuner = SDRplay() let demodSwitch:DemodulatorSwitch let tunerSpectrum:SpectrumData var pilotDetect:AutoGainControl<RealSamples>? override init() { tuner.setOption(SDRplay.OptRFNotch, SDRplay.Opt_Disable) tunerSpectrum = SpectrumData("ReceiveSDR SpectrumData", source:tuner, asThread:true, log2Size:10) demodSwitch = DemodulatorSwitch() demodSwitch.setSource(tuner) super.init() setDemodulator(.None) } var deviceDescription: String { return tuner.deviceDescription } func printTimes() { //tuner.printTimes() //audio.fillTime.printAccumulated(reset:true) //if self.startTime != DispatchTime.distantFuture { // let t = Float(DispatchTime.now().uptimeNanoseconds - self.startTime.uptimeNanoseconds) / 1e9 // print("Tuner rate", Float(tuner.sampleCount) / t) // print("Audio rate", Float(audio.sampleCount) / t) //} if let pilot = pilotDetect { print("Pilot", pilot.getSignalLevel()) } } func startReceive() { demodSwitch.currentDemod?.audioOut.resume() tuner.startReceive() } func stopReceive() { //TODO fix noise on stopping demodSwitch.currentDemod?.audioOut.stop() tuner.stopReceive() var spectrumData = [Float](repeating:0, count:tunerSpectrum.N) tunerSpectrum.getdBandClear(&spectrumData) } enum Demodulator { case None case WFM case AM case DSBSC } var demod = Demodulator.None func setDemodulator(_ demod:Demodulator) { if self.demod == demod { return } switch demod { case .None: demodSwitch.sink = nil demodSwitch.set(DemodulateNone(source:demodSwitch)) pilotDetect = nil case .WFM: demodSwitch.sink = nil let demodWFM: DemodulateWFM = DemodulateWFM(source:demodSwitch) demodSwitch.set(demodWFM) pilotDetect = demodWFM.pilotDetect case .AM: demodSwitch.sink = nil demodSwitch.set(DemodulateAM(source:demodSwitch)) pilotDetect = nil case .DSBSC: demodSwitch.sink = nil demodSwitch.set(DemodulateAM(source:demodSwitch, suppressedCarrier:true)) pilotDetect = nil } self.demod = demod } override func mainLoop() { tuner.receiveLoop() } }
// // ViewController.swift // lab13-1-3 // // Created by taizhou on 2019/7/31. // Copyright © 2019 taizhou. All rights reserved. // import UIKit class DataModel : Codable{ var myNumber = 0 var myString = "" } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let jsonData = encoder() decoder(jsonData: jsonData) } func encoder()->Data{ //Step1:建立一個物件,並放入資料至物件中 let data = DataModel() data.myNumber = 123 data.myString = "abc" //Step2:使用「JSONEncoder()」的「encode()」函式將物件轉為Json資料 let jsonData = try? JSONEncoder().encode(data) if let jsonStr = String(data: jsonData!, encoding: .utf8){ print("jsonStr = ",jsonStr) } return jsonData! } func decoder(jsonData:Data){ //Step1:準備一個JSON字串,並將其轉為Data let stringData = "{\"myString\":\"abc\",\"myNumber\":123}".data(using: .utf8)! //Step2:使用「JSONDecoder()」的「decode()」將輸入的Json Data以DataModel的格式做轉換並輸出 let data = try? JSONDecoder().decode(DataModel.self, from:stringData) print("myNumber = ",data?.myNumber ?? "","myString =", data?.myString ?? "") } }
import Foundation class UseCaseGetParsedParser { class func action(transactionID: String, parserID: String, projectID: String) -> Composed.Action<Any, PCParsedParser> { return Composed .action(UseCaseGetEnvironmentForProject.action(projectID: projectID)) .action(UseCaseBuildFullyConstructedEnvironment.buildEnvironment()) .action{ environment, completion in let environment = environment! let variables = environment.variables ?? PCList<PCVariable>() Composed .action(PCParserRepository.fetchList(transactionID: transactionID)) .action(PCParserRepository.getParsedParserFromList(parserID, variables: variables)) .onFailure { completion(.failure($0)) } .execute { completion(.success($0)) }} .wrap() } }
// // JSONResponse.swift // OmiseGO // // Created by Mederic Petit on 10/10/2017. // Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved. // struct JSONResponse<ObjectType: Decodable> { let version: String let success: Bool let data: Response<ObjectType> } extension JSONResponse: Decodable { private enum CodingKeys: String, CodingKey { case version case success case data } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) version = try container.decode(String.self, forKey: .version) success = try container.decode(Bool.self, forKey: .success) if self.success { let result = try container.decode(ObjectType.self, forKey: .data) data = .success(data: result) } else { let error = try container.decode(APIError.self, forKey: .data) data = .fail(error: .api(apiError: error)) } } }
import Foundation import MultipeerConnectivity class PlayerManager { /* Manage dictionary of Player Invariant: includes self player Note distinction between connecteeRole (invitor or invitee) and gameRole (self or opponent) */ var players = [GameRole : Player]() var isSinglePlayer : Bool { return players.count == 1 } var maxPlayers : Int var myMCPeerID: MCPeerID init(maxPlayers: Int, myMCPeerID: MCPeerID) { self.maxPlayers = maxPlayers self.myMCPeerID = myMCPeerID } func addPlayer(peer: MCPeerID) { /* Called when: - game startup for .me - connected to .opponent A player may be in the middle of a solitary game when they accept an invitation. So any new player resets the score for all players. */ println("Scoreboard.addPlayer \(peer.displayName)") if players.count >= self.maxPlayers { // Should not happen since we stop advertising when max is reached. NSLog("Too many players") } else if existsPlayer(peer) { NSLog("adding player already exists peer") } else { addPlayerInGameRole(peer) // Caller should: scoreBoard.resetScores() } } private func addPlayerInGameRole(peer: MCPeerID) { // Add player in appropriate role. assert(!existsPlayer(peer)) let playerName = peer.displayName println("Scoreboard.addPlayerInGameRole \(playerName)") if peer == self.myMCPeerID { players[.me] = Player(peer: peer) } else { println("Adding opponent \(playerName)") // TODO: feedbackManager.onAddOpponent(playerName) players[.opponent] = Player(peer: peer) } } func deletePlayer(peer: MCPeerID) { // Player disconnected println("Deleted player \(peer.displayName)") assert(peer != self.myMCPeerID, "Can only delete opponent") assert(existsPlayer(peer)) // Max two player: doesn't matter what displayName is, it is opponent let deletedPlayer = players.removeValueForKey(.opponent) if deletedPlayer == nil { NSLog("Failed to delete player") } // Caller should: scoreBoard.resetScores() // game is reset elsewhere // Max two player game => delete leaves one assert(players.count == 1) } internal func existsPlayer(peer: MCPeerID ) -> Bool { /* Is peer already a player? !!! Note we don't check displayName. A device may crash and rejoin the game with same displayName but new, unique peerID. */ var result = false if let existingMe = players[.me] { if existingMe.peer == peer { result = true } } if let existingOpponent = players[.opponent] { if existingOpponent.peer == peer { result = true } } return result } }
// // NSColorExtensions.swift // SwiftExtensions // // The MIT License (MIT) // // Created by Elmar Tampe on 13/11/14. // // Copyright (c) 2014 Elmar Tampe. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Cocoa extension NSColor { // ------------------------------------------------------------------------------------------ //MARK: - String to Integer conversion // ------------------------------------------------------------------------------------------ class func colorWithHexValue(hexValue: NSString) -> NSColor { var hexString = hexValue.stringByReplacingOccurrencesOfString("#", withString: "0x") var hexStringValueAsInt: uint = 0 let scanner = NSScanner(string: hexString) var color: NSColor? if scanner.scanHexInt(&hexStringValueAsInt) { color = NSColor.colorWithIntegerHexValue(hexStringValueAsInt) } return color! } // ------------------------------------------------------------------------------------------ //MARK: - RGBA Color creation // ------------------------------------------------------------------------------------------ class func colorWithIntegerHexValue(hexValueAsInt: uint) -> NSColor { if hexValueAsInt == 0 { return NSColor.blackColor()} let digitCount:NSInteger = NSInteger((log10(Double(hexValueAsInt)) + 1)) let alpha = ((digitCount == 10) ? (((CGFloat)((hexValueAsInt & 0xFF000000) >> 24)) / 255.0) : 1.0) let red = ((CGFloat)((hexValueAsInt & 0xFF0000) >> 16)) / 255.0 let green = ((CGFloat)((hexValueAsInt & 0xFF00) >> 8)) / 255.0 let blue = ((CGFloat)(hexValueAsInt & 0xFF)) / 255.0 return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) } }
// // Service.swift // LocoFramework // // Created by Qaptive Technologies on 13/06/19. // Copyright © 2019 Qaptive Technologies. All rights reserved. // import Foundation public class Service { private init () {} public static func doSomething() -> String { return "This is done!!" } }
// // PlantTableViewCell.swift // BotanicalGarden // // Created by 黃偉勛 Terry on 2021/4/18. // import UIKit class PlantTableViewCell: UITableViewCell { @IBOutlet weak var plantImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var featureLabel: UILabel! func configure(imageURL: URL?, name: String, location: String, feature: String) { plantImageView.setImage(with: imageURL) nameLabel.text = name locationLabel.text = location featureLabel.text = feature } func configure(imageURL: URL?) { plantImageView.setImage(with: imageURL) } func cancelDownloadImage() { plantImageView.cancelDownloadTask() } }
// // ViewController.swift // Demo // // Created by Edmond on 03/04/2560 BE. // Copyright © 2560 BE Edmond. All rights reserved. // import UIKit class ViewController: UIViewController { enum Insets: Int { case top, left, bottom, right } @IBOutlet weak var pageCtrl: UIPageControl! @IBOutlet weak var contentInsetsSlider: UISlider! @IBOutlet weak var contentInsetSegment: UISegmentedControl! @IBOutlet weak var infiniteControlButton: UIButton! @IBOutlet weak var autoScrollButton: UIButton! @IBOutlet weak var infiniteView: InfiniteScrollView! var views = [UIView]() var curretnInset = Insets.left override func viewDidLoad() { super.viewDidLoad() let pageCount = 4 for i in 0 ..< pageCount { let pageView = UIView() pageView.backgroundColor = .yellow let label = UILabel() label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 28) label.text = i.description label.backgroundColor = .red label.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] pageView.addSubview(label) label.bounds = CGRect(origin: .zero, size: CGSize(width: 200, height: 80)) label.center = pageView.center views.append(pageView) } pageCtrl.numberOfPages = pageCount infiniteView.delegate = self infiniteView.reload(data: views) infiniteView.bringSubview(toFront: pageCtrl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func touchIsInfiniteButton(_ sender: UIButton) { sender.isSelected = !sender.isSelected infiniteView.isInfiniteEnable = !sender.isSelected infiniteView.reload(data: views) } @IBAction func touchAutoScrollButton(_ sender: UIButton) { sender.isSelected = !sender.isSelected infiniteView.isAutoScrollEnable = sender.isSelected } @IBAction func swiftSegmentControl(_ sender: UISegmentedControl) { if let inset = Insets(rawValue: sender.selectedSegmentIndex) { curretnInset = inset switch inset { case .top: contentInsetsSlider.value = Float(infiniteView.contentInsets.top) case .left: contentInsetsSlider.value = Float(infiniteView.contentInsets.left) case .bottom: contentInsetsSlider.value = Float(infiniteView.contentInsets.bottom) case .right: contentInsetsSlider.value = Float(infiniteView.contentInsets.right) } } } @IBAction func sliderValueChange(_ sender: UISlider) { var insets = infiniteView.contentInsets switch curretnInset { case .top: insets.top = CGFloat(contentInsetsSlider.value) case .left: insets.left = CGFloat(contentInsetsSlider.value) case .bottom: insets.bottom = CGFloat(contentInsetsSlider.value) case .right: insets.right = CGFloat(contentInsetsSlider.value) } infiniteView.contentInsets = insets } } extension ViewController : InfiniteScrollDelegate { // func didScroll(on scrollView: UIScrollView) { // print("didScroll: \(scrollView.contentOffset)") // } // // func willBeginDragging(on scrollView: UIScrollView) { // print("willBeginDragging: \(scrollView.contentOffset)") // } // // func didEndDragging(on scrollView: UIScrollView) { // print("didEndDragging: \(scrollView.contentOffset)") // } // // func willBeginDecelerating(on scrollView: UIScrollView) { // print("willBeginDecelerating: \(scrollView.contentOffset)") // } func didEndDecelerating(on scrollView: UIScrollView, at index: Int) { pageCtrl.currentPage = index print("didEndDecelerating: \(scrollView.contentOffset), index: \(index)") } }
// // GrimoireManager.swift // Grimoire // // Created by Hesham Salman on 7/12/16. // import Foundation struct GrimoireManager { let relativePath = "/platform/destiny/Vanguard/Grimoire/Definition/" let client: NetworkClient let responseParser: GrimoireResponseParser = GrimoireResponseParser() init(client: NetworkClient = APIClient()) { self.client = client } func fetchGrimoireCards(callback: (success: Bool, grimoirePages: [GrimoirePage]?) -> Void) { client.performRequest(.GET, path: relativePath, parameters: nil) { (success, response) in if let response = response as? [NSObject: AnyObject] where success, let grimoirePages = self.responseParser.parseToObject(response) { callback(success: success, grimoirePages: grimoirePages) } else { callback(success: success, grimoirePages: nil) } } } }
// // CellMovie.swift // AliveCor // // Created by Sandeep Rana on 02/12/20. // import UIKit import CoreData import Kingfisher class CellMovie: UICollectionViewCell { @IBOutlet var lMovieName:UILabel! @IBOutlet var bFavorite:UIButton! @IBOutlet var iMovieCover:UIImageView! @IBAction func onClickFavorite(_ sender:UIButton) { let context = AppDelegate.getAppDelegate().getContext() if self.movie?.getIsFavorite() ?? false { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorite") let predicate = NSPredicate(format: "id == \(self.movie?.id?.description ?? "")"); fetchRequest.predicate = predicate do{ let result = try context.fetch(fetchRequest) if result.count > 0{ for object in result { print(object) context.delete(object as! NSManagedObject) } try context.save() } }catch{ print("Error occured while deleting") } }else { let entity = NSEntityDescription.entity(forEntityName: "Favorite", in: context) let newFavMovie = NSManagedObject(entity: entity!, insertInto: context) newFavMovie.setValuesForKeys(["id":self.movie?.id ?? "", "title":self.movie?.title ?? "", "poster_cover":self.movie?.poster_path ?? ""]) do { try context.save() }catch let error { print("Error Fault:",error) } } self.bFavorite.isSelected = !self.bFavorite.isSelected AppDelegate.getAppDelegate().updateFavList() } var movie:Movie? func updateCell(movie:Movie) { self.movie = movie; self.lMovieName.text = movie.title ?? "" self.bFavorite.isSelected = movie.getIsFavorite() if self.iMovieCover.image == nil { self.bFavorite.imageView?.addShadow() self.lMovieName.addShadow() } self.iMovieCover.kf.setImage(with: URL(string: movie.getCoverUrl())) } }
// --------------------------------------------------------------------------------------------------------- // // PhotosViewController.swift // PhotoFilters // // Created by Gru on 01/12/15. // Copyright (c) 2015 GruTech. All rights reserved. // import UIKit import Photos class PhotosViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { let DBUG = true var assetsFetchResults : PHFetchResult! var assetCollection : PHAssetCollection! var collectionView : UICollectionView! var destinationImageSize : CGSize! var delegate : ImageSelectedProtocol? var imageManager = PHCachingImageManager() // --------------------------------------------------------------------------------------------------------- // Function: loadView() // override func loadView() { let rootView = UIView( frame: UIScreen.mainScreen().bounds ) // let flowlayout = UICollectionViewFlowLayout() self.collectionView = UICollectionView( frame: rootView.bounds, collectionViewLayout: UICollectionViewFlowLayout() ) collectionView.setTranslatesAutoresizingMaskIntoConstraints( false ) let flowLayout = collectionView.collectionViewLayout as UICollectionViewFlowLayout flowLayout.itemSize = CGSize(width: 100, height: 100) rootView.addSubview( collectionView ) self.view = rootView } // --------------------------------------------------------------------------------------------------------- // Function: viewDidLoad() // override func viewDidLoad() { super.viewDidLoad() self.imageManager = PHCachingImageManager() self.assetsFetchResults = PHAsset.fetchAssetsWithOptions(nil) self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.registerClass( GalleryCell.self, forCellWithReuseIdentifier: "PHOTO_CELL" ) // Do any additional setup after loading the view. } //MARK: UICollectionViewDataSource // --------------------------------------------------------------------------------------------------------- // Function: collectionView() - numberOfItemsInSection // func collectionView( collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { if DBUG { println( "PhotosViewController - numberOfItemsInSection, indexPath[\(self.assetsFetchResults.count)] ") } return self.assetsFetchResults.count } // --------------------------------------------------------------------------------------------------------- // Function: collectionView() - cellForItemAtIndexPath // func collectionView( collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath ) -> UICollectionViewCell { if DBUG { println( "PhootosViewController - cellForItemAtIndexPath, indexPath[\(indexPath.row)] ") } let cell = collectionView.dequeueReusableCellWithReuseIdentifier( "PHOTO_CELL", forIndexPath: indexPath ) as GalleryCell let asset = self.assetsFetchResults[indexPath.row] as PHAsset self.imageManager.requestImageForAsset( asset, targetSize: CGSize( width: 100, height: 100 ), contentMode: PHImageContentMode.AspectFill, options: nil ) { (requestedImage, info) -> Void in cell.imageView.image = requestedImage } return cell } // --------------------------------------------------------------------------------------------------------- // Function: collectionView() - didSelectItemAtIndexPath // func collectionView( collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath ) { if DBUG { println( "PhotosViewController - didSelectItemAtIndexPath indexPath[\(indexPath.row)] ") } let selectedAsset = self.assetsFetchResults[indexPath.row] as PHAsset self.imageManager.requestImageForAsset( selectedAsset, targetSize: self.destinationImageSize, contentMode: PHImageContentMode.AspectFill, options: nil) { (requestedImage, info) -> Void in println() // DO NOT REMOVE - This is purely for the xcode one line closure bug self.delegate?.controllerDidSelectImage( requestedImage ) self.navigationController?.popToRootViewControllerAnimated( true ) } } }
// // SwiftyStateSupplements.swift // Pods // // Created by Mertol Kasanan on 08/07/2019. // import Foundation /// Conform to this to have equatable store public protocol SwiftyStateStoreEquatable : SwiftyStateStore, Equatable{ func hasChanged(_ property : String)->Bool } /// The object that holds the state, not equatable public protocol SwiftyStateStore : Codable { /// A JSON String representation of the state /// /// - Returns: JSON as a String func toJSON()->String /// a Data representation of the state /// /// - Returns: Data func toData()->Data /// Converts a JSON String to an object /// /// - Parameter json: JSON String /// - Returns: Returns an object representing the state func fromJSON(_ json: String)->SwiftyStateStore? } // MARK: - The object that contains the state data. Inherit from this public extension SwiftyStateStore{ func toData()->Data{ let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let jsonObject = try! encoder.encode(self) return jsonObject } func toJSON()->String{ let json = NSString(data: self.toData(), encoding: String.Encoding.utf8.rawValue) return String(json ?? "error") } func fromJSON(_ json: String)->SwiftyStateStore?{ let decoder = JSONDecoder() var stateObject : Self? do{ stateObject = try decoder.decode(Self.self, from: json.data(using: .utf8)!) }catch{ print("Can't load SwiftState file \(error)") } return stateObject } } /// State Validiator. Create a function that returns true if the state is valid, false if there is a problem and the state is not valid. public protocol SwiftyStateValidiator { func validiator(_ state : SwiftyStateStore)->Bool } /// State and meta data. Used as a history point public struct SwiftyStateStoreHistory { let date : Date let action: String let state : SwiftyStateStore let valid: Bool init(action: String, state: SwiftyStateStore, valid: Bool = true) { self.date = Date() self.action = action self.state = state self.valid = valid } } /// It is returned by the subscribe function public class SwiftySubscription { public let id : String init(id : String) { self.id = id } /// unsubscribe public func unsubscribe(){ SwiftyState().unsubscribe(self.id) } /// call once at the start public func hotStart(){ SwiftyState().executeSubscription(id: self.id) } } /// You can extend this and add SwiftyActions to make it auto-complete friendly public struct AvailableSwiftyActions{ } public protocol SwiftyActionDefaultProtocol : SwiftyAction { } extension SwiftyActionDefaultProtocol { public static var available : AvailableSwiftyActions.Type {return AvailableSwiftyActions.self } } /// An empty action that can be used to access AvailableSwiftyActions via .available public enum SwiftyActionDefault : SwiftyActionDefaultProtocol { public func reducer(state: SwiftyStateStore) -> SwiftyStateStore { return state } } /// State Actions are actions that modify the state when called public protocol SwiftyAction { // associatedtype action func execute(_ currState : SwiftyStateStore)->(state: SwiftyStateStore, oldState: SwiftyStateStore) func reducer(state : SwiftyStateStore)->SwiftyStateStore } // MARK: - the execute function reduces boilerplate code by taking the arguments and calling the reducer. The user must create a reducer extension SwiftyAction { /// Runs the reducer to modify the state /// /// - Parameter currState: The current state /// - Returns: the modified state public func execute(_ currState : SwiftyStateStore)->(state: SwiftyStateStore, oldState: SwiftyStateStore){ let state = self.reducer(state: currState) return (state: state, oldState : currState) } }
// // DetailPin.swift // Sens // // Created by Rodrigo Takumi on 28/08/19. // Copyright © 2019 Bruno Cardoso Ambrosio. All rights reserved. // import UIKit import MapKit class DetailPin: UIViewController { @IBOutlet weak var titlePin: UILabel! @IBOutlet weak var adressPin: UILabel! @IBOutlet weak var emojiPin: UIImageView! @IBOutlet weak var colorPin: UIView! @IBOutlet weak var colorHexPin: UILabel! @IBOutlet weak var observacoesPin: UILabel! @IBOutlet weak var colorView: UIView! @IBOutlet weak var emojiView: UIView! @IBOutlet weak var experienceView: UIView! // var titlePintext: String? // var observacoesPintext: String? // var corPintext: String? var detailPin: Pin? let geoCoder: CLGeocoder = CLGeocoder() override func viewDidLoad() { super.viewDidLoad() // self.title = detailPin?.emotionPin.user // color View Shadow colorView.layer.shadowColor = UIColor.black.cgColor colorView.layer.shadowOpacity = 0.1 colorView.layer.shadowOffset = .zero colorView.layer.shadowRadius = 20 colorView.layer.shadowPath = UIBezierPath(rect: colorView.bounds).cgPath colorView.layer.shouldRasterize = true colorView.layer.rasterizationScale = UIScreen.main.scale // emoji View Shadow emojiView.layer.shadowColor = UIColor.black.cgColor emojiView.layer.shadowOpacity = 0.1 emojiView.layer.shadowOffset = .zero emojiView.layer.shadowRadius = 20 emojiView.layer.shadowPath = UIBezierPath(rect: emojiView.bounds).cgPath emojiView.layer.shouldRasterize = true emojiView.layer.rasterizationScale = UIScreen.main.scale // color View Shadow emojiView.layer.shadowColor = UIColor.black.cgColor emojiView.layer.shadowOpacity = 0.1 emojiView.layer.shadowOffset = .zero emojiView.layer.shadowRadius = 20 emojiView.layer.shadowPath = UIBezierPath(rect: emojiView.bounds).cgPath emojiView.layer.shouldRasterize = true emojiView.layer.rasterizationScale = UIScreen.main.scale } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) titlePin.text = (detailPin?.emotionPin.userName.capitalized)! emojiPin.image = detailPin?.emotionPin.icon.image(sizeSquare: 50) colorPin.backgroundColor = Utilities.hexStringToUIColor(hex: (detailPin?.emotionPin.color) ?? "ffffff") colorHexPin.text = "HEX: " + (detailPin?.emotionPin.color)! observacoesPin.text = detailPin?.emotionPin.testimonial // let loc: CLLocation = CLLocation(latitude: (detailPin?.infoAnnotation.coordinate.latitude)!, // longitude: (detailPin?.infoAnnotation.coordinate.longitude)!) // geoCoder.reverseGeocodeLocation(loc, completionHandler: { (placemarks, error) -> Void in // Place details // var placeMark: CLPlacemark! // placeMark = placemarks?[0] // // Location name // if let locationName = placeMark.location { // print(locationName) // } // // Street address // if let street = placeMark.thoroughfare { // print(street) // } // // City // if let city = placeMark.subAdministrativeArea { // print(city) // } // // Zip code // if let zip = placeMark.isoCountryCode { // print(zip) // } // // Country // if let country = placeMark.country { // print(country) // } // // // // }) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
import Foundation /// An object representing a version. /// Get more info: https://swagger.io/specification/#infoObject public struct SpecVersion: Codable, CustomStringConvertible, Changeable { // MARK: - Instance Properties /// The major release number, such as 1 in version 1.2.3. public var major: Int /// The minor release number, such as 2 in version 1.2.3. public var minor: Int /// The update release number, such as 3 in version 1.2.3. public var patch: Int // MARK: - CustomStringConvertible /// Full string representation of the version number. public var description: String { "\(major).\(minor).\(patch)" } // MARK: - Initializers /// Creates a new instance with the provided values. public init(major: Int, minor: Int = 0, patch: Int = 0) { self.major = major self.minor = minor self.patch = patch } /// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. public init(from decoder: Decoder) throws { let version = try String(from: decoder) let versionComponents = version.components(separatedBy: ".") guard let major = versionComponents[safe: 0].flatMap(Int.init) else { let errorContext = DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Invalid version: \(version)" ) throw DecodingError.dataCorrupted(errorContext) } let minor: Int? = try versionComponents[safe: 1].map { component in guard let minor = Int(component) else { let errorContext = DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Invalid version: \(version)" ) throw DecodingError.dataCorrupted(errorContext) } return minor } let patch: Int? = try versionComponents[safe: 2].map { component in guard let patch = Int(component) else { let errorContext = DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Invalid version: \(version)" ) throw DecodingError.dataCorrupted(errorContext) } return patch } self.major = major self.minor = minor ?? 0 self.patch = patch ?? 0 } // MARK: - Instance Methods /// Encodes this instance into the given encoder. /// /// This function throws an error if any values are invalid for the given encoder's format. /// /// - Parameter encoder: The encoder to write data to. public func encode(to encoder: Encoder) throws { try description.encode(to: encoder) } } extension SpecVersion: Comparable { // MARK: - Type Methods /// Returns a Boolean value indicating whether the instance of the first /// argument is less than that of the second argument. /// /// - Parameters: /// - lhs: A instance to compare. /// - rhs: Another instance to compare. public static func < (lhs: SpecVersion, rhs: SpecVersion) -> Bool { if lhs.major < rhs.major { return true } if lhs.minor < rhs.minor { return true } if lhs.patch < rhs.patch { return true } return false } }
#!/usr/bin/env swift import Darwin import AVFoundation let deviceId = getDefaultDeviceId() let name = String(getDeviceName(deviceId: deviceId)) let isHeadphones = name.contains("AirPods") || name.contains("Crossfade") let isMuted = getDeviceVolume(deviceId: deviceId) == 0.0 if isHeadphones && isMuted { print("ﳌ") } else if isHeadphones { print("") } else if isMuted { print("ﱝ") } else { print("") } func getDefaultDeviceId() -> AudioDeviceID { var deviceId = kAudioObjectUnknown var deviceSize = UInt32(MemoryLayout.size(ofValue: deviceId)) var address = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultOutputDevice, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain) let err = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &deviceSize, &deviceId) guard err == noErr else { print("#[fg=red]ﱝ") exit(1) } return deviceId } func getDeviceName(deviceId: AudioDeviceID) -> CFString { var deviceSize = UInt32(MemoryLayout.size(ofValue: deviceId)) var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceNameCFString, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain) var deviceName = "" as CFString deviceSize = UInt32(MemoryLayout.size(ofValue: deviceName)) guard AudioObjectGetPropertyData(deviceId, &address, 0, nil, &deviceSize, &deviceName) == noErr else { print("#[fg=red]ﱝ") exit(1) } return deviceName } enum Errors: Error { case badChannel case operationError(status: OSStatus) } func getDeviceVolumeForChannel(deviceId: AudioDeviceID, channel: AudioObjectPropertyElement) throws -> Float { var address = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyVolumeScalar, mScope: kAudioDevicePropertyScopeOutput, mElement: channel) var level = Float32(-1) var propertySize = UInt32(MemoryLayout<Float32>.size) let err = AudioObjectGetPropertyData(deviceId, &address, 0, nil, &propertySize, &level) guard err == noErr else { if err == 2003332927 { throw Errors.badChannel } else { throw Errors.operationError(status: err) } } return level } func getDeviceVolume(deviceId: AudioDeviceID) -> Float { // Idk why this is required, kAudioDevicePropertyPreferredChannelsForStereo isn't useful do { return try getDeviceVolumeForChannel(deviceId: deviceId, channel: 0) } catch (Errors.badChannel) { do { return try getDeviceVolumeForChannel(deviceId: deviceId, channel: 1) } catch { print("#[fg=red]ﱝ") return -1.0 } } catch { print("#[fg=red]ﱝ") return -1.0 } }
// // Codable.swift // BackpacDevelopmentTask // // Created by Hansub Yoo on 2020/05/23. // Copyright © 2020 Hansub Yoo. All rights reserved. // import Foundation struct ItunesAppInfo: Codable { let resultCount: Int? let results: [AppInfo]? enum CodingKeys: String, CodingKey { case resultCount, results } } struct AppInfo: Codable { let screenshotUrls, ipadScreenshotUrls: [String]? let appletvScreenshotUrls: [String]? let artworkUrl60, artworkUrl512: String? let artworkUrl100, artistViewURL: String? let supportedDevices: [String]? let advisories: [String]? let isGameCenterEnabled: Bool? let kind: String? let features: [String]? let trackCensoredName: String? let languageCodesISO2A: [String]? let fileSizeBytes, sellerURL, contentAdvisoryRating: String? let averageUserRatingForCurrentVersion: Double? let userRatingCountForCurrentVersion: Int? let averageUserRating: Double? let trackViewURL, trackContentRating: String? let isVppDeviceBasedLicensingEnabled: Bool? let minimumOSVersion: String? let trackID: Int? let trackName, releaseDate, primaryGenreName: String? let genreIDS: [String]? let formattedPrice, currentVersionReleaseDate: String? let releaseNotes: String? let primaryGenreID: Int? let sellerName, currency, wrapperType: String? let version: String? //this is what we need let artistID: Int? let artistName: String? let genres: [String]? let price: Double? let description, bundleID: String? let userRatingCount: Int? enum CodingKeys: String, CodingKey { case screenshotUrls, ipadScreenshotUrls case appletvScreenshotUrls, artworkUrl60 case artworkUrl512, artworkUrl100 case artistViewURL = "artistViewUrl" case supportedDevices, advisories case isGameCenterEnabled, kind case features, trackCensoredName case languageCodesISO2A, fileSizeBytes case sellerURL = "sellerUrl" case contentAdvisoryRating case averageUserRatingForCurrentVersion case userRatingCountForCurrentVersion case averageUserRating case trackViewURL = "trackViewUrl" case trackContentRating case isVppDeviceBasedLicensingEnabled case minimumOSVersion = "minimumOsVersion" case trackID = "trackId" case trackName, releaseDate, primaryGenreName case genreIDS = "genreIds" case formattedPrice, currentVersionReleaseDate case releaseNotes case primaryGenreID = "primaryGenreId" case sellerName, currency, version, wrapperType case artistID = "artistId" case artistName, genres, price, description case bundleID = "bundleId" case userRatingCount } } /** 출처: https://medium.com/@prafullkumar77/ios-check-and-show-update-with-apple-itunes-api-5e0b93a54de9 아이튠즈 api를 사용한다면 인터넷에 codable로 정리해놓은 자료가 있을 것이라 생각했습니다. */
// // MissionDetailsViewModel.swift // SpaceX // // Created by Bruno Guedes on 21/10/19. // Copyright © 2019 Bruno Guedes. All rights reserved. // import Foundation struct MissionDetailsViewModel { var details: String { return """ Mission Name: \(launchViewModel.name)\n Launch Date: \(launchViewModel.date)\n Launch Status: \(launchViewModel.status)\n Site Name: \(launchDetails.launchSiteName)\n Rocket Name: \(rocketDetails.rocketName)\n \(rocketDetails.details)\n """ } var wikipediaURL: URL { return rocketDetails.wikipediaURL } let launchDetails: LaunchDetails let rocketDetails: RocketDetails let launchViewModel: LaunchViewModel init(launchDetails: LaunchDetails, rocketDetails: RocketDetails) { self.launchDetails = launchDetails self.rocketDetails = rocketDetails self.launchViewModel = LaunchViewModel(launch: launchDetails) } }
import Foundation import RxSwift import RxRelay import MarketKit class NftMetadataService { private let nftMetadataManager: NftMetadataManager private let disposeBag = DisposeBag() private let assetsBriefMetadataRelay = PublishRelay<[NftUid: NftAssetBriefMetadata]>() init(nftMetadataManager: NftMetadataManager) { self.nftMetadataManager = nftMetadataManager } private func handle(assetsBriefMetadata: [NftAssetBriefMetadata]) { nftMetadataManager.save(assetsBriefMetadata: assetsBriefMetadata) let map = Dictionary(uniqueKeysWithValues: assetsBriefMetadata.map { ($0.nftUid, $0) }) assetsBriefMetadataRelay.accept(map) } } extension NftMetadataService { var assetsBriefMetadataObservable: Observable<[NftUid: NftAssetBriefMetadata]> { assetsBriefMetadataRelay.asObservable() } func assetsBriefMetadata(nftUids: Set<NftUid>) -> [NftUid: NftAssetBriefMetadata] { let array = nftMetadataManager.assetsBriefMetadata(nftUids: nftUids) return Dictionary(uniqueKeysWithValues: array.map { ($0.nftUid, $0) }) } func fetch(nftUids: Set<NftUid>) { nftMetadataManager.assetsBriefMetadataSingle(nftUids: nftUids) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .utility)) .subscribe(onSuccess: { [weak self] assetsBriefMetadata in self?.handle(assetsBriefMetadata: assetsBriefMetadata) }) .disposed(by: disposeBag) } }
// // SceneNormal.swift // projetoWWDC20 // // Created by Gustavo Feliciano Figueiredo on 02/04/20. // Copyright © 2020 Gustavo Feliciano Figueiredo. All rights reserved. // import SpriteKit import GameplayKit class SceneNormal: SceneState{ override func isValidNextState(_ stateClass: AnyClass) -> Bool { return stateClass is SceneTourist.Type || stateClass is ScenePassport.Type } override func didEnter(from previousState: GKState?) { self.sceneGame.character?.isPaused = false } }
// // LoginViewController.swift // DrawAndGuess // // Created by Troy on 2017/2/4. // Copyright © 2017年 Huanyan's. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var avatar: UIButton! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var message: UILabel! var avatarIndex = 1 @IBAction func changeAvatar(_ sender: UIButton) { avatarIndex += 1 if (avatarIndex == 10) { avatarIndex = 1 } sender.setImage(UIImage.init(named: "avatar\(avatarIndex)") , for: .normal) } @IBAction func changeStatus(_ sender: UIButton) { let status = message.text if (status == "Tap to start") { message.text = "Waiting for other users" let avatarData = UIImageJPEGRepresentation((avatar.imageView?.image)!, 1.0) let userID = nameField.text! UserDefaults.standard.set(userID, forKey:"userID") SocketIOManager.sharedInstance.connectUser(userID: userID,avatar:NSData(data: avatarData!)) } else { message.text = "Tap to start" SocketIOManager.sharedInstance.disConnectUser(userID: nameField.text!) } sender.sizeToFit() } func startNewGame() { message.text = "Tap to start" self.performSegue(withIdentifier: "toGame", sender: self) } override func viewDidLoad() { super.viewDidLoad() nameField.delegate = self self.navigationController?.isNavigationBarHidden = true self.navigationItem.hidesBackButton = true SocketIOManager.sharedInstance.receiveStartNewGame { DispatchQueue.main.async { self.startNewGame() } } } @IBAction func unwindToBegin(_ segue:UIStoryboardSegue) { } }
// // Quest.swift // underTaking // // Created by Anita Souv on 11/18/18. // Copyright © 2018 Anita Souv. All rights reserved. // import Foundation class Quest: NSObject { var uniqueID: String; var name:String = ""; var participants:Int = 0; // can change to an array of sorts so can display the players playing AND the number of players // var location: logLat // var duration? var mission: String = ""; var startDate:NSDate; var endDate: NSDate; var completion: Float; var clues:[Clue] = []; override init() { self.uniqueID = "UNIQUERAND"; self.name = "temp quest"; self.participants = 2; self.mission = "This is the mission. This sample mission is to find all of the vases" self.startDate = Date() as NSDate; self.endDate = Date(timeInterval: 2*86400, since: startDate as Date) as NSDate; self.completion = 0.0; self.clues = [Clue(), Clue()]; } init(name: String, participants: Int, startDate: Date, endDate: Date, completion: Float, mission: String, clues: [Clue]) { // generate a uniqueID self.uniqueID = "UNIQUERAND123"; self.name = name; self.participants = participants; self.mission = mission; self.startDate = startDate as NSDate; self.endDate = endDate as NSDate; self.completion = completion; self.clues = clues; } }
// // StadiumViewCell.swift // Book Phui // // Created by Thanh Tran on 3/11/17. // Copyright © 2017 Half Bird. All rights reserved. // import UIKit import SDWebImage class StadiumViewCell: UITableViewCell { @IBOutlet weak var avatarImage: UIAvatar! @IBOutlet weak var lbName: UILabel! @IBOutlet weak var lbAddress: UILabel! @IBOutlet weak var lbRating: 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 config(with stadium: Stadium) { if let thumbnailUrl = stadium.thumbnailUrl, let url = URL(string: thumbnailUrl) { avatarImage.sd_setImage(with: url) } lbName.text = stadium.name lbAddress.text = stadium.address lbRating.text = "\(stadium.rating)" } }
import Spectre @testable import Requests func describeHTTPParser() { describe("HTTP Parser") { var parser: HTTPParser! var outSocket: Socket! var inSocket: Socket! $0.before { let pipe = try! Socket.pipe() inSocket = pipe[0] outSocket = pipe[1] parser = HTTPParser(socket: inSocket) } $0.it("can parse a HTTP response") { outSocket.write("HTTP/1.1 200 OK\r\nContent-Length: 12\r\nConnection: close\r\nContent-Type: text/plain\r\n\r\nHello World!") let response = try parser.parse() try expect(response.status.rawValue) == 200 try expect(response["Content-Length"]) == "12" try expect(response["Content-Type"]) == "text/plain" guard var payload = response.body else { throw failure("response has no payload") } var body = [CChar]() while let chunk = payload.next() { body.appendContentsOf(chunk.map({ return CChar($0) })) } body.append(0) try body.withUnsafeBufferPointer { buffer in guard let string = String.fromCString(buffer.baseAddress) else { throw failure("response payload is broken") } try expect(string) == "Hello World!" } } } }
// // PPPizzaDetailsViewModel.swift // PizzaPlaces // // Created by Marco Guerrieri on 03/12/18. // Copyright © 2018 Marco Guerrieri. All rights reserved. // import UIKit import RxSwift import RxCocoa class PPPizzaDetailsViewModel : PPViewModel { private let apiHandler : PPApiHandler private let resturant : PPResturant private let privateResturantImage = BehaviorRelay<UIImage?>(value: nil) public var resturantImage : Observable<UIImage?> { return self.privateResturantImage.asObservable() } private let privateResturantName = BehaviorRelay<String>(value: "") public var resturantName : Observable<String> { return self.privateResturantName.asObservable() } private let privateIsOpened = BehaviorRelay<String>(value: "") public var isOpened : Observable<String> { return self.privateIsOpened.asObservable() } private let privateResturantDescription = BehaviorRelay<String>(value: "") public var resturantDescription : Observable<String> { return self.privateResturantDescription.asObservable() } private let privateFriendsListSource = BehaviorRelay<[PPFriend]>(value: []) public var friendsListSource : Observable<[PPFriend]> { return self.privateFriendsListSource.asObservable() } init(apiHandler: PPApiHandler, resturant: PPResturant) { self.apiHandler = apiHandler self.resturant = resturant } public func initBindings(viewWillAppear: Driver<Void>){ if let imageUri = resturant.images.first?.url, let url = URL(string: imageUri){ self.apiHandler .downloadImage(uri: url) .bind(to: self.privateResturantImage) .disposed(by: self.disposeBag) self.privateResturantName .accept(self.resturant.name) self.privateIsOpened .accept(self.resturant.isOpenString()) //just to show something, I know that is not nice to do this string in this way var description = (self.resturant.formattedAddress ?? "") + "\n" description.append((self.resturant.phone ?? "") + "\n") description.append((self.resturant.website ?? "") + "\n\n" + PPStrings.ResturantDetails.openingHours + ": \n") self.resturant.openingHours.forEach { (hour) in description.append(hour + "\n") } self.privateResturantDescription .accept(description) self.apiHandler .getFriendsList() .subscribe(onNext: { [weak self] (friendsList) in if let self = self { let friends = friendsList.filter { self.resturant.friendIds.contains("\($0.id)") } self.privateFriendsListSource.accept(friends) } }, onError: { [weak self] (error) in if let self = self { self.privateError.accept(error as! PPError) } }) .disposed(by: self.disposeBag) } } }
// // ViewController.swift // SimonSays // // Created by Radomyr Bezghin on 3/28/21. // import UIKit /// /// View-controller of the Simon Says game /// class SimonSaysViewController: UIViewController { private let gameView = GameView() private let game = SimonSaysGame() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupGameView() setupGameHandlers() } } //MARK: -- Game setup extension SimonSaysViewController{ private func setupGameHandlers(){ game.gameOverHandler = { [weak self] score in self?.displayAlertWithScore() self?.updateUIWithModel() } game.newLevelHandler = { [weak self] in self?.initiateNewLevel() } } private func setupGameView(){ self.view.addSubview(gameView) gameView.addAnchors(top: self.view.topAnchor, leading: self.view.leadingAnchor, bottom: self.view.bottomAnchor, trailing: self.view.trailingAnchor) gameView.newGameButton.addTarget(self, action: #selector(didTapNewGameButton), for: .touchUpInside) gameView.redButton.addTarget(self, action: #selector(didTapSimonButton( _:)), for: .touchUpInside) gameView.blueButton.addTarget(self, action: #selector(didTapSimonButton( _:)), for: .touchUpInside) gameView.greenButton.addTarget(self, action: #selector(didTapSimonButton( _:)), for: .touchUpInside) gameView.yellowButton.addTarget(self, action: #selector(didTapSimonButton( _:)), for: .touchUpInside) } } //MARK: -- Game functionality extension SimonSaysViewController { @objc private func didTapSimonButton(_ sender: AnyObject){ guard let button = sender as? SimonButton else {return} game.chooseButton(withColorType: button.buttonColorType) updateUIWithModel() } @objc private func didTapNewGameButton(){ game.startGame() updateUIWithModel() initiateNewLevel() } ///calls show button sequesnce on the global queue, since showButtonsSequence uses sleep between button calls we dont want to block main queue private func initiateNewLevel(){ DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: .now() + 1){ self.showButtonsSequence(self.game.currentSequence) } } ///shows sequence of buttons with pauses in between private func showButtonsSequence(_ buttonsSequence: [ButtonItem]){ DispatchQueue.main.async { self.gameView.lockButtons() } for button in buttonsSequence { if !game.isGameRunning{break} //changes color DispatchQueue.main.async { self.gameView.highlightButton(button.buttonType) } sleep(1) DispatchQueue.main.async { self.gameView.highlightButton(button.buttonType) } sleep(1) } DispatchQueue.main.async { self.gameView.unlockButtons() } } private func displayAlertWithScore(){ let generator = UINotificationFeedbackGenerator() generator.prepare() generator.notificationOccurred(.error) let alert = UIAlertController(title: "Game Over!", message: "Your current score is: \(game.score.currentScore)", preferredStyle: .alert) alert.addAction(.init(title: "OK", style: .cancel, handler: { (alertAction) in self.gameView.newGameUI() })) self.present(alert, animated: true) } private func updateUIWithModel(){ gameView.updateUIWith(score: game.score) } }
// // KeyboardKeyOutput.swift // KeyboardKit // // Created by Valentin Shergin on 3/2/16. // Copyright © 2016 AnchorFree. All rights reserved. // import Foundation public struct KeyboardKeyOutput { public var lowercase: String public var uppercase: String public init(unified: String) { self.lowercase = unified self.uppercase = unified } public init(automated: String) { self.lowercase = automated.lowercaseString self.uppercase = automated.uppercaseString } public init(lowercase: String, uppercase: String) { self.lowercase = lowercase self.uppercase = uppercase } internal func outputWithShiftMode(shiftMode: KeyboardShiftMode) -> String { if shiftMode.needCapitalize() { return self.uppercase } else { return self.lowercase } } }
// // PhotoLoadingCell.swift // viperIOSExample // // Created by Vinicius Ricci on 11/03/2018. // Copyright © 2018 Vinicius Ricci. All rights reserved. // import UIKit class PhotoLoadingCell: UICollectionViewCell, ReuseIdentifierProtocol { }
import XCTest import Epic class EpicTests: XCTestCase { func testAppLaunchEpic() { let operations: [EpicOperation] = [ EpicOperation("app.dismiss_current_modal", block: nil), EpicOperation("app.open.safari_vc", block: nil), ] let epic = Epic(operations: operations) var epicIterator = epic.iterator() XCTAssertEqual(epicIterator.next()?.identifier, "app.dismiss_current_modal") XCTAssertEqual(epicIterator.next()?.identifier, "app.open.safari_vc") XCTAssertTrue(epicIterator.finished) // Operations are finished } func testRunEpic() { let operations: [EpicOperation] = [ EpicOperation("app.dismiss_current_modal", block: nil), EpicOperation("app.open.safari_vc", block: nil), ] let epic = Epic(operations: operations) let epicIterator = epic.run() XCTAssertEqual(epicIterator.lastIndex, 2) XCTAssertTrue(epicIterator.finished) // Operations are finished } }
// // ViewController.swift // GameOfLife // // Created by Joseph Lau on 1/18/17. // Copyright © 2017 Joseph Lau. All rights reserved. // import UIKit class ViewController: UIViewController { //MARK: Properties var life = Life() var timer: Timer! // Game Board lazy var gameBoard: GameBoard = { let board = GameBoard(life: self.life) board.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(startTimer))) board.backgroundColor = UIColor.blue return board }() // Reset Button var resetButton: UIButton = { let button = UIButton() button.setTitle("Reset", for: .normal) button.setTitleColor(UIColor.blue, for: .normal) button.addTarget(self, action: #selector(resetButtonPressed), for: .touchUpInside) return button }() //MARK: Methods override func viewDidLoad() { super.viewDidLoad() setupSubviews() setupConstraints() } } //MARK: Setup Layout extension ViewController { func setupSubviews() { view.addSubview(gameBoard) view.addSubview(resetButton) } func setupConstraints() { view.addConstraintsWithFormat(format: "H:|[v0]|", views: gameBoard) view.addConstraintsWithFormat(format: "H:|[v0]|", views: resetButton) view.addConstraintsWithFormat(format: "V:|-20-[v0(\(view.bounds.width))]-20-[v1(40)]", views: gameBoard, resetButton) } } //MARK: Actions extension ViewController { func initializeGame() { life.cells.forEach { $0.state = State.randomState() } } func moment() { life.evolve() gameBoard.setNeedsDisplay() } func startTimer() { timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(moment), userInfo: nil, repeats: true) } func resetButtonPressed() { timer.invalidate() initializeGame() gameBoard.setNeedsDisplay() } }
// // infoScreen1.swift // dasCriancas // // Created by Cassia Aparecida Barbosa on 28/06/19. // Copyright © 2019 Cassia Aparecida Barbosa. All rights reserved. // import UIKit class infoScreen1: UIViewController, UIScrollViewDelegate { @IBOutlet var scrollView: UIScrollView!{ didSet{ scrollView.delegate = self } } @IBOutlet var pageControl: UIPageControl! var slides: [slide] = []; var paisScreenImages: [UIImage] = [UIImage(named: "pS1")!, UIImage(named: "pS2")!, UIImage(named: "pS3")!, UIImage(named: "pS4")!, UIImage(named: "pS5")!, UIImage(named: "pS6")!, UIImage(named: "pS7")!, UIImage(named: "pS8")!, UIImage(named: "pS9")!, UIImage(named: "pS10")!, UIImage(named: "pS11")!] var storyScreenImages: [UIImage] = [UIImage(named: "sS1")!, UIImage(named: "sS2")!, UIImage(named: "sS3")!, UIImage(named: "sS4")!, UIImage(named: "sS5")!] var relaxScreenImages: [UIImage] = [UIImage(named: "rS1")!, UIImage(named: "rS2")!, UIImage(named: "rS2")!, UIImage(named: "rS3")!, UIImage(named: "rS4")!, UIImage(named: "rS5")!] override func viewDidLoad() { super.viewDidLoad() slides = createSlides() setupSlideScrollView(slides: slides) pageControl.numberOfPages = slides.count pageControl.currentPage = 0 view.bringSubviewToFront(pageControl) slides[0].imagem.frame.size.width = self.view.frame.width * 0.7 slides[0].imagem.frame.size.height = self.view.frame.height * 0.57 slides[0].imagem.center.x = self.view.center.x slides[0].imagem.center.y = self.view.center.y * 1.365 slides[1].imagem.frame.size.width = self.view.frame.width * 0.7 slides[1].imagem.frame.size.height = self.view.frame.height * 0.57 slides[1].imagem.center.x = self.view.center.x slides[1].imagem.center.y = self.view.center.y * 1.365 slides[2].okButton.imageView?.image = slides[2].okButton.imageView?.image?.circleMask slides[2].imagem.frame.size.width = self.view.frame.width * 0.7 slides[2].imagem.frame.size.height = self.view.frame.height * 0.57 slides[2].imagem.center.x = self.view.center.x slides[2].imagem.center.y = self.view.center.y * 1.365 } func createSlides() -> [slide ] { let slide1:slide = Bundle.main.loadNibNamed("slide", owner: self, options: nil)?.first as! slide slide1.descricao.text = "Cadastre sua criança no app. Pelo menos uma vez na semana, faça as sessões de relaxamento e crie uma história com sua criança. Em seguida, avalie como ela estava no dia. Os registros permanecerão a fim de você poder avaliar como sua criança está lidando com as emoções." slide1.descricao.adjustsFontForContentSizeCategory = true slide1.okButton.isHidden = true slide1.imagem.animationImages = paisScreenImages slide1.imagem.animationDuration = 11 slide1.imagem.startAnimating() slide1.imagem.layer.cornerRadius = 10 slide1.imagem.layer.borderWidth = 2 slide1.imagem.layer.borderColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) slide1.backgroundColor = #colorLiteral(red: 0.7529411765, green: 0.8078431373, blue: 0.8352941176, alpha: 1) let slide2:slide = Bundle.main.loadNibNamed("slide", owner: self, options: nil)?.first as! slide slide2.descricao.text = "Inicie, ou continue a história, a partir das palavras que surgem toda vez que o balão é clicado. Essa interação entre as ideias dos pais e dos filhos auxilia a confiança mútua, além de estimular a imaginação da criança." slide2.descricao.adjustsFontForContentSizeCategory = true slide2.imagem.animationImages = storyScreenImages slide2.imagem.animationDuration = 5 slide2.imagem.startAnimating() slide2.imagem.layer.cornerRadius = 10 slide2.imagem.layer.borderWidth = 2 slide2.imagem.layer.borderColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) slide2.backgroundColor = #colorLiteral(red: 0.7351616025, green: 0.9265401959, blue: 0.9626358151, alpha: 1) slide2.okButton.isHidden = true let slide3:slide = Bundle.main.loadNibNamed("slide", owner: self, options: nil)?.first as! slide slide3.descricao.text = "Em um ambiente aconchegante e silencioso, clique no botão para começar, assim, um cronômetro aparecerá e pedirá para que o ar seja inspirado vagarosamente, e após 5 segundos, para que seja expirado. Essa sessão poderá ser repetida quantas vezes quiserem. Ao final, clique para que o cronômetro desligue." slide3.descricao.adjustsFontForContentSizeCategory = true slide3.imagem.animationImages = relaxScreenImages slide3.imagem.animationDuration = 5 slide3.imagem.startAnimating() slide3.isUserInteractionEnabled = true slide3.backgroundColor = #colorLiteral(red: 0.7987042069, green: 0.912568748, blue: 0.9627984166, alpha: 1) slide3.imagem.layer.cornerRadius = 10 slide3.imagem.layer.borderWidth = 2 slide3.imagem.layer.borderColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) slide3.okButton.addTarget(self, action: #selector(go(_:)), for: .touchUpInside) return [slide1, slide2, slide3] } func setupSlideScrollView(slides : [slide]) { scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(slides.count), height: view.frame.height) scrollView.isPagingEnabled = true for i in 0 ..< slides.count { slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height) scrollView.addSubview(slides[i]) } } func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageIndex = round(scrollView.contentOffset.x/view.frame.width) pageControl.currentPage = Int(pageIndex) } @objc func go (_ sender: Any) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "tabScreen") as! UITabBarController? vc!.selectedIndex = 3 //paisScreen self.present(vc!, animated: true, completion: nil) } }
// // ViewController.swift // HiSwift // // Created by Theta Wang on 2017/2/19. // Copyright © 2017年 Theta Wang. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var Mainlab: UILabel! @IBAction func showMessage(_ sender: Any) { Mainlab.text = "HI" } @IBAction func HTTPRequest(_ sender: Any) { let reback :String = HTTPRequest_Get() print(reback) } @IBAction func POSTBUTTON(_ sender: Any) { let reback :String = HTTPRequest_Post() print(reback) } func HTTPRequest_Get()->String { var ReData : String = "init" // Set up the URL request let url = NSURL(string: "http://140.130.36.221/README.txt") let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error)->Void in if data != nil{ print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String) ReData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String }else{print("no data error") } } task.resume() sleep(1) return ReData } func HTTPRequest_Post()->String{ var ReData : String = "init" ReData = "init2" // Set up the URL request var request = URLRequest(url: URL(string: "http://www.thisismylink.com/postName.php")!) request.httpMethod = "POST" let postString = "id=13&name=Jack" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(response)") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(responseString)") } task.resume() return ReData } }
// // DB.swift // RiseAlarm // // Created by Tiffany Cai on 5/17/20. // Copyright © 2020 Tiffany Cai. All rights reserved. // import UIKit import CoreData class DB { static let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext static func saveData(){ do { try context.save() print("Data Save!") } catch { print("Error saving Context \(error)") } } //MARK: quote entity static func getQuotes()->[QuoteEntity]? { let request: NSFetchRequest<QuoteEntity> = QuoteEntity.fetchRequest() var temp:[QuoteEntity]! do { temp = try context.fetch(request) }catch { print("Error getting quotes \(error)") } return temp } static func deleteQuote(quote: QuoteEntity) { context.delete(quote) saveData() } //MARK:alarm entity static func getAlarms()->[AlarmEntity]? { let request: NSFetchRequest<AlarmEntity> = AlarmEntity.fetchRequest() var temp:[AlarmEntity]! do { temp = try context.fetch(request) } catch { print("Error getting alarms \(error)") } return temp } static func deleteAlarm(alarm: AlarmEntity) { context.delete(alarm) saveData() } }
// // UITextViewController.swift // Created by Modo Ltunzher on 05.04.16. // import UIKit class UITextViewController: UIViewController, UITextViewDelegate { // MARK: Publics typealias Handler = (controller: UITextViewController) -> Void var handlerTextChange: Handler? = nil var handlerCancel: Handler? = nil var handlerDone: Handler? = nil // MARK: Privates lazy var textView = UITextView() // MARK: - Memory Management init() { super.init(nibName: nil, bundle: nil) self.title = "Edit" self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(UITextViewController.onCancel)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .Done, target: self, action: #selector(UITextViewController.onDone)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func loadView() { textView.backgroundColor = UIColor.whiteColor() textView.delegate = self let view = UIView(frame: CGRectMake(0, 0, 100, 100)) textView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] textView.frame = view.bounds view.addSubview(textView) self.view = view } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UITextViewController.onKeyboardFrameDidChange(_:)), name: UIKeyboardDidChangeFrameNotification, object: nil) textView.becomeFirstResponder() } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidChangeFrameNotification, object: nil) super.viewDidAppear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateInsets() } // MARK: - Public func getText() -> String { return self.textView.text } func setText(text: String) { self.textView.text = text self.textView.selectAll(self) } // MARK: - Private private func setTopInset(val: CGFloat) { var inset = self.textView.contentInset inset.top = val self.textView.contentInset = inset self.textView.scrollIndicatorInsets = inset } private func setBottomInset(val: CGFloat) { var inset = self.textView.contentInset inset.bottom = val self.textView.contentInset = inset self.textView.scrollIndicatorInsets = inset } private func updateInsets() { // var bottomOffSet: CGFloat = 0 if (self.tabBarController != nil) && (self.tabBarController!.tabBar.translucent) { bottomOffSet = self.tabBarController!.tabBar.frame.size.height } // var topOffset: CGFloat = 0 if (self.navigationController != nil) && (self.navigationController!.navigationBar.translucent) { let bar = self.navigationController!.navigationBar topOffset = bar.frame.size.height if bar.barPosition == .TopAttached { // window rotates starting with iOS 8, so "height" contains correct value topOffset += UIApplication.sharedApplication().statusBarFrame.size.height } } // setTopInset(topOffset) setBottomInset(bottomOffSet) } // MARK: - UITextViewDelegate func textViewDidChange(textView: UITextView) { self.handlerTextChange?(controller: self) } // MARK: - Action Handlers @objc internal func onCancel() { self.handlerCancel?(controller: self) } @objc internal func onDone() { self.handlerDone?(controller: self) } @objc internal func onKeyboardFrameDidChange(notification: NSNotification) { if let frameValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue { let windowRect = frameValue.CGRectValue() let viewRect = self.view.convertRect(windowRect, fromView: self.view.window) setBottomInset(max(0, CGRectGetMaxY(self.view.frame) - CGRectGetMinY(viewRect))) } } }
// // NewSchoolViewController.swift // TheBestKCProgrammingContest // // Created by Nick Pierce on 3/12/19. // Copyright © 2019 SmartShopperTeam. All rights reserved. // import UIKit class NewSchoolViewController: UIViewController { // property holding parent ViewController var presented: SchoolsTableViewController! // enumerates outlets @IBOutlet weak var name: UITextField! @IBOutlet weak var coach: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // action to dimiss all data comprised in textfields and transitions back to modally presented ViewController @IBAction func dismisses(_ sender: Any){ // invokes dismiss method self.dismiss(animated: true) { // clears any data in textfields self.name.text = "" self.coach.text = "" } } // renders new School and appends to Schools's shared instance while dismissing modally @IBAction func done(_ sender: Any){ // starts animating and bars subsequent user interaction self.presented.activityIndicator.startAnimating() UIApplication.shared.beginIgnoringInteractionEvents() // holding references to passed args for background thread let name = self.name.text! let coach = self.coach.text! // invokes dismiss self.dismiss(animated: true) { DispatchQueue.global(qos: .userInitiated).async{ // creates Schools instance and appends to shared's collection Schools.shared.addSchool(school: School(name: name, coach: coach, teams: nil)) // still on main thread, work is dismiss handler pushed serially after viewWillAppear and vieDidAppear } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // Muscle.swift // Crepatura // // Created by Yaroslav Pasternak on 13/04/2019. // Copyright © 2019 Thorax. All rights reserved. // import CoreData import Foundation @objc(Muscle) class Muscle: NSManagedObject, FetchableById { typealias Id = String @NSManaged public var name: Id @NSManaged public var exercises: Set<Exercise> @NSManaged func addExercisesObject(_ objects: Set<Exercise>) @NSManaged func removeExercisesObject(_ objects: Set<Exercise>) }
// // BudgetListDataRetriver.swift // Habitissimo // // Created by Marc Tamarit on 13/01/2020. // Copyright © 2020 marc. All rights reserved. // import Foundation class BudgetListDataRetriver { private let localService = LocalService() func getBudgets(completion: @escaping ([Budget]?) -> ()) { localService.fetchData(entity: .budget) { (data) in guard let data = data, let budgets = try? self.localService.context.fetch(data) as? [Budget] else { completion (nil) return } completion (budgets) } } }
// // NotificationTab.swift // Tooli // // Created by impero on 10/01/17. // Copyright © 2017 impero. All rights reserved. import UIKit import ENSwiftSideMenu import Toast_Swift import NVActivityIndicatorView import ObjectMapper import Alamofire import Kingfisher import TTTAttributedLabel class NotificationTab: UIViewController, UITableViewDataSource, UITableViewDelegate, ENSideMenuDelegate, NVActivityIndicatorViewable, TTTAttributedLabelDelegate,UISearchBarDelegate,RetryButtonDeleget { @IBOutlet weak var btnAgain: UIButton! @IBOutlet weak var imgError: UIImageView! @IBOutlet weak var lblError: UILabel! @IBOutlet weak var viewError: UIView! @IBAction func btnAgainErrorAction(_ sender: UIButton) { self.imgError.isHidden = true self.btnAgain.isHidden = true self.lblError.isHidden = true self.startAnimating() getNotifications(); } @IBOutlet var tvnoti : UITableView! var sharedManager : Globals = Globals.sharedInstance var currentPage = 1 var notificationList : GetAllNotificationList = GetAllNotificationList(); var isFull : Bool = false var isFirstTime : Bool = true var refreshControl:UIRefreshControl! var isCallWebService : Bool = true var activityIndicator = UIActivityIndicatorView() @IBOutlet weak var SearchbarView: UISearchBar! @IBOutlet var TBLSearchView:UITableView! @IBOutlet var viewSearch:UIView! var Searchdashlist : [SerachDashBoardM] = [] override func viewDidLoad() { super.viewDidLoad() SearchbarView.delegate = self tvnoti.delegate = self tvnoti.dataSource = self tvnoti.rowHeight = UITableViewAutomaticDimension tvnoti.estimatedRowHeight = 450 tvnoti.tableFooterView = UIView() TBLSearchView.delegate = self TBLSearchView.dataSource = self refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(NotificationTab.refreshPage), for: UIControlEvents.valueChanged) tvnoti.addSubview(refreshControl) AppDelegate.sharedInstance().setSearchBarWhiteColor(SearchbarView: SearchbarView) activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) activityIndicator.startAnimating() activityIndicator.color = UIColor.black activityIndicator.hidesWhenStopped = true self.startAnimating() // Do any additional setup after loading the view. } func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool{ var strUpdated:NSString = searchBar.text! as NSString strUpdated = strUpdated.replacingCharacters(in: range, with: text) as NSString if(Reachability.isConnectedToNetwork()) { onSerach(str: strUpdated as String) } return true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { SearchbarView.text = "" SearchbarView.resignFirstResponder() viewSearch.isHidden = true } @IBAction func btnHomeScreenAction(_ sender: UIButton) { AppDelegate.sharedInstance().moveToDashboard() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if(searchBar.text == "") { SearchbarView.resignFirstResponder() viewSearch.isHidden = true } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { SearchbarView.resignFirstResponder() SearchbarView.text = "" viewSearch.isHidden = true } override func viewWillAppear(_ animated: Bool) { self.startAnimating() refreshPage() guard let tracker = GAI.sharedInstance().defaultTracker else { return } tracker.set(kGAIScreenName, value: "Notification Tab Screen.") guard let builder = GAIDictionaryBuilder.createScreenView() else { return } tracker.send(builder.build() as [NSObject : AnyObject]) } func refreshPage() { isFirstTime = true isFull = false currentPage = 1 getNotifications() } func onSerach(str:String) { self.startAnimating() let param = ["QueryText":str] as [String : Any] AFWrapper.requestPOSTURL(Constants.URLS.AccountSearchUser, params :param as [String : AnyObject]? ,headers : nil , success: { (JSONResponse) -> Void in self.stopAnimating() print(JSONResponse["Status"].rawValue) if JSONResponse["Status"].int == 1 { let temp:SearchContractoreList = Mapper<SearchContractoreList>().map(JSONObject: JSONResponse.rawValue)! self.Searchdashlist = temp.DataList if(self.Searchdashlist.count > 0) { self.viewSearch.isHidden = false self.TBLSearchView.reloadData() } else { self.viewSearch.isHidden = true } } else { } }) { (error) -> Void in self.stopAnimating() self.view.makeToast("Server error. Please try again later", duration: 3, position: .center) } } func getNotifications() { self.isCallWebService = true if(currentPage != 1) { self.tvnoti.tableFooterView = activityIndicator } var param = [:] as [String : Any] param["PageIndex"] = currentPage print(param) AFWrapper.requestPOSTURL(Constants.URLS.NotificationList, params :param as [String : AnyObject]? ,headers : nil , success: { (JSONResponse) -> Void in print(JSONResponse["Status"].rawValue) self.refreshControl.endRefreshing() self.viewError.isHidden = true self.imgError.isHidden = true self.btnAgain.isHidden = true self.lblError.isHidden = true self.isCallWebService = false self.tvnoti.tableFooterView = UIView() if JSONResponse["Status"].int == 1 { self.stopAnimating() if self.isFirstTime { self.notificationList = GetAllNotificationList(); self.notificationList = Mapper<GetAllNotificationList>().map(JSONObject: JSONResponse.rawValue)! self.isFirstTime = false; NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "RefreshSideMenu"), object: nil) as Notification) } else { let tmpList : GetAllNotificationList = Mapper<GetAllNotificationList>().map(JSONObject: JSONResponse.rawValue)! if(tmpList.Result.count == 0) { self.isFull = true self.isFirstTime = false; } for tmpNotifcation in tmpList.Result { self.notificationList.Result.append(tmpNotifcation) } } if(self.notificationList.Result.count == 0) { let viewBlur:PopupView = PopupView(frame:self.tvnoti.frame) viewBlur.frame = self.tvnoti.frame viewBlur.delegate = self self.view.addSubview(viewBlur) viewBlur.lblTitle.text = "No notification available." } self.currentPage = self.currentPage + 1 self.tvnoti.reloadData() //self.setValues() } else { self.stopAnimating() self.isFull = true self.isFirstTime = false; if(self.notificationList.Result.count == 0) { let viewBlur:PopupView = PopupView(frame:self.tvnoti.frame) viewBlur.frame = self.tvnoti.frame viewBlur.delegate = self self.view.insertSubview(viewBlur, belowSubview: self.viewSearch) viewBlur.lblTitle.text = JSONResponse["Message"].rawString()! } else { if(self.view.viewWithTag(9898) != nil) { self.view.viewWithTag(9898)?.removeFromSuperview() } } } }) { (error) -> Void in self.stopAnimating() self.isCallWebService = true self.isFull = true self.isFirstTime = false; self.tvnoti.tableFooterView = UIView() self.refreshControl.endRefreshing() // self.view.makeToast("Server error. Please try again later", duration: 3, position: .center) } } func RetrybuttonTaped() { refreshPage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnMenu(button: AnyObject) { SearchbarView.resignFirstResponder() toggleSideMenuView() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if(tableView == TBLSearchView) { return self.Searchdashlist.count } else { return notificationList.Result.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ if(tableView == TBLSearchView) { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = self.Searchdashlist[indexPath.row].Name cell.textLabel?.font = UIFont.systemFont(ofSize: 15) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NotificationTabCell let name : String = notificationList.Result[indexPath.row].Name; cell.lbltitle.text = notificationList.Result[indexPath.row].Name + " " + notificationList.Result[indexPath.row].NotificationText cell.lbldate.text = notificationList.Result[indexPath.row].TimeCaption cell.lbltitle.delegate = self if(notificationList.Result[indexPath.row].IsRead) { cell.viewBack.backgroundColor = UIColor.white } else { cell.viewBack.backgroundColor = UIColor(red: 255/255.0, green: 111/255.0, blue: 111/255.0, alpha: 0.4) } var statusMessage = "" switch notificationList.Result[indexPath.row].NotificationStatus { case 1: statusMessage = " sent you new message" break; case 2: statusMessage = " applied to your \(notificationList.Result[indexPath.row].TimeCaption) job" break; case 3: statusMessage = " started following you" break; case 4: statusMessage = " company has posted new offer" break; case 5: statusMessage = " followed you via your share link" break; default: statusMessage = " " break; } let finalText = name + statusMessage; let string = finalText let nsString = string as NSString let range = nsString.range(of: name) let range1 = nsString.range(of: "message") let range3 = nsString.range(of: notificationList.Result[indexPath.row].NotificationText); let range4 = nsString.range(of: "offer"); var keyID : String = "" if(notificationList.Result[indexPath.row].Role == 1) { keyID = "action://contactor/" + String(notificationList.Result[indexPath.row].UserID) } else if(notificationList.Result[indexPath.row].Role == 2) { keyID = "action://company/" + String(notificationList.Result[indexPath.row].UserID) } else if (notificationList.Result[indexPath.row].Role == 3) { keyID = "action://supplier/" + String(notificationList.Result[indexPath.row].UserID) } cell.lbltitle.setText(finalText) { (mutableAttributedString) -> NSMutableAttributedString? in var boldSystemFont : UIFont = UIFont.boldSystemFont(ofSize: 16) if Constants.DeviceType.IS_IPHONE_5 { boldSystemFont=UIFont(name: (boldSystemFont.fontName), size: (boldSystemFont.pointSize)-1)! } if Constants.DeviceType.IS_IPHONE_6P { boldSystemFont=UIFont(name: (boldSystemFont.fontName), size: (boldSystemFont.pointSize)+4)! } if Constants.DeviceType.IS_IPAD { boldSystemFont=UIFont(name: (boldSystemFont.fontName), size: (boldSystemFont.pointSize)+7)! } mutableAttributedString?.addAttribute(String(kCTFontAttributeName), value: boldSystemFont, range: range) mutableAttributedString?.addAttribute(String(kCTFontAttributeName), value: boldSystemFont, range: range1) return mutableAttributedString; } let url1 = NSURL(string: keyID)! let url2 = NSURL(string: "action://message/\(notificationList.Result[indexPath.row].TablePrimaryID)")! cell.lbltitle.addLink(to: url1 as URL!, with: range) cell.lbltitle.addLink(to: url2 as URL!, with: range1) cell.lbltitle.addLink(to: url2 as URL!, with: range3) cell.lbltitle.addLink(to: url2 as URL!, with: range4) let url = URL(string: notificationList.Result[indexPath.row].ProfileImageLink)! let resource = ImageResource(downloadURL: url, cacheKey: notificationList.Result[indexPath.row].ProfileImageLink) cell.imguser.kf.indicatorType = .activity cell.imguser.kf.setImage(with: resource) cell.imguser.clipsToBounds = true return cell } } func OnReadNotification(NotificationID:Int) { let param = ["NotificationID":notificationList.Result[NotificationID].NotificationID] as [String : Any] AFWrapper.requestPOSTURL(Constants.URLS.AccountNotification, params :param as [String : AnyObject]? ,headers : nil , success: { (JSONResponse) -> Void in self.notificationList.Result[NotificationID].IsRead = true self.tvnoti.reloadData() AppDelegate.sharedInstance().GetNotificationCount() }) { (error) -> Void in self.view.makeToast("Server error. Please try again later", duration: 3, position: .center) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Check for Message if(tableView == TBLSearchView) { if(self.Searchdashlist[indexPath.row].Role == 0) { print("Admin") } else if(self.Searchdashlist[indexPath.row].Role == 1) { print("Contractor") if(self.Searchdashlist[indexPath.row].IsMe) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "ContractorProfileView") as! ContractorProfileView vc.userId = self.Searchdashlist[indexPath.row].UserID self.navigationController?.pushViewController(vc, animated: true) } else { let vc = self.storyboard?.instantiateViewController(withIdentifier: "OtherContractorProfile") as! OtherContractorProfile vc.userId = self.Searchdashlist[indexPath.row].UserID self.navigationController?.pushViewController(vc, animated: true) } } else if(self.Searchdashlist[indexPath.row].Role == 2) { print("Company") let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "CompanyView") as! CompanyView companyVC.userId = self.Searchdashlist[indexPath.row].UserID self.navigationController?.pushViewController(companyVC, animated: true) } else if(self.Searchdashlist[indexPath.row].Role == 3) { print("Supplier") let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "SupplierView") as! SupplierView companyVC.userId = self.Searchdashlist[indexPath.row].UserID self.navigationController?.pushViewController(companyVC, animated: true) } SearchbarView.text = "" SearchbarView.resignFirstResponder() viewSearch.isHidden = true } else { OnReadNotification(NotificationID: indexPath.row) if (notificationList.Result[indexPath.row].NotificationStatus == 1) { let currentBuddy:BuddyM = BuddyM() currentBuddy.ChatUserID = notificationList.Result[indexPath.row].UserID currentBuddy.Name = notificationList.Result[indexPath.row].Name currentBuddy.IsReadLastMessage = true currentBuddy.Role = 1 currentBuddy.ProfileImageLink = notificationList.Result[indexPath.row].ProfileImageLink let chatDetail = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MessageDetails") as! MessageDetails chatDetail.currentBuddy = currentBuddy self.navigationController?.pushViewController(chatDetail, animated: true) } else if (notificationList.Result[indexPath.row].NotificationStatus == 2) { // Redirect to Job Screen } else if (notificationList.Result[indexPath.row].NotificationStatus == 4) { let companyVC : OfferDetailViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OfferDetailViewController") as! OfferDetailViewController companyVC.OfferId = Int(notificationList.Result[indexPath.row].TablePrimaryID)! companyVC.isNotification = true self.navigationController?.pushViewController(companyVC, animated: true) } else if (notificationList.Result[indexPath.row].NotificationStatus != 1 && notificationList.Result[indexPath.row].NotificationStatus != 2 ) { if(notificationList.Result[indexPath.row].Role == 1) { let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "OtherContractorProfile") as! OtherContractorProfile companyVC.userId = notificationList.Result[indexPath.row].UserID self.navigationController?.pushViewController(companyVC, animated: true) } else if (notificationList.Result[indexPath.row].Role == 2) { let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "CompanyView") as! CompanyView companyVC.userId = notificationList.Result[indexPath.row].UserID self.navigationController?.pushViewController(companyVC, animated: true) } else { let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "SupplierView") as! SupplierView companyVC.userId = notificationList.Result[indexPath.row].UserID self.navigationController?.pushViewController(companyVC, animated: true) } } } } func scrollViewDidScroll(_ scrollView: UIScrollView) { if !self.isCallWebService { if(scrollView == self.tvnoti) { if(scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) { if(!isFull) { getNotifications() } } } } } func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) { print(url) if url.absoluteString.contains("action://contactor/") { let userId = url.absoluteString.replacingOccurrences(of: "action://contactor/", with: "") print(userId) let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "OtherContractorProfile") as! OtherContractorProfile companyVC.userId = "\(userId)" self.navigationController?.pushViewController(companyVC, animated: true) } else if url.absoluteString.contains("action://company/") { let userId = url.absoluteString.replacingOccurrences(of: "action://company/", with: "") print(userId) let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "CompanyView") as! CompanyView companyVC.userId = "\(userId)" self.navigationController?.pushViewController(companyVC, animated: true) } else if url.absoluteString.contains("action://supplier/") { let userId = url.absoluteString.replacingOccurrences(of: "action://supplier/", with: "") let vc = self.storyboard?.instantiateViewController(withIdentifier: "SupplierView") as! SupplierView vc.userId = "\(userId)" self.navigationController?.pushViewController(vc, animated: true) } } }
// // KeyMacro.swift // TemplateSwiftAPP // // Created by wenhua yu on 2018/3/21. // Copyright © 2018年 wenhua yu. All rights reserved. // import Foundation // 友盟 - 测试用,需要修改为自己的友盟APPkey let kUmengAppKey = "5b9879fdf29d98699a000023" /// swiftcn // 微信 let kWechatAppId = "wxdd44c96a85693969" let kWechatAppScrict = "2488abf8baaca7f5a7a9d10701eee281" // QQ let kQQAppId = "1104913493" let kQQAppScrict = "dxwjnHSxuWdS7Mv6" // 新浪微博 let kSinaAppId = "508896767" let kSinaAppScrict = "4e6ef081542540cf1ec50c1f6e778263"
// // Router.swift // ExchangeRates // // Created by Andrey Novikov on 9/12/20. // Copyright © 2020 Andrey Novikov. All rights reserved. // import UIKit protocol MainRouterProtocol { var navigationController: UINavigationController? { get set } var assembilityBuilder: AssembilityBuilderProtocol? { get set } } protocol RouterProtocol: MainRouterProtocol { func initialViewController() func showDetailViewController(withRates rates: [Rate], selectedRate rate: Rate) func popToRoot() } class Router: RouterProtocol { var navigationController: UINavigationController? var assembilityBuilder: AssembilityBuilderProtocol? init(navigationController: UINavigationController, assembilityBuilder: AssembilityBuilderProtocol) { self.navigationController = navigationController self.assembilityBuilder = assembilityBuilder } func initialViewController() { if let navigationController = navigationController { guard let initinalViewController = assembilityBuilder?.buildMainModule(self) else { return } navigationController.viewControllers = [initinalViewController] } } func showDetailViewController(withRates rates: [Rate], selectedRate rate: Rate) { if let navigationController = navigationController { guard let detailViewController = assembilityBuilder?.buildDetailModule(withRouter: self, rates: rates, selectedRate: rate) else { return } navigationController.pushViewController(detailViewController, animated: true) } } func popToRoot() { if let navigationController = navigationController { navigationController.popToRootViewController(animated: true) } } }
// // EncounterTreasureList.swift // MC3 // // Created by Aghawidya Adipatria on 05/08/20. // Copyright © 2020 Aghawidya Adipatria. All rights reserved. // import SwiftUI struct EncounterTreasureList: View { @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> @EnvironmentObject var moduleInfo: ModuleInfo @ObservedObject var dataCenter = DataCenter() @State private var treasureID: Int? @State private var treasureEditing: Int? @State private var editMode: EditMode = .add var body: some View { VStack(spacing: 0) { NavigationLink( destination: EncounterTreasureEdit(editMode: editMode), tag: -1, selection: $treasureEditing ){ EmptyView() } ModuleHeader(action: {self.presentationMode.wrappedValue.dismiss()}) ZStack { BackgroundCard() VStack(spacing: 0) { EncounterHeader( section: .Treasure, isEditable: true, action: {self.treasureEditing = -1}) ScrollView { ZStack { VStack(spacing: 0) { Rectangle() .fill(Color.white) .cornerRadius(10) .frame(height: CGFloat((self.moduleInfo.currentModule.content.encounters[self.moduleInfo.encounterIndex].treasure?.count ?? 0) * 134 + 30)) //TODO: Programatically edit height } VStack(spacing: 0) { Rectangle() .fill(Color.separator) .frame(width: UIScreen.main.bounds.width, height: 1) ForEach(0..<(self.moduleInfo.currentModule.content.encounters[self.moduleInfo.encounterIndex].treasure?.count ?? 1), id: \.self) { (index) in NavigationLink( destination: EncounterTreasureDetail(), tag: index, selection: self.treasureBinding(index) ) { self.getContentCard(index) }.buttonStyle(PlainButtonStyle()) .foregroundColor(Color.black)// } } .padding(.vertical, 20) } } } } } .navigationBarTitle("", displayMode: .inline) .navigationBarHidden(true) .navigationBarBackButtonHidden(true) } private func treasureBinding(_ index: Int) -> Binding<Int?> { let binding = Binding<Int?>(get: { self.treasureID }, set: { self.moduleInfo.treasureIndex = index self.treasureID = $0 }) return binding } private func getContentCard(_ index: Int) -> ContentCard { let encounter = self.moduleInfo.currentModule.content.encounters[self.moduleInfo.encounterIndex] if let baseTreasure = encounter.treasure?[index] { var title: String = "" var desc: String = "" switch baseTreasure.treasureType { case .weapon: if let treasure = baseTreasure as? Weapon { title = treasure.name desc = treasure.desc } case .magic: if let treasure = baseTreasure as? Magic { title = treasure.name desc = treasure.desc } case .item: if let treasure = baseTreasure as? Item { title = treasure.name desc = treasure.desc } case .coin: if let treasure = baseTreasure as? Coin { title = "Coins" if treasure.platinum > 0 { desc += "\(treasure.platinum) platinum coins\n" } if treasure.gold > 0 { desc += "\(treasure.gold) gold coins\n" } if treasure.emerald > 0 { desc += "\(treasure.emerald) emeralds\n" } if treasure.silver > 0 { desc += "\(treasure.silver) silver coins\n" } if treasure.copper > 0 { desc += "\(treasure.copper) copper coins\n" } } case .armor: if let treasure = baseTreasure as? Armor { title = treasure.name desc = treasure.desc } } return ContentCard( title: title, description: desc, actionDelete: { self.moduleInfo.currentModule.content.encounters[self.moduleInfo.encounterIndex].treasure?.remove(at: index) self.dataCenter.saveModule(module: self.moduleInfo.currentModule) }, actionEdit: { self.moduleInfo.treasureIndex = index self.editMode = .edit self.treasureEditing = -1 } ) } else { return ContentCard(title: "", description: "", actionDelete: {}, actionEdit: {}) } } } struct EncounterTreasureList_Previews: PreviewProvider { static var previews: some View { EncounterTreasureList().environmentObject(ModuleInfo()) } }
// // CreatorsViewController.swift // MarvelComic // // Created by Alec Malcolm on 2018-03-22. // Copyright © 2018 Alec Malcolm. All rights reserved. // import UIKit class CreatorsViewController : UICollectionViewController { fileprivate let reuseIdentifier = "CreatorCell" var creators: [CreatorModel]? override func viewDidLoad() { super.viewDidLoad() MarvelApi.apiCreators(self.setCreators) } func setCreators(_ creator: [CreatorModel]?) { self.creators = creator self.collectionView?.reloadData() } } private extension CreatorsViewController { func CreatorsForIndexPath(indexPath: IndexPath) -> String? { guard let results = creators else { return nil } guard let fuck = results[(indexPath as NSIndexPath).section].firstName else { return nil } return fuck } } extension CreatorsViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { guard let results = creators else { return 1 } return results.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CreatorCell let creatorItem = CreatorsForIndexPath(indexPath: indexPath) cell.backgroundColor = UIColor.white cell.nameLabel.text = creatorItem return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let results = self.creators else { return } let creator = results[(indexPath as NSIndexPath).section] let creatorController = self.storyboard?.instantiateViewController(withIdentifier: "creatorViewController") as! CreatorViewController creatorController.creator = creator navigationController?.pushViewController(creatorController, animated: true) } }
import Foundation extension Double { func currencyFormat(symbol: CurrencySymbol? = nil) -> String { let prefix: String if let symbol = symbol { prefix = "\(symbol.rawValue) " } else { prefix = "" } return "\(prefix)\(Formatter.currency.string(for: self)!)" } }
public struct Config { let align: Bool let finalSemicolon: Bool let indentation: String let lbrace: String let newline: String let rbrace: String let sep: String let warn: Bool public static let pretty = Config( align: true, finalSemicolon: true, indentation: " ", lbrace: "{", newline: "\n", rbrace: "}", sep: " ", warn: true ) public static let compact = Config( align: false, finalSemicolon: false, indentation: "", lbrace: "{", newline: "", rbrace: "}", sep: "", warn: false ) public static let inline = Config( align: false, finalSemicolon: false, indentation: "", lbrace: "", newline: "", rbrace: "", sep: "", warn: false ) }
// // ViewController.swift // VVAudiaApp // // Created by Evsei, Vladimir on 8/15/16. // Copyright © 2016 Evsei, Vladimir. All rights reserved. // import UIKit //import AVFoundation class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, CommunicationModalControllerProtocol { var collectionView: UICollectionView! var imagesPathArray: [String]! var initialView: UIView! var playerModel: VVAudioPlayer! override func viewDidLoad() { imagesPathArray = NSBundle.mainBundle().pathsForResourcesOfType(nil, inDirectory: "images") createMainView() createInitialButton() playerModel = VVAudioPlayer() playerModel.prepareForUse() super.viewDidLoad() } override func viewWillAppear(animated: Bool) { print("WillAppear") } func createMainView() { let viewSize = self.view.frame let minSide = viewSize.height > viewSize.width ? viewSize.width : viewSize.height let parentView = UIView(frame: CGRect(x: 0, y: 0, width: minSide, height: minSide)) parentView.center = self.view.center parentView.backgroundColor = UIColor.redColor() parentView.autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin , UIViewAutoresizing.FlexibleTopMargin , UIViewAutoresizing.FlexibleLeftMargin , UIViewAutoresizing.FlexibleRightMargin] self.view.addSubview(parentView) let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) layout.itemSize = calculateSizeOfCell(withView: parentView) // CGSize(width: 130, height: 130) collectionView = UICollectionView(frame: parentView.bounds, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") collectionView.backgroundColor = UIColor.whiteColor() parentView.addSubview(collectionView) } func calculateSizeOfCell(withView subView : UIView) -> CGSize { let viewSize = subView.bounds let height = round( (viewSize.height - 40) / 3) - 1 let wight = round( (viewSize.width - 40) / 3) - 1 print(CGSize(width: wight, height: height)) return CGSize(width: wight, height: height) } func createInitialButton() { let buttonFrame = CGRect(x: 0, y: 0, width: 150, height: 150) let button = UIButton(type: .Custom) button.frame = buttonFrame button.center = self.view.center button.backgroundColor = UIColor.greenColor() button.setTitle("Start game", forState: .Normal) button.addTarget(self, action: #selector(buttonTapped(_:)), forControlEvents: .TouchUpInside) let parentView = UIView(frame: self.view.bounds) let lightBlur = UIBlurEffect(style: .Light) let blurView = UIVisualEffectView(effect: lightBlur) blurView.frame = parentView.bounds blurView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] blurView.addSubview(button) parentView.addSubview(blurView) initialView = parentView self.view.addSubview(parentView) } //# MARK: UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 9 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) // cell.backgroundColor = UIColor.blueColor() let imageView = UIImageView(frame: cell.bounds) let imagePath = imagesPathArray[indexPath.row] imageView.image = UIImage.init(contentsOfFile: imagePath) imageView.contentMode = UIViewContentMode.ScaleAspectFit cell.addSubview(imageView) return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let path = imagesPathArray[indexPath.row] let fileName = NSURL(fileURLWithPath: path).URLByDeletingPathExtension?.lastPathComponent let image = UIImage(contentsOfFile: path) if fileName! == playerModel.currentSound!.name { if let image = image { showModalViewWithImage(image) } } else { print("NOT EQUAL") } } func showModalViewWithImage(image: UIImage) { let modalVC = VVModalViewController() modalVC.image = image modalVC.delegate = self self.presentViewController(modalVC, animated: true, completion: nil) } //# MARK: CommunicationModalControllerProtocol func modalControllerWillDismiss() { print("CommunicationModalControllerProtocol") playerModel.playRandomSound() } //# MARK: Actions func buttonTapped(button : UIButton) { print("1111111") initialView.hidden = true playerModel.playRandomSound() } }
// // CustomColors.swift // SweepBright Beta // // Created by Kaio Henrique on 24/11/15. // Copyright © 2015 madewithlove. All rights reserved. // import UIKit //add colors used on the project extension UIColor { /** #17A8E6 - returns: The UIColor equivalent of #17A8E6 */ class func navigationBarColor() -> UIColor { return UIColor(red:0.09, green:0.659, blue:0.902, alpha:1.0) } /** #47C9AD - returns: The UIColor equivalent of #47C9AD */ class func navigationBarProject() -> UIColor { return UIColor(red:0.28, green:0.79, blue:0.68, alpha:1.00) } /** #044059 - returns: The UIColor equivalent of #044059 */ class func navigationBarShadowColor() -> UIColor { return UIColor(red:0.016, green:0.251, blue:0.349, alpha:1.0) } class func greenProgressBar() -> UIColor { return UIColor(red:0.34, green:0.75, blue:0.61, alpha:1.0) } class func blueProgressBar() -> UIColor { return UIColor(red:0.25, green:0.56, blue:0.93, alpha:1.0) } class func searchBarColor() -> UIColor { return UIColor(red:0.94, green:0.95, blue:0.95, alpha:1.00) } class func switchOnTintColor() -> UIColor { return UIColor(red: 0.278, green: 0.788, blue: 0.678, alpha: 1.0) } class func switchOffTintColor() -> UIColor { return UIColor(red: 0.941, green: 0.945, blue: 0.949, alpha: 1.0) } class func getPlanBackground() -> UIColor { return UIColor(red:0.941, green:0.945, blue:0.949, alpha:1.0) //#f0f1f2 } class func get706a7c() -> UIColor { return UIColor(red:0.439, green:0.416, blue:0.486, alpha:1.0) /*#706a7c*/ } class func getAAA7b0() -> UIColor { return UIColor(red:0.667, green:0.655, blue:0.69, alpha:1.0) /*#aaa7b0*/ } class func getSliderArrayOfColours() -> [UIColor] { return [ UIColor(red: 0.929, green: 0, blue: 0.345, alpha: 1.0), UIColor(red: 0.929, green: 0.176, blue: 0.596, alpha: 1.0), UIColor(red: 0.09, green: 0.659, blue: 0.902, alpha: 1.0), UIColor(red: 0.278, green: 0.725, blue: 0.788, alpha: 1.0), UIColor(red: 0.278, green: 0.788, blue: 0.678, alpha: 1.0) ] } class func getStepperColor() -> UIColor { return UIColor(red:0.34, green:0.33, blue:0.36, alpha:1.00) } /** #D7D8D9 - returns: The UIColor equivalent of D7D8D9 */ class func getBorderColor() -> UIColor { return UIColor(red:0.84, green:0.85, blue:0.85, alpha:1.00) } }
import Foundation import UIKit /// Regular Expression--helper method // 匹配字符串并高亮显示 public func highlightMatches(pattern: String, inString string: String) -> NSAttributedString { let regex = try! NSRegularExpression(pattern: pattern, options: []) let range = NSMakeRange(0, string.characters.count) let matches = regex.matches(in: string, options: [], range: range) let attributedText = NSMutableAttributedString(string: string) for match in matches { attributedText.addAttributes([NSBackgroundColorAttributeName:UIColor.yellow], range: match.range) } return attributedText.copy() as! NSAttributedString } // 匹配字符串 public func listMatches(pattern: String, inString string: String) -> [String] { let regex = try! NSRegularExpression(pattern: pattern, options: []) let range = NSMakeRange(0, string.characters.count) let matches = regex.matches(in: string, options: [], range: range) return matches.map { let range = $0.range let matchString = (string as NSString).substring(with: range) //print("matchString: \(matchString)") return matchString } } // ??? public func listGroups(pattern: String, inString string: String) -> [String] { let regex = try! NSRegularExpression(pattern: pattern, options: []) let range = NSMakeRange(0, string.characters.count) let matches = regex.matches(in: string, options: [], range: range) var groupMatches = [String]() for match in matches { let rangeCount = match.numberOfRanges for group in 0..<rangeCount { groupMatches.append((string as NSString).substring(with: match.rangeAt(group))) } } return groupMatches } // public func containsMatch(pattern: String, inString string: String) -> Bool { let regex = try? NSRegularExpression(pattern: pattern, options: []) let range = NSMakeRange(0, string.characters.count) let matchString = regex?.firstMatch(in: string, options: [], range: range) return matchString != nil } // 匹配后替换字符串 public func replaceMatches(pattern: String, inString string: String, withString replacementString: String) -> String? { let regex = try! NSRegularExpression(pattern: pattern, options: []) let range = NSMakeRange(0, string.characters.count) return regex.stringByReplacingMatches(in: string, options: [], range: range, withTemplate: replacementString) }
import UIKit import ThemeKit import SnapKit class TextFieldStackView: UIView { private let stackView = UIStackView() private let textField = UITextField() var onChangeText: ((String?) -> ())? var onReturn: (() -> ())? var onSpaceKey: (() -> Bool)? var isValidText: ((String?) -> Bool)? init() { super.init(frame: .zero) textField.keyboardAppearance = .themeDefault textField.tintColor = .themeInputFieldTintColor textField.font = .body textField.textColor = .themeLeah textField.clearButtonMode = .whileEditing textField.delegate = self textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) addSubview(stackView) stackView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } stackView.spacing = .margin8 stackView.alignment = .fill stackView.layoutMargins = UIEdgeInsets(top: 0, left: .margin16, bottom: 0, right: .margin16) stackView.isLayoutMarginsRelativeArrangement = true stackView.addArrangedSubview(textField) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func becomeFirstResponder() -> Bool { textField.becomeFirstResponder() } @objc private func textFieldDidChange() { onChangeText?(textField.text) } } extension TextFieldStackView: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { onReturn?() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let isValid = isValidText?(string) ?? true if !isValid { shakeView() } return isValid } } extension TextFieldStackView { var placeholder: String? { get { textField.placeholder } set { textField.placeholder = newValue } } var text: String? { get { textField.text } set { textField.text = newValue } } var keyboardType: UIKeyboardType { get { textField.keyboardType } set { textField.keyboardType = newValue } } var autocapitalizationType: UITextAutocapitalizationType { get { textField.autocapitalizationType } set { textField.autocapitalizationType = newValue } } var returnKeyType: UIReturnKeyType { get { textField.returnKeyType } set { textField.returnKeyType = newValue } } var isSecureTextEntry: Bool { get { textField.isSecureTextEntry } set { textField.isSecureTextEntry = newValue } } func prependSubview(_ view: UIView, customSpacing: CGFloat? = nil) { stackView.insertArrangedSubview(view, at: 0) if let customSpacing = customSpacing { stackView.setCustomSpacing(customSpacing, after: view) } } func appendSubview(_ view: UIView) { stackView.addArrangedSubview(view) } }
// // WodsModelProvider.swift // WODmvp // // Created by Will Ellis on 10/8/17. // Copyright © 2017 Will Ellis Inc. All rights reserved. // import Foundation import ReSwift extension WodState { init(_ wod: Wod) { name = wod.name content = wod.content } } enum WodsError: Error { case networkError } struct WodsModel { var wods: Request<[WodState]> init(wods: Request<[WodState]> = .notStarted) { self.wods = wods } init(_ state: AppState) { guard case .initialized(let browsingState) = state.initialization else { self.init() return } self.init( wods: browsingState.wods ) } } protocol WodsModelSubscriber: AnyObject { func update(_ model: WodsModel) } protocol WodsModelProviderType: AnyObject { weak var subscriber: WodsModelSubscriber? { get set } func loadModel() } class WodsModelProvider: WodsModelProviderType, StoreSubscriber { private let store: AppStore private let dataService: DataServiceType init(_ store: AppStore = AppStore.main, _ dataService: DataServiceType = DataService.main) { self.store = store self.dataService = dataService } weak var subscriber: WodsModelSubscriber? { didSet { store.unsubscribe(self) store.subscribe(self) } } func loadModel() { DataService.main.getWods { result in let wodsState: Request<[WodState]> switch result { case .success(let value): wodsState = Request.success(value.map { WodState($0) }) case .failure: wodsState = Request.failure(WodsError.networkError) } AppStore.main.dispatch(WodsAction.updateWods(wodsState)) } } // MARK: StoreSubscriber typealias StoreSubscriberStateType = AppState func newState(state: AppState) { subscriber?.update(WodsModel(state)) } }
// // Statuses.swift // MastodonKit // // Created by Ornithologist Coder on 4/9/17. // Copyright © 2017 MastodonKit. All rights reserved. // import Foundation /// `Statuses` requests. public enum Statuses { /// Fetches a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func status(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)") } /// Gets a status context. /// /// - Parameter id: The status id. /// - Returns: Request for `Context`. public static func context(id: String) -> Request<Context> { return Request<Context>(path: "/api/v1/statuses/\(id)/context") } /// Gets a card associated with a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Card`. public static func card(id: String) -> Request<Card> { return Request<Card>(path: "/api/v1/statuses/\(id)/card") } /// Gets who reblogged a status. /// /// - Parameters: /// - id: The status id. /// - range: The bounds used when requesting data from Mastodon. /// - Returns: Request for `[Account]`. public static func rebloggedBy(id: String, range: RequestRange = .default) -> Request<[Account]> { let parameters = range.parameters(limit: between(1, and: 80, default: 40)) let method = HTTPMethod.get(.parameters(parameters)) return Request<[Account]>(path: "/api/v1/statuses/\(id)/reblogged_by", method: method) } /// Gets who favourited a status. /// /// - Parameters: /// - id: The status id. /// - range: The bounds used when requesting data from Mastodon. /// - Returns: Request for `[Account]`. public static func favouritedBy(id: String, range: RequestRange = .default) -> Request<[Account]> { let parameters = range.parameters(limit: between(1, and: 80, default: 40)) let method = HTTPMethod.get(.parameters(parameters)) return Request<[Account]>(path: "/api/v1/statuses/\(id)/favourited_by", method: method) } /// Posts a new status. /// /// - Parameters: /// - status: The text of the status. /// - replyTo: The local ID of the status you want to reply to. /// - mediaIDs: The array of media IDs to attach to the status (maximum 4). /// - sensitive: Marks the status as NSFW. /// - spoilerText: the text to be shown as a warning before the actual content. /// - visibility: The status' visibility. /// - Returns: Request for `Status`. public static func create(status: String, replyToID: String? = nil, mediaIDs: [String] = [], sensitive: Bool? = nil, spoilerText: String? = nil, visibility: Visibility = .public) -> Request<Status> { let parameters = [ Parameter(name: "status", value: status), Parameter(name: "in_reply_to_id", value: replyToID), Parameter(name: "sensitive", value: sensitive.flatMap(trueOrNil)), Parameter(name: "spoiler_text", value: spoilerText), Parameter(name: "visibility", value: visibility.rawValue) ] + mediaIDs.map(toArrayOfParameters(withName: "media_ids")) let method = HTTPMethod.post(.parameters(parameters)) return Request<Status>(path: "/api/v1/statuses", method: method) } /// Deletes a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Empty`. public static func delete(id: String) -> Request<Empty> { return Request<Empty>(path: "/api/v1/statuses/\(id)", method: .delete(.empty)) } /// Reblogs a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func reblog(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/reblog", method: .post(.empty)) } /// Unreblogs a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unreblog(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unreblog", method: .post(.empty)) } /// Favourites a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func favourite(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/favourite", method: .post(.empty)) } /// Unfavourites a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unfavourite(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unfavourite", method: .post(.empty)) } /// Bookmarks a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func bookmark(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/bookmark", method: .post(.empty)) } /// Unbookmarks a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unbookmark(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unbookmark", method: .post(.empty)) } /// Pins a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func pin(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/pin", method: .post(.empty)) } /// Unpins a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unpin(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unpin", method: .post(.empty)) } /// Mutes a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func mute(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/mute", method: .post(.empty)) } /// Unmutes a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unmute(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unmute", method: .post(.empty)) } }
import UIKit import Foundation let EA_selfView = "selfView"; let EA_contentView = "contentView"; let EA_contentHeaderView = "contentHeaderView"; let EA_bottomView = "bottomView"; let EA_titleBgView = "titleBgView"; let EA_tableView = "tableView"; let EA_tableHeaderView = "tableHeaderView"; let EA_titleLeftView = "titleLeftView"; let EA_titleMiddleView = "titleMiddleView"; let EA_titleRightView = "titleRightView"; enum UpdateTitleMask : Int { case EUpdateTitle = 1 case EUpdateLeft = 2 case EUpdateMiddle = 4 case EUpdateRight = 8 case EUpdateBg = 16 case EUpdateAll = 31 } class EAViewController : UIViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) _skinParser = SkinParser.getParserByName(NSStringFromClass(self.classForCoder)) _skinParser?.eventTarget = self self.automaticallyAdjustsScrollViewInsets = false } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() _skinParser?.parse(EA_selfView, view: self.view) let contentView = _skinParser?.parse(EA_contentView) if (contentView != nil) { self.view.addSubview(contentView!) } self._contentLayoutView = contentView let contentHeaderView = _skinParser?.parse(EA_contentHeaderView) if (contentHeaderView != nil) { self.view.addSubview(contentHeaderView!) } self._contentHeaderLayoutView = contentHeaderView let bottomView = _skinParser?.parse(EA_bottomView, view: nil) if (bottomView != nil) { self.view.addSubview(bottomView!) } self._bottomLayoutView = bottomView updateTilteView(UpdateTitleMask.EUpdateAll.rawValue) } override func viewDidLoad() { self.view.spUpdateLayout() layoutSelfView() self.view.spUpdateLayout() if nil != _titleBgView { self.view.bringSubviewToFront(_titleBgView!) } } #if DEBUG func freshSkin() { #if (arch(x86_64) || arch(i386)) self.view = UIView() _skinParser = SkinParser.getParserByName( NSStringFromClass(self.classForCoder) ) loadView() viewDidLoad() #else //真机上调试界面 #endif } #endif func updateTilteView(var mask:Int=UpdateTitleMask.EUpdateTitle.rawValue) { var newTitleBgView = _titleBgView if 0 != UpdateTitleMask.EUpdateBg.rawValue & mask { newTitleBgView = createTitleBgView() self._topLayoutView = newTitleBgView } if nil == newTitleBgView { _titleBgView?.removeFromSuperview() _titleBgView = newTitleBgView return } if newTitleBgView != _titleBgView { if nil != _titleLeftView { newTitleBgView?.addSubview(_titleLeftView!) } if nil != _titleMiddleView { newTitleBgView?.addSubview(_titleMiddleView!) } if nil != _titleRightView { newTitleBgView?.addSubview(_titleRightView!) } _titleBgView?.removeFromSuperview() _titleBgView = newTitleBgView self.view.addSubview(newTitleBgView!) } if 0 != UpdateTitleMask.EUpdateLeft.rawValue & mask { _titleLeftView?.removeFromSuperview() _titleLeftView = createTitleLeftView() if nil != _titleLeftView { newTitleBgView?.addSubview(_titleLeftView!) } } if 0 != UpdateTitleMask.EUpdateRight.rawValue & mask { _titleRightView?.removeFromSuperview() _titleRightView = createTitleRightView() if nil != _titleRightView { newTitleBgView?.addSubview(_titleRightView!) } } if 0 != UpdateTitleMask.EUpdateMiddle.rawValue & mask { _titleMiddleView?.removeFromSuperview() _titleMiddleView = createTitleMiddleView() if nil != _titleMiddleView { newTitleBgView?.addSubview(_titleMiddleView!) } mask |= UpdateTitleMask.EUpdateTitle.rawValue } if 0 != UpdateTitleMask.EUpdateTitle.rawValue & mask { let textTitle = getTitle() if nil != textTitle { (_titleMiddleView as? UILabel)?.text = textTitle! as String } _titleBgView?.spUpdateLayout() } } func getTitle()->NSString? { return self.title; } func createTitleBgView()->UIView? { return _skinParser?.parse(EA_titleBgView, view: nil) } func createTitleLeftView()->UIView? { return _skinParser?.parse(EA_titleLeftView, view: nil) } func createTitleMiddleView()->UIView? { return _skinParser?.parse(EA_titleMiddleView, view: nil) } func createTitleRightView()->UIView? { return _skinParser?.parse(EA_titleRightView, view: nil) } var _titleBgView : UIView? var _titleLeftView : UIView? var _titleMiddleView : UIView? var _titleRightView : UIView? //MARK:Layout controller views var _topLayoutView : UIView? { didSet { if oldValue != _topLayoutView { layoutSelfView() } } } var _contentHeaderLayoutView : UIView? { didSet { if oldValue != _contentHeaderLayoutView { layoutSelfView() } } } var _contentLayoutView : UIView? { didSet { if oldValue != _contentLayoutView { layoutSelfView() } } } var _bottomLayoutView : UIView? { didSet { if oldValue != _bottomLayoutView { layoutSelfView() } } } func layoutSelfView() { let bound = self.view.bounds var topFrame = CGRectZero if nil != _topLayoutView { topFrame = _topLayoutView!.frame topFrame.origin.y = 0 _topLayoutView!.frame = topFrame let layoutDes = _topLayoutView?.createViewLayoutDesIfNil() layoutDes?.setTop(0, forTag: 0) } var contentHeaderFrame = CGRectZero if nil != _contentHeaderLayoutView { contentHeaderFrame = _contentHeaderLayoutView!.frame contentHeaderFrame.origin.y = CGRectGetMaxY(topFrame) let layoutDes = _contentHeaderLayoutView?.createViewLayoutDesIfNil() if 0 != (layoutDes!.styleTypeByTag(0).rawValue & ELayoutTop.rawValue) { contentHeaderFrame.origin.y = layoutDes!.topByTag(0) } else { layoutDes!.setTop(contentHeaderFrame.origin.y, forTag: 0) } _contentHeaderLayoutView!.frame = contentHeaderFrame } var bottomFrame = CGRectZero if nil != _bottomLayoutView { _bottomLayoutView!.calcHeight(); bottomFrame = _bottomLayoutView!.frame bottomFrame.origin.y = CGRectGetHeight(bound) - CGRectGetHeight(bottomFrame) _bottomLayoutView!.frame = bottomFrame let layoutDes = _bottomLayoutView?.createViewLayoutDesIfNil() layoutDes?.setBottom(0, forTag: 0) } var contentFrame = CGRectZero if nil != _contentLayoutView { contentFrame = _contentLayoutView!.frame contentFrame.origin.y = CGRectGetMaxY(topFrame) + CGRectGetHeight(contentHeaderFrame) contentFrame.size.height = CGRectGetHeight(bound) - CGRectGetHeight(topFrame) - CGRectGetHeight(bottomFrame) - CGRectGetHeight(contentHeaderFrame) let layoutDes = _contentLayoutView?.createViewLayoutDesIfNil() if 0 != (layoutDes!.styleTypeByTag(0).rawValue & ELayoutTop.rawValue) { contentFrame.origin.y = layoutDes!.topByTag(0) } else { layoutDes!.setTop(contentFrame.origin.y, forTag: 0) } if 0 != (layoutDes!.styleTypeByTag(0).rawValue & ELayoutBottom.rawValue) { contentFrame.size.height = CGRectGetHeight(bound) - layoutDes!.topByTag(0) - layoutDes!.bottomByTag(0) } _contentLayoutView!.frame = contentFrame } for childViewControler in self.childViewControllers { if childViewControler.isKindOfClass(EAViewController) { (childViewControler as! EAViewController).layoutSelfView() } } } internal var _skinParser : SkinParser? }
// BitcoinTicker import UIKit import Alamofire import SwiftyJSON class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate { let baseURL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC" let currencyArray = ["GBP","EUR","USD"] let currencySym = [ "£","€", "$"] var currencySelect = "" var finalURL = "" @IBOutlet weak var bitcoinPriceLabel: UILabel! @IBOutlet weak var currencyPicker: UIPickerView! override func viewDidLoad() { super.viewDidLoad() currencyPicker.delegate = self currencyPicker.dataSource = self } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return currencyArray.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return currencyArray[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { finalURL = baseURL + currencyArray[row] print(finalURL) currencySelect = currencySym[row] getbitcoinPrice(url: finalURL) } //MARK: - Networking func getbitcoinPrice(url: String ) { Alamofire.request(url, method: .get) .responseJSON { response in if response.result.isSuccess { print("Sucess!") let bitcoinPriceJSON : JSON = JSON(response.result.value!) self.updatebitcoinPrice(json: bitcoinPriceJSON) } else { self.bitcoinPriceLabel.text = "Connection Issues" } } } //MARK: - JSON Parsing func updatebitcoinPrice(json : JSON) { if let bitcoinPriceResult = json["ask"].double { bitcoinPriceLabel.text = "\(currencySelect)\(bitcoinPriceResult)" } else { bitcoinPriceLabel.text = "Price Error" } } }
// // ViewController.swift // Project2 // // Created by Andrei Chenchik on 22/5/21. // import UIKit import UserNotifications class ViewController: UIViewController { @IBOutlet var button1: UIButton! @IBOutlet var button2: UIButton! @IBOutlet var button3: UIButton! var countries = [String]() var score = 0 var correctAnswer = 0 var attempt = 0 var maxAttempts = 10 var highScore = 0 let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() highScore = defaults.integer(forKey: "highScore") navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "chart.bar.fill"), style: .plain, target: self, action: #selector(showScore)) countries += ["estonia", "france", "germany", "italy", "ireland", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"] let borderWidth: CGFloat = 1 let borderColor = UIColor.lightGray.cgColor button1.layer.borderWidth = borderWidth button2.layer.borderWidth = borderWidth button3.layer.borderWidth = borderWidth button1.layer.borderColor = borderColor button2.layer.borderColor = borderColor button3.layer.borderColor = borderColor askQuestion() registerNotifications() } func registerNotifications() { let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .badge, .sound]) { [weak self] granted, error in if granted { self?.setNotifications() } else { print("D'oh! No notification for that mister!") } } } func setNotifications() { let center = UNUserNotificationCenter.current() center.removeAllPendingNotificationRequests() let content = UNMutableNotificationContent() content.title = "It's time to play!" content.body = "We miss you! It's been a week already :(" content.categoryIdentifier = "comeback" content.sound = .default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) center.add(request) print("Notifications set!") } func askQuestion() { countries.shuffle() correctAnswer = Int.random(in: 0...2) button1.transform = .identity button2.transform = .identity button3.transform = .identity button1.setImage(UIImage(named: countries[0]), for: .normal) button2.setImage(UIImage(named: countries[1]), for: .normal) button3.setImage(UIImage(named: countries[2]), for: .normal) let question = countries[correctAnswer].uppercased() title = "Guess the FLAG of \(question)" } func displayAlert(title: String, message: String, action: String) { let ac = UIAlertController(title: title, message: message, preferredStyle: .alert) ac.addAction(UIAlertAction(title: action, style: .default, handler: { _ in self.askQuestion() })) present(ac, animated: true) } @IBAction func buttonTapped(_ sender: UIButton) { let selectedCountry = countries[sender.tag].uppercased() UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: []) { sender.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) } attempt += 1 if sender.tag == correctAnswer { score += 1 } else { score -= 1 } if attempt == maxAttempts { if score > highScore { displayAlert(title: "Game ended", message: "You scored \(score) in \(attempt) attempts.\n And set a new high score! 🥳", action: "Start over") highScore = score defaults.set(highScore, forKey: "highScore") } else { displayAlert(title: "Game ended", message: "You scored \(score) in \(attempt) attempts 🥳\n Current high score is \(highScore)", action: "Start over") } score = 0 attempt = 0 } else if sender.tag != correctAnswer { displayAlert(title: "Wrong answer", message: "You tapped \(selectedCountry) 🙃", action: "Try again") } else { askQuestion() } } @objc func showScore() { let ac = UIAlertController(title: "Score board", message: "Your score is \(score).\nCurrent high score is \(highScore).", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: nil)) present(ac, animated: true) } }
// // ViewController.swift // CalculatorOsip // // Created by AndreOsip on 6/26/17. // Copyright © 2017 AndreOsip. All rights reserved. // import UIKit var isTypedSomething = false class ViewController: UIViewController { /* input.enter(value: "1") input.enter(value: "+") input.enter(value: "1") input.enter(value: "=") */ @IBOutlet weak var Label: UILabel! var digit: String? = nil var output: OutputController! var brain: Brain! var input: InputController! override func viewDidLoad() { super.viewDidLoad() output = OutputController() brain = Brain(with: output) input = InputController(with: brain) } @IBAction func OperationButton(_ sender: UIButton) { isTypedSomething = false let operationTitle = sender.currentTitle! if let checkDigit = digit { input.enter(value: checkDigit) } input.enter(value: operationTitle) if sender.currentTitle! == "=" { Label!.text = output.result } digit = nil } @IBAction func NumButton(_ sender: UIButton) { digit = sender.currentTitle! let textCurrentlyInDysplay = Label!.text! if !isTypedSomething { Label.text = digit } else { Label!.text = textCurrentlyInDysplay + digit! } isTypedSomething = true } }
// // BoardView.swift // KnitBoard // // Created by Stephen Nary on 10/26/19. // Copyright © 2019 Stephen Nary. All rights reserved. // import SwiftUI struct BoardView: View { let columnSpacing: CGFloat = 5.0 var statuses = TicketStatus.allCases @EnvironmentObject var backlog: Backlog var body: some View { GeometryReader { proxy in VStack() { HStack(alignment: .top, spacing: self.columnSpacing) { ForEach(self.statuses, id: \.self){ status in ColumnHeaderView(status: status) } } ScrollView() { HStack(alignment: .top, spacing: self.columnSpacing) { ForEach(self.statuses, id: \.self) { status in BoardColumnView(status: status, width: proxy.size.width/CGFloat(self.statuses.count) - 2 * self.columnSpacing ,tickets: self.$backlog.tickets ) } } } } } } } struct BoardView_Previews: PreviewProvider { static var previews: some View { BoardView().environmentObject(testBacklog) } }