text
stringlengths
8
1.32M
// // SearchViewController.swift // Unit4Assessment // // Created by Gregory Keeley on 2/11/20. // Copyright © 2020 Alex Paul. All rights reserved. // import UIKit import DataPersistence protocol SearchFlashCardDelegate: AnyObject { func flashCardAdded(_ savedFlashCardCell: SearchFlashCardCell, flashCard: Card) } class SearchViewController: UIViewController { weak var delegate: SearchFlashCardDelegate? private let searchView = SearchView() public var dataPersistence: DataPersistence<Card>! public var flashCard: Card? private var flashCards = [Card]() { didSet { if flashCards.isEmpty { searchView.collectionView.backgroundView = EmptyView(title: "Flash Card Collection is Empty", message: "You can add flash cards by making your own in the create tab, or using the suggestions in the search tab") } else { searchView.collectionView.backgroundView = nil DispatchQueue.main.async { self.searchView.collectionView.reloadData() } } } } override func loadView() { view = searchView } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .green searchView.collectionView.delegate = self searchView.collectionView.dataSource = self searchView.collectionView.register(SearchFlashCardCell.self, forCellWithReuseIdentifier: "cardCell") navigationItem.title = "Search Flash Cards" fetchFlashCards() } private func fetchFlashCards() { do { let localFlashCards = try FlashCardAPI.fetchLocalFlashCards() flashCards = localFlashCards } catch { print("Failed to parse local flash card: \(error)") } // NOTE: API went 503, changed out function to parse local data in meantime // FlashCardAPI.getFlashCards() { [weak self] (result) in // switch result { // case .failure(let appError): // print("failed to load flashCards: \(appError)") // case .success(let flashCards): // self?.flashCards = flashCards.cards // } // } } } extension SearchViewController: SearchFlashCardDelegate { func flashCardAdded(_ savedFlashCardCell: SearchFlashCardCell, flashCard: Card) { if dataPersistence.hasItemBeenSaved(flashCard) { showAlert(title: "Item was already saved", message: "Please select a different flash card") return } do { try dataPersistence.createItem(flashCard) showAlert(title: "Flash card Saved", message: "You can now view this card in your collection") } catch { showAlert(title: "Error", message: "There was an error adding this card to your collection") } } } extension SearchViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let maxwidth = (UIScreen.main.bounds.size.width) let adjustedWidth = (maxwidth * 0.95) let maxHeight = (UIScreen.main.bounds.height) let adjustedHeight = (maxHeight * 0.30) return CGSize(width: adjustedWidth, height: adjustedHeight) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0) } } extension SearchViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return flashCards.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cardCell", for: indexPath) as? SearchFlashCardCell else { fatalError("Failed to downcast as \"cardCell") } cell.backgroundColor = .white cell.layer.cornerRadius = 8 cell.delegate = self cell.configureCell(flashCards[indexPath.row]) return cell } }
// // RecursiveBugGrid.swift // aoc2019 // // Created by Shawn Veader on 1/4/20. // Copyright © 2020 Shawn Veader. All rights reserved. // import Foundation struct RecursiveBugGrid { private let size = 5 // 5x5 grid /// Location of the bugs within this recursive grid let bugs: [DepthCoordinate] /// Increment the recursive grid(s) by one step in time... func increment() -> RecursiveBugGrid { var newBugLocations = [DepthCoordinate]() let centerCoord = Coordinate(x: 2, y: 2) let depths = bugs.map { $0.depth }.unique().sorted() // min and max should be one more to allow infestations of other depths let minDepth = (depths.min() ?? 0) - 1 let maxDepth = (depths.max() ?? 0) + 1 for depth in minDepth...maxDepth { for y in (0..<size) { for x in (0..<size) { let coordinate = Coordinate(x: x, y: y) if coordinate == centerCoord { // don't try to do anything in the center... continue } let dCoord = DepthCoordinate(depth: depth, coordinate: coordinate) // print("Evaluating: \(dCoord)") // print("\tAdjacent: \(dCoord.adjacent(size: size))") let adjacent = dCoord.adjacent(size: size).filter { bugs.contains($0) } // print("\tInfected Adjacent: \(adjacent)") // TODO: shouldn't have the center in our list... if bugs.contains(dCoord) { // infected space // print("\tInfected Space -> \(adjacent.count)") if adjacent.count == 1 { newBugLocations.append(dCoord) } } else { // empty space // print("\tEmpty Space -> \(adjacent.count)") if adjacent.count == 1 || adjacent.count == 2 { newBugLocations.append(dCoord) } } } // for(x) } // for(y) } // for(depth) return RecursiveBugGrid(bugs: newBugLocations) } } extension RecursiveBugGrid { /// Create a recursive BugGrid with a base (depth 0) set of bugs. init(bugs: [Coordinate]) { self.bugs = bugs.map { DepthCoordinate(depth: 0, coordinate: $0) } } /// Create a recursive BugGrid with a base (depth 0) set of bugs from a BugGrid. init(other grid: BugGrid) { self.bugs = grid.bugs.map { DepthCoordinate(depth: 0, coordinate: $0) } } } extension RecursiveBugGrid: CustomStringConvertible { var description: String { let centerCoord = Coordinate(x: 2, y: 2) let depths = bugs.map { $0.depth }.unique().sorted() let minDepth = depths.min() ?? 0 let maxDepth = depths.max() ?? 0 var output = "" for depth in minDepth...maxDepth { output += "Depth \(depth):\n" for y in 0..<size { for x in 0..<size { let dCoord = DepthCoordinate(depth: depth, coordinate: Coordinate(x: x, y: y)) if dCoord.coordinate == centerCoord { output += "?" } else if bugs.contains(dCoord) { output += "#" } else { output += "." } } output += "\n" } output += "\n" } return output } }
// // LandingEntity.swift // koshelek_ru_testAPI_VIPER // // Created by maksim on 06.11.2020. // import Foundation enum From { case bid case ask } final class LandingResponse : Codable{ let e : String? // Event type let E : Int? // Event time let s : String? // Symbol let U : Int? // First update ID in event let u : Int? // Final update ID in event let b : [[Double]]? // Bids to be updated let a : [[Double]]? // Asks to be updated init(e: String, E: Int, s: String, U: Int, u: Int, b: [[Double]], a: [[Double]]) { self.e = e self.E = E self.s = s self.U = U self.u = u self.b = b self.a = a } }
// // Order.swift // DakkenApp // // Created by Sayed Abdo on 10/24/18. // Copyright © 2018 sayedAbdo. All rights reserved. // import Foundation class Order{ var id : Int var item_id : Int var item_title : String var item_img : String var order_id : Int var owner : Int var trader : Int var qty : Int var price : Double var status : String var created_at : String init(id : Int , item_id : Int , item_title : String , item_img : String , order_id : Int , owner : Int , trader : Int , qty : Int , price : Double , status : String , created_at : String) { self.id = id self.item_id = item_id self.item_title = item_title self.item_img = item_img self.order_id = order_id self.owner = owner self.trader = trader self.qty = qty self.price = price self.status = status self.created_at = created_at } }
// // PostTableViewCell.swift // Instagram // // Created by saito-takumi on 2018/01/03. // Copyright © 2018年 saito-takumi. All rights reserved. // import UIKit import Spring protocol PostTableViewCellDelegate { func commentButtonClicked(post: Post) } class PostTableViewCell: UITableViewCell { // MARK: Outlet @IBOutlet weak var userProfileImage: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var createdAt: UILabel! @IBOutlet weak var postImage: UIImageView! @IBOutlet weak var postText: UILabel! @IBOutlet weak var likeButton: UIButton! @IBOutlet weak var commentButton: UIButton! var delegate: PostTableViewCellDelegate? // MARK: property var post: Post! { didSet{ updateUI() } } private var currentUserDidLike = false 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 } // MARK: Method private func updateUI() { //画像を丸くする処理 userProfileImage.layer.cornerRadius = userProfileImage.layer.bounds.width / 2 postImage.layer.cornerRadius = 5.0 userProfileImage.clipsToBounds = true postImage.clipsToBounds = true post.user.profileImageFile.getDataInBackground(block: { (imageData, error) in if error == nil { if let imageData = imageData { self.userProfileImage.image = UIImage(data: imageData) } } }) post.postImageFile.getDataInBackground { (imageData, error) in if error == nil { if let imageData = imageData { self.postImage.image = UIImage(data: imageData) } } else { print(error) } } userNameLabel.text = post.user.username createdAt.text = Utility.formatDate(date: post.createdAt!) postText.text = post.postText likeButton.setTitle("\(post.numberOfLikes) Likes", for: .normal) configureButtonAppearance() applyLikeButtonColor() } private func configureButtonAppearance() { likeButton.layer.cornerRadius = 3.0 likeButton.layer.borderWidth = 2.0 likeButton.layer.borderColor = UIColor.lightGray.cgColor likeButton.tintColor = UIColor.lightGray commentButton.layer.cornerRadius = 3.0 commentButton.layer.borderWidth = 2.0 commentButton.layer.borderColor = UIColor.lightGray.cgColor commentButton.tintColor = UIColor.lightGray } private func applyLikeButtonColor() { if post.userDidLike(user: User.current()!) { likeButton.layer.borderColor = #colorLiteral(red: 0.7254901961, green: 0.2509803922, blue: 0.2784313725, alpha: 1) likeButton.tintColor = #colorLiteral(red: 0.7254901961, green: 0.2509803922, blue: 0.2784313725, alpha: 1) } else { likeButton.layer.borderColor = UIColor.lightGray.cgColor likeButton.tintColor = UIColor.lightGray } } // MARK: IBAction @IBAction func likeButtonTapAction(_ sender: DesignableButton) { post.changeLike() likeButton.setTitle("\(post.numberOfLikes) Likes", for: .normal) applyLikeButtonColor() //animation sender.animation = "pop" sender.curve = "spring" sender.duration = 1.5 sender.damping = 0.1 sender.velocity = 0.2 sender.animate() } @IBAction func commentButtonTapAction(_ sender: DesignableButton) { //animation sender.animation = "pop" sender.curve = "spring" sender.duration = 1.5 sender.damping = 0.1 sender.velocity = 0.2 sender.animate() delegate?.commentButtonClicked(post: post) } }
// // GuideViewController.swift // Trip // // Created by haojunhua on 15/3/30. // Copyright (c) 2015年 kidsedu. All rights reserved. // import UIKit class GuideViewController: UIViewController,MAMapViewDelegate, UICollectionViewDelegate, UIScrollViewDelegate, NSObjectProtocol, UICollectionViewDataSource{ @IBOutlet weak var _mapView: MAMapView! @IBOutlet weak var _collectionView: UICollectionView! var _isMapMode:Bool=true var _jd:JD? override func viewDidLoad() { super.viewDidLoad() _mapView.centerCoordinate=CLLocationCoordinate2D(latitude: 39.91608921,longitude: 116.39705658) _mapView.zoomLevel=15.2 _mapView.delegate = self for jd in DataSource().JDDatas { var annotation = MAPointAnnotation() annotation.coordinate = jd.location annotation.title="\(jd.id)" _mapView.addAnnotation(annotation) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: MAMapView!, didSelectAnnotationView view: MAAnnotationView!) { println(NSDate().timeIntervalSince1970) _jd=DataSource().JDDatas[view.annotation.title!.toInt()!-1] self.performSegueWithIdentifier("guideToJD", sender: self) mapView.deselectAnnotation(view.annotation, animated: false) println(NSDate().timeIntervalSince1970) } func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! { let AnnotationViewID = "JDAnnotaionView"; var annotationView:MAPPAnnotationView! = mapView.dequeueReusableAnnotationViewWithIdentifier(AnnotationViewID) as! MAPPAnnotationView! if annotationView == nil { annotationView = MAPPAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID) var jd:JD=DataSource().JDDatas[annotation.title!.toInt()!-1] annotationView.setThumb(jd.picPath) } return annotationView } @IBAction func changeShowMode(sender: UIBarButtonItem) { _isMapMode = !_isMapMode var fromView:UIView = self._isMapMode ? _collectionView : _mapView var toView:UIView = self._isMapMode ? _mapView :_collectionView if !_isMapMode { _collectionView.hidden=false UIView.transitionWithView(_collectionView, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromRight, animations: {}, completion: { finished in if finished { sender.title = "列表" } }) }else { _collectionView.hidden=true // UIView.transitionWithView(_mapView, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromLeft, animations: {}, completion: { // finished in // if finished { // sender.title = "地图" // } // }) sender.title = "地图" } // UIView.transitionFromView(fromView, toView: toView, duration: 0.5, options: transitionDirection, completion: { // finished in // if finished { // sender.title = self._isMapMode ? "列表" : "地图" // } // }) } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return DataSource().JDDatas.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! JDCollectionCell var jd:JD=DataSource().JDDatas[indexPath.row] cell.nameLabel.text=jd.name cell._view.layer.masksToBounds=true cell._view.layer.cornerRadius=10.0 cell._image.image=UIImage(named: jd.picPath) return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var jdViewController:JDViewController = segue.destinationViewController as! JDViewController; if _jd == nil { _jd = DataSource().JDDatas[_collectionView.indexPathsForSelectedItems()[0].row] } jdViewController._jd = _jd } }
// // Game.swift // // Created by Chuck Krutsinger on 2/12/19. // Copyright © 2019 Countermind, LLC. All rights reserved. // typealias GameName = String typealias Objective = String struct Game { let name: GameName let minPlayers: Int let maxPlayers: Int let objective: Objective static func displayGameDetails(_ game: Game) { let players = game.minPlayers == game.maxPlayers ? "\(game.minPlayers)" : "\(game.minPlayers) to \(game.maxPlayers)" let message = """ Players: \(players) Objective: \(game.objective) """ appRouterAction( .alert(title: game.name, message: message, completion: nil) ) } }
// // Serie+CoreDataClass.swift // CoreDataSample // // Created by Nelson on 9/1/2017. // Copyright © 2017 T@d. All rights reserved. // This file was automatically generated and should not be edited. // import Foundation import CoreData public class Serie: NSManagedObject { }
// // AuthUserOpenListController.swift // MsdGateLock // // Created by ox o on 2017/6/30. // Copyright © 2017年 xiaoxiao. All rights reserved. // 授权用户开门记录 import UIKit class AuthUserOpenListController: UIViewController { var tableView : UITableView! var headView : UIView! var isHiddenSub : Bool = false var currentLockID : String? //当前门锁id var lockTitle : String? var openLockModel : [OpenLockList]? var listIndex : Int = 1 var subTitleStr : String? //刷新 let header = MJRefreshNormalHeader() var footer : MJRefreshAutoNormalFooter! var placeHolderView : UIView? override func viewDidLoad() { super.viewDidLoad() self.title = "开门记录" self.view.backgroundColor = UIColor.globalBackColor setupUI() //底部视图 setupPlaceHolderUI() //占位视图 header.beginRefreshing() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.openLockModel?.removeAll() } } extension AuthUserOpenListController{ func setupUI(){ headView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 59)) headView.backgroundColor = UIColor.globalBackColor self.view.addSubview(headView) let homeLabel = UILabel() homeLabel.textColor = UIColor.textBlueColor homeLabel.text = lockTitle ?? "家" homeLabel.font = UIFont.systemFont(ofSize: 30) headView.addSubview(homeLabel) homeLabel.snp.makeConstraints { (make) in make.left.equalTo(14) make.top.equalTo(9) } let listLabel = UILabel() listLabel.textColor = UIColor.textBlackColor listLabel.text = "\(subTitleStr ?? "")的记录" listLabel.font = UIFont.systemFont(ofSize: 14) listLabel.isHidden = isHiddenSub headView.addSubview(listLabel) listLabel.snp.makeConstraints { (make) in make.right.equalTo(-12) make.bottom.equalTo(homeLabel) } let line = UIView() line.backgroundColor = UIColor.hex(hexString: "f0f0f0") headView.addSubview(line) line.snp.makeConstraints { (make) in make.left.equalTo(0) make.right.equalTo(0) make.height.equalTo(1) make.bottom.equalTo(0) } tableView = UITableView() tableView.rowHeight = 30 tableView.separatorStyle = .none tableView.delegate = self tableView.dataSource = self self.view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.left.equalTo(0) make.right.equalTo(0) make.top.equalTo(0) make.bottom.equalTo(0) } tableView.tableHeaderView = headView header.setRefreshingTarget(self, refreshingAction: #selector(AuthUserOpenListController.reloadNewData)) self.tableView.mj_header = header footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(AuthUserOpenListController.reloadMoreData)) self.tableView.mj_footer = footer } func setupPlaceHolderUI(){ placeHolderView = UIView() placeHolderView?.backgroundColor = UIColor.globalBackColor self.view.addSubview(placeHolderView!) placeHolderView?.snp.makeConstraints { (make) in make.top.equalTo(0) make.left.equalTo(0) make.right.equalTo(0) make.bottom.equalTo(0) } let placeImgView = UIImageView(image: UIImage.init(named: "placeholderPic")) placeHolderView?.addSubview(placeImgView) placeImgView.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.top.equalTo(80*kHeight6Scale) } let tipLabel = UILabel() tipLabel.text = "还未任何记录" tipLabel.textColor = UIColor.hex(hexString: "999999") tipLabel.font = kGlobalTextFont placeHolderView?.addSubview(tipLabel) tipLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.top.equalTo(placeImgView.snp.bottom).offset(10*kHeight6Scale) } } } extension AuthUserOpenListController:UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard self.openLockModel != nil else { self.placeHolderView?.isHidden = false return 0 } if (self.openLockModel?.count)! > 0{ self.placeHolderView?.isHidden = true } return (self.openLockModel?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentfier = "OpenListCell" var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentfier) as? OpenListCell if cell == nil{ cell = Bundle.main.loadNibNamed("OpenListCell", owner: nil, options: nil)?.last as? UITableViewCell as? OpenListCell } cell?.openModel = self.openLockModel?[indexPath.row] return cell! } } //MARK:- http extension AuthUserOpenListController{ //下拉刷新最新内容 @objc func reloadNewData(){ if isHiddenSub { let req = BaseReq<LockAllLogReq>() req.action = GateLockActions.ACTION_GetLockLog req.sessionId = UserInfo.getSessionId() ?? "" // let userID = UserDefaults.standard.object(forKey: UserInfo.userId) as? Int let lockId = currentLockID ?? "" let limit = 20 req.data = LockAllLogReq.init(lockId, start: 1, limit: limit) AjaxUtil<OpenLockList>.actionArrPost(req: req, backArrJSON: { (resp) in QPCLog(resp) if let lockModel = resp.data { self.openLockModel = lockModel } self.tableView.reloadData() self.tableView.mj_header?.endRefreshing() }) }else{ let req = BaseReq<LockInfoReq>() req.action = GateLockActions.ACTION_GetLockOneLog req.sessionId = UserInfo.getSessionId()! let userID = UserInfo.getUserId() let lockId = currentLockID let limit = 20 req.data = LockInfoReq.init(userID!, lockId: lockId!, start: 1, limit: limit) AjaxUtil<OpenLockList>.actionArrPost(req: req, backArrJSON: { [weak self](resp) in QPCLog(resp) if let lockModel = resp.data { self?.openLockModel = lockModel } self?.tableView.reloadData() self?.tableView.mj_header?.endRefreshing() }) } } @objc func reloadMoreData(){ if isHiddenSub{ listIndex += 1 let req = BaseReq<LockAllLogReq>() req.action = GateLockActions.ACTION_GetLockLog req.sessionId = UserInfo.getSessionId()! // let userID = UserDefaults.standard.object(forKey: UserInfo.userId) as? Int let lockId = currentLockID let start = listIndex let limit = 20 req.data = LockAllLogReq.init(lockId!, start: start, limit: limit) AjaxUtil<OpenLockList>.actionArrPost(req: req, backArrJSON: { [weak self](resp) in QPCLog(resp) if let lockModel = resp.data { self?.openLockModel = (self?.openLockModel)! + lockModel } self?.tableView.reloadData() self?.tableView.mj_footer?.endRefreshing() }) }else{ listIndex += 1 let req = BaseReq<LockInfoReq>() req.action = GateLockActions.ACTION_GetLockOneLog req.sessionId = UserInfo.getSessionId()! let userID = UserInfo.getUserId() let lockId = currentLockID let start = listIndex let limit = 20 req.data = LockInfoReq.init(userID!, lockId: lockId!, start: start, limit: limit) AjaxUtil<OpenLockList>.actionArrPost(req: req, backArrJSON: { [weak self](resp) in QPCLog(resp) if let lockModel = resp.data { self?.openLockModel = (self?.openLockModel)! + lockModel } self?.tableView.reloadData() self?.tableView.mj_footer?.endRefreshing() }) } } }
// // AccountTypeSquareButton.swift // homefinancing // // Created by 辰 宫 on 5/7/16. // Copyright © 2016 wph. All rights reserved. // class AccountTypeSquareButton: UIButton { static internal let buttonPadding:CGFloat = 17 static internal let buttonWidth:CGFloat = (SCREEN_WIDTH / 4 * 3 - buttonPadding * 4) / 3 static internal let buttonHeight:CGFloat = 30 var buttonIndex:Int? var accountType:AccountType = AccountType.pay var buttonId:String? var buttonTitle:String? lazy var selectImageView: UIImageView = UIImageView() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initViews() } init(frame: CGRect,type: AccountType,title: String) { super.init(frame: frame) accountType = type buttonTitle = title self.initViews() } func initViews() { self.layer.borderWidth = 1 self.layer.borderColor = UIColor.lightGray.cgColor self.layer.cornerRadius = 3 self.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13) self.titleLabel?.adjustsFontSizeToFitWidth = true self.setTitle(buttonTitle, for: UIControlState()) self.setTitleColor(UIColor.lightGray, for: UIControlState()) // self.addTarget(self, action: #selector(AccountTypeSquareButton.clickAction), forControlEvents: UIControlEvents.TouchUpInside) let imgWidth:CGFloat = 16 let imgHeight:CGFloat = 15 selectImageView.frame = CGRect(x: self.frame.size.width - 13, y: self.frame.size.height - 11, width: imgWidth, height: imgHeight) self.addSubview(selectImageView) } var selectedSquare:Bool = false { didSet { if selectedSquare == true { if accountType == AccountType.pay { self.layer.borderColor = appPayColor.cgColor self.setTitleColor(appPayColor, for: UIControlState()) selectImageView.isHidden = false selectImageView.image = UIImage(named: "star_blue") } else { self.layer.borderColor = appIncomeColor.cgColor self.setTitleColor(appIncomeColor, for: UIControlState()) selectImageView.isHidden = false selectImageView.image = UIImage(named: "star_yellow") } } else { self.layer.borderColor = UIColor.lightGray.cgColor self.setTitleColor(UIColor.lightGray, for: UIControlState()) selectImageView.isHidden = true } } } // func clickAction() { // selectedSquare = !selectedSquare // } }
// // ControlVC.swift // FoodVoucher // // Created by 임명심 on 2021/09/06. // import UIKit class ControlVC: UIViewController { private let slider = UISlider() private let star1 = UIImageView() private let star2 = UIImageView() private let star3 = UIImageView() private let star4 = UIImageView() private let star5 = UIImageView() // 0.5 단위로 var sliderValue: Float { if slider.value - Float(Int(slider.value)) >= 0.5 { return Float(Int(slider.value)) + 0.5 } else { return Float(Int(slider.value)) } } override func viewDidLoad() { super.viewDidLoad() slider.minimumValue = 0 slider.maximumValue = 5 slider.frame = CGRect(x: 0, y: 0, width: 170, height: 30) self.view.addSubview(slider) star1.image = UIImage(named: "starEmpty") star1.frame = CGRect(x: 0, y: 0, width: 33, height: 30) star1.tag = 1 self.view.addSubview(star1) star2.image = UIImage(named: "starEmpty") star2.frame = CGRect(x: 34, y: 0, width: 33, height: 30) star2.tag = 2 self.view.addSubview(star2) star3.image = UIImage(named: "starEmpty") star3.frame = CGRect(x: 68, y: 0, width: 33, height: 30) star3.tag = 3 self.view.addSubview(star3) star4.image = UIImage(named: "starEmpty") star4.frame = CGRect(x: 102, y: 0, width: 33, height: 30) star4.tag = 4 self.view.addSubview(star4) star5.image = UIImage(named: "starEmpty") star5.frame = CGRect(x: 136, y: 0, width: 33, height: 30) star5.tag = 5 self.view.addSubview(star5) self.preferredContentSize = CGSize(width: slider.frame.width, height: slider.frame.height + 10) slider.addTarget(self, action: #selector(onChangeValue(_:)), for: .valueChanged) // 슬라이더 안보이게 처리하기 self.slider.minimumTrackTintColor = .clear self.slider.maximumTrackTintColor = .clear self.slider.thumbTintColor = .clear } @objc func onChangeValue(_ sender: UISlider) { let floatVlaue = floor(sender.value * 10) / 10 for index in 1...5 { if let starImage = view.viewWithTag(index) as? UIImageView { if Float(index) <= floatVlaue { starImage.image = UIImage(named: "starFull") } else if (Float(index)-floatVlaue) <= 0.5 { starImage.image = UIImage(named: "starHalf") } else { starImage.image = UIImage(named: "starEmpty") } } } } }
// // HopperAPIGetHomePageResponse.swift // Cryptohopper-iOS-SDK // // Created by Kaan Baris Bayrak on 02/11/2020. // import Foundation import Foundation class HopperAPIGetHomePageResponse: Codable { var data : HopperAPIGetHomePageData? private enum CodingKeys: String, CodingKey { case data = "data" } } public class HopperAPIGetHomePageData: Codable { public private(set) var featuredHome : [MarketItem]? public private(set) var homeEditorsPick : [MarketItem]? public private(set) var homeTopSignals : [MarketItem]? public private(set) var homeBestRatedStrategies : [MarketItem]? public private(set) var homeBestRatedTemplates : [MarketItem]? public private(set) var homeBestRatedSignals : [MarketItem]? private enum CodingKeys: String, CodingKey { case featuredHome = "featured_home" case homeEditorsPick = "home_editors_pick" case homeTopSignals = "home_top_signals" case homeBestRatedStrategies = "home_best_rated_strategies" case homeBestRatedTemplates = "home_best_rated_templates" case homeBestRatedSignals = "home_best_rated_signals" } }
// // demo_SwiftUIApp.swift // demo_SwiftUI // // Created by li’Pro on 2020/11/13. // import SwiftUI @main struct demo_SwiftUIApp: App { var body: some Scene { WindowGroup { ContentView() } } }
// // ViewController.swift // Guess_animal // // Created by slava bily on 29/1/20. // Copyright © 2020 slava bily. All rights reserved. // import UIKit import GameplayKit class ViewController: UIViewController, Storyboarded { var model = GuessAnimalModel() var score = 0 var showMainViewAction: ((_ button1Name: String, _ button2Name: String, _ buttonName: String, _ score: Int) -> Void)? var correctAnswer = Int() var question = String() override func viewDidLoad() { super.viewDidLoad() prepareAnswer() title = question navigationItem.largeTitleDisplayMode = .never } func prepareAnswer() { question = model.question correctAnswer = model.correctAnswer let button1Name = model.buttonNames[0] let button2Name = model.buttonNames[1] let button3Name = model.buttonNames[2] showMainViewAction!(button1Name, button2Name, button3Name, score) } func buttonAction(_ sender: UIButton) { var title: String if sender.tag == correctAnswer { title = "Correct" score += 1 } else { title = "Wrong" score -= 1 } let ac = UIAlertController(title: title, message: "Your score is \(score)", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: reloadMainView(action:))) present(ac, animated: true) } func reloadMainView(action: UIAlertAction) { model = GuessAnimalModel() prepareAnswer() title = question } }
import UIKit import AGSAuth class MemesListViewController: UITableViewController { var memes: [AllMemesQuery.Data.Meme]? { didSet { tableView.reloadData() } } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 64 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadData() } // MARK: - Data loading func loadData() { let watcher = SyncService.instance.client.watch(query: AllMemesQuery()) { result, error in if let error = error { NSLog("Error while fetching query: \(error.localizedDescription)") return } self.memes = result?.data?.memes } watcher.refetch() } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return memes?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? MemesTableViewCell else { fatalError("Could not dequeue PostTableViewCell") } guard let meme = memes?[indexPath.row] else { fatalError("Could not find post at row \(indexPath.row)") } cell.configure(with: meme.fragments.memeDetails) return cell } @IBAction func onLogout(_ sender: Any) { try? AgsAuth.instance.logout(onCompleted: { _ in self.navigationController!.present(UINavigationController(rootViewController: LoginViewController()), animated: true) }) } }
// // XHEnum.swift // ObjcTools // // Created by douhuo on 2021/2/18. // Copyright © 2021 wangergang. All rights reserved. // // MARK: - scorollview 刷新类型 enum TVloadType { /** 没有加载效果 */ case none /** 只有refresh效果 */ case refresh /** 只有加载更多 */ case more /** 刷新和加载更多都有 */ case all } // MARK: - 网络加载类型 enum LoadWebType { /** 无法网页 */ case unknown /** 用户协议 */ case Service_agreement /** 用户隐私协议 */ case pricaty_protoco }
// // Petition.swift // WhiteHousePetitions // // Created by Salma Salah on 2/19/20. // Copyright © 2020 Salma Salah. All rights reserved. // import Foundation struct Petition: Codable { var title: String var body: String var signatureCount: Int } //make sure you named all the properties in the Petition struct correctly – the Codable protocol matches those names against the JSON directly, so if you have a typo in “signatureCount” then it will fail. //we can make our struct conforms to codable , if each member in it condorms codable
// // JsonParser.swift // Countries Game // // Created by Yoni on 01/06/2020. // Copyright © 2020 Yoni. All rights reserved. // import UIKit class JsonParser { let url = URL(string: "https://restcountries.eu/rest/v2/all") var countries = [Country]() func parseCountriesJson(completion: @escaping ([Country]) -> ()) { if let url = url { let session = URLSession.shared session.dataTask(with: url) { (data, response, error) in if let data = data { do { self.countries = try JSONDecoder().decode([Country].self, from: data) completion(self.countries) } catch let error { print(error) } } }.resume() } } }
// // HomePage.swift // N3RVE // // Created by Camilo Rossi on 2018-10-13. // Copyright © 2018 Camilo Rossi. All rights reserved. // import UIKit import AVFoundation import FirebaseAnalytics import FirebaseAuth import Firebase class HomePage: UIViewController { var avPlayer: AVPlayer! var avPlayerLayer: AVPlayerLayer! var paused: Bool = false var player: AVPlayer? var AudioPlayer = AVAudioPlayer() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidAppear(_ animated: Bool) { if Auth.auth().currentUser != nil { self.performSegue(withIdentifier: "fromHomePageToHome", sender: nil) } NotificationCenter.default.addObserver(self, selector: #selector(HomePage.finishBackgroundVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) } override func viewDidLoad() { super.viewDidLoad() // Load the video from the app bundle. let videoURL: NSURL = Bundle.main.url(forResource: "BackgroundVid", withExtension: "mp4")! as NSURL player = AVPlayer(url: videoURL as URL) player?.actionAtItemEnd = .none player?.isMuted = true let playerLayer = AVPlayerLayer(player: player) playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill playerLayer.zPosition = -1 playerLayer.frame = view.frame view.layer.addSublayer(playerLayer) //player?.play() } /* func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer { //1 var path = Bundle.main.path(forResource: file as String, ofType: type as String) var url = NSURL.fileURL(withPath: path!) //2 var error: NSError? //3 var audioPlayer:AVAudioPlayer? audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error) //4 return audioPlayer! } */ @IBAction func gotoLogin(_ sender: Any) { performSegue(withIdentifier: "fromHomePageToLogin", sender: self) } @IBAction func gotoSignUp(_ sender: Any) { performSegue(withIdentifier: "fromHomePageToSignUp", sender: self) } @objc func finishBackgroundVideo(notification: NSNotification) { if let playerItem = notification.object as? AVPlayerItem { playerItem.seek(to: CMTime.zero, completionHandler: nil) } } }
// // AddAptitudeViewController.swift // WeNetwork // // Created by Josefina Bustamante on 26/08/2018. // Copyright © 2018 BiteInc. All rights reserved. // import UIKit class AddAptitudeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // 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. } */ }
// // AddressBookModuleOutput.swift // WavesWallet-iOS // // Created by Pavel Gubin on 9/23/18. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import DomainLayer protocol AddressBookModuleOutput: AnyObject { func addressBookDidSelectContact(_ contact: DomainLayer.DTO.Contact) }
import MetalPerformanceShaders public class AreaMax: BasicMPSFilter { @objc public var kernelRadius: Float = 2.0 { didSet { if useMetalPerformanceShaders { let kernelSize = roundToOdd(kernelRadius) // MPS area max kernels need to be odd internalImageKernel = MPSImageAreaMax(device: renderTarget.context.device, kernelWidth: kernelSize, kernelHeight: kernelSize) } else { fatalError("Area Max isno't available on pre-MPS OS versions") } } } public init(context: MIContext = .default) { super.init(context: context) ({ kernelRadius = 2.0 })() } }
//// //// CommentView.swift //// oneone //// //// Created by levi.luo on 2017/10/29. //// Copyright © 2017年 levi.luo. All rights reserved. //// // //import Foundation //import UIKit // //class CommentView: UIView { // private var contentView:UIView! // // override init() { // super.init(frame: CGRect(x:0,y:0,height:50,width:screenW)) // } // // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // // func show(){ // let window: UIWindow = UIApplication.shared.keyWindow! // window.addSubview(self) // window.bringSubview(toFront: self) // } // // func close(){ // // print(self) // // print(self.superview) // // print(self) // self.image.removeFromSuperview() // self.removeFromSuperview() // // self.contentView.removeFromSuperview() // } // // /* // // MARK: - Navigation // // // In a storyboard-based application, you will often want to do a little preparation before navigation // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // // Get the new view controller using segue.destinationViewController. // // Pass the selected object to the new view controller. // } // */ // //}
// // ExplorePhotosViewController.swift // Travel Companion // // Created by Stefan Jaindl on 14.08.18. // Copyright © 2018 Stefan Jaindl. All rights reserved. // import CoreData import GoogleMaps import GooglePlaces import UIKit class ExplorePhotosViewController: UIViewController { @IBOutlet private var map: GMSMapView! @IBOutlet private var collectionView: UICollectionView! @IBOutlet private var flowLayout: UICollectionViewFlowLayout! @IBOutlet private var countryButton: UIButton! @IBOutlet private var placeButton: UIButton! @IBOutlet private var latlongButton: UIButton! @IBOutlet private var activityIndicator: UIActivityIndicatorView! @IBOutlet private var noPhotoLabel: UILabel! var pin: Pin? var dataController: DataController? var dataSource: GenericListDataSource<Photos, AlbumCollectionViewCell>? var fetchType: Int = FetchType.Country.rawValue var choosePhoto = false var plan: Plan! override public func viewDidLoad() { super.viewDidLoad() self.tabBarController?.navigationItem.title = pin?.name } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) initMap() initResultsController() fetchData() setButtonState() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) dataSource?.fetchedResultsController = nil } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() UiUtils.setupFlowLayout(for: self, view: view, flowLayout: flowLayout) } @IBAction func fetchByCountry(_ sender: Any) { fetch(by: FetchType.Country.rawValue) } @IBAction func fetchByPlace(_ sender: Any) { fetch(by: FetchType.Place.rawValue) } @IBAction func fetchByLatLong(_ sender: Any) { fetch(by: FetchType.LatLong.rawValue) } func fetch(by type: Int) { resetFetchedResultsController() fetchType = type initResultsController() setButtonState() fetchData() } func setButtonState() { countryButton.isEnabled = fetchType != FetchType.Country.rawValue ? true : false placeButton.isEnabled = fetchType != FetchType.Place.rawValue ? true : false latlongButton.isEnabled = fetchType != FetchType.LatLong.rawValue ? true : false } func resetFetchedResultsController() { if let pin = pin { NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: "\(Constants.CoreData.cacheNamePhotos)-\(pin.objectID)") } dataSource?.fetchedResultsController = nil collectionView.reloadData() } func initResultsController() { guard let dataController = dataController else { debugPrint("dataController is nil, cannot init results controller") return } let fetchRequest: NSFetchRequest<Photos> = Photos.fetchRequest() let sortDescriptor = NSSortDescriptor(key: Constants.CoreData.sortKey, ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] if let pin = pin { let predicate = NSPredicate(format: "pin = %@ AND type = %d", pin, fetchType) fetchRequest.predicate = predicate } var cacheName: String? = nil if let pin = pin { cacheName = "\(Constants.CoreData.cacheNamePhotos)-\(pin.objectID)" } dataSource = GenericListDataSource( collectionView: collectionView, managedObjectContext: dataController.viewContext, fetchRequest: fetchRequest, cellReuseId: Constants.ReuseIds.albumCell, cacheName: cacheName ) } func fetchData() { enableUi(false) self.noPhotoLabel.isHidden = true DispatchQueue.global().async { do { try self.dataSource?.performFetch() if let result = self.dataSource?.fetchedObjects() { if result.count == 0 { self.fetchRemoteData() } else { DispatchQueue.main.async { self.collectionView.reloadData() self.enableUi(true) } } } } catch { DispatchQueue.main.async { self.enableUi(true) self.noPhotoLabel.isHidden = false UiUtils.showError(error.localizedDescription, controller: self) } } } } func fetchRemoteData() { if fetchType == FetchType.Place.rawValue { fetchDataFromGooglePlacePhotos() } else { fetchDataFromFlickr() } } func fetchDataFromGooglePlacePhotos() { guard let placeId = pin?.placeId else { debugPrint("Could not fetchDataFromGooglePlacePhotos") return } DispatchQueue.main.async { self.loadPhotosOfPlace(placeID: placeId) } } func fetchDataFromFlickr() { let latitude = pin?.latitude let longitude = pin?.longitude var country = pin?.countryCode if let countryName = pin?.country { country = countryName //search primarily by whole country name, if not available by country code } DispatchQueue.global().async { var queryItems = FlickrClient.sharedInstance.buildQueryItems() if self.fetchType == FetchType.Country.rawValue { guard let country = country else { UiUtils.showError("noCountryPhotos".localized(), controller: self) DispatchQueue.main.async { self.noPhotoLabel.isHidden = false self.enableUi(true) } return } queryItems[FlickrConstants.ParameterKeys.text] = country } else if self.fetchType == FetchType.LatLong.rawValue { guard let latitude = latitude, let longitude = longitude else { debugPrint("Could not fetch photos by latitude/longitude") return } queryItems[FlickrConstants.ParameterKeys.boundingBox] = FlickrClient.sharedInstance.bboxString(latitude: latitude, longitude: longitude) } FlickrClient.sharedInstance.fetchPhotos(with: queryItems) { (error, isEmpty, photos) in if let error = error { DispatchQueue.main.async { UiUtils.showError(error, controller: self) self.noPhotoLabel.isHidden = false self.enableUi(true) } } else { DispatchQueue.main.async { guard let photos = photos else { self.noPhotoLabel.isHidden = false self.enableUi(true) return } if let dataController = self.dataController, let pin = self.pin { for photo in photos { _ = CoreDataClient.sharedInstance.storePhoto(dataController, photo: photo, pin: pin, fetchType: self.fetchType) } } self.enableUi(true) } } } } } func loadPhotosOfPlace(placeID: String) { GMSPlacesClient.shared().lookUpPhotos(forPlaceID: placeID) { (photos, error) -> Void in if let error = error { UiUtils.showError(error.localizedDescription, controller: self) self.noPhotoLabel.isHidden = false self.enableUi(true) return } else { if let photos = photos?.results, photos.count > 0 { if let dataController = self.dataController, let pin = self.pin { for photo in photos { CoreDataClient.sharedInstance.storePhoto(dataController, placePhoto: photo, pin: pin, fetchType: self.fetchType) { (error) in if let error = error { UiUtils.showError(error, controller: self) } } } } } else { self.noPhotoLabel.isHidden = false } } self.enableUi(true) self.collectionView.reloadData() } } func initMap() { let zoom = UserDefaults.standard.float(forKey: Constants.UserDefaults.zoomLevel) if let pin = pin { let camera = GMSCameraPosition.camera(withLatitude: pin.latitude, longitude: pin.longitude, zoom: zoom) map.camera = camera addPinToMap(with: CLLocationCoordinate2D(latitude: pin.latitude, longitude: pin.longitude)) } } func enableUi(_ enable: Bool) { if enable { activityIndicator.stopAnimating() } else { activityIndicator.startAnimating() } } func addPinToMap(with coordinate: CLLocationCoordinate2D) { let position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude) let marker = GMSMarker(position: position) marker.map = map } } extension ExplorePhotosViewController: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource?.numberOfSections(in: collectionView) ?? 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource?.collectionView(collectionView, numberOfItemsInSection: section) ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.ReuseIds.albumCell, for: indexPath) as! AlbumCollectionViewCell cell.locationImage.image = UIImage(named: Constants.CoreData.placeholderImage) if let imageData = dataSource?.object(at: indexPath)?.imageData { cell.locationImage.image = UIImage(data: imageData) } else { if let imagePath = dataSource?.object(at: indexPath)?.imageUrl { WebClient.sharedInstance.downloadImage(imagePath: imagePath) { (imageData, error) in if let error = error { UiUtils.showError(error, controller: self) } else { guard let imageData = imageData else { UiUtils.showError("errorDownloadImage".localized(), controller: self) return } DispatchQueue.main.async { cell.locationImage.image = UIImage(data: imageData) } } } } } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let photo = dataSource?.fetchedResultsController?.object(at: indexPath) guard photo?.imageData != nil else { debugPrint("No image data to display") UiUtils.showToast(message: "waitForPhotos".localized(), view: self.view) return } if choosePhoto { plan.imageData = photo?.imageData self.navigationController?.popViewController(animated: true) } else { performSegue(withIdentifier: Constants.Segues.photoDetail, sender: photo) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Constants.Segues.photoDetail { let destinationViewController = segue.destination as! PhotosDetailViewController let photo = sender as! Photos destinationViewController.data = photo.imageData destinationViewController.text = photo.title } } }
// // BusinessSettingViewController.swift // Trispective // // Created by USER on 2017/5/12. // Copyright © 2017年 Trispective. All rights reserved. // import UIKit import Firebase class BusinessSettingViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView=UIView() self.navigationController?.navigationBar.titleTextAttributes=[NSFontAttributeName: UIFont(name: DemoImage.font,size: DemoImage.fontSize)!,NSForegroundColorAttributeName: UIColor(red: 30/225, green: 155/225, blue: 156/225, alpha: 1)] let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil) self.navigationItem.backBarButtonItem = item // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.alpha=1 } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return DemoImage.businessSet1.count case 1: return DemoImage.businessSet2.count case 2: return 1 default: return 1 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return " " } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let v=UIView() v.backgroundColor=tableView.backgroundColor return v } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "settingCell", for: indexPath) as! SettingTableViewCell cell.accessoryType = .disclosureIndicator switch indexPath.section { case 0: cell.title.text=DemoImage.businessSet1[indexPath.row] case 1: cell.title.text=DemoImage.businessSet2[indexPath.row] case 2: cell.title.text="Log out" cell.title.textAlignment = .center default: break } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.section { case 0: if indexPath.row==0{ if ModelManager.getInstance().customer.getId().isEmpty{ performSegue(withIdentifier: "showBusinessGeneral", sender: nil) }else{ performSegue(withIdentifier: "showCustomerGeneral", sender: nil) } }else if indexPath.row==1{ let alertController = UIAlertController(title: "Change Password",message: "", preferredStyle: .alert) alertController.addTextField { (textField: UITextField!) -> Void in textField.isSecureTextEntry=true textField.placeholder = "New Password" } alertController.addTextField { (textField: UITextField!) -> Void in textField.isSecureTextEntry=true textField.placeholder = "Confirm New Password" } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let okAction = UIAlertAction(title: "Ok", style: .default, handler: { action in let new1=alertController.textFields!.first!.text! let new2=alertController.textFields!.last!.text! if new1 == new2{ self.setNewPassword(newPassword: new1) }else{ self.createAlert(title: "Failed", message: "Please confirm your new password!") } }) alertController.addAction(cancelAction) alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } case 2: ModelManager.getInstance().setAvatarData(data: Data()) ModelManager.getInstance().setCoverData(data: Data()) ModelManager.getInstance().customer=Customer() ModelManager.getInstance().restaurant=Restaurant() ModelManager.getInstance().publishDish=Dish() handleLogout() self.tabBarController?.dismiss(animated: true, completion: nil) default: break } } func handleLogout(){ do{ try FIRAuth.auth()?.signOut() }catch let logoutError{ print(logoutError) } } func setNewPassword(newPassword:String){ FIRAuth.auth()?.currentUser?.updatePassword(newPassword) { (error) in if error != nil{ self.createAlert(title: "Failed", message: (error?.localizedDescription)!) return }else{ self.createAlert(title: "Success", message: "Password has been changed.") } } } }
// // ReceiveAddressTypes.swift // WavesWallet-iOS // // Created by Pavel Gubin on 10/13/18. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import DomainLayer import Extensions enum ReceiveAddress { enum DTO { struct Info { let assetName: String let address: String let icon: AssetLogo.Icon let qrCode: String let invoiceLink: String? let isSponsored: Bool let hasScript: Bool } } }
// // NumericAttributeFilter.swift // // // Created by Vladislav Fitc on 12.03.2020. // import Foundation public enum NumericAttributeFilter: Equatable, Codable { case `default`(Attribute) case equalOnly(Attribute) } extension NumericAttributeFilter: ExpressibleByStringInterpolation { public init(stringLiteral value: String) { self.init(rawValue: value) } } extension NumericAttributeFilter: RawRepresentable { private enum Prefix: String { case equalOnly } public var rawValue: String { switch self { case .default(let attribute): return attribute.rawValue case .equalOnly(let attribute): return PrefixedString(prefix: Prefix.equalOnly.rawValue, value: attribute.rawValue).description } } public init(rawValue: String) { if let prefixedString = PrefixedString(rawValue: rawValue), let prefix = Prefix(rawValue: prefixedString.prefix) { switch prefix { case .equalOnly: self = .equalOnly(.init(rawValue: prefixedString.value)) } } else { self = .default(.init(rawValue: rawValue)) } } }
// // ZDXSlideMenuView.swift // ZDXSlideMenuDemo // // Created by zzMBP on 2017/6/25. // // import Foundation import UIKit fileprivate let kMenuScrollViewHeight: CGFloat = 50.0 fileprivate let kMenuLabelWidth: CGFloat = 60.0 fileprivate let kMenuLabelLeftRightMargin: CGFloat = 10.0 fileprivate let kSelectedColorRed: CGFloat = 0.75 fileprivate let kSelectedColorGreen: CGFloat = 0.22 fileprivate let kSelectedColorBlue: CGFloat = 0.20 class ZDXSlideMenuView: UIView, UIScrollViewDelegate { fileprivate let titleArray: Array<String> fileprivate var menuLabelArray = [UILabel]() fileprivate let controllerArray: Array<UIViewController> fileprivate let menuScrollView = UIScrollView() fileprivate let seperateLine = UIView() fileprivate let contentScrollView = UIScrollView() var selectedIndex: Int = 0 { didSet(oldIndex) { if selectedIndex != oldIndex { let selectedLabel = self.menuLabelArray[selectedIndex] let lastLabel = self.menuLabelArray[oldIndex] UIView.animate(withDuration: 0.2, animations: { selectedLabel.transform = CGAffineTransform.identity.scaledBy(x: 1.2, y: 1.2) selectedLabel.textColor = UIColor(red: kSelectedColorRed, green: kSelectedColorGreen, blue: kSelectedColorBlue, alpha: 1.0) lastLabel.transform = CGAffineTransform.identity lastLabel.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0) }, completion: nil) var newOffset = selectedLabel.center.x - self.menuScrollView.frame.width / 2 if newOffset > self.menuScrollView.contentSize.width - self.menuScrollView.frame.width { newOffset = self.menuScrollView.contentSize.width - self.menuScrollView.frame.width } else if newOffset < 0 { newOffset = 0 } self.menuScrollView.setContentOffset(CGPoint(x: newOffset, y: 0) , animated: true) self.contentScrollView.contentOffset.x = self.contentScrollView.frame.width * CGFloat(selectedIndex) } } } init(frame: CGRect, titleArray: Array<String>, controllerArray: Array<UIViewController>) { assert(titleArray.count != 0, "titleArray's count cann't be 0") assert(titleArray.count == controllerArray.count, "titleArray's count must equel to controllerArray's count") self.titleArray = titleArray self.controllerArray = controllerArray super.init(frame: frame) self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { self.menuScrollView.showsHorizontalScrollIndicator = false self.menuScrollView.alwaysBounceHorizontal = true self.menuScrollView.backgroundColor = .white self.menuScrollView.delegate = self self.menuScrollView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: kMenuScrollViewHeight) self.addSubview(menuScrollView) self.setupMenulabels() self.menuScrollView.contentSize = CGSize(width: (self.menuLabelArray.last?.frame.maxX)! + kMenuLabelLeftRightMargin, height: self.menuScrollView.frame.height) self.seperateLine.frame = CGRect(x: 0, y: self.menuScrollView.frame.maxY, width: self.frame.width, height: CGFloat(0.5)) self.seperateLine.backgroundColor = .gray self.addSubview(self.seperateLine) /// self.contentScrollView.showsVerticalScrollIndicator = false self.contentScrollView.isPagingEnabled = true self.contentScrollView.backgroundColor = .white self.contentScrollView.delegate = self self.contentScrollView.frame = CGRect(x: 0, y: self.seperateLine.frame.maxY, width: self.frame.width, height: self.frame.height - self.seperateLine.frame.maxY) self.addSubview(contentScrollView) self.setupControllers() self.contentScrollView.contentSize = CGSize(width: CGFloat(self.controllerArray.count) * self.contentScrollView.frame.width, height: self.contentScrollView.frame.height) } private func setupMenulabels() { var preLabel: UILabel! for index in 0 ..< self.titleArray.count { let label = UILabel(frame: .zero) label.isUserInteractionEnabled = true label.text = self.titleArray[index] label.textColor = .black label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 16) label.textColor = .black if preLabel != nil { label.frame = CGRect(x: kMenuLabelLeftRightMargin + preLabel.frame.maxX, y: 0, width: kMenuLabelWidth, height: kMenuScrollViewHeight) } else { label.frame = CGRect(x: kMenuLabelLeftRightMargin, y: 0, width: kMenuLabelWidth, height: kMenuScrollViewHeight) } let tapgestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapedAction(_:))) label.addGestureRecognizer(tapgestureRecognizer) self.menuScrollView.addSubview(label); self.menuLabelArray.append(label) preLabel = label } } private func setupControllers() { for index in 0 ..< self.controllerArray.count { let viewcontroller = self.controllerArray[index] viewcontroller.view.frame = CGRect(x: CGFloat(index) * self.contentScrollView.frame.width, y: 0, width: self.contentScrollView.frame.width, height: self.contentScrollView.frame.height) self.contentScrollView.addSubview(viewcontroller.view) } } @objc private func tapedAction(_ recognizer: UITapGestureRecognizer) { print("View: %@", recognizer.view!) guard let selectedLabel = recognizer.view as? UILabel else { return } guard let index = self.menuLabelArray.index(of: selectedLabel) else { return } self.selectedIndex = Int(index) } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.contentScrollView { let currentLabel = self.menuLabelArray[self.selectedIndex] let nextIndex = scrollView.contentOffset.x > CGFloat(self.selectedIndex) * scrollView.frame.width ? self.selectedIndex + 1 : self.selectedIndex - 1 guard nextIndex >= 0, nextIndex < self.menuLabelArray.count else { return } let nextLabel = self.menuLabelArray[nextIndex] let rate = fabs((scrollView.contentOffset.x - CGFloat(self.selectedIndex) * scrollView.frame.width) / scrollView.frame.width) currentLabel.transform = CGAffineTransform.identity.scaledBy(x: 1.2 - 0.2 * rate, y: 1.2 - 0.2 * rate) nextLabel.transform = CGAffineTransform.identity.scaledBy(x: 1 + 0.2 * rate, y: 1 + 0.2 * rate) currentLabel.textColor = UIColor(red: kSelectedColorRed * (1 - rate), green: kSelectedColorGreen * (1 - rate), blue: kSelectedColorBlue * (1 - rate), alpha: 1.0) nextLabel.textColor = UIColor(red: kSelectedColorRed * rate, green: kSelectedColorGreen * rate, blue: kSelectedColorBlue * rate, alpha: 1.0) } print("offset: %f", scrollView.contentOffset.x) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.contentScrollView { self.selectedIndex = Int(scrollView.contentOffset.x / scrollView.frame.width) } } }
// // ViewController.swift // IntergalacticTravelSwift // // Created by Peter Hitchcock on 9/30/14. // Copyright (c) 2014 Peter Hitchcock. 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. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destinationViewController: VacationViewController = segue.destinationViewController as VacationViewController destinationViewController.title = sender?.currentTitle if segue.identifier == "RedDwarfSegue" { destinationViewController.vacationImageView.image = UIImage(named: "redStar.jpg") destinationViewController.view.backgroundColor = UIColor.redColor() } else { destinationViewController.view.backgroundColor = UIColor.blueColor() destinationViewController.vacationImageView.image = UIImage(named: "blueStar.jpg") } } }
// // ServicesProtocol.swift // SDKGithubServices // // Created by Gabriel Sousa on 10/04/21. // import Foundation enum HTTPMethod: String { case get = "GET" } struct Params { // MARK: - Public Properties var method: HTTPMethod = .get var header: [String: Any] = [:] var body: [String: Any] = [:] var query: [String: Any] = [:] var queryString: String { var queryItemList: [URLQueryItem] = [] query.forEach { item in let valueString = "\(item.value)" queryItemList.append(URLQueryItem(name: item.key, value: valueString)) } let query = "\(queryItemList)" return query } } public protocol ServicesProtocol: AnyObject { func getRepositories(language: String, page: Int, sortBy: String, success: @escaping(Data) -> Void, failure: @escaping(Error) -> Void) func getUser(username: String, success: @escaping(Data) -> Void, failure: @escaping(Error) -> Void) func request(url: URL, success: @escaping(Data) -> Void, failure: @escaping(Error) -> Void) }
import Quick import Nimble import Clappr class CoreFactoryTests: QuickSpec { override func spec() { describe("Core Factory") { context("Creation") { it("Should be able to create a core") { let options = [kSourceUrl : "testUrl"] let core = CoreFactory.create(options: options) expect(core).toNot(beNil()) expect(core.container).toNot(beNil()) } it("Should be able to create container with plugins") { let loader = Loader(externalPlugins: [FakeUICorePlugin.self]) let core = CoreFactory.create(loader) expect(core.hasPlugin(FakeUICorePlugin)).to(beTrue()) } it("Should add a core context to all plugins") { let loader = Loader(externalPlugins: [FakeUICorePlugin.self]) let core = CoreFactory.create(loader) expect(core.plugins).toNot(beEmpty()) for plugin in core.plugins { expect(plugin.core) == core } } } } } class FakeUICorePlugin: UICorePlugin { override var pluginName: String { return "FakeCorePLugin" } } }
// // RadiusCell.swift // Monithor // // Created by Alessandro Ilardi Garofalo on 19/05/17. // Copyright © 2017 Pipsqueaks. All rights reserved. // import UIKit class RadiusCell: UITableViewCell { @IBOutlet public weak var radiusTextField: UITextField! @IBOutlet public weak var noteTextField: UITextField! override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor(red: 245/255, green: 254/255, blue: 247/255, alpha: 1.0) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // Comet.swift // comets // // Created by Matt Ariane Clarke on 28/07/2017. // Copyright © 2017 MN MobileDevelopers. All rights reserved. // import UIKit import MapKit import Kingfisher class CometDetail: UIViewController, MapManagerDelegate, FlickrDelegate { @IBOutlet weak var cometName: UILabel! @IBOutlet weak var countryName: UILabel! @IBOutlet weak var countryImage: UIImageView! @IBOutlet weak var map: MKMapView! @IBOutlet weak var cometMass: UILabel! @IBOutlet weak var cometYear: UILabel! @IBOutlet weak var countryImageHeight: NSLayoutConstraint! var comet:Comet? var cometCountry:String? { didSet{ countryName.text = "It fell around \(cometCountry ?? "" )" setCountryImage() } } let mapM = MapManager() override func viewDidLoad() { super.viewDidLoad() mapM.delegate = self if comet != nil { self.populateView() } else { self.chuckNorisPopulate() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func populateView() { _ = mapM.setCometLocation() cometName.text = comet!.name cometMass.text = " \(comet!.mass)g" cometYear.text = " \(comet!.cyear)" } private func setCountryImage() { let flickr = FlickrImage() flickr.delegate = self flickr.researchRandonImage(countryToSearch: cometCountry!) } private func chuckNorisPopulate() { cometName.text = "Uh Oh!" countryName.text = "Chuck Norris kicked this comet away!" countryImage.image = UIImage(named: "chuckNorris") } private func reduceImage(){ countryImage.image = nil UIView.animate(withDuration: 0.5, animations: { [unowned self] in self.countryImageHeight.constant = 10 self.view.layoutIfNeeded() },completion: nil) } // delegates func getCometLocation() -> (lat:String, lon:String) { var latitude = "0.0" var longitude = "0.0" if let lat = comet?.lat{ latitude = lat } if let lon = comet?.lon{ longitude = lon } return (latitude, longitude) } func receiveImage(dictionary:Dictionary<String, Any>) { if let media = dictionary["media"] as? Dictionary<String, Any> { if let imageURLString = media["m"] as? String { let imageURL = URL(string: imageURLString) countryImage.kf.setImage(with: imageURL) } } } func noImageAvailable() { reduceImage() } func noInternet() { countryName.text = "It fell around the planet Earth" reduceImage() } }
// // Wrapper.swift // DiscountAsciiWerehouse // // Created by Matheus Ruschel on 8/1/16. // Copyright © 2016 Matheus Ruschel. All rights reserved. // import Foundation protocol Wrappable { init?(data:AnyObject) }
// // BlypFonts.swift // blyp // // Created by Hayden Hong on 4/19/20. // Copyright © 2020 Team Sonar. All rights reserved. // import Foundation import SwiftUI extension Font { static let Agenda = Font(UIFont(name: "agenda-medium", size: UIFont.labelFontSize)!) }
// // Adaptive.swift // Adaptive // // Created by Chris Eidhof on 21.07.17. // Copyright © 2017 objc.io. All rights reserved. // import Foundation struct T: Comparable { static func <(lhs: T, rhs: T) -> Bool { return lhs.time < rhs.time } static func ==(lhs: T, rhs: T) -> Bool { return lhs.time == rhs.time } fileprivate let time: Double } struct Time { private var backing: SortedArray<T> = SortedArray(unsorted: [T(time: 0.0)]) var initial: T { return T.init(time: 0) } func compare(l: T, r: T) -> Bool { return l.time < r.time } mutating func insert(after: T) -> T { let index = backing.index(of: after)! let newTime: T let nextIndex = backing.index(after: index) if nextIndex == backing.endIndex { newTime = T(time: after.time + 0.1) } else { let nextValue = backing[nextIndex] newTime = T(time: (after.time + nextValue.time)/2) } backing.insert(newTime) return newTime } mutating func delete(between from: T, and to: T) { assert(from.time <= to.time) backing.remove(where: { $0 > from && $0 < to}) } func contains(t: T) -> Bool { return backing.contains(t) } } struct Edge: Comparable { static func <(lhs: Edge, rhs: Edge) -> Bool { if lhs.timeSpan.start < rhs.timeSpan.start { return true } return rhs.timeSpan.start < rhs.timeSpan.start } static func ==(lhs: Edge, rhs: Edge) -> Bool { return lhs.timeSpan == rhs.timeSpan // not sure if this makes sense (we're not comparing reader) } let reader: () -> () let timeSpan: (start: T, end: T) } final class Node<A> { fileprivate var value: () -> A var write: (A) -> () var outEdges: [Edge] unowned let adaptive: Adaptive init(adaptive: Adaptive, value: @escaping () -> A, write: @escaping (A) -> (), outEdges: [Edge] = []) { self.adaptive = adaptive self.value = value self.write = write self.outEdges = outEdges } func read(_ f: @escaping (A) -> ()) { adaptive.read(node: self, f) } } typealias PriorityQueue = SortedArray<Edge> final class Adaptive { var time: Time = Time() var currentTime: T var queue: PriorityQueue init() { currentTime = time.initial queue = SortedArray(unsorted: []) } func new<A>(compare: @escaping (A, A) -> Bool, _ f: @escaping (Node<A>) -> ()) -> Node<A> { var node = Node<A>(adaptive: self, value: { fatalError() }, write: { _ in fatalError() }) func change(time: T, value: A) { if compare(value, node.value()) { return } node.value = { value } for edge in node.outEdges { queue.insert(edge) } currentTime = time } node.write = { value in node.value = { value } self.currentTime = self.time.insert(after: self.currentTime) let theTime = self.currentTime node.write = { change(time: theTime, value: $0) } } f(node) return node } fileprivate func read<A>(node: Node<A>, _ f: @escaping (A) -> ()) -> () { currentTime = time.insert(after: currentTime) let start = currentTime func run() { f(node.value()) node.outEdges.append(Edge(reader: run, timeSpan: (start: start, end: currentTime))) } run() } func propagate() { let theTime = currentTime while !queue.isEmpty { let edge = self.queue.remove(at: 0) guard time.contains(t: edge.timeSpan.start) else { continue } time.delete(between: edge.timeSpan.start, and: edge.timeSpan.end) currentTime = edge.timeSpan.start edge.reader() } currentTime = theTime } } extension Adaptive { func new<A: Equatable>(transform: @escaping (Node<A>) -> ()) -> Node<A> { return new(compare: ==, transform) } func new<A: Equatable>(value: A) -> Node<A> { return new(compare: ==) { node in node.write(value) } } } indirect enum AList<A>: Equatable { case empty case cons(A, Node<AList<A>>) static func ==(lhs: AList, rhs: AList) -> Bool { if case .empty = lhs, case .empty = rhs { return true } return false } } extension Adaptive { func fromSequence<S, A>(_ sequence: S) -> (Node<AList<A>>, Node<AList<A>>) where S: Sequence, S.Iterator.Element == A { let tail: Node<AList<A>> = new(value: .empty) var result: Node<AList<A>> = tail for item in sequence { result = new(value: .cons(item, result)) } return (result, tail) } func map<A, B>(_ list: Node<AList<A>>, _ transform: @escaping (A) -> B) -> Node<AList<B>> { func mapH(_ list: Node<AList<A>>, destination: Node<AList<B>>) { list.read { switch $0 { case .empty: destination.write(.empty) case let .cons(el, tail): destination.write(.cons(transform(el), self.new(transform: { mapH(tail, destination: $0)}))) } } } return new { mapH(list, destination: $0) } } func reduce2<A, Result>(compare: @escaping (Result, Result) -> Bool, _ list: Node<AList<A>>, _ initial: (Result), _ transform: @escaping (Result, A) -> Result) -> Node<Result> { func reduceH(_ list: Node<AList<A>>, intermediate: Result, destination: Node<Result>) { list.read { switch $0 { case .empty: destination.write(intermediate) case let .cons(el, tail): reduceH(tail, intermediate: transform(intermediate, el), destination: destination) } } } return new(compare: compare) { reduceH(list, intermediate: initial, destination: $0) } } func reduce<A, Result>(_ list: Node<AList<A>>, initial: (Result), _ transform: @escaping (Result, A) -> Result) -> Node<Result> where Result: Equatable { return reduce2(compare: ==, list, initial, transform) } func map<A,B>(node: Node<A>, f: @escaping (A) -> B) -> Node<B> where B: Equatable { return new { newNode in node.read { newNode.write(f($0)) } } } func array<Element: Equatable>(initial: [Element]) -> (Node<AdaptiveArray<Element>>, (Array<Element>.Change) -> ()) { typealias C = Array<Element>.Change typealias Changelist = Node<AList<C>> var (changes, tail): (Changelist, Changelist) = fromSequence([]) let node: Node<AdaptiveArray<Element>> = reduce(changes, initial: .initial(initial), { (acc: AdaptiveArray<Element>, change: C) in var copy: [Element] = acc.latest copy.apply(change: change) return .changed(previous: acc, change: change, latest: copy) }) return (node, { change in let newTail: Changelist = self.new(value: .empty) tail.write(.cons(change, newTail)) tail = newTail }) } // func array<Element: Equatable>(initial: [Element]) -> Node<AdaptiveArray<Element>> { // let list: AdaptiveArray<Element>.Changelist = new(value: .empty) // return new(value: AdaptiveArray(initial: initial, changes: list, tail: list)) // } // func mutate<Element>(_ array: Node<AdaptiveArray<Element>>, change: Array<Element>.Change) -> Node<AdaptiveArray<Element>> { // return self.new(transform: { destination in // array.read { a in // var new = a // let newTail: AdaptiveArray<Element>.Changelist = self.new(value: .empty) // new.tail.write(.cons(change, newTail)) // new.tail = newTail // destination.write(new) // } // }) // } // // func } indirect enum AdaptiveArray<Element>: Equatable where Element: Equatable { case initial([Element]) case changed(previous: AdaptiveArray, change: Array<Element>.Change, latest: [Element]) var latest: [Element] { switch self { case .initial(let els): return els case .changed(_, change: _, latest: let els): return els } } var changes: [Array<Element>.Change] { var result: [Array<Element>.Change] = [] var current = self while case let .changed(prev, change, _) = current { result.append(change) current = prev } return Array(result.reversed()) } static func ==(lhs: AdaptiveArray, rhs: AdaptiveArray) -> Bool { if case let .initial(x) = lhs, case let .initial(y) = rhs, x == y { return true } return false // todo } } extension Array where Element: Equatable { enum Change: Equatable { case insert(element: Element, at: Int) case remove(elementAt: Int) case append(Element) static func ==(lhs: Array<Element>.Change, rhs: Array<Element>.Change) -> Bool { switch (lhs, rhs) { case (.insert(let e1, let a1), .insert(let e2, let a2)): return e1 == e2 && a1 == a2 case (.remove(let i1), .remove(let i2)): return i1 == i2 case (.append(let e), .append(let e2)): return e == e2 default: return false } } } mutating func apply(change: Change) { switch change { case let .insert(element: e, at: i): self.insert(e, at: i) case .remove(elementAt: let i): self.remove(at: i) case .append(element: let i): self.append(i) } } } //extension AdaptiveArray: Equatable { // static func ==(lhs: AdaptiveArray<A>, rhs: AdaptiveArray<A>) -> Bool { // return false // } // //}
// // ViewController.swift // DigitalFrame // // Created by 사명구 on 2018. 4. 20.. // Copyright © 2018 Quest4I. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var toggleButton: UIButton! @IBOutlet weak var speedSlider: UISlider! @IBOutlet weak var speedLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let cuteImages = [ UIImage(named: "cat1.jpg")!, UIImage(named: "cat2.jpg")!, UIImage(named: "cat3.jpg")!, UIImage(named: "cat4.jpg")!, UIImage(named: "cat5.jpg")!, UIImage(named: "cat6.jpg")!, UIImage(named: "cat7.jpg")!, UIImage(named: "cat8.jpg")!, UIImage(named: "cat9.jpg")!, UIImage(named: "cat10.jpg")!, UIImage(named: "cat11.jpg")!, UIImage(named: "cat12.jpg")!, UIImage(named: "cat13.jpg")!, UIImage(named: "cat14.jpg")!, UIImage(named: "cat15.jpg")! ] imgView.animationImages = cuteImages imgView.animationDuration = 15 speedLabel.text = String(format: "%.2f", speedSlider.value) } @IBAction func toggleButton(_ sender: Any) { if imgView.isAnimating { imgView.stopAnimating() toggleButton.setTitle("Start", for: UIControlState.normal) } else { imgView.animationDuration = Double(speedSlider.value) imgView.startAnimating() toggleButton.setTitle("Stop", for: UIControlState.normal) } } @IBAction func speedSliderAction(_ sender: Any) { imgView.animationDuration = Double(speedSlider.value) imgView.startAnimating() toggleButton.setTitle("Stop", for: UIControlState.normal) toggleButton.setTitle("Stop", for: UIControlState.normal) speedLabel.text = String(format: "%.2f", speedSlider.value) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // SettingsView.swift // ReaderTranslator // // Created by Viktor Kushnerov on 18/1/20. // Copyright © 2020 Viktor Kushnerov. All rights reserved. // import SwiftUI struct SettingsView: View { @ObservedObject var viewStore = ViewsStore.shared var body: some View { Group { if viewStore.showSettings { VStack { SettingsView_Views() SettingsView_Voice().padding([.top, .bottom], 5) Button( action: { self.viewStore.showSettings = false }, label: { Text("Close") } ) } .padding() .background(Color(NSColor.windowBackgroundColor)) .modifier(RoundedEdge(width: 2, color: .black, cornerRadius: 10)) .shadow(radius: 10) } } } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() } }
// // XRC721Events.swift // XDC // // Created by Developer on 15/06/21. // import Foundation import BigInt public enum XRC721Events { public struct Transfer: ABIEvent { public static let name = "Transfer" public static let types: [ABIType.Type] = [ XDCAddress.self , XDCAddress.self , BigUInt.self] public static let typesIndexed = [true, true, true] public let log: XDCLog public let from: XDCAddress public let to: XDCAddress public let tokenId: BigUInt public init?(topics: [ABIDecoder.DecodedValue], data: [ABIDecoder.DecodedValue], log: XDCLog) throws { try Transfer.checkParameters(topics, data) self.log = log self.from = try topics[0].decoded() self.to = try topics[1].decoded() self.tokenId = try topics[2].decoded() } } public struct Approval: ABIEvent { public static let name = "Approval" public static let types: [ABIType.Type] = [ XDCAddress.self , XDCAddress.self , BigUInt.self] public static let typesIndexed = [true, true, true] public let log: XDCLog public let from: XDCAddress public let approved: XDCAddress public let tokenId: BigUInt public init?(topics: [ABIDecoder.DecodedValue], data: [ABIDecoder.DecodedValue], log: XDCLog) throws { try Approval.checkParameters(topics, data) self.log = log self.from = try topics[0].decoded() self.approved = try topics[1].decoded() self.tokenId = try topics[2].decoded() } } public struct ApprovalForAll: ABIEvent { public static let name = "ApprovalForAll" public static let types: [ABIType.Type] = [ XDCAddress.self , XDCAddress.self , BigUInt.self] public static let typesIndexed = [true, true, true] public let log: XDCLog public let from: XDCAddress public let `operator`: XDCAddress public let approved: Bool public init?(topics: [ABIDecoder.DecodedValue], data: [ABIDecoder.DecodedValue], log: XDCLog) throws { try ApprovalForAll.checkParameters(topics, data) self.log = log self.from = try topics[0].decoded() self.operator = try topics[1].decoded() self.approved = try topics[2].decoded() } } }
// // MoreInfoView.swift // Roboty // // Created by Julia Debecka on 11/05/2020. // Copyright © 2020 Julia Debecka. All rights reserved. // import UIKit @IBDesignable class CustomView: UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius }set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } } @IBDesignable class customIV: UIImageView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius }set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } } @IBDesignable class customButton: UIButton { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } }
// // FriendCollectionViewCell.swift // MultiSense // // Created by RaviSharma on 15/11/17. // Copyright © 2017 Ravi Sharma. All rights reserved. // import UIKit class FriendCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imgVw_friend: UIImageView! @IBOutlet weak var lbl_Name: UILabel! @IBOutlet weak var imgVw_selected: UIImageView! @IBOutlet weak var lbl_selected: UILabel! let cell_width = Double((Int(UIScreen.main.bounds.width)-46)/3) override func awakeFromNib() { super.awakeFromNib() self.layer.cornerRadius = 8.0 self.clipsToBounds = true imgVw_friend.frame = CGRect(x: 0 , y: 0, width: cell_width, height: cell_width); lbl_Name.frame = CGRect(x: 0, y:cell_width, width: cell_width, height: 40) lbl_Name.backgroundColor = .white lbl_Name.textAlignment = NSTextAlignment.center; lbl_selected.frame = CGRect(x: 0, y:0, width: cell_width, height: cell_width); imgVw_selected.frame = CGRect(x: (cell_width-60)/2, y:(cell_width-78)/2, width: 60, height:78) } }
// // WatchCityWeatherView.swift // WatchWeatherMan Extension // // Created by Jesse Tayler on 8/9/19. // Copyright © 2019 Jesse Tayler. All rights reserved. // import SwiftUI import Combine struct WatchCityWeatherView : View { @ObservedObject var city: City @State private var isPresenting: Bool = false func prefixList() -> Array<DailyWeather> { guard let weather = city.weather else { return [] } let val = weather.week.list.prefix(5) return Array(val) } func fetch() { Network.fetchWeather(for: self.city) { (weather) in } } var body: some View { ScrollView(showsIndicators: false) { VStack { HStack { city.weather?.current.icon.glyph .font(.system(size: 55, weight: .light)) .imageScale(.small) .padding(.top) Text(city.weather?.current.temperature .temperatureFormatted ?? "-º") .font(.system(size: 55, weight: .light)) } .animation(.easeInOut(duration: 1)) .padding([.top, .bottom]) VStack { Text(city.name) .font(.system(.title)) Text("\(city.formattedSummary)") .fontWeight(.light) .foregroundColor(.secondary) .fixedSize(horizontal: false, vertical: true) // this should not be needed because lineLimit should work? } .frame(height:80) Divider() VStack { ForEach(city.weather?.alerts ?? []) { alert in Text("\(alert.title)") .foregroundColor(.red) Text(self.isPresenting ? "\(alert.description)" : "") .foregroundColor(.secondary) .fixedSize(horizontal: false, vertical: true) .padding([.leading,.trailing]) } Text("\(city.longerSummary)") .fontWeight(.light) .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) // this should not be needed because lineLimit should work? Spacer() Text("Updated \(city.formattedTime)") .fontWeight(.light) .multilineTextAlignment(.center) .frame(height:60) } .padding(.top) .animation(.easeInOut(duration: 1)) } } } }
// // XORObfuscator.swift // Obfuscator // // Created by dmytro.andreikiv@philips.com on 07/09/2017. // Copyright © 2017 Dmytro Andreikiv. All rights reserved. // import Foundation public class XORObfuscator: ObfuscationAlgorithm { public init() {} public func obfuscate(source: String) throws -> String { return try transform(source) } public func unObfuscate(source: String) throws -> String { return try transform(source) } private func transform(_ source: String) throws -> String { guard let data = source.data(using: .utf8) else { throw ObfuscationError.StringConvertionError } let key = data.count let original = [UInt8](data) var modified = [UInt8](repeating: 0, count: original.count) var index = 0 for code in original { modified[index] = (code ^ UInt8(key)) index = index + 1 } let newData = Data(modified) guard let obfuscatedString = String(data: newData, encoding: .utf8) else { throw ObfuscationError.DataConvertionError } return obfuscatedString } }
// // Extension-UITextField.swift // gezhongxianzhi // // Created by Dongze Li on 9/25/16. // Copyright © 2016 Dongze Li. All rights reserved. // import UIKit extension UITextField { class func customInit (placeholder: String, font: CGFloat, style: UITextBorderStyle) -> UITextField { let tf = UITextField() tf.placeholder = placeholder tf.font = UIFont.systemFont(ofSize: font) tf.borderStyle = style return tf } }
// // DifficultyViewController.swift // math-exercise // // Created by Furkan Kaan Ugsuz on 07/12/2020. // import UIKit class DifficultyViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func easyButton(_ sender: Any) { selectedDiffuculty = Diffuculty.Easy performSegue(withIdentifier: "toCalculation", sender: nil) } @IBAction func mediumButton(_ sender: Any) { selectedDiffuculty = Diffuculty.Medium performSegue(withIdentifier: "toCalculation", sender: nil) } @IBAction func hardButton(_ sender: Any) { selectedDiffuculty = Diffuculty.Hard performSegue(withIdentifier: "toCalculation", sender: nil) } @IBAction func Expert(_ sender: Any) { selectedDiffuculty = Diffuculty.Expert performSegue(withIdentifier: "toCalculation", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toCalculation" { let destinationVC = segue.destination as! CalculationViewController destinationVC.checkSegue = "Calculation" } } }
// // ProjectsCollectionViewCell.swift // HowdyHack // // Created by Abhishek More on 9/7/19. // Copyright © 2019 Abhishek More. All rights reserved. // import UIKit class ProjectsCollectionViewCell: UICollectionViewCell { @IBOutlet var projectName: UILabel! }
// // AppleSignInWrapperTests.swift // AppleIDButtonWrapperTests // // Created by Genaro Arvizu on 05/10/20. // Copyright © 2020 Luis Genaro Arvizu Vega. All rights reserved. // import XCTest import AuthenticationServices @testable import AppleSignInWrapper class AppleSignInWrapperTests: XCTestCase { var wrapper: AppleSignInWrapper! var spy: AppleIDLoginDelegateSpy! override func setUpWithError() throws { wrapper = AppleSignInWrapper() spy = AppleIDLoginDelegateSpy() wrapper.delegate = spy } override func tearDownWithError() throws { wrapper = nil spy = nil } func testDelegate_whenFail_signIn() throws { wrapper.view = UIView() let error: NSError = NSError(domain: "Local Error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Local Error"]) wrapper.delegate?.appleSignInWrapper(didComplete: error) XCTAssert(spy.error.localizedDescription == error.localizedDescription, "Different Error") } func testDelegate_WhenUser_SignIn() throws { wrapper = AppleSignInWrapper(view: UIView()) wrapper.delegate = spy let identifier: String = UUID().uuidString let firstName: String = "Fulano" let lastName: String = "Perengano" let email: String = "your@email.com" let token: String = "Token" let model: UserInformation = UserInformation(userIdentifier: identifier, firstName: firstName, lastName: lastName, email: email, token: token) wrapper.delegate?.appleSignInWrapper(didComplete: model, nonce: nil) XCTAssert(spy.user.userIdentifier == model.userIdentifier, "Different User") } func testDelegate_WhenUserUseNonce_SignIn() throws { wrapper = AppleSignInWrapper(view: UIView()) wrapper.delegate = spy let identifier: String = UUID().uuidString let firstName: String = "Fulano" let lastName: String = "Perengano" let email: String = "your@email.com" let token: String = "Token" let model: UserInformation = UserInformation(userIdentifier: identifier, firstName: firstName, lastName: lastName, email: email, token: token) wrapper.delegate?.appleSignInWrapper(didComplete: model, nonce: "MyNonce") XCTAssert(spy.user.userIdentifier == model.userIdentifier, "Different User") } }
import XCTest @testable import EasyImagy private let WIDTH = 1024 private let HEIGHT = 512 private func getImage() -> Image<RGBA> { return Image(width: WIDTH, height: HEIGHT, pixels: (0..<(WIDTH * HEIGHT)).map { RGBA(gray: UInt8($0 % 256)) }) } class MapPerformanceTests: XCTestCase { func testNormalMap() { let image = getImage() measureBlock { let mapped: Image<RGBA> = image.map { $0 } XCTAssertEqual(0, mapped[0, 0].red) } } func testNormalInternalMap() { let image = getImage() measureBlock { let mapped: Image<RGBA> = image._map { $0 } XCTAssertEqual(0, mapped[0, 0].red) } } func testNormalMap1() { let image = getImage() measureBlock { let mapped: Image<RGBA> = image.map1 { $0 } XCTAssertEqual(0, mapped[0, 0].red) } } func testMap() { let image = getImage() measureBlock { let mapped = image.map(transform) XCTAssertEqual(0, mapped[0, 0].red) } } func testMap1() { let image = getImage() measureBlock { let mapped = image.map1(transform) XCTAssertEqual(0, mapped[0, 0].red) } } func testMap2() { let image = getImage() measureBlock { let mapped = image.map2(transform) XCTAssertEqual(0, mapped[0, 0].red) } } func testMap3() { let image = getImage() measureBlock { let mapped = image.map3(transform) XCTAssertEqual(0, mapped[0, 0].red) } } func testMap4() { let image = getImage() measureBlock { let mapped = image.map4(transform) XCTAssertEqual(0, mapped[0, 0].red) } } } private func transform(x: Int, y: Int, pixel: RGBA) -> RGBA { return RGBA(gray: UInt8((x + y) % 256)) } extension Image { private func map1<T>(transform: Pixel -> T) -> Image<T> { return Image<T>(width: width, height: height, pixels: pixels.map(transform)) } private func map1<T>(transform: (x: Int, y: Int, pixel: Pixel) -> T) -> Image<T> { let w = width return Image<T>(width: width, height: height, pixels: pixels.enumerate().map { i, pixel in transform(x: i % w, y: i / w, pixel: pixel) }) } private func map2<T>(transform: (x: Int, y: Int, pixel: Pixel) -> T) -> Image<T> { return Image<T>(width: width, height: height, pixels: pixels.enumerate().map { i, pixel in transform(x: i % self.width, y: i / self.width, pixel: pixel) }) } private func map3<T>(transform: (x: Int, y: Int, pixel: Pixel) -> T) -> Image<T> { var pixels: [T] = [] pixels.reserveCapacity(count) for y in 0..<height { for x in 0..<width { pixels.append(transform(x: x, y: y, pixel: self[x, y])) } } return Image<T>(width: width, height: height, pixels: pixels) } private func map4<T>(transform: (x: Int, y: Int, pixel: Pixel) -> T) -> Image<T> { var pixels: [T] = [] pixels.reserveCapacity(count) var generator = generate() for y in 0..<height { for x in 0..<width { pixels.append(transform(x: x, y: y, pixel: generator.next()!)) } } return Image<T>(width: width, height: height, pixels: pixels) } }
// // Address.swift // GV24 // // Created by HuyNguyen on 5/30/17. // Copyright © 2017 admin. All rights reserved. // import UIKit import SwiftyJSON import CoreLocation class Address: AppModel { var name : String? var location : CLLocationCoordinate2D? override init() { super.init() } // init(name : String, location : CLLocationCoordinate2D){ // super.init() // self.name = name // self.location = location // } override init(json : JSON){ super.init(json: json) self.name = json["name"].string ?? "" self.location = CLLocationCoordinate2D() guard let addressLocation = json["coordinates"].dictionary else {return} self.location?.latitude = (addressLocation["lat"]?.double)! self.location?.longitude = (addressLocation["lng"]?.double)! } }
// // UpdateUserPresenceAction.swift // Mitter // // Created by Rahul Chowdhury on 22/11/18. // Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved. // import Foundation import RxSwift class UpdateUserPresenceAction: BiParamAction { private let userRepository: UserRepository init(userRepository: UserRepository) { self.userRepository = userRepository } func execute(t1: String, t2: Presence) -> PrimitiveSequence<SingleTrait, Empty> { return userRepository.setUserPresence(userId: t1, presence: t2) } }
import AudioKit import AudioKitUI import AVFoundation import SoundpipeAudioKit import SwiftUI //: Allows you to create a large variety of effects, usually reverbs or environments, //: but it could also be for modeling. struct ConvolutionData { var dryWetMix: AUValue = 0.5 var stairwellDishMix: AUValue = 0.5 } class ConvolutionConductor: ObservableObject, ProcessesPlayerInput { let engine = AudioEngine() let player = AudioPlayer() let buffer: AVAudioPCMBuffer let dishConvolution: Convolution! let stairwellConvolution: Convolution! var dryWetMixer: DryWetMixer! var mixer: DryWetMixer! @Published var data = ConvolutionData() { didSet { dryWetMixer.balance = data.dryWetMix mixer.balance = data.stairwellDishMix } } init() { buffer = Cookbook.sourceBuffer player.buffer = buffer player.isLooping = true let bundle = Bundle.main guard let stairwell = bundle.url(forResource: "Impulse Responses/stairwell", withExtension: "wav"), let dish = bundle.url(forResource: "Impulse Responses/dish", withExtension: "wav") else { fatalError() } stairwellConvolution = Convolution(player, impulseResponseFileURL: stairwell, partitionLength: 8_192) dishConvolution = Convolution(player, impulseResponseFileURL: dish, partitionLength: 8_192) mixer = DryWetMixer(stairwellConvolution, dishConvolution, balance: 0.5) dryWetMixer = DryWetMixer(player, mixer, balance: 0.5) engine.output = dryWetMixer } func start() { do { try engine.start() } catch let err { Log(err) } stairwellConvolution.start() dishConvolution.start() } func stop() { engine.stop() } } struct ConvolutionView: View { @StateObject var conductor = ConvolutionConductor() var body: some View { VStack { PlayerControls(conductor: conductor) ParameterSlider(text: "Dry Audio to Convolved", parameter: self.$conductor.data.dryWetMix, range: 0...1, units: "%") ParameterSlider(text: "Stairwell to Dish", parameter: self.$conductor.data.stairwellDishMix, range: 0...1, units: "%") } .padding() .navigationBarTitle(Text("Convolution")) .onAppear { self.conductor.start() } .onDisappear { self.conductor.stop() } } }
import UIKit import ThemeKit import ComponentKit import SectionsTableView class BottomSingleSelectorViewController: ThemeActionSheetController { private let viewItems: [SelectorModule.ViewItem] private let onSelect: (Int) -> () private let tableView = SelfSizedSectionsTableView(style: .grouped) private let titleView = BottomSheetTitleView() init(image: BottomSheetTitleView.Image?, title: String, subtitle: String?, viewItems: [SelectorModule.ViewItem], onSelect: @escaping (Int) -> ()) { self.viewItems = viewItems self.onSelect = onSelect super.init() titleView.bind(image: image, title: title, subtitle: subtitle, viewController: self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(titleView) titleView.snp.makeConstraints { maker in maker.leading.top.trailing.equalToSuperview() } view.addSubview(tableView) tableView.snp.makeConstraints { maker in maker.leading.trailing.equalToSuperview() maker.top.equalTo(titleView.snp.bottom).offset(CGFloat.margin12) maker.bottom.equalTo(view.safeAreaLayoutGuide).inset(CGFloat.margin24) } tableView.backgroundColor = .clear tableView.separatorStyle = .none tableView.sectionDataSource = self tableView.buildSections() } private func onSelect(index: Int) { onSelect(index) dismiss(animated: true) } } extension BottomSingleSelectorViewController: SectionsDataSource { func buildSections() -> [SectionProtocol] { [ Section( id: "main", rows: viewItems.enumerated().map { index, viewItem in SelectorModule.row( viewItem: viewItem, tableView: tableView, selected: viewItem.selected, backgroundStyle: .bordered, index: index, isFirst: index == 0, isLast: index == viewItems.count - 1 ) { [weak self] in self?.onSelect(index: index) } } ) ] } }
// Copyright 2018, Oath Inc. // Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms. import XCTest import Nimble import struct PlayerCore.Progress @testable import VerizonVideoPartnerSDK class VideoTimeDetectorTests: XCTestCase { var detector = Detectors.VideoTime() var id = UUID() var isCompleted = false var isStreamPlaying = true var progress: Progress = 0 var playTime: TimeInterval = 0 var index = 0 var payload: Detectors.VideoTime.Payload { return Detectors.VideoTime.Payload( index: index, progress: progress, session: id, playTime: playTime) } var detectedPayload: Detectors.VideoTime.Payload? { return detector.process(sessionID: id, isCompleted: isCompleted, isStreamPlaying: isStreamPlaying, payload: payload) } override func setUp() { super.setUp() detector = Detectors.VideoTime() id = UUID() isCompleted = false isStreamPlaying = false progress = 0 playTime = 0 index = 0 } func testNoReports() { isStreamPlaying = true XCTAssertNil(detectedPayload) isStreamPlaying = false XCTAssertNil(detectedPayload) isStreamPlaying = false playTime = 10 progress = 1 XCTAssertNil(detectedPayload) } func testSessionEnd() { playTime = 10 isStreamPlaying = true progress = 1.0 XCTAssertNil(detectedPayload) isStreamPlaying = false isCompleted = true guard let payload = detectedPayload else { return XCTFail("Session end did not detected") } XCTAssertEqual(payload.playTime, 10) XCTAssertEqual(payload.index, 0) XCTAssertEqual(payload.progress, 1) } func testVideoSwitch() { isStreamPlaying = true XCTAssertNil(detectedPayload) playTime = 10 progress = 0.6 XCTAssertNil(detectedPayload) let oldSessionID = id id = UUID() index = 1 guard let payload = detectedPayload else { return XCTFail("Session end did not detected") } XCTAssertEqual(payload.playTime, 10) XCTAssertEqual(payload.index, 0) XCTAssertEqual(payload.progress, 0.6) XCTAssertEqual(payload.session, oldSessionID) } func testVideoPlaybackHasEndedPlayerWasClosed() { isStreamPlaying = true XCTAssertNil(detectedPayload) isStreamPlaying = false XCTAssertNil(detectedPayload) isCompleted = true XCTAssertNotNil(detectedPayload) } func testVideoPlaybackHasEndedVideoWasSwitched() { isStreamPlaying = true XCTAssertNil(detectedPayload) isStreamPlaying = false XCTAssertNil(detectedPayload) id = UUID() index = 1 XCTAssertNotNil(detectedPayload) } }
// // Pokemon.swift // pokedex // // Created by Jonathan Bohrer on 7/31/16. // Copyright © 2016 Jonathan Bohrer. All rights reserved. // import Foundation import Alamofire class Pokemon { private var _name: String! private var _pokedexId: Int! private var _type: String! private var _description: String! private var _defense: String! private var _height: String! private var _weight: String! private var _attack: String! private var _nextEvoTxt: String! private var _nextEvoId: String! private var _pokemonUrl: String! var name: String { return _name } var pokedexId: Int { return _pokedexId } var type: String { if _type == nil { _type = "" } return _type } var description: String { if _description == nil { _description = "" } return _description } var defense: String { if _defense == nil { _defense = "" } return _defense } var height: String { if _height == nil { _height = "" } return _height } var weight: String { if _weight == nil { _weight = "" } return _weight } var attack: String { if _attack == nil { _attack = "" } return _attack } var nextEvoTxt: String { if _nextEvoTxt == nil { _nextEvoTxt = "" } return _nextEvoTxt } var nextEvoId: String { if _nextEvoId == nil { _nextEvoId = "" } return _nextEvoId } init(name: String, id: Int) { self._name = name self._pokedexId = id self._pokemonUrl = URL_base + URL_pokemon + String(self._pokedexId) + "/" } func downloadPokemonDetails(completed: DownloadComplete) { let url = NSURL(string: _pokemonUrl)! Alamofire.request(.GET, url).responseJSON { (response: Response<AnyObject, NSError>) in let result = response.result if let dict = result.value as? Dictionary<String,AnyObject> { if let attack = dict["attack"] as? Int { self._attack = "\(attack)" } if let defense = dict["defense"] as? Int { self._defense = String(defense) } if let height = dict["height"] as? String { self._height = height } if let weight = dict["weight"] as? String { self._weight = weight } if let types = dict["types"] as? [Dictionary<String,String>] where types.count > 0 { self._type = "" for item in types { let name = item["name"]!.capitalizedString + "/" self._type = self._type + name } self._type = String(self._type.characters.dropLast()) } if let descArray = dict["descriptions"] as? [Dictionary<String,String>] where descArray.count > 0 { if let url = descArray[0]["resource_uri"] { let nsurl = NSURL(string: "\(URL_base)\(url)") Alamofire.request(.GET, nsurl!).responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) in let desresult = response.result if let desdict = desresult.value as? Dictionary<String,AnyObject> { if let desc = desdict["description"] as? String { self._description = desc } } completed() }) } } else { self._description = "No description" } if let evolutions = dict["evolutions"] as? [Dictionary<String,AnyObject>] where evolutions.count > 0 { if let to = evolutions[0]["to"] as? String { // Can't support mega pokemon right now but api still has mega data if !to.lowercaseString.containsString("mega") { if let evourl = evolutions[0]["resource_uri"] as? String { let evoId = evourl.stringByReplacingOccurrencesOfString(URL_pokemon, withString: "") self._nextEvoId = String(evoId.characters.dropLast()) self._nextEvoTxt = to if let lvl = evolutions[0]["level"] as? Int { self._nextEvoTxt = "\(to) Lvl \(lvl)" } } } } } } } } }
// // Storyboard.swift // Storyboard // // Created by Rogy on 6/22/17. // Copyright © 2017 RogyMD. All rights reserved. // import UIKit /// Represents a type that should load an `UIStoryboard` instance. public protocol StoryboardType { /// The bundle containing the storyboard file and its related resources. If you specify nil, this method looks in the main bundle of the current application. var bundle: Bundle? { get } /// An **new** `UIStoryboard` instance. var storyboard: UIStoryboard { get } } public extension StoryboardType { var bundle: Bundle? { return nil } var initialViewController: UIViewController? { return storyboard.instantiateInitialViewController() } func viewController(withIdentifier sceneIdentifier: String) -> UIViewController { return storyboard.instantiateViewController(withIdentifier: sceneIdentifier) } } public extension StoryboardType where Self: RawRepresentable, Self.RawValue == String { var storyboard: UIStoryboard { return UIStoryboard(name: rawValue, bundle: bundle) } } public extension StoryboardType { /// An **new** instance of `Scene` type. func scene<Scene: StoryboardSceneType>() -> Scene where Scene.Storyboard == Self { guard let sceneIdentifier = Scene.sceneIdentifier(in: self) else { fatalError("Undefined scene identifier for storyboard: \(String(describing: self))") } return viewController(withIdentifier: sceneIdentifier) as! Scene } }
// // PlacesInteractorTests.swift // MusicBrainzTests // // Created by BOGU$ on 21/05/2019. // Copyright © 2019 lyzkov. All rights reserved. // import XCTest @testable import MusicBrainz final class PlacesInteractorTests: XCTestCase { private var locationDataManagerSpy: PlacesLocationDataManagerSpy! private var apiDataManagerSpy: PlacesAPIDataManagerSpy! private var presenter: PlacesPresenterSpy! private var interactor: PlacesInteractor! override func setUp() { super.setUp() locationDataManagerSpy = PlacesLocationDataManagerSpy() apiDataManagerSpy = PlacesAPIDataManagerSpy() presenter = PlacesPresenterSpy() interactor = PlacesInteractor(apiDataManager: apiDataManagerSpy, locationDataManager: locationDataManagerSpy) interactor.presenter = presenter } func testLoadRegion_whenFetchingLocationIsSuccessful_thenPresentsRegion() { let region: Region = .fake() locationDataManagerSpy.successRegion = region interactor.loadRegion() XCTAssertEqual(region.latitude, presenter.didPresentRegion?.latitude) XCTAssertEqual(region.longitude, presenter.didPresentRegion?.longitude) XCTAssertEqual(region.delta, presenter.didPresentRegion?.delta) XCTAssertNil(locationDataManagerSpy.failureError) } func testLoadRegion_whenFetchingLocationFailed_thenPresentsError() { locationDataManagerSpy.failureError = FakeError.unknown interactor.loadRegion() guard case .some(FakeError.unknown) = presenter.didShowError else { XCTFail("Expected unknown error") return } XCTAssertNil(presenter.didPresentRegion) } func testLoadPlaces_whenFetchingPlacesIsSuccessful_thenPresentsPlaces() { let places: [Place] = [.fake(), .fake()] apiDataManagerSpy.resultFetchAll = .success(places) let since = shortFormatter.date(from: "1990")! interactor.loadPlaces(region: Region.fake(), since: since) let expectedAnnotations = places.map { PlaceAnnotation(from: $0, lifespanSince: since) } guard let resultingAnnotations = presenter.didPresentPlaces else { XCTFail() return } for (expected, result) in zip(expectedAnnotations, resultingAnnotations) { XCTAssertEqual(expected.longitude, result.longitude) XCTAssertEqual(expected.title, result.title) XCTAssertEqual(expected.subtitle, result.subtitle) XCTAssertEqual(expected.lifespan, result.lifespan) } } func testLoadPlaces_whenFetchingPlacesFailed_thenPresentsError() { apiDataManagerSpy.resultFetchAll = .failure(FakeError.unknown) let since = shortFormatter.date(from: "1990")! interactor.loadPlaces(region: Region.fake(), since: since) guard case .some(FakeError.unknown) = presenter.didShowError else { XCTFail("Expected unknown error") return } XCTAssertNil(presenter.didPresentPlaces) } }
protocol VersionControl { func isBadVersion(_ n: Int) -> Bool } class Solution : VersionControl { func isBadVersion(_ n: Int) -> Bool { return false } func firstBadVersion(_ n: Int) -> Int { var (s, e) = (1, n) var mid: Int while s < e { mid = s + (e - s) / 2 if isBadVersion(mid) { e = mid } else { s = mid + 1 } } return s } }
import UIKit import SnapKit import MarkdownView import WebKit protocol ReadMeTableViewCellDelegate: class { func didFinishLoad(_ readMeTableViewCell: ReadMeTableViewCell) func touchedLink(_ readMeTableViewCell: ReadMeTableViewCell, link: URL) } final class ReadMeTableViewCell: UITableViewCell, Reusable { weak var delegate: ReadMeTableViewCellDelegate? var readme: ReadMe? = nil { didSet { guard let readme = self.readme, let markdown = try? String(contentsOf: readme.downloadUrl, encoding: .utf8) else { return } markdownView.load(markdown: markdown) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError() } private lazy var markdownView: MarkdownView = { let markdownView = MarkdownView() markdownView.isScrollEnabled = false markdownView.onRendered = { [weak self] height in guard let self = self else { return } self.markdownView.snp.makeConstraints { $0.height.equalTo(height + 48).priority(.medium) } self.delegate?.didFinishLoad(self) } markdownView.onTouchLink = { [weak self] request in guard let self = self, let url = request.url, url.scheme == "https" || url.scheme == "http" else { return false } self.delegate?.touchedLink(self, link: url) return false } return markdownView }() private func setupSubviews() { contentView.addSubview(markdownView) markdownView.snp.makeConstraints { $0.edges.equalToSuperview() } } }
// // NightscoutProfile.swift // NightscoutUploadKit // import Foundation public class ProfileSet { public struct ScheduleItem { let offset: TimeInterval let value: Double public init(offset: TimeInterval, value: Double) { self.offset = offset self.value = value } public var dictionaryRepresentation: [String: Any] { var rep = [String: Any]() let hours = floor(offset.hours) let minutes = floor((offset - TimeInterval(hours: hours)).minutes) rep["time"] = String(format:"%02i:%02i", Int(hours), Int(minutes)) rep["value"] = value rep["timeAsSeconds"] = Int(offset) return rep } } public struct Profile { let timezone : TimeZone let dia : TimeInterval let sensitivity : [ScheduleItem] let carbratio : [ScheduleItem] let basal : [ScheduleItem] let targetLow : [ScheduleItem] let targetHigh : [ScheduleItem] let units: String public init(timezone: TimeZone, dia: TimeInterval, sensitivity: [ScheduleItem], carbratio: [ScheduleItem], basal: [ScheduleItem], targetLow: [ScheduleItem], targetHigh: [ScheduleItem], units: String) { self.timezone = timezone self.dia = dia self.sensitivity = sensitivity self.carbratio = carbratio self.basal = basal self.targetLow = targetLow self.targetHigh = targetHigh self.units = units } public var dictionaryRepresentation: [String: Any] { return [ "dia": dia.hours, "carbs_hr": "0", "delay": "0", "timezone": timezone.identifier, "target_low": targetLow.map { $0.dictionaryRepresentation }, "target_high": targetHigh.map { $0.dictionaryRepresentation }, "sens": sensitivity.map { $0.dictionaryRepresentation }, "basal": basal.map { $0.dictionaryRepresentation }, "carbratio": carbratio.map { $0.dictionaryRepresentation }, ] } } let startDate : Date let units: String let enteredBy: String let defaultProfile: String let store: [String: Profile] public init(startDate: Date, units: String, enteredBy: String, defaultProfile: String, store: [String: Profile]) { self.startDate = startDate self.units = units self.enteredBy = enteredBy self.defaultProfile = defaultProfile self.store = store } public var dictionaryRepresentation: [String: Any] { let dateFormatter = DateFormatter.ISO8601DateFormatter() let mills = String(format: "%.0f", startDate.timeIntervalSince1970.milliseconds) let dictProfiles = Dictionary(uniqueKeysWithValues: store.map { key, value in (key, value.dictionaryRepresentation) }) let rval : [String: Any] = [ "defaultProfile": defaultProfile, "startDate": dateFormatter.string(from: startDate), "mills": mills, "units": units, "enteredBy": enteredBy, "store": dictProfiles ] return rval } }
// // TimersTableViewPresenter.swift // 3Dlook // // Created by Тимур Кошевой on 25.08.2020. // Copyright © 2020 homeAssignment. All rights reserved. // import UIKit typealias TableViewDelegateAndDataSource = UITableViewDelegate & UITableViewDataSource class TimersTableViewPresenter: NSObject { private var timers: [TimerModel]? public func setDataSource(_ dataSource: [TimerModel]?) { guard let timers = dataSource else { return } self.timers = timers } } extension TimersTableViewPresenter: UITableViewDelegate { func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } extension TimersTableViewPresenter: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let timers = timers else { return 0 } return timers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "timerCell", for: indexPath) as! TimerTableViewCell guard let timers = timers else { return cell } cell.setupCellWithTimer(timers[indexPath.row]) return cell } }
// // Entity+CoreDataProperties.swift // testNotification // // Created by Giuseppe De Simone on 21/08/2019. // Copyright © 2019 Giuseppe De Simone. All rights reserved. // // import Foundation import CoreData extension Entity { @nonobjc public class func fetchRequest() -> NSFetchRequest<Entity> { return NSFetchRequest<Entity>(entityName: "Entity") } @NSManaged public var test: String? }
// // WordListViewController.swift // FlashCards // // Created by Pedro Sousa on 20/10/20. // import UIKit import CoreData class TermListViewController: UIViewController { private let termList = TermList() private let coreDataManager = CoreDataManager.shared private var flashCards: [NSManagedObject] = [] override func loadView() { super.loadView() self.view = self.termList } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.loadWordsDataSource() } override func viewDidLoad() { super.viewDidLoad() setupNavBar() registerTableViewCell() self.termList.tableView.dataSource = self self.termList.tableView.delegate = self } private func setupNavBar() { self.title = "My Terms" } private func registerTableViewCell() { self.termList.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "termCell") } private func loadWordsDataSource() { self.flashCards = self.coreDataManager.readAllFlashCards() self.termList.tableView.reloadData() } } extension TermListViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return flashCards.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let flashCard = flashCards[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "termCell", for: indexPath) cell.textLabel?.text = flashCard.value(forKey: "term") as? String cell.accessoryType = .disclosureIndicator return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let card = flashCards[indexPath.row] self.coreDataManager.deleteFlashCard(card) self.flashCards.remove(at: indexPath.row) self.termList.tableView.deleteRows(at: [indexPath], with: .fade) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let controller = EditiTermViewController() controller.card = flashCards[indexPath.row] self.navigationController?.pushViewController(controller, animated: true) } }
// // CameraResultViewController.swift // SmartNote // // Created by 행복한 개발자 on 04/07/2019. // Copyright © 2019 Alex Lee. All rights reserved. // import UIKit import NVActivityIndicatorView class CameraResultViewController: UIViewController, NVActivityIndicatorViewable { let cameraResultImageView = UIImageView() let retakeBtn = UIButton() let okBtn = UIButton() let cancelBtn = UIButton() var capturedImage = UIImage() let notiCenter = NotificationCenter.default override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() print("--------------------------[CameraResultVC view did load]--------------------------") setAutoLayout() configureViewsOptions() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() print("--------------------------[CameraResultViewController]--------------------------") print("SafeInset: ", view.safeAreaInsets) print(self.presentingViewController) guard let priorVC = self.presentingViewController as? CameraViewController else { print("변환 실패"); return } // priorVC.dismiss(animated: false, completion: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } private func setAutoLayout() { let safeGuide = view.safeAreaLayoutGuide view.addSubview(cameraResultImageView) cameraResultImageView.translatesAutoresizingMaskIntoConstraints = false cameraResultImageView.topAnchor.constraint(equalTo: safeGuide.topAnchor, constant: 40).isActive = true cameraResultImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true cameraResultImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true cameraResultImageView.heightAnchor.constraint(equalTo: cameraResultImageView.widthAnchor, multiplier: 1.25).isActive = true let bottomMargin: CGFloat = -40 view.addSubview(cancelBtn) cancelBtn.translatesAutoresizingMaskIntoConstraints = false cancelBtn.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true cancelBtn.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor, constant: bottomMargin).isActive = true cancelBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true cancelBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true view.addSubview(okBtn) okBtn.translatesAutoresizingMaskIntoConstraints = false okBtn.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true okBtn.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor, constant: bottomMargin).isActive = true okBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true okBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true view.addSubview(retakeBtn) retakeBtn.translatesAutoresizingMaskIntoConstraints = false retakeBtn.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true retakeBtn.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor, constant: bottomMargin).isActive = true retakeBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true retakeBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true } private func configureViewsOptions() { view.backgroundColor = .black cameraResultImageView.contentMode = .scaleAspectFit cameraResultImageView.image = capturedImage let buttonTitleSize: CGFloat = 18 let buttonWeight: UIFont.Weight = .light cancelBtn.setTitle("Cancel", for: .normal) cancelBtn.setTitleColor(.white, for: .normal) cancelBtn.titleLabel?.font = .systemFont(ofSize: buttonTitleSize, weight: buttonWeight) cancelBtn.addTarget(self, action: #selector(bottomBtnDidTap(_:)), for: .touchUpInside) okBtn.setTitle("OK", for: .normal) okBtn.setTitleColor(.white, for: .normal) okBtn.titleLabel?.font = .systemFont(ofSize: buttonTitleSize+4, weight: .regular) okBtn.addTarget(self, action: #selector(bottomBtnDidTap(_:)), for: .touchUpInside) retakeBtn.setTitle("Retake", for: .normal) retakeBtn.setTitleColor(.white, for: .normal) retakeBtn.titleLabel?.font = .systemFont(ofSize: buttonTitleSize, weight: buttonWeight) retakeBtn.addTarget(self, action: #selector(bottomBtnDidTap(_:)), for: .touchUpInside) } @objc func bottomBtnDidTap(_ sender: UIButton) { switch sender { case cancelBtn: print("Cancel") guard let cameraVC = self.presentingViewController as? CameraViewController , let naviVC = cameraVC.presentingViewController as? UINavigationController else { print("변환 실패") return } naviVC.navigationBar.barStyle = .default dismiss(animated: true) cameraVC.modalPresentationStyle = .overCurrentContext cameraVC.view.alpha = 0 cameraVC.dismiss(animated: false, completion: nil) case okBtn: print("OK") guard let cameraVC = self.presentingViewController as? CameraViewController , let naviVC = cameraVC.presentingViewController as? UINavigationController , let memoVC = naviVC.viewControllers.first as? MemoViewController else { print("OK버튼 변환 실패") return } guard let image = capturedImage.resize(to: view.frame.size) else { print("‼️ caputredImage resize error ") return } let activityData = ActivityData(size: CGSize(width: 50, height: 50), message: "Converting", messageFont: .systemFont(ofSize: 14), messageSpacing: 10, type: .ballScaleMultiple, color: .white) NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData) GoogleCloudOCR().detect(from: image) { ocrResult in guard let ocrResult = ocrResult else { print("fixedImage ocrResult convert error!"); return } memoVC.memoView.textView.text = ocrResult.annotations.first?.text self.notiCenter.post(name: .memoTextViewEditingDidEnd, object: nil) print("텍스트 추출 결과 / ocrResult: ", ocrResult) NVActivityIndicatorPresenter.sharedInstance.stopAnimating() self.dismiss(animated: true) cameraVC.modalPresentationStyle = .overCurrentContext cameraVC.view.alpha = 0 cameraVC.dismiss(animated: false, completion: nil) naviVC.navigationBar.barStyle = .default } case retakeBtn: dismiss(animated: true, completion: nil) default: break } } }
// // TopupView.swift // QuanZai // // Created by i-chou on 6/30/16. // Copyright © 2016 i-chou. All rights reserved. // protocol TopupViewProtocol { func openAlipay() func openWechatPay() func selectedButton(radioButton : DLRadioButton) } //import DLRadioButton @IBDesignable class TopupView: UIView { @IBOutlet weak var headerTitle: Label! @IBOutlet weak var otherMoneyTitle: UILabel! @IBOutlet weak var otherMoneyTxt: UITextField! @IBOutlet weak var remarkLabel: UILabel! @IBOutlet weak var alipayBtn: Button! @IBOutlet weak var wechatPayBtn: Button! var selectedRadioBtn: DLRadioButton? var selected_money : String? var delegate : TopupViewProtocol? override func awakeFromNib() { super.awakeFromNib() self.layout() } func layout() { headerTitle.snp_makeConstraints { (make) in make.top.equalTo(0) make.left.equalTo(0) make.right.equalTo(self.snp_right) make.height.equalTo(40) } let frame = CGRectMake(20, CGRectGetMaxY(headerTitle.frame)+20, 100, 40) let firstRadioButton = createRadioButton(frame, title: "100元") firstRadioButton.selected = true firstRadioButton.iconSquare = true self.selectedRadioBtn = firstRadioButton var otherbuttons : [DLRadioButton] = [] let titles = ["200元", "500元", "1000元"] var i = 0 var bottom : CGFloat = 0 for title in titles { let frame = CGRectMake(20, CGRectGetMaxY(firstRadioButton.frame) + 40 * CGFloat(i), 100, 40) let radioButton = createRadioButton(frame, title: title) radioButton.iconSquare = true otherbuttons.append(radioButton) i += 1 bottom = CGRectGetMaxY(radioButton.frame) } firstRadioButton.otherButtons = otherbuttons otherMoneyTitle.snp_makeConstraints { (make) in make.top.equalTo(bottom+20) make.left.equalTo(20) make.width.equalTo(100) make.height.equalTo(30) } otherMoneyTxt.snp_makeConstraints { (make) in make.top.equalTo(otherMoneyTitle.snp_bottom).offset(10) make.left.equalTo(20) make.width.equalTo(150) make.height.equalTo(30) } otherMoneyTxt.delegate = self remarkLabel.snp_makeConstraints { (make) in make.top.equalTo(otherMoneyTxt.snp_top) make.left.equalTo(otherMoneyTxt.snp_right).offset(10) make.right.equalTo(self.snp_right) make.height.equalTo(otherMoneyTxt.snp_height) } alipayBtn.snp_makeConstraints { (make) in make.top.equalTo(otherMoneyTxt.snp_bottom).offset(20) make.left.equalTo(20) make.width.equalTo((k_SCREEN_W-70)/2) make.height.equalTo(30) } wechatPayBtn.snp_makeConstraints { (make) in make.top.equalTo(alipayBtn.snp_top) make.width.equalTo(alipayBtn.snp_width) make.right.equalTo(self.snp_right).offset(-20) make.height.equalTo(30) } } @IBAction func openAlipay(sender: AnyObject) { self.delegate?.openAlipay() } @IBAction func openWechatPay(sender: AnyObject) { self.delegate?.openWechatPay() } private func createRadioButton(frame : CGRect, title : String) -> DLRadioButton { let radioButton = DLRadioButton(frame: frame) radioButton.titleLabel!.font = HS_FONT(14) radioButton.setTitle(title, forState: UIControlState.Normal) radioButton.setTitleColor(UIColorFromRGB(0x727272), forState: UIControlState.Normal) radioButton.iconColor = UIColorFromRGB(0x00928b) radioButton.indicatorColor = UIColorFromRGB(0x00928b) radioButton.marginWidth = 10 radioButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left; radioButton.addTarget(self, action: #selector(logSelectedButton), forControlEvents: UIControlEvents.TouchUpInside); self.addSubview(radioButton); return radioButton; } @objc @IBAction private func logSelectedButton(radioButton : DLRadioButton) { if (radioButton.multipleSelectionEnabled) { for button in radioButton.selectedButtons() { print(String(format: "%@ is selected.\n", button.titleLabel!.text!)); } } else { print(String(format: "%@ is selected.\n", radioButton.selectedButton()!.titleLabel!.text!)); self.selectedRadioBtn = radioButton self.otherMoneyTxt.endEditing(true) self.otherMoneyTxt.text = "" self.delegate?.selectedButton(radioButton) } } } // MARK: - UITextFieldDelegate extension TopupView : UITextFieldDelegate { func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string.characters.count > 0 { self.selectedRadioBtn?.selected = false } return true } }
// // Constant.swift // RoambeeDemo // // Created by Nidhi Joshi on 26/09/2021. // import Foundation class Constant { static var deviceCellIdentifier = "DeviceCell" static var dataCellIdentifier = "DataCell" static var pinTitle = "Location" }
// // MongoPersistanceService.swift // mongodb-mobile-sample // // Created by Ilya Usikov on 11/28/18. // Copyright © 2018 Ilya Usikov. All rights reserved. // import Foundation import StitchCore import StitchLocalMongoDBService import MongoSwift protocol MongoStorageProtocol: StorageProtocol { } public class MongoStorageProvider: MongoStorageProtocol { var type: StorageType? var adapter: MongoAdapterProtocol var database: MongoDatabase? init(adapter: MongoAdapterProtocol) { self.type = .MongoDB self.adapter = adapter do { self.database = try adapter.localMongoClient?.db("mongo_db") } catch { print("") } } func getCount() -> Int { var itemsCount = -1 do { let collection = try self.database?.collection("my_collection") itemsCount = try collection?.count() ?? -1; } catch { } return itemsCount } } // let doc: Document = [ // "me": "cool", // "numbers": 42 // ] // Point to the target collection and insert a document // let myLocalCollection = try localMongoClient.db("my_db").collection("my_collection") // let result = try myLocalCollection.insertOne(doc) // print(result) // let itemsCount = try myLocalCollection.count(); // print(itemsCount) // // let query: Document = ["numbers": 42] // let documents = try myLocalCollection.find(query) // for d in documents { // print(d) // }
import Foundation import UIKit extension UILabel { func setBodyFont() { self.font = Font.preferredFontForTextStyle(UIFontTextStyleBody) self.font = Font.body(self.font.pointSize + 2) } func setPickerFontLarge() { self.font = Font.preferredFontForTextStyle(UIFontTextStyleBody) self.font = Font.body(self.font.pointSize + 7) } func setHeadingFontSmall() { self.font = Font.preferredFontForTextStyle(UIFontTextStyleBody) self.font = Font.heading(self.font.pointSize + 4) } func setHeadingFontLarge() { self.font = Font.preferredFontForTextStyle(UIFontTextStyleBody) self.font = UIFont(name: "AlternateGothicLT-No2", size: self.font.pointSize + 10) } }
// // RoundedCornerView.swift // DeliriumOver // // Created by mate.redecsi on 2020. 10. 08.. // Copyright © 2020. rmatesz. All rights reserved. // import Foundation import UIKit class RoundedCornerView: UIView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } }
// // ExternalSceneDelegate.swift // Kabetsu // // Created by Hai Long Danny Thi on 2020/02/25. // Copyright © 2020 Hai Long Danny Thi. All rights reserved. // import UIKit class ExternalSceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(frame: windowScene.coordinateSpace.bounds) window?.windowScene = windowScene window?.rootViewController = configureExternalDisplayManager() window?.isHidden = false setUserInterfaceStyle() } private func configureExternalDisplayManager() -> UINavigationController { let navCon = UINavigationController(rootViewController: ExternalDisplayManager.shared) navCon.navigationBar.isHidden = true return navCon } private func setUserInterfaceStyle() { let settings = Settings.shared settings.updateUserInterfaceStyle(settings.interfaceStyle) } }
// // CTFScaleFormResult.swift // Impulse // // Created by James Kizer on 2/25/17. // Copyright © 2017 James Kizer. All rights reserved. // import UIKit import ResearchSuiteResultsProcessor import ResearchKit class CTFScaleFormResult: RSRPIntermediateResult, RSRPFrontEndTransformer { static public let kType = "CTFScaleFormResult" private static let supportedTypes = [ kType ] public static func supportsType(type: String) -> Bool { return supportedTypes.contains(type) } public static func transform( taskIdentifier: String, taskRunUUID: UUID, parameters: [String: AnyObject] ) -> RSRPIntermediateResult? { guard let schemaID = parameters["schemaID"] as? String, let schemaVersion = parameters["schemaVersion"] as? Int else { return nil } let stepResults: [ORKStepResult] = parameters.flatMap { (pair) -> ORKStepResult? in return pair.value as? ORKStepResult } let childResults = stepResults.flatMap({ (stepResult) -> [ORKScaleQuestionResult]? in return stepResult.results as? [ORKScaleQuestionResult] }).joined() guard childResults.count > 0 else { return nil } let identifierSuffix = parameters["identifierSuffix"] as? String let resultMap:[String: Int] = { var map: [String: Int] = [:] childResults.forEach { (result) in let identifier = result.identifier + (identifierSuffix ?? "") if let scaleAnswer = result.scaleAnswer { map[identifier] = scaleAnswer.intValue } } return map }() return CTFScaleFormResult( uuid: UUID(), taskIdentifier: taskIdentifier, taskRunUUID: taskRunUUID, startDate: stepResults.first?.startDate, endDate: stepResults.last?.endDate, schemaID: schemaID, schemaVersion: schemaVersion, resultMap: resultMap ) } let schemaID: String let version: Int let resultMap:[String: Int] public init( uuid: UUID, taskIdentifier: String, taskRunUUID: UUID, startDate: Date?, endDate: Date?, schemaID: String, schemaVersion: Int, resultMap: [String: Int]) { self.schemaID = schemaID self.version = schemaVersion self.resultMap = resultMap super.init( type: DemographicsResult.kType, uuid: uuid, taskIdentifier: taskIdentifier, taskRunUUID: taskRunUUID ) } }
// // QuestionClass.swift // PET // // Created by liuyal on 10/27/17. // Copyright © 2017 TEAMX. All rights reserved. // import Foundation // Enum for QuestionClass -> emotion enum emotionID{ case happy case sad case angry case scared } // Enum for QuestionClass -> questionState enum state{ case initial // 0 case correct // 1 case incorrect // 2 case skipped // 3 } // Class: QuestionClass // Members: // 1. userID: String -> linking to user DB to store progress // 2. ArraySize: int -> Size of progress array detected should = ARRAY_SIZE // 3. percComp: Double -> array of doubles repressenting completion rate of each level // 4. questionArray: QuestionClass() -> Array of question objects // Description: class QuestionClass { // Function: Defult Constructor create defult QuestionClass object // Pre-Req: N/A // Input: N/A // Ouput: N/A public init(){ self.questionID = 0 self.levelID = 0 self.emotion = .happy self.errCnt = 0 self.questionState = .initial self.imageFileRef = "" } // Function: Pass in value to create object QuestionClass // Pre-Req: N/A // Input: // 1. levelID: Int -> User UID // 2. questionID: Int -> emotion enum that matches question // 3. emotion: emotionID -> question state enum that matches question // 4. errCnt: Int -> Counter or error selection // 5. questionState: state -> state of question // 6. imageFileRef: String -> reference to image file *** Currently not used // Ouput: N/A init(levelID: Int, questionID: Int, emotion: emotionID, errCnt: Int, questionState: state, imageFileRef: String){ if levelID < 0{ self.levelID = 0 } else if levelID >= TIER_SIZE { self.levelID = TIER_SIZE } else { self.levelID = levelID} if questionID < 0{ self.questionID = 0 } else if questionID >= Q_PER_TIER { self.questionID = Q_PER_TIER } else { self.questionID = questionID } self.emotion = emotion if errCnt < 0{ self.errCnt = 0 } else { self.errCnt = errCnt} self.questionState = questionState self.imageFileRef = imageFileRef } // ----------------MEMBER VARIABLE--------------- var levelID: Int var questionID: Int var emotion: emotionID var errCnt: Int var questionState: state var imageFileRef: String }
// // ClaimDetailSectionGenerator.swift // Homework2 // // Created by Henry mo on 11/21/20. // Copyright © 2020 Henry mo. All rights reserved. // import UIKit class ClaimDetailSectionGenerator { func generate() -> UIStackView { let stackView = UIStackView() stackView.axis = .vertical stackView.distribution = .fill stackView.spacing = 20 let stackView1 = UIStackView() stackView1.distribution = .fill let title = UILabel() title.text = "Please Enter Claim Information" title.textAlignment = .center title.font = UIFont(name:"Georgia-Bold", size: 18) stackView1.addArrangedSubview(title) stackView.addArrangedSubview(stackView1) var vGenerator = FieldValueViewGenerator(n: "Claim Title") var sView = vGenerator.generate() stackView.addArrangedSubview(sView) vGenerator = FieldValueViewGenerator(n: "Date") sView = vGenerator.generate() stackView.addArrangedSubview(sView) /* let bStackView = UIStackView() let button = UIButton() button.setTitle("Add", for: .normal) button.setTitleColor(UIColor.black, for: .normal) button.layer.borderColor = UIColor.cyan.cgColor button.layer.borderWidth = 2 bStackView.addArrangedSubview(button) stackView.addArrangedSubview(bStackView) */ stackView1.translatesAutoresizingMaskIntoConstraints = false let sv1Cnt1 = stackView1.topAnchor.constraint(equalTo: stackView.safeAreaLayoutGuide.topAnchor) let sv1Cnt2 = stackView1.leadingAnchor.constraint(equalTo: stackView.safeAreaLayoutGuide.leadingAnchor) let sv1Cnt3 = stackView1.trailingAnchor.constraint(equalTo: stackView.safeAreaLayoutGuide.trailingAnchor) sv1Cnt1.isActive = true sv1Cnt2.isActive = true sv1Cnt3.isActive = true /* bStackView.translatesAutoresizingMaskIntoConstraints = false let bCnt1 = bStackView.trailingAnchor.constraint(equalTo: stackView.safeAreaLayoutGuide.trailingAnchor) bCnt1.isActive = true */ return stackView } }
import Foundation import XCTest @testable import XcodeProj final class PBXCopyFilesBuildPhaseTests: XCTestCase { func test_subFolder_Path_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.absolutePath.rawValue, 0) } func test_subFolder_producsDirectory_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.productsDirectory.rawValue, 16) } func test_subFolder_wrapper_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.wrapper.rawValue, 1) } func test_subFolder_executables_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.executables.rawValue, 6) } func test_subFolder_resources_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.resources.rawValue, 7) } func test_subFolder_javaResources_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.javaResources.rawValue, 15) } func test_subFolder_frameworks_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.frameworks.rawValue, 10) } func test_subFolder_sharedFrameworks_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.sharedFrameworks.rawValue, 11) } func test_subFolder_sharedSupport_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.sharedSupport.rawValue, 12) } func test_subFolder_plugins_hasTheCorrectValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.SubFolder.plugins.rawValue, 13) } func test_init_fails_whenDstPathIsMissing() { var dictionary = testDictionary() dictionary.removeValue(forKey: "dstPath") let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let decoder = XcodeprojJSONDecoder() do { let phase = try decoder.decode(PBXCopyFilesBuildPhase.self, from: data) XCTAssertNil(phase.dstPath, "Expected dstPath to be nil but it's present") } catch {} } func test_init_fails_whenBuildActionMaskIsMissing() { var dictionary = testDictionary() dictionary.removeValue(forKey: "buildActionMask") let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let decoder = XcodeprojJSONDecoder() do { let phase = try decoder.decode(PBXCopyFilesBuildPhase.self, from: data) XCTAssertEqual(phase.buildActionMask, PBXBuildPhase.defaultBuildActionMask, "Expected buildActionMask to be equal to \(PBXBuildPhase.defaultBuildActionMask) but it's \(phase.buildActionMask)") } catch {} } func test_init_fails_whenDstSubfolderSpecIsMissing() { var dictionary = testDictionary() dictionary.removeValue(forKey: "dstSubfolderSpec") let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let decoder = XcodeprojJSONDecoder() do { let phase = try decoder.decode(PBXCopyFilesBuildPhase.self, from: data) XCTAssertNil(phase.dstSubfolderSpec, "Expected dstSubfolderSpec to be nil but it's present") } catch {} } func test_init_fails_whenFilesIsMissing() { var dictionary = testDictionary() dictionary.removeValue(forKey: "files") let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let decoder = XcodeprojJSONDecoder() do { let phase = try decoder.decode(PBXCopyFilesBuildPhase.self, from: data) XCTAssertNil(phase.files, "Expected files to be nil but it's present") } catch {} } func test_init_fails_whenRunOnlyForDeploymentPostprocessingIsMissing() { var dictionary = testDictionary() dictionary.removeValue(forKey: "runOnlyForDeploymentPostprocessing") let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let decoder = XcodeprojJSONDecoder() do { let phase = try decoder.decode(PBXCopyFilesBuildPhase.self, from: data) XCTAssertFalse(phase.runOnlyForDeploymentPostprocessing, "Expected runOnlyForDeploymentPostprocessing to default to false") } catch {} } func test_isa_returnsTheRightValue() { XCTAssertEqual(PBXCopyFilesBuildPhase.isa, "PBXCopyFilesBuildPhase") } func testDictionary() -> [String: Any] { [ "dstPath": "dstPath", "buildActionMask": 0, "dstSubfolderSpec": 12, "files": ["a", "b"], "runOnlyForDeploymentPostprocessing": 0, "reference": "reference", ] } }
// // Formulas.swift // CheatSheetApp // // Created by Virtual Enteprise on 1/14/16. // Copyright (c) 2016 NuApps. All rights reserved. // import UIKit class Formulas: UIViewController { @IBOutlet weak var quotientImg: UIImageView! @IBAction func backBtn(sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() let gesture = UISwipeGestureRecognizer(target: self, action: Selector(("backSwipe:"))) quotientImg.image = UIImage(named: "quotientrule.png") view.addGestureRecognizer(gesture) } func backSwipe(sender: UISwipeGestureRecognizer){ if(sender.direction == .left){ dismiss(animated: true, completion: nil) } } }
// // PTLocationManager.swift // Path // // Created by dewey on 2018. 7. 3.. // Copyright © 2018년 path. All rights reserved. // import UIKit class PTLocationManager: NSObject { }
// // PagesManager.swift // OnlineTutor // // Created by Rojan Bajracharya on 5/23/20. // Copyright © 2020 Rojan Bajracharya. All rights reserved. // import Foundation import UIKit struct PagesManager { private var pageData: [Pages] init() { self.pageData = [] } // Pages( // pageName: "Draw Numbers", // pageViewController: storyboard.instantiateViewController(identifier: "DisplayCardVC") as! DisplayCardViewController, // pageID: "DisplayCardVC", // pageIcon: "icon_doodle" // ), init(storyboard: UIStoryboard) { self.pageData = [ Pages( pageName: "Cards", pageViewController: storyboard.instantiateViewController(identifier: "DisplayCardVC") as! DisplayCardViewController, pageID: "DisplayCardVC", pageIcon: "icon_flashCard" ), Pages( pageName: "Numbers & Letters", pageViewController: storyboard.instantiateViewController(identifier: "DisplaySelectedVC") as! DisplaySelectedViewController, pageID: "DisplaySelectedVC", pageIcon: "icon_alphabet" ), Pages( pageName: "Animals", pageViewController: storyboard.instantiateViewController(identifier: "AnimalVC") as! AnimalViewController, pageID: "AnimalVC", pageIcon: "icon_animal" ), Pages( pageName: "Mathematics", pageViewController: storyboard.instantiateViewController(identifier: "MathsTableVC") as! MathsTableViewController, pageID: "MathsTableVC", pageIcon: "icon_maths" ), Pages( pageName: "Solar System", pageViewController: storyboard.instantiateViewController(identifier: "SolarSystemTableVC") as! SolarSystemTableViewController, pageID: "SolarSystemTableVC", pageIcon: "icon_solarSystem" ), Pages( pageName: "Test Yourself", pageViewController: storyboard.instantiateViewController(identifier: "TestDashboardVC") as! TestDashboardViewController, pageID: "TestVC", pageIcon: "icon_test" ) ] } func getPagesCount() -> Int { return pageData.count } func getPageName(dataNumber: Int) -> String { return self.pageData[dataNumber].pageName } func getPageIcon(dataNumber: Int) -> String { return self.pageData[dataNumber].pageIcon } func getPageViewController(dataNumber: Int) -> UIViewController { return self.pageData[dataNumber].pageViewController } func getPageId(dataNumber: Int) -> String { return self.pageData[dataNumber].pageID } }
// Copyright 2019 Kakao Corp. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// 카카오 SDK를 사용하면서 발생하는 모든 에러를 나타냅니다. public enum SdkError : Error { /// SDK 내에서 발생하는 클라이언트 에러 case ClientFailed(reason:ClientFailureReason, errorMessage:String?) /// API 호출 에러 case ApiFailed(reason:ApiFailureReason, errorInfo:ErrorInfo?) /// 로그인 에러 case AuthFailed(reason:AuthFailureReason, errorInfo:AuthErrorInfo?) /// 네트워크 실패 등 일반적인 외부 에러 case GeneralFailed(error:Error) } /// :nodoc: extension SdkError { public init(reason:ClientFailureReason = .Unknown, message:String? = nil) { switch reason { case .ExceedKakaoLinkSizeLimit: self = .ClientFailed(reason: reason, errorMessage: message ?? "failed to send message because it exceeds the message size limit.") case .MustInitAppKey: self = .ClientFailed(reason: reason, errorMessage: "initSDK(appKey:) must be initialized.") case .Cancelled: self = .ClientFailed(reason: reason, errorMessage:message ?? "user cancelled") case .NotSupported: self = .ClientFailed(reason: reason, errorMessage: "target app is not installed.") case .BadParameter: self = .ClientFailed(reason: reason, errorMessage:message ?? "bad parameters.") case .TokenNotFound: self = .ClientFailed(reason: reason, errorMessage: message ?? "authentication tokens don't exist.") case .CastingFailed: self = .ClientFailed(reason: reason, errorMessage: message ?? "casting failed.") case .Unknown: self = .ClientFailed(reason: reason, errorMessage:message ?? "unknown error.") } } } /// :nodoc: extension SdkError { public init?(response:HTTPURLResponse, data:Data, type:ApiType) { if 200 ..< 300 ~= response.statusCode { return nil } switch type { case .KApi: if let errorInfo = try? SdkJSONDecoder.custom.decode(ErrorInfo.self, from: data) { self = .ApiFailed(reason: errorInfo.code, errorInfo:errorInfo) } else { return nil } case .KAuth: if let authErrorInfo = try? SdkJSONDecoder.custom.decode(AuthErrorInfo.self, from: data) { self = .AuthFailed(reason: authErrorInfo.error, errorInfo:authErrorInfo) } else { return nil } } } public init?(parameters: [String: String]) { if let authErrorInfo = try? SdkJSONDecoder.custom.decode(AuthErrorInfo.self, from: JSONSerialization.data(withJSONObject: parameters, options: [])) { self = .AuthFailed(reason: authErrorInfo.error, errorInfo: authErrorInfo) } else { return nil } } public init(scopes:[String]?) { let errorInfo = ErrorInfo(code: .InsufficientScope, msg: "", requiredScopes: scopes) self = .ApiFailed(reason: errorInfo.code, errorInfo: errorInfo) } } /// :nodoc: extension SdkError { public init(error:Error) { self = .GeneralFailed(error:error) } } //helper extension SdkError { /// 클라이언트 에러인지 확인합니다. /// - seealso: `ClientFailureReason` public var isClientFailed : Bool { if case .ClientFailed = self { return true } return false } /// API 서버 에러인지 확인합니다. /// - seealso: `ApiFailureReason` public var isApiFailed : Bool { if case .ApiFailed = self { return true } return false } /// 인증 서버 에러인지 확인합니다. /// - seealso: `AuthFailureReason` public var isAuthFailed : Bool { if case .AuthFailed = self { return true } return false } /// 클라이언트 에러 정보를 얻습니다. `isClientFailed`가 true인 경우 사용해야 합니다. /// - seealso: `ClientFailureReason` public func getClientError() -> (reason:ClientFailureReason, message:String?) { if case let .ClientFailed(reason, message) = self { return (reason, message) } return (ClientFailureReason.Unknown, nil) } /// API 요청 에러에 대한 정보를 얻습니다. `isApiFailed`가 true인 경우 사용해야 합니다. /// - seealso: `ApiFailureReason` <br> `ErrorInfo` public func getApiError() -> (reason:ApiFailureReason, info:ErrorInfo?) { if case let .ApiFailed(reason, info) = self { return (reason, info) } return (ApiFailureReason.Unknown, nil) } /// 로그인 요청 에러에 대한 정보를 얻습니다. `isAuthFailed`가 true인 경우 사용해야 합니다. /// - seealso: `AuthFailureReason` <br> `AuthErrorInfo` public func getAuthError() -> (reason:AuthFailureReason, info:AuthErrorInfo?) { if case let .AuthFailed(reason, info) = self { return (reason, info) } return (AuthFailureReason.Unknown, nil) } /// 유효하지 않은 토큰 에러인지 체크합니다. public func isInvalidTokenError() -> Bool { if case .ApiFailed = self, getApiError().reason == .InvalidAccessToken { return true } else if case .AuthFailed = self, getAuthError().reason == .InvalidGrant { return true } return false } } //MARK: - error code enum /// 클라이언트 에러 종류 입니다. public enum ClientFailureReason { /// 기타 에러 case Unknown /// 사용자의 취소 액션 등 case Cancelled /// API 요청에 사용할 토큰이 없음 case TokenNotFound /// 지원되지 않는 기능 case NotSupported /// 잘못된 파라미터 case BadParameter /// SDK 초기화를 하지 않음 case MustInitAppKey /// 카카오링크 템플릿 용량 초과 case ExceedKakaoLinkSizeLimit /// type casting 실패 case CastingFailed } /// API 서버 에러 종류 입니다. public enum ApiFailureReason : Int, Codable { /// 기타 서버 에러 case Unknown = -9999 /// 기타 서버 에러 case Internal = -1 /// 잘못된 파라미터 case BadParameter = -2 /// 지원되지 않는 API case UnsupportedApi = -3 /// API 호출이 금지됨 case Blocked = -4 /// 호출 권한이 없음 case Permission = -5 /// 더이상 지원하지 않은 API를 요청한 경우 case DeprecatedApi = -9 /// 쿼터 초과 case ApiLimitExceed = -10 /// 연결되지 않은 사용자 case NotSignedUpUser = -101 /// 이미 연결된 사용자에 대해 signup 시도 case AlreadySignedUpUsercase = -102 /// 존재하지 않는 카카오계정 case NotKakaoAccountUser = -103 /// 등록되지 않은 user property key case InvalidUserPropertyKey = -201 /// 등록되지 않은 앱키의 요청 또는 존재하지 않는 앱으로의 요청. (앱키가 인증에 사용되는 경우는 -401 참조) case NoSuchApp = -301 /// 앱키 또는 토큰이 잘못된 경우. 예) 토큰 만료 case InvalidAccessToken = -401 /// 해당 API에서 접근하는 리소스에 대해 사용자의 동의를 받지 않음 case InsufficientScope = -402 ///연령인증이 필요함 case RequiredAgeVerification = -405 ///연령제한에 걸림 case UnderAgeLimit = -406 /// 앱의 연령제한보다 사용자의 연령이 낮음 case LowerAgeLimit = -451 /// 이미 연령인증이 완료 됨 case AlreadyAgeAuthorized = -452 /// 연령인증 허용 횟수 초과 case AgeCheckLimitExceed = -453 /// 이전 연령인증과 일치하지 않음 case AgeResultMismatched = -480 /// CI 불일치 case CIResultMismatched = -481 /// 카카오톡 사용자가 아님 case NotTalkUser = -501 /// 지원되지 않는 기기로 메시지 보내는 경우 case UserDevicedUnsupported = -504 /// 메시지 수신자가 수신을 거부한 경우 case TalkMessageDisabled = -530 /// 월간 메시지 전송 허용 횟수 초과 case TalkSendMessageMonthlyLimitExceed = -531 /// 일간 메시지 전송 허용 횟수 초과 case TalkSendMessageDailyLimitExceed = -532 /// 카카오스토리 사용자가 아님 case NotStoryUser = -601 /// 카카오스토리 이미지 업로드 사이즈 제한 초과 case StoryImageUploadSizeExceed = -602 /// 카카오스토리 이미지 업로드 타임아웃 case StoryUploadTimeout = -603 /// 카카오스토리 스크랩시 잘못된 스크랩 URL로 호출할 경우 case StoryInvalidScrapUrl = -604 /// 카카오스토리의 내정보 요청시 잘못된 내스토리 아이디(포스트 아이디)로 호출할 경우 case StoryInvalidPostId = -605 /// 카카오스토리 이미지 업로드시 허용된 업로드 파일 수가 넘을 경우 case StoryMaxUploadNumberExceed = -606 /// 서버 점검 중 case UnderMaintenance = -9798 } /// :nodoc: extension ApiFailureReason { public init(from decoder: Decoder) throws { self = try ApiFailureReason(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .Unknown } } /// 로그인 요청 에러 종류 입니다. public enum AuthFailureReason : String, Codable { /// 기타 에러 case Unknown = "unknown" /// 요청 파라미터 오류 case InvalidRequest = "invalid_request" /// 유효하지 않은 앱 case InvalidClient = "invalid_client" /// 유효하지 않은 scope case InvalidScope = "invalid_scope" /// 인증 수단이 유효하지 않아 인증할 수 없는 상태 case InvalidGrant = "invalid_grant" /// 설정이 올바르지 않음. 예) bundle id case Misconfigured = "misconfigured" /// 앱이 요청 권한이 없음 case Unauthorized = "unauthorized" /// 접근이 거부 됨 (동의 취소) case AccessDenied = "access_denied" /// 서버 내부 에러 case ServerError = "server_error" /// :nodoc: 카카오싱크 전용 case AutoLogin = "auto_login" } /// :nodoc: extension AuthFailureReason { public init(from decoder: Decoder) throws { self = try AuthFailureReason(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .Unknown } }
// // ForgotPasswordViewController.swift // Saga Plus // // Created by Gokul Murugan on 2021-01-09. // import UIKit import Firebase class ForgotPasswordViewController: UIViewController { // MARK: Outlet @IBOutlet weak var E_Mail: UITextField! // MARK: View Did Load override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: true) } // MARK: Reset Link @IBAction func Reset_Link(_ sender: Any) { if(E_Mail.text == "") { alert(message: "Please enter email and try again", title: "Enter E-Mail!") } else { Auth.auth().sendPasswordReset(withEmail: E_Mail.text!) { error in if (error != nil ) { self.alert(message: "Please check your E-Mail and try again later", title: "Reset link unsuccessful") } else if (error == nil ) { self.alert(message: "Please check your E-Mail and login", title: "Reset link sent successfully") } } } } }
import Foundation import Bradel struct ArticleCellVM: TableViewCellVMProtocol { let article: Article var typeID: AnyTypeID var isSelectable = true var displayArticle: (() -> Void)? init(article: Article, typeID: AnyTypeID) { self.article = article self.typeID = typeID self.displayArticle = nil } func select() { self.displayArticle?() } }
// // PokerApp.swift // Poker // // Created by Matthew Popov on 12.08.2021. // import SwiftUI @main struct PokerApp: App { var body: some Scene { WindowGroup { ContentView() } } }
// // PostListView.swift // UsersApp-SwiftUI // // Created by Jorge Luis Rivera Ladino on 4/09/21. // import SwiftUI struct PostListView: View { var post: PostList.Post.Domain var body: some View { VStack(alignment: .leading, spacing: 8) { Text(post.title) .foregroundColor(.primaryGreenColor) Text(post.body) } } }
import Foundation @objc(Counter) class Counter: NSObject { @objc static func requiresMainQueueSetup() -> Bool { return true } private var count = 1 @objc func increment() { count += 1 print("count is \(count)") } @objc func constantsToExport() -> Any { return ["initialCount": 0] } @objc func getCount(_ callback: RCTResponseSenderBlock) { callback([count]) } @objc func decrement( _ resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock ) -> Void { if (count == 0) { let error = NSError(domain: "", code: 200, userInfo: nil) reject("E_COUNT", "count cannot be negative", error) } else { count -= 1 resolve("count was decremented") } } }
// // MainTabBar.swift // NV_ORG // // Created by Netventure on 28/03/20. // Copyright © 2020 netventure. All rights reserved. // import Foundation import UIKit class MainTabBar : UITabBarController{ var viewcontroller : [UIViewController]? required init?(coder: NSCoder) { super.init(coder: coder) // fatalError("init(coder:) has not been implemented") } func setUPViewController(){ let mainstoryBoard = UIStoryboard.init(name: "Main", bundle: nil) let dashBoard = mainstoryBoard.instantiateViewController(withIdentifier: "DashBoardViewController") as! DashBoardViewController let directory = mainstoryBoard.instantiateViewController(withIdentifier: "DirectoryViewController") as! DirectoryViewController let notification = mainstoryBoard.instantiateViewController(withIdentifier: "NotificationViewController") as! NotificationViewController let profile = mainstoryBoard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController viewcontroller = [dashBoard,directory,notification,profile] self.viewControllers = viewcontroller } }
// // ListHeaderView.swift // SimpleGoceryList // // Created by Payton Sides on 6/13/21. // import SwiftUI struct ListHeaderView: View { //MARK: - Properties var topCircleIcon: String var bottomCircleIcon: String var text: String var backgroundColor: Color var circleColor: Color var lineColor: Color var scale: CGFloat //MARK: - Body var body: some View { HStack(alignment: .bottom) { // ListIconView(backgroundColor: backgroundColor, circleColor: circleColor, lineColor: lineColor, topCircleIcon: topCircleIcon, bottomCircleIcon: bottomCircleIcon, scale: scale) Text(text) .textCase(.none) .font(.title3.bold()) .foregroundColor(.orangeLight) } } } //MARK: - Preview struct ListHeaderView_Previews: PreviewProvider { static var previews: some View { ListHeaderView(topCircleIcon: "circle", bottomCircleIcon: "checkmark.circle.fill", text: "Current List", backgroundColor: Color.mint, circleColor: .white, lineColor: .secondary.opacity(0.6), scale: 1) } }
import SwiftUI struct DrawView: UIViewRepresentable { func makeUIView(context: Context) -> UIView { let view = UIView() //white background var rect = CGRect(x: 55, y: 20, width: 300, height: 200) let backGroundView = UIView(frame: rect) backGroundView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) //redbanner rect = CGRect(x: 0, y: 0, width: 300, height: 100) let redBanner = UIView(frame: rect) redBanner.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) backGroundView.addSubview(redBanner) backGroundView.layer.borderWidth = 1 view.addSubview(backGroundView) //moon //eclip let ecPath = UIBezierPath(ovalIn: CGRect(x:29, y: 11, width: 80 , height: 80)) //moon circle let moonPath = UIBezierPath(ovalIn: CGRect(x: 43, y: 8, width: 83, height: 83)) // startop let topPath = UIBezierPath() topPath.move(to: CGPoint(x: 74, y: 24)) topPath.addLine(to: CGPoint(x: 75, y: 28)) topPath.addLine(to: CGPoint(x: 80, y: 29 )) topPath.addLine(to: CGPoint(x: 77, y: 32)) topPath.addLine(to: CGPoint(x: 78, y: 37)) topPath.addLine(to: CGPoint(x: 74, y: 35)) topPath.addLine(to: CGPoint(x: 70, y: 37)) topPath.addLine(to: CGPoint(x: 71, y: 33)) topPath.addLine(to: CGPoint(x: 69, y: 30)) topPath.addLine(to: CGPoint(x: 74, y: 29)) topPath.close() //but let butPath = UIBezierPath() butPath.move(to: CGPoint(x: 65, y: 61)) butPath.addLine(to: CGPoint(x: 66, y: 63)) butPath.addLine(to: CGPoint(x: 71, y: 65)) butPath.addLine(to: CGPoint(x: 68, y: 67 )) butPath.addLine(to: CGPoint(x: 69, y: 73)) butPath.addLine(to: CGPoint(x: 65, y: 69)) butPath.addLine(to: CGPoint(x: 62, y: 72)) butPath.addLine(to: CGPoint(x: 62, y: 68)) butPath.addLine(to: CGPoint(x: 59, y: 65)) butPath.addLine(to: CGPoint(x: 63, y: 64)) butPath.close() //twin b let twinbPath = UIBezierPath() twinbPath.move(to: CGPoint(x: 83, y: 61)) twinbPath.addLine(to: CGPoint(x:84, y: 63)) twinbPath.addLine(to: CGPoint(x: 90, y: 65)) twinbPath.addLine(to: CGPoint(x: 86, y: 67 )) twinbPath.addLine(to: CGPoint(x: 88, y: 73)) twinbPath.addLine(to: CGPoint(x: 84, y: 69)) twinbPath.addLine(to: CGPoint(x: 79, y: 72)) twinbPath.addLine(to: CGPoint(x: 81, y: 68)) twinbPath.addLine(to: CGPoint(x: 78, y: 65)) twinbPath.addLine(to: CGPoint(x: 82, y: 64)) twinbPath.close() // star mid start here let starPath = UIBezierPath() starPath.move(to: CGPoint(x: 60, y: 39)) starPath.addLine(to: CGPoint(x: 61, y: 43)) starPath.addLine(to: CGPoint(x: 65, y: 46)) starPath.addLine(to: CGPoint(x: 62, y: 47)) starPath.addLine(to: CGPoint(x: 64, y: 52)) starPath.addLine(to: CGPoint(x: 60, y: 50)) starPath.addLine(to: CGPoint(x: 55, y: 52)) starPath.addLine(to: CGPoint(x: 57, y: 47)) starPath.addLine(to: CGPoint(x: 54, y: 44)) starPath.addLine(to: CGPoint(x: 58, y: 43)) starPath.close() //twin m let twinmPath = UIBezierPath() twinmPath.move(to: CGPoint(x: 94, y: 39)) twinmPath.addLine(to: CGPoint(x: 95, y: 43)) twinmPath.addLine(to: CGPoint(x: 100, y: 46)) twinmPath.addLine(to: CGPoint(x: 95, y: 47)) twinmPath.addLine(to: CGPoint(x: 98, y: 52)) twinmPath.addLine(to: CGPoint(x: 94, y: 50)) twinmPath.addLine(to: CGPoint(x: 91, y: 52)) twinmPath.addLine(to: CGPoint(x: 91, y: 47)) twinmPath.addLine(to: CGPoint(x: 88, y: 44)) twinmPath.addLine(to: CGPoint(x: 92, y: 43)) twinmPath.close() //combine starPath.append(topPath) starPath.append(butPath) starPath.append(twinbPath) starPath.append(twinmPath) // show let starShape = CAShapeLayer() starShape.fillColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) starShape.strokeColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) starShape.lineWidth = 1 starShape.path = starPath.cgPath let moonShape = CAShapeLayer() moonShape.fillColor = CGColor(red: 1, green: 0, blue: 0, alpha: 1) moonShape.path = moonPath.cgPath let ecShape = CAShapeLayer() ecShape.fillColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) ecShape.path = ecPath.cgPath redBanner.layer.addSublayer(ecShape) redBanner.layer.addSublayer(moonShape) redBanner.layer.addSublayer(starShape) return view } func updateUIView(_ uiView: UIView, context: Context) { } } struct ContentView: View { var body: some View { DrawView() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView() ContentView() } } }
#if canImport(UIKit) import UIKit internal final class FocusIndicatorView: UIView { @IBOutlet private weak var indicatorView: UIView! // Circle private let baseAlpha: CGFloat = 0.5 private let movingTime: TimeInterval = 0.25 private let fadeTime: TimeInterval = 0.3 private let afterDelay: TimeInterval = 2.0 private var resetBounds: CGRect { let shortSide = min(bounds.width, bounds.height) / 3.0 * 0.85 return CGRect(x: 0.0, y: 0.0, width: shortSide, height: shortSide) } private var focusBounds: CGRect { let shortSide = min(bounds.width, bounds.height) / 3.0 * 0.7 return CGRect(x: 0.0, y: 0.0, width: shortSide, height: shortSide) } internal func focusResetAnimation(animated: Bool = true) { let selector = #selector(animateIndicatorViewAlpha) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) UIView.animate(withDuration: animated ? movingTime : 0.0, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.indicatorView.alpha = self.baseAlpha self.indicatorView.center = self.center self.indicatorView.bounds = self.resetBounds }, completion: { (finished: Bool) -> Void in NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) self.perform(selector, with: nil, afterDelay: self.afterDelay) }) } internal func focusAnimation(to point: CGPoint) { let selector = #selector(animateIndicatorViewAlpha) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) UIView.animate(withDuration: movingTime, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.indicatorView.alpha = self.baseAlpha self.indicatorView.center = point self.indicatorView.bounds = self.focusBounds }, completion: { (finished: Bool) -> Void in NSObject.cancelPreviousPerformRequests(withTarget: self, selector: selector, object: nil) self.perform(selector, with: nil, afterDelay: self.afterDelay) }) } @objc private func animateIndicatorViewAlpha() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #function, object: nil) let alpha: CGFloat = indicatorView.center == center ? 0.0 : baseAlpha / 2.0 UIView.animate(withDuration: fadeTime, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.indicatorView.alpha = alpha }, completion: { (finished: Bool) -> Void in // nop }) } } #endif
var solutions = [[String]]() var queens = [Int]() var columuns = Set<Int>() var diagonal1 = Set<Int>() var diagonal2 = Set<Int>() var row = [String]() func solveNQueens(_ n: Int) -> [[String]] { queens = Array.init(repeating: -1, count: n) row = Array.init(repeating: ".", count: n) backtrace(row: 0, n: n) return solutions } func backtrace(row: Int, n: Int) { if row == n { let board = generateBoard(n: n) solutions.append(board) } else { for i in 0..<n { if columuns.contains(i) || diagonal1.contains(row-i) || diagonal2.contains(row+i) { continue } queens[row] = i columuns.insert(i) diagonal1.insert(row-i) diagonal2.insert(row+i) backtrace(row: row + 1, n: n) columuns.remove(i) diagonal1.remove(row-i) diagonal2.remove(row+i) } } } func generateBoard(n: Int) -> [String] { var board = [String]() for i in 0..<n { row[queens[i]] = "Q" board.append(row.joined()) row[queens[i]] = "." } return board }
// // CreateAccountViewController.swift // Binder // // Created by Isaac on 3/26/18. // Copyright © 2018 The University of Texas at Austin. All rights reserved. // import UIKit import CoreData class CreateAccountViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var retypePasswordTextField: UITextField! @IBOutlet weak var errorLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() errorLabel.text = "" //PersistenceService.shared.fetchPeople() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func saveButton(_ sender: Any) { if noErrors() && newAccount(){ let index:Int = DataStore.shared.countOfPeople() //CREATE A PERSON HERE let thePersonCreated:People = People(username: usernameTextField.text!, password: passwordTextField.text!, personID: index, fontSize: "small", backgroundColor: "blue", firebaseRandomID: "") DataStore.shared.addPerson(person: thePersonCreated) //Opens connection to core data let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.persistentContainer.viewContext //Creates new entity that will hold the information to be added to Core Data let entity = NSEntityDescription.entity(forEntityName: "PersonLoggedIn", in: managedContext) let personDM = NSManagedObject(entity: entity!, insertInto:managedContext) personDM.setValue(index, forKey: "personID") //Saves to core data do{ try managedContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } DataStore.shared.setIndexOfUserLoggedIn(_setValue: index) performSegue(withIdentifier: "ToTabController", sender: self) // performSegue(withIdentifier: "unwindToLogin", sender: self) } } func noErrors() -> Bool { var errorMessage:String = "" var noError:Bool = true if usernameTextField.text == "" || passwordTextField.text == "" || retypePasswordTextField.text == ""{ errorMessage = "Enter both username and password" noError = false }else{ if passwordTextField.text != retypePasswordTextField.text { errorMessage = "Passwords must match" noError = false } } errorLabel.text = errorMessage //the default settings are added for this user //Config.setUserBackgroundColor("blue") return noError } func newAccount() -> Bool { let count:Int = DataStore.shared.countOfPeople() let username:String = usernameTextField.text! if count > 0 { //only need to check if the username already exists if other accounts have been created //if you try and check when count is 0 youll get an index error //if no acounts have been created then you can instantly return true because it will be a new account for i in 0...count-1 { let person = DataStore.shared.getPerson(index: i) let gottenUsername:String = person.username if username == gottenUsername { errorLabel.text = "Username already exists" return false } } } return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // PlaySoundViewController.swift // try // // Created by MAC on 29/10/2018. // Copyright © 2018 MAC. All rights reserved. // import UIKit import AVFoundation class PlaySoundViewController: UIViewController { @IBOutlet weak var slowOutlet: UIButton! @IBOutlet weak var rabbitOutlet: UIButton! @IBOutlet weak var highPichOutlet: UIButton! @IBOutlet weak var lowPitchOutlet: UIButton! @IBOutlet weak var echoOutlet: UIButton! @IBOutlet weak var reverbOutlet: UIButton! @IBOutlet weak var stopOutlet: UIButton! var recordedAudio: URL! var audioFile: AVAudioFile! var audioEngine: AVAudioEngine! var audioPlayerNode: AVAudioPlayerNode! var stopTimer: Timer! enum ButtonType: Int { case slow = 0, fast, HighPitch, lowPitch, Echo, Reverb } override func viewDidLoad() { super.viewDidLoad() setupAudio() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureUI(.notPlaying) } @IBAction func playSoundForButton(_ sender: UIButton){ switch(ButtonType(rawValue: sender.tag)!) { case .slow: playSound(rate: 0.5) case .fast: playSound(rate: 1.5) case .HighPitch: playSound(pitch: 1000) case .lowPitch: playSound(pitch: -1000) case .Echo: playSound(echo: true) case .Reverb: playSound(reverb: true) } configureUI(.playing) } @IBAction func stopButtonPressed(_ sender: Any){ stopAudio() } }
// // main.swift // 设计模式 // // Created by Bert on 2/3/15. // Copyright (c) 2015 Bert. All rights reserved. // import Foundation //简单工厂模式 var factory = Factory() var A = factory.Create("A") A.TurnOn() A.TurnOff() //工厂模式 var factory1 = ContreteFactory1() var factory2 = ContreteFactory2() var model_a = factory1.createModel() var model_b = factory2.createModel() model_a.print_name("A") model_b.print_name("B") //抽象工厂 var afactory = ConcreteFactoryA() var e = Environment(factory: afactory); e.showProduct() var bfactory = ConcreteFactoryB() var e2 = Environment(factory: bfactory) e2.showProduct()
// // AppDelegate.swift // Seeing-Behind-Alpha // // Created by lyjtour on 2/21/18. // Copyright © 2018 lyjtour. All rights reserved. // import UIKit import NMSSH let host_url = "35.3.119.28" let username = "billy" let password = "seeingbehind" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var myViewController1: ViewController? var myViewController2: ViewControllerII? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. /* var session: NMSSHSession = NMSSHSession (host:host_url, andUsername:username) session.connect() if (session.isConnected) { session.authenticate(byPassword: password) if (session.isAuthorized) { NSLog("Authentication succeeded"); } } var error: NSError? var response: String? = session.channel.execute("sudo motion", error: &error, timeout: nil) //NSLog("List of my sites: %@", response) //var BOOL success = [session.channel uploadFile:@"~/index.html" to:@"/var/www/9muses.se/"]; session.disconnect() print("give Pi time to sudo motion") usleep(2000000) */ return true } /* func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. var session: NMSSHSession = NMSSHSession (host:host_url, andUsername:username) session.connect() if (session.isConnected) { session.authenticate(byPassword: password) if (session.isAuthorized) { NSLog("Authentication succeeded"); } } var error: NSError? var response: String? = session.channel.execute("sh ./command.sh", error: &error, timeout: nil) //NSLog("List of my sites: %@", response) //var BOOL success = [session.channel uploadFile:@"~/index.html" to:@"/var/www/9muses.se/"]; session.disconnect() } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. var session: NMSSHSession = NMSSHSession (host:host_url, andUsername:username) session.connect() if (session.isConnected) { session.authenticate(byPassword: password) if (session.isAuthorized) { NSLog("Authentication succeeded"); } } var error: NSError? var response: String? = session.channel.execute("sudo motion", error: &error, timeout: nil) //NSLog("List of my sites: %@", response) //var BOOL success = [session.channel uploadFile:@"~/index.html" to:@"/var/www/9muses.se/"]; session.disconnect() myViewController1?.reloadCamView() myViewController2?.reloadCamView() } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. var session: NMSSHSession = NMSSHSession (host:host_url, andUsername:username) session.connect() if (session.isConnected) { session.authenticate(byPassword: password) if (session.isAuthorized) { NSLog("Authentication succeeded"); } } var error: NSError? var response: String? = session.channel.execute("sudo motion", error: &error, timeout: nil) //NSLog("List of my sites: %@", response) //var BOOL success = [session.channel uploadFile:@"~/index.html" to:@"/var/www/9muses.se/"]; session.disconnect() myViewController1?.reloadCamView() myViewController2?.reloadCamView() } */ func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. var session: NMSSHSession = NMSSHSession (host:host_url, andUsername:username) session.connect() if (session.isConnected) { session.authenticate(byPassword: password) if (session.isAuthorized) { NSLog("Authentication succeeded"); } } var error: NSError? var response: String? = session.channel.execute("sh /home/pi/command.sh", error: &error, timeout: nil) //NSLog("List of my sites: %@", response) //var BOOL success = [session.channel uploadFile:@"~/index.html" to:@"/var/www/9muses.se/"]; session.disconnect() print("App terminate - will kill motion") } }
// // YNPorterhouseOrderView.swift // 2015-08-06 // // Created by 农盟 on 15/9/6. // Copyright (c) 2015年 农盟. All rights reserved. //点菜 import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } protocol YNPorterhouseOrderViewDelegate { func porterhouseOrderViewCrollViewScrolledEnable(_ enable: Bool) func porterhouseOrderViewDoneButtonDidClick(_ controller: YNPorterhouseOrderView, totalPrice: Float) func porterhouseOrderViewInteractivePopGestureRecognizer(_ enabled: Bool) } class YNPorterhouseOrderView: UIView, UITableViewDataSource, UITableViewDelegate, YNDishTableViewCellDelegate, YNCartViewDelegate, PriceViewDelegate, YNOrderTableCellDelegate { //MARK: - public property var delegate: YNPorterhouseOrderViewDelegate? //父页面topview的高度 var superViewTopViewHeight: CGFloat = 0 { didSet { self.keywindowBgView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 64 + superViewTopViewHeight) } } var data: Array<YNPorthouseType>? { didSet { if data?.count > 0 { self.setupInterface() } } } var selectedArray: Array<YNPorterhouseDish>? { get { var tempArray = [YNPorterhouseDish]() for item:YNPorthouseType in data! { for dish:YNPorterhouseDish in item.dataArray { if dish.number > 0 { tempArray.append(dish) } } } return tempArray } } //MARK: - private method func setupInterface() { self.addSubview(typeTableView) self.addSubview(dishTableView) self.addSubview(bottomPriceView) self.addSubview(doneButton) self.addSubview(cartView) let typeTableViewWidth = self.frame.size.width * 0.3 let dishTableViewWidth = self.frame.size.width - (typeTableViewWidth + 8) typeTableView.frame = CGRect(x: 0, y: 0, width: typeTableViewWidth, height: self.frame.size.height - self.bottomViewHeight) dishTableView.frame = CGRect(x: typeTableViewWidth + 8, y: 0, width: dishTableViewWidth, height: self.frame.size.height - self.bottomViewHeight) bottomPriceView.frame = CGRect(x: 0, y: dishTableView.frame.maxY, width: self.frame.size.width * 0.63, height: self.bottomViewHeight) doneButton.frame = CGRect(x: bottomPriceView.frame.maxX, y: dishTableView.frame.maxY, width: self.frame.size.width * 0.37, height: self.bottomViewHeight) cartView.frame = CGRect(x: 10 , y: self.frame.size.height - 10 - self.cartViewH, width: self.cartViewW, height: self.cartViewH) } func createAJumpImageView() -> UIImageView { let tempView = UIImageView(image: UIImage(named: "shop_menu_jump_icon")) tempView.bounds = CGRect(x: 0, y: 0, width: 16, height: 16) return tempView } func translateCoorinate(_ view: UIView) { let jumpImagecenter: CGPoint = view.superview!.convert(view.center, to: self) let controlPoint: CGPoint = CGPoint(x: jumpImagecenter.x - 220, y: jumpImagecenter.y - 120) let endPoint = self.cartView.convert(self.cartView.cartBackgroundView.center, to: self) let jumpView = createAJumpImageView() jumpView.center = jumpImagecenter self.addSubview(jumpView) jumpToCart(jumpView, startPoint: jumpImagecenter, controlPoint: controlPoint, endPoint: endPoint) } func jumpToCart(_ view: UIView, startPoint: CGPoint, controlPoint: CGPoint, endPoint: CGPoint) { //TODO: 动画 let animation = CAKeyframeAnimation(keyPath: "position") let path: CGMutablePath = CGMutablePath() path.move(to: CGPoint(x: startPoint.x, y: startPoint.y)) path.addQuadCurve(to: CGPoint(x: endPoint.x, y: endPoint.y), control: CGPoint(x: controlPoint.x, y: controlPoint.y)) // CGPathMoveToPoint(path, nil, startPoint.x, startPoint.y) // CGPathAddCurveToPoint(path, nil, startPoint.x, startPoint.y, controlPoint.x, controlPoint.y, endPoint.x, endPoint.y) animation.path = path let duration = 0.55 animation.duration = duration animation.beginTime = 0 animation.repeatCount = 0 animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) view.layer.add(animation, forKey: "position") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(duration * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in view.removeFromSuperview() self.animateCartView() } } func animateCartView() { let animation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale") animation.values = [1.2, 0.7, 1] animation.keyTimes = [0, 0.4, 0.6, 0.3] animation.beginTime = 0 animation.repeatCount = 0 animation.isRemovedOnCompletion = true animation.fillMode = kCAFillModeForwards self.cartView.layer.add(animation, forKey: "position") } //MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView.tag == 1 { if let tempData = self.data { return tempData.count } } else if tableView.tag == 2 { if let tempData = self.data { let type: YNPorthouseType = tempData[typeSelectedIndex] return type.dataArray.count } }else if tableView.tag == 3 { if selectedArray?.count > 0 { return selectedArray!.count } } return 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView.tag == 2 { return 119 } else if tableView.tag == 1 { return 50 } return orderTableCellHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView.tag == 1 { let identify: String = "CELL_TYPE" var cell: YNTypeTableViewCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNTypeTableViewCell if cell == nil { cell = YNTypeTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: identify) } cell?.data = self.data![(indexPath as NSIndexPath).row] return cell! } else if tableView.tag == 2 { let identify: String = "CELL_Dish" var cell:YNDishTableViewCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNDishTableViewCell if cell == nil { cell = YNDishTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: identify) } let temptype: YNPorthouseType = self.data![typeSelectedIndex] cell?.data = temptype.dataArray[(indexPath as NSIndexPath).row] cell?.delegate = self return cell! } else if tableView.tag == 3 { let identify: String = "CELL_ORDER" var cell: YNOrderTableCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNOrderTableCell if cell == nil { cell = YNOrderTableCell(style: UITableViewCellStyle.default, reuseIdentifier: identify) } if selectedArray?.count > 0 { cell?.data = selectedArray![(indexPath as NSIndexPath).row] cell?.delegate = self } return cell! } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if tableView.tag == 3 { return orderTableHeaderHeight } return 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if tableView.tag == 3 { let header: YnOrderTableHeaderView = YnOrderTableHeaderView() return header } return nil } //MARK: - UITableViewDelagate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.tag == 1 { self.data![self.typeSelectedIndex].selected = false let type: YNPorthouseType = self.data![(indexPath as NSIndexPath).row] type.selected = true self.typeSelectedIndex = (indexPath as NSIndexPath).row self.typeTableView.reloadData() self.dishTableView.reloadData() } } //MARK: - YNDishTableViewCellDelegate func dishTableViewCellAddButtonDidClick(_ cell: YNDishTableViewCell, button: UIButton) { translateCoorinate(button) let type: YNPorthouseType = self.data![self.typeSelectedIndex] type.selectedNumber += 1 self.typeTableView.reloadData() //处理下面的购物篮数量 self.cartView.selectedNumber += 1 //确定按钮的处理 if self.cartView.selectedNumber > 0{ self.doneButton.backgroundColor = kStyleColor self.doneButton.isUserInteractionEnabled = true } else { self.doneButton.backgroundColor = UIColor.gray self.doneButton.isUserInteractionEnabled = false } //总价格 if let price = cell.data!.price { self.bottomPriceView.totalPrice += price } } func dishTableViewCellMinusButtonDidClick(_ cell: YNDishTableViewCell) { let type: YNPorthouseType = self.data![self.typeSelectedIndex] type.selectedNumber -= 1 self.typeTableView.reloadData() //处理下面的购物篮数量 self.cartView.selectedNumber -= 1 //确定按钮的处理 if self.cartView.selectedNumber > 0{ self.doneButton.backgroundColor = kStyleColor self.doneButton.isUserInteractionEnabled = true } else { self.doneButton.backgroundColor = UIColor.gray self.doneButton.isUserInteractionEnabled = false } //总价格 if let price = cell.data!.price { self.bottomPriceView.totalPrice -= price } } //MARK: YNOrderTableCellDelegate func orderTableCellAddButtonDidClick(_ cell: YNOrderTableCell) { let type: YNPorthouseType = self.data![cell.data!.firstIndex] type.selectedNumber += 1 //处理下面的购物篮数量 self.cartView.selectedNumber += 1 self.typeTableView.reloadData() self.dishTableView.reloadData() //总价格 if let price = cell.data!.price { self.bottomPriceView.totalPrice += price } } func orderTableCellMinusButtonDidClick(_ cell: YNOrderTableCell) { let type: YNPorthouseType = self.data![cell.data!.firstIndex] type.selectedNumber -= 1 //处理下面的购物篮数量 self.cartView.selectedNumber -= 1 self.typeTableView.reloadData() self.dishTableView.reloadData() //总价格 if let price = cell.data!.price { self.bottomPriceView.totalPrice -= price } if cell.data?.number <= 0 { setOrderTabelView(true) self.delegate?.porterhouseOrderViewCrollViewScrolledEnable(true) } } //MARK: - YNCartViewDelegate func cartViewDidClick(_ view: YNCartView) { cartViewOrPriceViewClick(view) } //MARK: - PriceViewDelegate func priceViewDidClick(_ view: PriceView) { cartViewOrPriceViewClick(view) } func cartViewOrPriceViewClick(_ view: UIView) { if let _ = selectedArray { if selectedArray!.count > 0 { isShowOrderView = !isShowOrderView if isShowOrderView { showOrderView() } else { hideOrderView() } } } } func setOrderTabelView(_ isframe: Bool) { self.addSubview(orderTableView) orderTableView.reloadData() if isframe { self.orderTableView.frame = CGRect(x: 0, y: self.orderTableViewY, width: kScreenWidth, height: self.orderTableViewHeight) if self.orderTableViewHeight == orderTableHeaderHeight { isShowOrderView = false keywindowBgView.removeFromSuperview() orderBgView.removeFromSuperview() orderTableView.removeFromSuperview() self.doneButton.backgroundColor = UIColor.gray } } self.insertSubview(bottomPriceView, aboveSubview: orderTableView) self.insertSubview(doneButton, aboveSubview: orderTableView) self.insertSubview(cartView, aboveSubview: bottomPriceView) } func showOrderView() { self.delegate?.porterhouseOrderViewInteractivePopGestureRecognizer(false) //设置orderTable的位置 setOrderTabelView(false) //设置背景蒙板 setBgView() //通知父视图scrollView不能滚动 self.delegate?.porterhouseOrderViewCrollViewScrolledEnable(false) UIView.animate(withDuration: self.animateDuration, animations: { () -> Void in self.keywindowBgView.alpha = 1 self.orderBgView.alpha = 1 self.orderTableView.frame = CGRect(x: 0, y: self.orderTableViewY, width: kScreenWidth, height: self.orderTableViewHeight) }, completion: { (finished) -> Void in }) } func hideOrderView() { UIView.animate(withDuration: self.animateDuration, animations: { () -> Void in self.orderTableView.frame = CGRect(x: 0, y: kScreenHeight - self.bottomViewHeight, width: kScreenWidth, height: 0) self.keywindowBgView.alpha = 0 self.orderBgView.alpha = 0 self.isShowOrderView = false }, completion: { (finish) -> Void in self.keywindowBgView.removeFromSuperview() self.orderBgView.removeFromSuperview() self.orderTableView.removeFromSuperview() self.delegate?.porterhouseOrderViewCrollViewScrolledEnable(true) self.delegate?.porterhouseOrderViewInteractivePopGestureRecognizer(true) }) } func setBgView() { let tgr: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YNPorterhouseOrderView.viewDidClick)) keywindowBgView.addGestureRecognizer(tgr) orderBgView.addGestureRecognizer(tgr) //自己view上的蒙板 orderBgView.frame = self.bounds self.addSubview(orderBgView) //window 上的蒙板 这样看起来才像一个完整的蒙板 keywindowBgView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 64 + self.superViewTopViewHeight) let window = UIApplication.shared.keyWindow! window.addSubview(keywindowBgView) self.insertSubview(orderBgView, belowSubview: orderTableView) } func viewDidClick() { isShowOrderView = false hideOrderView() } //MARK: - event response func doneButtonDidClick() { if let _ = orderTableView.superview { hideOrderView() } self.delegate?.porterhouseOrderViewDoneButtonDidClick(self, totalPrice: bottomPriceView.totalPrice) } //MARK: - private property fileprivate let bottomViewHeight: CGFloat = 50 fileprivate var typeSelectedIndex: Int = 0 fileprivate let cartViewH: CGFloat = 55 fileprivate let cartViewW: CGFloat = 56 fileprivate let animateDuration: TimeInterval = 0.5 fileprivate var isShowOrderView: Bool = false fileprivate let orderTableHeaderHeight: CGFloat = 36 fileprivate let orderTableCellHeight: CGFloat = 48 fileprivate var maxNumberOrderTableCell:Int { get { if kIS_iPhone6() || kIS_iPhone6Plus() { return 8 } return 6 } } fileprivate var orderTableViewY: CGFloat { get { let viewY = self.frame.size.height - bottomViewHeight - orderTableViewHeight return viewY } } fileprivate var orderTableViewHeight: CGFloat { get { let exceedsTheMaximumNumber: Bool = self.selectedArray!.count >= self.maxNumberOrderTableCell let maxHeight: CGFloat = CGFloat(maxNumberOrderTableCell)*orderTableCellHeight let normalHeight: CGFloat = CGFloat(self.selectedArray!.count) * self.orderTableCellHeight let cellHeight = exceedsTheMaximumNumber ? maxHeight : normalHeight let viewHeight = cellHeight + self.orderTableHeaderHeight return viewHeight } } fileprivate lazy var typeTableView: UITableView = { var tempTableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain) tempTableView.delegate = self tempTableView.dataSource = self tempTableView.tag = 1 tempTableView.separatorStyle = UITableViewCellSeparatorStyle.none tempTableView.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1) return tempTableView }() fileprivate lazy var dishTableView: UITableView = { var tempTableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain) tempTableView.delegate = self tempTableView.dataSource = self tempTableView.separatorStyle = UITableViewCellSeparatorStyle.none tempTableView.tag = 2 return tempTableView }() fileprivate lazy var bottomPriceView: PriceView = { var tempView = PriceView() tempView.delegate = self return tempView }() fileprivate lazy var doneButton: UIButton = { var tempView: UIButton = UIButton() tempView.backgroundColor = UIColor.gray tempView.setTitle("选好了", for: UIControlState()) tempView.addTarget(self, action: #selector(YNPorterhouseOrderView.doneButtonDidClick), for: UIControlEvents.touchUpInside) tempView.isUserInteractionEnabled = false return tempView }() fileprivate lazy var cartView: YNCartView = { var tempView = YNCartView() tempView.delegate = self return tempView }() fileprivate lazy var orderTableView: UITableView = { var tempTableView = UITableView(frame: CGRect(x: 0, y: kScreenHeight - self.bottomViewHeight, width: kScreenWidth, height: 0), style: UITableViewStyle.plain) tempTableView.delegate = self tempTableView.dataSource = self tempTableView.tag = 3 //iOS7使用frame的时候一定不要加这个 // tempTableView.setTranslatesAutoresizingMaskIntoConstraints(false) tempTableView.bounces = false return tempTableView }() fileprivate lazy var keywindowBgView: UIView = { var tempView: UIView = UIView() tempView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) tempView.tag = 100 tempView.alpha = 0 return tempView }() fileprivate lazy var orderBgView: UIView = { var tempView = UIView() tempView.alpha = 0 tempView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) return tempView }() }
// // ControllerConstants.swift // RecipeApp // // Created by Kishor Pahalwani on 18/02/20. // Copyright © 2020 Kishor Pahalwani. All rights reserved. // import Foundation class ControllerConstants { static let recipeViewController = "RecipeViewController" static let recipeCell = "RecipeCell" static let recipeDetailsViewController = "RecipeDetailsViewController" static let recipeDetailsCell = "RecipeDetailsCell" static let addCategoryViewController = "AddCategoryViewController" static let addCategoryCell = "AddCategoryCell" } class CodingKeysConstant { static let categoryName = "categoryName" static let id = "id" static let category = "Category" //For XML Path Parsing static let categoryType = "RecipeType" static let categoryFormat = "xml" } class DBConstants { static let categoryDB = "CategoryDB" static let recipeDB = "RecipeDB" }
// // AEFormPickerTCell.swift // AESwiftWorking_Example // // Created by Adam on 2021/4/9. // Copyright © 2021 CocoaPods. All rights reserved. // import UIKit class AEFormPickerTCell: AEFormBaseTCell { // var actionClosure: AEActionClosure? // lazy var titleLabel: UILabel = { // let label = UILabel() // label.textColor = UIColor.colorHex(0x231A2F) // addSubview(label) // label.snp.makeConstraints { (make) in // make.left.top.equalToSuperview().offset(5) // make.width.greaterThanOrEqualTo(0) //// make.height.equalTo(30) // make.bottom.equalToSuperview().offset(-5) // } // return label // }() //right_arrow_icon override class func loadCode(tableView: UITableView, index: IndexPath) -> AEFormPickerTCell { let identifier: String = String(describing: AEFormPickerTCell.self) tableView.register(AEFormPickerTCell.self, forCellReuseIdentifier: identifier) let cell: AEFormPickerTCell = tableView.dequeueReusableCell(withIdentifier: identifier, for: index as IndexPath) as! AEFormPickerTCell cell.selectionStyle = .none cell.indexPath = index cell.configEvent() cell.configUI() return cell } 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 } private lazy var actionButton: UIButton = { let button = UIButton(type: .custom) button.titleLabel?.numberOfLines = 0 button.titleLabel?.textAlignment = .center button.titleLabel?.adjustsFontSizeToFitWidth = true button.setTitle("提醒类", for: .normal) button.setImage(UIImage(named: "right_arrow_icon"), for: .normal) button.setTitleColor(UIColor.colorHex(0x655A72), for: .normal) // button.setTitleColor(UIColor.colorHex(0x040404), for: .selected) button.addTarget(self, action: #selector(actionButtonClick(button:)), for: UIControl.Event.touchUpInside) backView.addSubview(button) button.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(15) make.left.greaterThanOrEqualTo(titleLabel.snp.right).offset(10) make.bottom.right.equalToSuperview().offset(-15) make.height.equalTo(titleLabel.snp.height) } return button }() override var detailModel: AEFormModel? { didSet { if (detailModel?.title?.count ?? 0) > 0 { titleLabel.text = detailModel?.title } if let inpout = detailModel?.value { actionButton.setTitle(inpout, for: .normal) } } } override func layoutSubviews() { super.layoutSubviews() actionButton.setLayoutType(type: .rightImage, space: 10) } } extension AEFormPickerTCell { @objc func actionButtonClick(button: UIButton) { AESwiftWorking_Example.endEditing() if detailModel?.cellType == .picker { /// let title = "选择"+(detailModel?.title ?? "") let data = detailModel?.selectedArray ?? [] let selected = detailModel?.value ?? "" ICBottomListSelectionView.bottomListSelectionView(title, data: data, selected: selected) { (selectionModel) in if let model = selectionModel { self.detailModel?.value = model.title guard let closure = self.closure else { return } closure(model.title) } } } } }
// // ViewController.swift // $125 Million App // // Created by John Gallaugher on 1/16/17. // Copyright © 2017 Gallaugher. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var userInput: UITextField! @IBOutlet weak var resultsLabel: UILabel! 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. } // Executes if the user clicks on the "Convert" button @IBAction func convertButtonPressed(_ sender: UIButton) { // The .text property of a UITextField is always an optional. We've created the text field and it's been displayed on screen so we can force unwrap it with "!" and have the confidence that it won't ever be nil. // If we can take the text from the userInput UITextField and convert it into a Double then create a constant miles that is a Double... if let miles = Double(userInput.text!) { // ... and multiply miles by 1.6, assigning this value to the new constant named km let km = miles * 1.6 // Assign the string below to the resultsLabel's .text property. The \() with a value inside is String interpolation - it'll convert anything into a String. resultsLabel.text = "\(miles) miles = \(km) kilometers" } else { // otherwise, if the userInput.text couldn't be converted to a Double and we have a nil, instead, set the resultsLabel.text to the empty string so it shows up blank, with no result. resultsLabel.text = "" // perform the four-step process to create an alert, create an action, assign an action to the alert, and preset the alert. let alertController = UIAlertController(title: "Entry Error", message: "Please enter a valid number. Not an empty string, no commas, symbols, or non-numeric characters", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } } }
// // ChatViewController.swift // Loustagram // // Created by Kiet on 12/23/17. // Copyright © 2017 Kiet. All rights reserved. // import Foundation import AsyncDisplayKit import JSQMessagesViewController import FirebaseDatabase class ChatViewController: JSQMessagesViewController { var messagesHandle: DatabaseHandle = 0 var messagesRef: DatabaseReference? var chat: Chat! var messages = [Message]() var outgoingBubbleImageView: JSQMessagesBubbleImage = { guard let bubbleImageFactory = JSQMessagesBubbleImageFactory() else { fatalError("Error creating bubble image factory.") } let color = UIColor.jsq_messageBubbleBlue() return bubbleImageFactory.outgoingMessagesBubbleImage(with: color) }() var incomingBubbleImageView: JSQMessagesBubbleImage = { guard let bubbleImageFactory = JSQMessagesBubbleImageFactory() else { fatalError("Error creating bubble image factory.") } let color = UIColor.jsq_messageBubbleLightGray() return bubbleImageFactory.incomingMessagesBubbleImage(with: color) }() override func viewDidLoad() { super.viewDidLoad() tryObservingMessages() setupJSQMessagesViewController() } deinit { messagesRef?.removeObserver(withHandle: messagesHandle) } func setupJSQMessagesViewController() { // 1. identify current user senderId = User.current.uid senderDisplayName = User.current.username title = chat.title // 2. remove attachment button inputToolbar.contentView.leftBarButtonItem = nil // 3. remove avatars collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSize.zero collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero } func tryObservingMessages() { guard let chatKey = chat?.key else { return } messagesHandle = ChatService.observeMessages(forChatKey: chatKey, completion: { [weak self] (ref, message) in self?.messagesRef = ref if let message = message { self?.messages.append(message) self?.finishReceivingMessage() } }) } } // MARK: - JSQMessagesCollectionViewDataSource extension ChatViewController { // 1 override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } // 2 override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! { return nil } // 3 override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! { return messages[indexPath.item].jsqMessageValue } // 4 override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! { let message = messages[indexPath.item] let sender = message.sender if sender.uid == senderId { return outgoingBubbleImageView } else { return incomingBubbleImageView } } // 5 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let message = messages[indexPath.item] let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell cell.textView?.textColor = (message.sender.uid == senderId) ? .white : .black return cell } } // MARK: - Send Message extension ChatViewController { func sendMessage(_ message: Message) { // 1 if chat?.key == nil { // 2 ChatService.create(from: message, with: chat, completion: { [weak self] chat in guard let chat = chat else { return } self?.chat = chat // 3 self?.tryObservingMessages() }) } else { // 4 ChatService.sendMessage(message, for: chat) } } override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) { // 1 let message = Message(content: text) // 2 sendMessage(message) // 3 finishSendingMessage() // 4 JSQSystemSoundPlayer.jsq_playMessageSentAlert() } }
// // AsyncTaskQueueTests.swift // AsyncTaskQueueTests // // Created by SuXinDe on 2021/3/13. // Copyright © 2021 Skyprayer Studio. All rights reserved. // import XCTest @testable import AsyncTaskQueue /// A contrived example illustrating the use of AsyncBlockOperation. /// /// Prints the following to the console: /// /// One. /// Two. /// Three. /// func doSomethingSlow(queue: OperationQueue, completion: @escaping () -> Void) { // `AsyncBlockOperation` allows you to run arbitrary blocks of code // asynchronously. The only obligation is that the block must invoke the // `finish` block argument when finished, or else the AsyncBlockOperation // will remain stuck in the isExecuting state indefinitely. // For example, even though the execution blocks for the `one`, `two`, and // `three` operations below exit scope before each of their `.asyncAfter()` // calls fire, each operation will remain in its executing state until the // `finish` handlers are invoked. This allows you to make each operation // depend upon the previous via `.addDependency()`. let one = AsyncBlockOperation { (finish) in DispatchQueue.global().asyncAfter(deadline: .now() + 3) { print("One.") finish() } } let two = AsyncBlockOperation { (finish) in DispatchQueue.global().asyncAfter(deadline: .now() + 2) { print("Two.") finish() } } let three = AsyncBlockOperation { (finish) in DispatchQueue.global().asyncAfter(deadline: .now() + 1) { print("Three.") finish() } } // In contrast, (NS)BlockOperation is marked finished as soon as the outer- // most scope of the execution block exits. let completionOp = BlockOperation { completion() } two.addDependency(one) three.addDependency(two) completionOp.addDependency(three) let ops = [one, two, three, completionOp] queue.addOperations(ops, waitUntilFinished: false) } class AysncBlockOperationTests: XCTestCase { func testExecOneBlock() { let exp = expectation(description: #function) let op = AsyncBlockOperation { finish in exp.fulfill() finish() } op.start() waitForExpectations(timeout: 5) } func test_executesACompletionBlock() { let exp = expectation(description: #function) let op = AsyncBlockOperation { finish in finish() } op.addCompletionHandler { exp.fulfill() } op.start() waitForExpectations(timeout: 5) } func test_remainsExecutingUntilFinished() { let exp = expectation(description: #function) var results: [String] = ["idle"] let asyncOp = AsyncBlockOperation { finish in DispatchQueue.main.asyncAfter(deadline: .now() + 1) { results.append("async") finish() } } let syncOp = BlockOperation { results.append("sync") XCTAssertEqual(["idle", "async", "sync"], results) exp.fulfill() } syncOp.addDependency(asyncOp) let queue = OperationQueue() queue.addOperations([asyncOp, syncOp], waitUntilFinished: false) waitForExpectations(timeout: 5) } func test_doSomethingSlow() { let queue = OperationQueue() doSomethingSlow(queue: queue) { } } } class AsyncTaskOperationTests: XCTestCase { private class TestAccumulator { var strings = [String]() } func test_executesASimpleTask() { let exp = expectation(description: #function) let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op }, preferredPriority: .normal, tokenHandler: { token in // no op }, resultHandler: { result in XCTAssertEqual(result, ["One"]) exp.fulfill() } ) task.start() waitForExpectations(timeout: 5) } func test_executesAMultiStepTask() { let exp = expectation(description: #function) let utilityQueue = OperationQueue() let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() let one = BlockOperation { accumulator.strings.append("One") } let two = BlockOperation { accumulator.strings.append("Two") } let three = BlockOperation { accumulator.strings.append("Three") } let finish = BlockOperation { finish(accumulator.strings) } two.addDependency(one) three.addDependency(two) finish.addDependency(three) utilityQueue.addOperations([one, two, three, finish], waitUntilFinished: false) }, cancellation: { utilityQueue.cancelAllOperations() }, preferredPriority: .normal, tokenHandler: { token in // no op }, resultHandler: { result in XCTAssertEqual(result, ["One", "Two", "Three"]) exp.fulfill() } ) task.start() waitForExpectations(timeout: 5) } // MARK: Result Handlers func test_invokesAllResultHandlers() { let exp = expectation(description: #function) let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op } ) var resultCount = 0 for _ in 0...9 { task.addRequest( preferredPriority: .normal, tokenHandler: { token in // no op }, resultHandler: { result in XCTAssertEqual(result, ["One"]) resultCount += 1 if resultCount == 10 { exp.fulfill() } } ) } task.start() waitForExpectations(timeout: 5) } // MARK: Cancellation func test_cancelsAfterRemovingAllRequests() { let exp = expectation(description: #function) // Create a task that takes several seconds to finish. let task = AsyncTaskOperation<[String]>( task: { finish in DispatchQueue.main.asyncAfter(deadline: .now() + 5) { let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) } }, cancellation: { // The cancellation handler should be invoked after the // last remaining request is removed. exp.fulfill() } ) // Add 10 requests, collecting their tokens. typealias TokenType = AsyncTaskOperation<[String]>.RequestToken var tokens = [TokenType]() for _ in 0...9 { task.addRequest( preferredPriority: .normal, tokenHandler: { token in if let token = token { tokens.append(token) } }, resultHandler: { result in XCTFail() } ) } XCTAssert(tokens.count > 0) // Start the task. Remember it takes 5 seconds to finish. task.start() // Immediately cancel all requests. tokens.forEach { task.cancelRequest(with: $0) } // Wait 10 seconds to be sure there's plenty of time to test for the // cancellation. waitForExpectations(timeout: 10) } // MARK: Request Tokens func test_returnsATokenFromTheAdvancedInitializer() { let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op }, preferredPriority: .normal, tokenHandler: { token in XCTAssertNotNil(token) }, resultHandler: { result in // no op } ) task.start() } func test_returnsATokenWhenAddingTheFirstRequest() { let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op } ) task.addRequest( preferredPriority: .normal, tokenHandler: { (token) in XCTAssertNotNil(token) }, resultHandler: { (result) in // no op } ) task.start() } func test_returnsTokensWhenAddingAdditionalRequests() { let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op } ) for _ in 0...9 { task.addRequest( preferredPriority: .normal, tokenHandler: { (token) in XCTAssertNotNil(token) }, resultHandler: { (result) in // no op } ) } task.start() } func test_returnsNoTokenWhenTheTaskIsCancelled() { let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op } ) task.cancel() task.addRequest( preferredPriority: .normal, tokenHandler: { (token) in XCTAssertNil(token) }, resultHandler: { (result) in XCTFail("The result handler should not be invoked.") } ) } func test_returnsNoTokenWhenTheTaskIsFinished() { let exp = expectation(description: #function) let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op } ) task.addRequest( preferredPriority: .normal, tokenHandler: { (token) in XCTAssertNotNil(token) }, resultHandler: { (result) in task.addRequest( preferredPriority: .normal, tokenHandler: { (token) in XCTAssertNil(token) exp.fulfill() }, resultHandler: { (result) in XCTFail("The result handler should not be invoked.") } ) } ) task.start() waitForExpectations(timeout: 5) } func test_returnsATokenSynchronously_simpleInit() { var token: AsyncTaskOperation<[String]>.RequestToken? = nil let task = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op } ) task.addRequest( preferredPriority: .normal, tokenHandler: { t in token = t }, resultHandler: { (result) in // no op } ) XCTAssertNotNil(token) } func test_returnsATokenSynchronously_advancedInit() { var token: AsyncTaskOperation<[String]>.RequestToken? = nil _ = AsyncTaskOperation<[String]>( task: { finish in let accumulator = TestAccumulator() accumulator.strings.append("One") finish(accumulator.strings) }, cancellation: { // no op }, preferredPriority: .normal, tokenHandler: { t in token = t }, resultHandler: { result in // no op } ) XCTAssertNotNil(token) } } class AsyncTaskQueueTests: XCTestCase { func test_executesATask() { let exp = expectation(description: #function) let queue = AsyncTaskQueue<String, [String]>() queue.enqueue( task: { (finish) in finish(["One"]) }, taskId: "abc", cancellation: { // no op }, preferredPriority: .normal, tokenHandler: { (token) in // no op }, resultHandler: { (results) in XCTAssertEqual(["One"], results) exp.fulfill() } ) waitForExpectations(timeout: 5) } func test_executesATaskOnlyOncePerTaskId() { let exp = expectation(description: #function) let queue = AsyncTaskQueue<String, [String]>() var taskAccumulator = [String]() var resultAccumulator = 0 for _ in 0...9 { queue.enqueue( task: { (finish) in taskAccumulator.append("One") finish(taskAccumulator) }, taskId: "abc", cancellation: { // no op }, preferredPriority: .normal, tokenHandler: { (token) in // no op }, resultHandler: { (results) in XCTAssertEqual(["One"], results) resultAccumulator += 1 if resultAccumulator == 10 { exp.fulfill() } } ) } waitForExpectations(timeout: 5) } }
// // XRPAccount.swift // BigInt // // Created by Mitch Lang on 2/3/20. // import Foundation public struct XRPAccount: Codable { public var address: String public var secret: String public init(address: String, secret: String) { self.address = address self.secret = secret } }
// // ApplicationType.swift // Helios // // Created by Lars Stegman on 24-01-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation enum ApplicationType: String { case installed case script case webapp }
// // LogViewController.swift // SWABLE // // Created by Rob Visentin on 1/17/18. // Copyright © 2018 Raizlabs. All rights reserved. // import Anchorage #if os(OSX) typealias ViewController = NSViewController typealias TextView = NSTextView #else typealias ViewController = UIViewController typealias TextView = UITextView #endif final class LogViewController: ViewController { private let textView = TextView(frame: CGRect(x: 0, y: 0, width: 800, height: 500)) private let log = Log() override func loadView() { #if os(OSX) textView.isHorizontallyResizable = false textView.isVerticallyResizable = true textView.minSize = textView.frame.size textView.maxSize = NSSize(width: .max, height: .max) textView.textContainerInset = NSSize(width: 5, height: 10) textView.autoresizingMask = .width let scrollView = NSScrollView(frame: textView.frame) scrollView.hasVerticalScroller = true scrollView.documentView = textView view = scrollView #else view = textView #endif } override func viewDidLoad() { super.viewDidLoad() textView.isEditable = false NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessage), name: Message.notificationName, object: nil) } @IBAction func clear(_ sender: Any) { #if os(OSX) textView.textStorage?.setAttributedString(NSAttributedString()) #else textView.attributedText = nil #endif } @IBAction func uploadLog(_ sender: Any) { log.upload() } @objc private func onReceiveMessage(notification: Notification) { guard let message = notification.userInfo?[Message.objectKey] as? Message else { return } // Add the message to the log log.add(message) // Display the message in the view DispatchQueue.main.async { self.append(message: message) } } private func append(message: Message) { #if os(OSX) textView.textStorage?.append(NSMutableAttributedString(string: "\n")) textView.textStorage?.append(message.attributedDescription) if textView.visibleRect.minY >= textView.bounds.height - textView.visibleRect.height { textView.scrollRangeToVisible(NSRange(location: textView.textStorage?.length ?? 0, length: 0)) } #else let text = textView.attributedText.mutableCopy() as? NSMutableAttributedString ?? NSMutableAttributedString() text.append(NSMutableAttributedString(string: "\n")) text.append(message.attributedDescription) textView.attributedText = text textView.scrollRangeToVisible(NSRange(location: text.length, length: 0)) #endif } }