repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ilyasyurdaon/BinarySearchTreeValidator
BInarySearchTreeValidator/BinaryTreePlayground.playground/Contents.swift
1
828
import Foundation // Create any number of leaf or internal nodes connecting them to each other if necessary let node1 = LeafNode.init(value: 2) let node2 = LeafNode.init(value: 6) let node3 = InternalNode.init(value: 4, leftChild: node1, rightChild: node2) let node4 = LeafNode.init(value: 10) let node5 = LeafNode.init(value: 13) let node6 = InternalNode.init(value: 11, leftChild: node4, rightChild: node5) let rootNode = InternalNode.init(value: 7, leftChild: node3, rightChild: node6) /* Use the root node of the binary tree created above as "rootNode" below and set "allowDuplicates" accordingly to see the result */ let result = BinarySearchTreeValidator.isABinarySearchTree(rootNode: rootNode, allowDuplicates: false) let message = "Given node" + (result ? " FORMS" : " DOES NOT FORM") + " a binary search tree."
mit
aa81470156619d6775bf1f660ed12466
42.578947
127
0.753623
3.553648
false
false
false
false
yellowei/HWPicker
HWPhotoPicker-Swift/MultiPickerController.swift
1
30370
// // MultiPickerController.swift // HWPicker // // Created by yellowei on 2017/5/10. // Copyright © 2017年 yellowei. All rights reserved. // import UIKit import Photos @objc protocol MultiPickerViewControllerDelegate: NSObjectProtocol { @objc optional func didFinishPickingWithImages(picker: MultiPickerController, images: [Any]) -> () } class MultiPickerController: UIViewController, UITableViewDelegate, UITableViewDataSource, MultiPickerCellDelegate, HWScrollViewDelegate { //MARK: - 伪装的宏定义 private let LabDateWidth: CGFloat = 170.0 private let LabDateHeigth: CGFloat = 30.0 private let LabBackbuttonWidth: CGFloat = 60.0 private let LabBackbuttonHeight: CGFloat = 30.0 private let LabBigImageInfoWidth: CGFloat = 60.0 private let LabBigImageInfoHeight: CGFloat = 20.0 private let MorebuttonWidth: CGFloat = 45.0 private let MorebuttonHeigth: CGFloat = 30.0 //MARK: - public属性 var maximumNumberOfSelection: Int = 1 var limitsMaximumNumberOfSelection: Bool = false ///Delegate var delegate: MultiPickerViewControllerDelegate? //MARK:- Private属性 ///TableView private var aTableView: UITableView? private var elements: [PhotoObj] ///图像大小 private var imageSize: CGSize = CGSize(width: 0, height: 0) private var selectedElements: NSMutableOrderedSet private var _bigImgScroll: HWScrollView? private var bigImgScroll: HWScrollView { get { if _bigImgScroll == nil { _bigImgScroll = HWScrollView.init(frame: UIScreen.main.bounds) _bigImgScroll?.backgroundColor = UIColor.init(white: 0, alpha: 0.9) _bigImgScroll?.delegate = self } return _bigImgScroll! } set { _bigImgScroll = newValue } } private var m_rightNaviBtn: UIButton? //MARK: showBigImg相关的视图 private var m_topView: UIView? private var m_labDate: UILabel? private var m_backBtn: UIButton? private var m_completeBtn: UIButton? private var m_bottomView: UIView? private var m_overlayImageView: UIButton? private var m_currentPage: Int = 0 private var m_labBigImageInfo: UILabel? ///是否支持多选 var allowMutipleSelection: Bool = false; var filterType: PhotoPickerFilterType = .pickerFilterTypeAllAssets ///相册数据相关模型 var assetsGroup: AlbumObj? //MARK: - 生命周期方法 ///重写init方法 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { elements = [PhotoObj]() selectedElements = NSMutableOrderedSet() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } ///重写load方法 override func loadView() { var screenBounds = UIScreen.main.bounds let statusBarFrame = UIApplication.shared.statusBarFrame let statusBarHeight = min(statusBarFrame.width, statusBarFrame.height) screenBounds = CGRect(x: screenBounds.origin.x, y: screenBounds.origin.y, width: screenBounds.width, height: screenBounds.height - statusBarHeight) let mView = UIView.init(frame: screenBounds) mView.autoresizingMask = kECAutoResizingMask mView.backgroundColor = UIColor.white mView.isOpaque = true view = mView self.setTableView() } override func viewDidLoad() { super.viewDidLoad() self.imageSize = CGSize(width: 75, height: 75) if self.navigationItem.leftBarButtonItem == nil { let title = "返回" let nameSize = CGSize(width: 30, height: 20) let imgSize = CGSize(width: 11, height: 20) let btnSize = CGSize(width: 53, height: 28) let btnLeft = UIButton.init(type: .custom) btnLeft.frame = CGRect(x: 0, y: 0, width: btnSize.width, height: btnSize.height) btnLeft.setTitle(title, for: .normal) btnLeft.setTitleColor(UIColor.black, for: .normal) btnLeft.setImage(UIImage.init(named: "btn_navi_return_title"), for: .normal) btnLeft.titleLabel?.font = UIFont.systemFont(ofSize: 15) btnLeft.addTarget(self, action: #selector(goBack(sender:)), for: .touchUpInside) btnLeft.imageEdgeInsets = UIEdgeInsetsMake((btnLeft.bounds.size.height - imgSize.height), (btnLeft.bounds.size.width - (imgSize.width + nameSize.width + 8)) / 2, (btnLeft.bounds.size.height - imgSize.height) / 2, btnLeft.bounds.size.width - ((btnSize.width - (imgSize.width + nameSize.width + 8)) / 2) - imgSize.width) btnLeft.titleEdgeInsets = UIEdgeInsetsMake(0, -((btnLeft.imageView?.image?.size.width) ?? 0.0) + imgSize.width + 8, 0, 0) let leftItem = UIBarButtonItem.init(customView: btnLeft) self.navigationItem.leftBarButtonItem = leftItem } //rightBtn m_rightNaviBtn = UIButton.init(type: .custom) m_rightNaviBtn?.setTitleColor(UIColor.black, for: .normal) m_rightNaviBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 15) m_rightNaviBtn?.addTarget(self, action: #selector(dissmiss), for: .touchUpInside) let rightItem = UIBarButtonItem.init(customView: m_rightNaviBtn!) if self.maximumNumberOfSelection > 1 { let title = "完成(\(self.selectedElements.count)/\(maximumNumberOfSelection))" let size = String.commonSize(with: title, fontNum: 15.0, size: CGSize(width: CGFloat(MAXFLOAT), height: 17.0)) m_rightNaviBtn?.frame = CGRect(x: 0, y: 0, width: size.width, height: 25) m_rightNaviBtn?.setTitle(title, for: .normal) self.navigationItem.rightBarButtonItem = rightItem } let titleLabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: 100, height: 44)) titleLabel.textColor = UIColor.black titleLabel.backgroundColor = UIColor.clear titleLabel.textAlignment = NSTextAlignment.center titleLabel.text = self.title self.navigationItem.titleView = titleLabel } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.elements.count > 0 { elements.removeAll() } guard let guardAlbumObj = self.assetsGroup else { return } ImageDataAPI.shared.getPhotosWith(group: guardAlbumObj) { (ret, obj) in guard let photoObjArr = obj as? [PhotoObj] else { return } self.elements.append(contentsOf: photoObjArr) } self.aTableView?.reloadData() } //MARK: - 私有方法 private func setTableView() { aTableView = UITableView.init(frame: view.bounds, style: .grouped) aTableView?.dataSource = self aTableView?.delegate = self aTableView?.autoresizingMask = UIViewAutoresizing(rawValue: (UIViewAutoresizing.flexibleHeight.rawValue | UIViewAutoresizing.flexibleWidth.rawValue)) aTableView?.separatorStyle = .singleLine aTableView?.separatorColor = UIColor.color(hex: 0xececec) view.addSubview(aTableView!) } //MARK: - Events @objc private func goBack(sender: UIButton) { self.navigationController?.popToRootViewController(animated: true) } @objc private func dissmiss() { if self.selectedElements.count > 0 { var infoArray = [Any]() for asset in self.selectedElements { guard let guardAsset = asset as? PhotoObj, let guardPhAsset = guardAsset.photoObj else { continue } ImageDataAPI.shared.getImageForPhotoObj(asset: guardPhAsset, size: (IS_IOS8 ? PHImageManagerMaximumSize : CGSize.zero), completion: { (ret, image) in var dict = [String: Any]() if let image = image { dict.updateValue(image, forKey: "IMG") } dict.updateValue(0, forKey: "SIZE") dict.updateValue("", forKey: "NAME") infoArray.append(dict) }) } if self.delegate?.responds(to: #selector(MultiPickerViewControllerDelegate.didFinishPickingWithImages(picker:images:))) ?? false { self.delegate?.didFinishPickingWithImages!(picker: self, images: infoArray) } self.dismiss(animated: true, completion: nil) }else { self.dismiss(animated: true, completion: nil) } } @objc private func onBackTouch(sender: UIButton?) { UIView.transition(with: bigImgScroll, duration: 0.35, options: .curveEaseInOut, animations: { self.bigImgScroll.frame = CGRect(x: kECScreenWidth, y: 0, width: self.bigImgScroll.frame.size.width, height: self.bigImgScroll.frame.size.height) self.bigImgScroll.alpha = 0.0 self.navigationController?.navigationBar.isHidden = false UIApplication.shared.isStatusBarHidden = false }) { (finished) in self.bigImgScroll.removeFromSuperview() } } /// Overlay Btn Selected /// /// - Parameter sender: sender @objc private func onSelectedClick(sender: UIButton?) { var canSelect = true if self.allowMutipleSelection && self.limitsMaximumNumberOfSelection { canSelect = self.selectedElements.count < self.maximumNumberOfSelection } if canSelect == false && m_overlayImageView?.isSelected == false { let alertView = UIAlertController.init(title: "提示", message: "一次选择的图片不得超过\(self.maximumNumberOfSelection)张", preferredStyle: .alert) alertView.addAction(UIAlertAction.init(title: "确定", style: .cancel, handler: nil)) self.present(alertView, animated: true, completion: nil) }else { let asset = self.elements[m_currentPage] if self.allowMutipleSelection { let numberOfAssetsInRow = Int(self.view.frame.size.width / self.imageSize.width) let rowNum = m_currentPage / numberOfAssetsInRow let tag = (m_currentPage % numberOfAssetsInRow) + PICKER_ELEMENT_VIEW_TAG let cell = self.aTableView?.cellForRow(at: IndexPath.init(row: rowNum, section: 0)) if let elementView = cell?.viewWithTag(tag) as? PickerElementView { if self.m_overlayImageView?.isSelected == false { self.m_overlayImageView?.isSelected = true self.selectedElements.add(asset) elementView.selected = true }else { self.m_overlayImageView?.isSelected = false self.selectedElements.remove(asset) elementView.selected = false } } } } if self.maximumNumberOfSelection > 1 { let title = "完成(\(self.selectedElements.count)/\(maximumNumberOfSelection))" let size = String.commonSize(with: title, fontNum: 15.0, size: CGSize(width: CGFloat(MAXFLOAT), height: 17.0)) m_rightNaviBtn?.frame = CGRect(x: 0, y: 0, width: size.width, height: 25) m_rightNaviBtn?.setTitle(title, for: .normal) m_completeBtn?.frame = CGRect(x: self.view.frame.size.width - size.width - 8, y: self.view.frame.origin.y + 20 + 5, width: size.width, height: MorebuttonHeigth) m_completeBtn?.setTitle(title, for: .normal) } } @objc private func onCompleteBtnClick(sender: UIButton) { self.navigationController?.navigationBar.isHidden = false UIApplication.shared.isStatusBarHidden = false self.dissmiss() } //MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var numberOfRowsInSection = 0 if self.elements.count > 0,self.imageSize.width > 0 { let numberOfAssetsInRow = Int(view.bounds.size.width / self.imageSize.width) numberOfRowsInSection = Int(self.elements.count / numberOfAssetsInRow) if self.elements.count - numberOfRowsInSection * numberOfAssetsInRow > 0 { numberOfRowsInSection += 1 } } return numberOfRowsInSection } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "MutilPickerCell" var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? MultiPickerCell if cell == nil { //计算一行显示几个 var numberOfAssetsInRow = 0 if self.imageSize.width > 0 { numberOfAssetsInRow = Int(self.view.bounds.size.width / self.imageSize.width) } //计算间距 let margin = round((self.view.bounds.size.width - self.imageSize.width * CGFloat(numberOfAssetsInRow)) / CGFloat(numberOfAssetsInRow + 1)) cell = MultiPickerCell.init(style: .default, reuseIdentifier: cellIdentifier, imageSize: self.imageSize, numberOfAssets: numberOfAssetsInRow, margin: margin) cell?.selectionStyle = .none cell?.delegate = self cell?.allowsMultipleSelection = self.allowMutipleSelection } let numberOfAssetsInRow = Int(self.view.bounds.size.width / self.imageSize.width) let offset = numberOfAssetsInRow * indexPath.row let numberOfAssetsToSet = (offset + numberOfAssetsInRow > self.elements.count) ? (self.elements.count - offset) : numberOfAssetsInRow var assets = [PhotoObj]() for i in 0..<numberOfAssetsToSet { let asset = self.elements[offset + i] assets.append(asset) } cell?.elements = assets for i in 0..<numberOfAssetsToSet { let asset = self.elements[offset + i] if self.selectedElements.contains(asset) { cell?.selectElementAtIndex(index: i) }else{ cell?.deselectElementAtIndex(index: i) } } return cell! } //MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 85 } //MARK: - MultiPickerCellDelegate func canSelectElementAtIndex(pickerCell: MultiPickerCell, elementIndex: Int) -> (Bool) { var canSelect = true if self.allowMutipleSelection && self.limitsMaximumNumberOfSelection { canSelect = (self.selectedElements.count < self.maximumNumberOfSelection) } if !canSelect { let alertView = UIAlertController.init(title: "提示", message: "一次选择的图片不得超过\(self.maximumNumberOfSelection)张", preferredStyle: .alert) alertView.addAction(UIAlertAction.init(title: "确定", style: .cancel, handler: nil)) self.present(alertView, animated: true, completion: nil) } return canSelect } func didChangeElementSeletionState(pickerCell: MultiPickerCell, isSelected: Bool, atIndex: Int) { guard let indexPath = self.aTableView?.indexPath(for: pickerCell) else {return} let numberOfAssetsInRow = Int(self.view.bounds.size.width / self.imageSize.width) let assetIndex = indexPath.row * numberOfAssetsInRow + atIndex let asset = self.elements[assetIndex] if self.allowMutipleSelection { if isSelected { self.selectedElements.add(asset) }else { self.selectedElements.remove(asset) } if self.maximumNumberOfSelection > 1 { let title = "完成(\(self.selectedElements.count)/\(maximumNumberOfSelection))" let size = String.commonSize(with: title, fontNum: 15.0, size: CGSize(width: CGFloat(MAXFLOAT), height: 17.0)) m_rightNaviBtn?.frame = CGRect(x: 0, y: 0, width: size.width, height: 25) m_rightNaviBtn?.setTitle(title, for: .normal) } }else { self.selectedElements.add(asset) self.dissmiss() DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(0.1) * NSEC_PER_SEC), execute: { }) } } func showBigImageWith(imageIndex: Int, pickerCell: MultiPickerCell) { guard let indexPath = self.aTableView?.indexPath(for: pickerCell) else {return} let numberOfAssetsInRow = Int(self.view.bounds.size.width / self.imageSize.width) let assetIndex = indexPath.row * numberOfAssetsInRow + imageIndex self.view .addSubview(self.bigImgScroll) m_currentPage = assetIndex self.bigImgScroll.startWith(imageArray: self.elements, currentIndex: assetIndex) //顶视图 if m_topView == nil { m_topView = UIView.init(frame: CGRect(x: 0, y: 0, width: kECScreenWidth, height: 64)) m_topView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) self.bigImgScroll.addSubview(m_topView!) //时间Lable if (m_labDate == nil) { m_labDate = UILabel(frame: CGRect(x: (self.view.frame.size.width - LabDateWidth) / 2, y: self.view.frame.origin.y + 20 + 5, width: LabDateWidth, height: LabDateHeigth)) m_labDate?.font = UIFont.systemFont(ofSize: 18.0) m_labDate?.textAlignment = NSTextAlignment.center m_labDate?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0) m_labDate?.layer.cornerRadius = (m_labDate?.frame.height ?? 0.0) / 2.0 m_labDate?.layer.masksToBounds = true m_labDate?.textColor = UIColor.white m_labDate?.text = "图片预览" m_topView?.addSubview(m_labDate!) } //返回按钮 if (m_backBtn == nil) { m_backBtn = UIButton.init(type: .custom) m_backBtn?.frame = CGRect(x: 8, y: self.view.frame.origin.y + 20 + 5, width: LabBackbuttonWidth, height: LabBackbuttonHeight) m_backBtn?.titleLabel?.textAlignment = NSTextAlignment.center m_backBtn?.setImage(UIImage.init(named: "btn_navi_return_title_white"), for: .normal) m_backBtn?.imageEdgeInsets = UIEdgeInsetsMake((LabBackbuttonHeight - 14) / 2, (LabBackbuttonWidth - 45) / 2, (LabBackbuttonHeight - 14) / 2, (LabBackbuttonWidth - 45) / 2) m_backBtn?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0) m_backBtn?.layer.cornerRadius = (m_backBtn?.frame.height ?? 0.0) / 2.0 m_backBtn?.layer.masksToBounds = true m_backBtn?.addTarget(self, action: #selector(onBackTouch(sender:)), for: .touchUpInside) m_topView?.addSubview(m_backBtn!) } m_completeBtn = UIButton.init(type: .custom) m_completeBtn?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0) if self.maximumNumberOfSelection > 1 { let title = "完成(\(self.selectedElements.count)/\(maximumNumberOfSelection))" let size = String.commonSize(with: title, fontNum: 15.0, size: CGSize(width: CGFloat(MAXFLOAT), height: 17.0)) m_completeBtn?.frame = CGRect(x: self.view.frame.size.width - size.width - 8, y: self.view.frame.origin.y + 20 + 5, width: size.width, height: MorebuttonHeigth) m_completeBtn?.setTitle(title, for: .normal) }else { m_completeBtn?.frame = CGRect(x: self.view.frame.size.width - MorebuttonWidth - 8, y: self.view.frame.origin.y + 20 + 5, width: MorebuttonWidth, height: MorebuttonHeigth) m_completeBtn?.setTitle("完成", for: .normal) } m_completeBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 14) m_completeBtn?.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10) m_completeBtn?.addTarget(self, action: #selector(onCompleteBtnClick(sender:)), for: .touchUpInside) m_topView?.addSubview(m_completeBtn!) } //底视图 if m_bottomView == nil { m_bottomView = UIView.init(frame: CGRect(x: 0, y: bigImgScroll.frame.size.height - 49, width: bigImgScroll.frame.size.width, height: 49)) bigImgScroll.addSubview(m_bottomView!) m_bottomView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) let bottomLine = UIView.init(frame: CGRect(x: 0, y: 0, width: kECScreenWidth, height: 0.01)) bottomLine.backgroundColor = UIColor.init(white: 0, alpha: 0.5) bottomLine.alpha = 0.2 m_bottomView?.addSubview(bottomLine) //Overlay Image View if self.allowMutipleSelection { m_overlayImageView = UIButton.init(type: .custom) m_overlayImageView?.frame = CGRect(x: (m_bottomView?.frame.size.width ?? 0.0) - 35.0, y: ((m_bottomView?.frame.size.height ?? 0.0) - 25.0) / 2.0, width: 25, height: 25) m_overlayImageView?.contentMode = .scaleAspectFill m_overlayImageView?.layer.cornerRadius = 12.5 m_overlayImageView?.clipsToBounds = true m_overlayImageView?.backgroundColor = UIColor.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.5) m_overlayImageView?.setBackgroundImage(UIImage.init(named: "photopicker_nor.png"), for: .normal) m_overlayImageView?.setBackgroundImage(UIImage.init(named: "photopicker_sel.png"), for: .selected) m_overlayImageView?.autoresizingMask = kECAutoResizingMask m_overlayImageView?.clipsToBounds = true m_overlayImageView?.addTarget(self, action: #selector(onSelectedClick(sender:)), for: .touchUpInside) m_bottomView?.addSubview(m_overlayImageView!) } //页码显示label m_labBigImageInfo = UILabel.init(frame: CGRect(x: (self.view.frame.size.width - LabBigImageInfoWidth) / 2.0, y: self.view.frame.size.height - LabBigImageInfoHeight - 8, width: LabBigImageInfoWidth, height: LabBigImageInfoHeight)) m_labBigImageInfo?.font = UIFont.systemFont(ofSize: 18.0) m_labBigImageInfo?.textAlignment = NSTextAlignment.center m_labBigImageInfo?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) m_labBigImageInfo?.layer.cornerRadius = (m_labBigImageInfo?.frame.size.height ?? 0.0) / 2.0 m_labBigImageInfo?.layer.masksToBounds = true m_labBigImageInfo?.textColor = UIColor.white bigImgScroll.addSubview(m_labBigImageInfo!) } if self.selectedElements.contains(self.elements[assetIndex]) { m_overlayImageView?.isSelected = true }else { m_overlayImageView?.isSelected = false } m_labBigImageInfo?.text = "\(assetIndex + 1)/\(self.elements.count)" //添加动画效果 bigImgScroll.frame = CGRect(x: kECScreenWidth, y: 0, width: bigImgScroll.frame.size.width, height: bigImgScroll.frame.size.height) bigImgScroll.alpha = 0.0 //放大(全屏显示)ShowImage的动画 UIView.transition(with: bigImgScroll, duration: 0.35, options: .curveEaseInOut, animations: { self.bigImgScroll.frame = CGRect(x: 0, y: 0, width: self.bigImgScroll.frame.size.width, height: self.bigImgScroll.frame.size.height) self.bigImgScroll.alpha = 1.0 self.navigationController?.navigationBar.isHidden = true UIApplication.shared.isStatusBarHidden = true }) { (finish) in } //不支持多选的情况(通过长按来调用的查看大图的情况) if self.allowMutipleSelection == false { self.selectedElements.removeAllObjects() self.selectedElements.add(self.elements[assetIndex]) } } //MARK: - HWScrollViewDelegate func scrollToNextStateWithIndex(leftIndex: Int, middleIndex: Int, rightIndex: Int) { if m_currentPage != middleIndex { m_currentPage = middleIndex m_labBigImageInfo?.text = "\(middleIndex + 1)/\(self.elements.count)" let asset = self.elements[middleIndex] if self.allowMutipleSelection { if self.selectedElements.contains(asset) { m_overlayImageView?.isSelected = true }else { m_overlayImageView?.isSelected = false } } else { self.selectedElements.removeAllObjects() self.selectedElements.add(asset) } } } func endHiddenAnimation(scrollView: HWScrollView, isHide: Bool) { if m_topView?.alpha == 1.0 { UIView.animate(withDuration: 0.1, animations: { self.m_topView?.alpha = 0.0 self.m_bottomView?.alpha = 0.0 self.m_labBigImageInfo?.alpha = 0.0 }) }else { self.m_topView?.alpha = 1.0 self.m_bottomView?.alpha = 1.0 self.m_labBigImageInfo?.alpha = 1.0 } } }
mit
530083354c6a09315d68c957ef864b0f
40.141096
187
0.533713
5.053508
false
false
false
false
danielgindi/ios-charts
ChartsDemo-iOS/Swift/Formatters/DayAxisValueFormatter.swift
2
3114
// // DayAxisValueFormatter.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import Foundation import Charts public class DayAxisValueFormatter: NSObject, AxisValueFormatter { weak var chart: BarLineChartViewBase? let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] init(chart: BarLineChartViewBase) { self.chart = chart } public func stringForValue(_ value: Double, axis: AxisBase?) -> String { let days = Int(value) let year = determineYear(forDays: days) let month = determineMonth(forDayOfYear: days) let monthName = months[month % months.count] let yearName = "\(year)" if let chart = chart, chart.visibleXRange > 30 * 6 { return monthName + yearName } else { let dayOfMonth = determineDayOfMonth(forDays: days, month: month + 12 * (year - 2016)) var appendix: String switch dayOfMonth { case 1, 21, 31: appendix = "st" case 2, 22: appendix = "nd" case 3, 23: appendix = "rd" default: appendix = "th" } return dayOfMonth == 0 ? "" : String(format: "%d\(appendix) \(monthName)", dayOfMonth) } } private func days(forMonth month: Int, year: Int) -> Int { // month is 0-based switch month { case 1: var is29Feb = false if year < 1582 { is29Feb = (year < 1 ? year + 1 : year) % 4 == 0 } else if year > 1582 { is29Feb = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) } return is29Feb ? 29 : 28 case 3, 5, 8, 10: return 30 default: return 31 } } private func determineMonth(forDayOfYear dayOfYear: Int) -> Int { var month = -1 var days = 0 while days < dayOfYear { month += 1 if month >= 12 { month = 0 } let year = determineYear(forDays: days) days += self.days(forMonth: month, year: year) } return max(month, 0) } private func determineDayOfMonth(forDays days: Int, month: Int) -> Int { var count = 0 var daysForMonth = 0 while count < month { let year = determineYear(forDays: days) daysForMonth += self.days(forMonth: count % 12, year: year) count += 1 } return days - daysForMonth } private func determineYear(forDays days: Int) -> Int { switch days { case ...366: return 2016 case 367...730: return 2017 case 731...1094: return 2018 case 1095...1458: return 2019 default: return 2020 } } }
apache-2.0
489bccf033d8fa69ae2d15c3d72183a1
27.559633
98
0.489239
4.396893
false
false
false
false
VladasZ/iOSTools
Sources/iOS/Form/SupportedFormSources.swift
1
2963
// // SupportedFormSources.swift // SwiftTools // // Created by Vladas Zakrevskis on 4/24/17. // Copyright © 2017 VladasZ. All rights reserved. // #if os(iOS) import UIKit public protocol FormSource { var value: String? { get set } var intValue: Int? { get set } var isNumeric: Bool { get set } var isPassword: Bool { get set } var isEmail: Bool { get set } func resetInputType() } public extension FormSource { var value: String? { get { return nil } set { } } var intValue: Int? { get { return nil } set { } } var isNumeric: Bool { get { return false } set { } } var isPassword: Bool { get { return false } set { } } var isEmail: Bool { get { return false } set { } } func resetInputType() { } } extension UITextField : FormSource { public var isNumeric: Bool { get { return keyboardType == .numberPad } set { if newValue { keyboardType = .numberPad } else { keyboardType = .default } } } public var isPassword: Bool { get { return isSecureTextEntry == true } set { if newValue { isSecureTextEntry = true } else { isSecureTextEntry = false } } } public var isEmail: Bool { get { return keyboardType == .emailAddress } set { if newValue { keyboardType = .emailAddress } else { keyboardType = .default } } } public var value: String? { get { return text } set { } } public var intValue: Int? { get { return Int(text ?? "") } set { text = String(describing: newValue) } } public func resetInputType() { keyboardType = .default isSecureTextEntry = false } } extension UITextView : FormSource { public var isNumeric: Bool { get { return keyboardType == .numberPad } set { if newValue { keyboardType = .numberPad } else { keyboardType = .default } } } public var isPassword: Bool { get { return isSecureTextEntry == true } set { if newValue { isSecureTextEntry = true } else { isSecureTextEntry = false } } } public var isEmail: Bool { get { return keyboardType == .emailAddress } set { if newValue { keyboardType = .emailAddress } else { keyboardType = .default } } } public var value: String? { get { return text } set { text = newValue } } public var intValue: Int? { get { return Int(text ?? "") } set { text = String(describing: newValue) } } public func resetInputType() { keyboardType = .default isSecureTextEntry = false } } #endif
mit
d0cfe195bf1d8b44e3f08ba29cbf5f31
23.890756
60
0.523295
4.542945
false
false
false
false
volodg/iAsync.async
Lib/React/AsyncStream+Additions.swift
1
2693
// // AsyncStream+Additions.swift // iAsync_async // // Created by Gorbenko Vladimir on 07/02/16. // Copyright (c) 2016 EmbeddedSources. All rights reserved. // import Foundation import iAsync_utils import iAsync_reactiveKit import ReactiveKit public func asyncToStream<Value, Error: ErrorType>(loader: AsyncTypes<Value, Error>.Async) -> AsyncStream<Value, AnyObject, Error> { typealias Event = AsyncEvent<Value, AnyObject, Error> let result = AsyncStream { (observer: Event -> ()) -> DisposableType? in let handler = loader(progressCallback: { (progressInfo) -> () in observer(.Next(progressInfo)) }, finishCallback: { (result) -> Void in switch result { case .Success(let value): observer(.Success(value)) case .Failure(let error): observer(.Failure(error)) } }) return BlockDisposable({ () -> () in handler(task: .Cancel) }) } return result } public extension AsyncStreamType where Self.Next == AnyObject, Self.Error == NSError { public func toAsync() -> AsyncTypes<Self.Value, Self.Error>.Async { return { ( progressCallback: AsyncProgressCallback?, finishCallback : AsyncTypes<Self.Value, Self.Error>.DidFinishAsyncCallback?) -> AsyncHandler in var progressCallbackHolder = progressCallback var finishCallbackHolder = finishCallback let finishOnce = { (result: Result<Self.Value, Self.Error>) -> Void in progressCallbackHolder = nil if let finishCallback = finishCallbackHolder { finishCallbackHolder = nil finishCallback(result: result) } } let dispose = self.observe(on: nil, observer: { event -> () in if finishCallbackHolder == nil { return } switch event { case .Success(let value): finishOnce(.Success(value)) case .Failure(let error): finishOnce(.Failure(error)) case .Next(let next): progressCallbackHolder?(progressInfo: next) } }) return { (task: AsyncHandlerTask) -> Void in switch task { case .Cancel: dispose.dispose() finishOnce(.Failure(AsyncInterruptedError())) case .UnSubscribe: progressCallbackHolder = nil finishCallbackHolder = nil } } } } }
mit
6030b3663583460ae764853149421cb2
28.271739
132
0.55143
5.229126
false
false
false
false
celian-m/localizator
iOSComponents/LocalizedComponents.swift
1
9216
// // LocalizedLabel.swift // DirectAssurance // // Created by Célian MOUTAFIS on 17/03/2016. // Copyright © 2016 MyStudioFactory. All rights reserved. // import UIKit let _underline_height : CGFloat = 4 /** Shorthand for NSLocalizedStirng*/ func l( string : String) -> String { var locale = NSLocale.currentLocale().localeIdentifier if (locale.characters.count > 2) { locale = locale.substringToIndex(locale.startIndex.advancedBy(2)) return Localizator.localizedString(string, locale: locale) } return Localizator.localizedString(string) } prefix func ~ (string: String) -> String { return l(string) } @objc public class LocalizedLabel: UILabel { @IBInspectable public var localizedText : String = "" { didSet { self.reload() } } @IBInspectable public var uppercased : Bool = false { didSet { self.reload() } } func reload(){ let str = self.uppercased ? l(self.localizedText).uppercaseString : l(self.localizedText) if self.justified && self.text != nil{ let style = NSMutableParagraphStyle() style.alignment = NSTextAlignment.Justified style.firstLineHeadIndent = 0.00001 let attributed = NSAttributedString(string: str, attributes: [NSParagraphStyleAttributeName : style, NSFontAttributeName : self.font, NSForegroundColorAttributeName : self.textColor]) self.attributedText = attributed }else{ self.text = str; } } @IBInspectable public var underlined : Bool = false @IBInspectable public var justified : Bool = false { didSet { self.reload() } } override public func drawRect(rect: CGRect) { if self.underlined { let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, self.textColor.CGColor) CGContextSetLineWidth(context, _underline_height) CGContextMoveToPoint(context, self.frame.size.width / 2 - 12.5, self.frame.size.height) CGContextAddLineToPoint(context, self.frame.size.width / 2 + 12.5, self.frame.size.height) CGContextStrokePath(context) } super.drawRect(rect) } } public class LocalizedButton: UIButton { @IBInspectable public var numberOfLines : NSInteger = 0 @IBInspectable public var underlined : Bool = false @IBInspectable public var bordered : Bool = false { didSet { self.reload() } } @IBInspectable public var cornered : Bool = false { didSet { self.reload() } } @IBInspectable public var uppercased : Bool = false { didSet { self.reload() } } override public func drawRect(rect: CGRect) { if self.underlined { let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, self.titleColorForState(self.state)?.CGColor) CGContextSetLineWidth(context, _underline_height) CGContextMoveToPoint(context, self.frame.size.width / 2 - 12.5, self.frame.size.height) CGContextAddLineToPoint(context, self.frame.size.width / 2 + 12.5, self.frame.size.height) CGContextStrokePath(context) } super.drawRect(rect) } @IBInspectable public var localizedText : String = "" { didSet { self.reload() self.titleLabel!.numberOfLines = self.numberOfLines self.titleLabel!.textAlignment = .Center self.imageView?.contentMode = .ScaleAspectFit } } // private var _rightImage : String = "" @IBInspectable public var rightImage : String = "" { didSet { self.reload() } } private var rightImageViewContainer : UIView? private var rightImageView : UIView? func reload(){ let str = self.uppercased ? l(self.localizedText).uppercaseString : l(self.localizedText) self.setTitle(str, forState: .Normal) self.setTitle(str, forState: .Disabled) if (self.imageForState(.Normal) != nil) { self.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0); self.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0); } self.layer.cornerRadius = self.cornered ? self.frame.size.height / 2 : 0 self.layer.masksToBounds = true if (rightImageViewContainer != nil){ rightImageViewContainer?.removeFromSuperview() rightImageViewContainer = nil } if rightImage.characters.count > 0 { let titleFrame = self.titleLabel!.frame var size = self.frame.size size.width = (size.width - titleFrame.origin.x - titleFrame.size.width) rightImageViewContainer = UIView(frame: CGRectMake((titleFrame.origin.x + titleFrame.size.width), 0, size.width, size.height)) self.addSubview(rightImageViewContainer!) rightImageViewContainer?.contentMode = .Center rightImageViewContainer?.backgroundColor = UIColor.whiteColor() rightImageViewContainer?.translatesAutoresizingMaskIntoConstraints = false let ref : CGFloat = 25 let trailing = NSLayoutConstraint(item: rightImageViewContainer!, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: -5) let width = NSLayoutConstraint(item: rightImageViewContainer!, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: ref) let heigth = NSLayoutConstraint(item: rightImageViewContainer!, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: ref) let centerY = NSLayoutConstraint(item: rightImageViewContainer!, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0) self.addConstraints([trailing, width, heigth, centerY]) rightImageViewContainer?.userInteractionEnabled = false } if self.bordered { self.layer.borderColor = self.titleColorForState(.Normal)?.CGColor self.layer.borderWidth = 1 } } public override func layoutSubviews() { super.layoutSubviews() if (rightImageViewContainer != nil){ rightImageViewContainer!.layer.cornerRadius = rightImageViewContainer!.frame.size.height / 2 rightImageView?.removeFromSuperview() rightImageView = nil let margin : CGFloat = 3 let imageView = UIImageView(frame: CGRectMake(margin, margin, rightImageViewContainer!.frame.size.width - 2*margin, rightImageViewContainer!.frame.size.height - 2*margin)) imageView.image = UIImage(named: rightImage)?.imageWithRenderingMode(.AlwaysTemplate) imageView.tintColor = self.tintColor imageView.contentMode = .ScaleAspectFit rightImageViewContainer?.addSubview(imageView) rightImageView = imageView imageView.userInteractionEnabled = false } } private var _enabled:Bool = true override public var enabled : Bool { get { return _enabled } set { if newValue { self.alpha = 1 }else{ self.alpha = 0.6 } _enabled = newValue super.enabled = newValue } } } public class LocalizedTextField: UITextField { @IBInspectable public var localizedPlaceholder : String = "" { didSet { self.reload() } } func reload(){ let str = l(self.localizedPlaceholder) self.placeholder = str } func textFieldWantNextResponder(sender : AnyObject?){ let selector = #selector(textFieldWantNextResponder(_:)) if self.delegate != nil && self.delegate!.respondsToSelector(selector) { self.delegate!.performSelector(selector, withObject: sender!) } } func textFieldWantPreviousResponder(sender : AnyObject?){ let selector = #selector(textFieldWantPreviousResponder(_:)) if self.delegate != nil && self.delegate!.respondsToSelector(selector) { self.delegate!.performSelector(selector, withObject: sender!) } } } public class LocalizedBarButtonItem: UIBarButtonItem { @IBInspectable public var localizedTitle : String = "" { didSet { self.reload() } } func reload(){ let str = l(self.localizedTitle) self.title = str self.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : kRegularFontOfSize(14) ], forState: .Normal) } }
apache-2.0
cdd91258c1ef6b0198fb51fbea2d5fcd
33.509363
202
0.617864
5.232254
false
false
false
false
lucasmpaim/RMImagePicker
Source/RMImagePickerController.swift
1
2302
// // RMImagePickerController.swift // RMImagePicker // // Created by Riccardo Massari on 19/01/15. // Copyright (c) 2015 Riccardo Massari. All rights reserved. // import UIKit import Photos @objc public protocol RMImagePickerControllerDelegate: UINavigationControllerDelegate { func rmImagePickerController(picker: RMImagePickerController, didFinishPickingAssets assets: [PHAsset]) func rmImagePickerControllerDidCancel(picker: RMImagePickerController) optional func rmWarnMaximumOfImages(picker: UICollectionViewController) } public class RMImagePickerController: UINavigationController, RMAssetSelectionDelegate { public weak var pickerDelegate: RMImagePickerControllerDelegate? public var maxImagesToPick: Int = 0 var albumController: RMAlbumPickerController? var maxImages: Int { return maxImagesToPick } override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) } public convenience init() { var albumController = RMAlbumPickerController() self.init(rootViewController: albumController) albumController.assetsParent = self } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Actions func cancelImagePicker() { if let d = self.pickerDelegate { d.rmImagePickerControllerDidCancel(self) } } // MARK: - Asset Selection Delegate func selectedAssets(assets: [PHAsset]) { if let d = self.pickerDelegate { d.rmImagePickerController(self, didFinishPickingAssets: assets) } else { self.popToRootViewControllerAnimated(false) } } func showMessage(picker: UICollectionViewController){ self.pickerDelegate?.rmWarnMaximumOfImages?(picker) } }
mit
745503d18b761006e3d8b2df6852c4ec
29.693333
107
0.712858
5.161435
false
false
false
false
FuzzyHobbit/bitcoin-swift
BitcoinSwift/MessageParser.swift
1
4829
// // MessageParser.swift // BitcoinSwift // // Created by Kevin Greene on 9/13/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import Foundation public protocol MessageParserDelegate: class { func didParseMessage(message: Message) } /// Parses Messages from raw data received from the wire. Handles framing and ensuring message /// data integrety. When a message is successfully parsed, the delegate is notified. public class MessageParser { public weak var delegate: MessageParserDelegate? = nil private let network: Message.Network // We receive a message in chunks. When we have received only part of a message, but not the // whole thing, receivedBytes stores the pending bytes, and adds onto it the next time // we receive a NSStreamEvent.HasBytesAvailable event. private var receivedBytes: [UInt8] = [] // The header for the message we are about to receive. This is non-nil when we have received // enough bytes to parse the header, but haven't received the full message yet. private var receivedHeader: Message.Header? = nil public init(network: Message.Network) { self.network = network } /// Consumes the data in bytes by parsing it into Messages, or discarding invalid data. /// Doesn't return until all data in receivedBytes has been consumed, or until more data must be /// received to parse a valid message. public func parseBytes(bytes: [UInt8]) { receivedBytes += bytes while true { if receivedHeader == nil { let headerStartIndex = headerStartIndexInBytes(receivedBytes) if headerStartIndex < 0 { // We did not find the message start, so we must wait for more bytes. // Throw away the bytes we have since we couldn't figure out how to handle them. // We might have all but the last byte of the networkMagicBytes for the next message, // so keep the last 3 bytes. let end = receivedBytes.count - network.magicBytes.count + 1 if end > 0 { receivedBytes.removeRange(0..<end) } return } // Remove the bytes before startIndex since we don't know what they are. receivedBytes.removeRange(0..<headerStartIndex) if receivedBytes.count < Message.Header.length { // We're expecting a header, but there aren't enough bytes yet to parse one. // Wait for more bytes to be received. return } let stream = NSInputStream(data: NSData(bytes: receivedBytes, length: receivedBytes.count)) stream.open() receivedHeader = Message.Header.fromBitcoinStream(stream) stream.close() if receivedHeader == nil { // Failed to parse the header for some reason. It's possible that the networkMagicBytes // coincidentally appeared in the byte data, or the header was invalid for some reason. // Strip the networkMagicBytes so we can advance and try to parse again. receivedBytes.removeRange(0..<network.magicBytes.count) continue } // receivedHeader is guaranteed to be non-nil at this point. // We successfully parsed the header from receivedBytes, so remove those bytes. receivedBytes.removeRange(0..<Message.Header.length) } // NOTE: payloadLength can be 0 for some message types, e.g. VersionAck. let payloadLength = Int(receivedHeader!.payloadLength) // TODO: Need to figure out a maximum length to allow here, or somebody could DOS us by // providing a huge value for payloadLength. if receivedBytes.count < payloadLength { // Haven't received the whole message yet. Wait for more bytes. return } let payloadData = NSData(bytes: receivedBytes, length: payloadLength) let message = Message(header: receivedHeader!, payloadData: payloadData) if message.isChecksumValid() { delegate?.didParseMessage(message) } else { Logger.warn("Dropping \(message.command.rawValue) message with invalid checksum") } receivedBytes.removeRange(0..<payloadLength) receivedHeader = nil } } // MARK: - Private Methods // Returns -1 if the header start (the position of network.magicBytes) was not found. // Otherwise returns the position where the message header begins. private func headerStartIndexInBytes(bytes: [UInt8]) -> Int { let networkMagicBytes = network.magicBytes if bytes.count < networkMagicBytes.count { return -1 } for i in 0...(bytes.count - networkMagicBytes.count) { var found = true for j in 0..<networkMagicBytes.count { if bytes[i + j] != networkMagicBytes[j] { found = false break } } if found { return i } } return -1 } }
apache-2.0
ddba3da0b7e6ab0ae87593920f9d4073
39.241667
99
0.673224
4.638809
false
false
false
false
iOSDevLog/InkChat
InkChat/Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallScale.swift
1
1744
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallScale: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color) circle.frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallScale { var animation: CAAnimationGroup { let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } var scaleAnimation: CABasicAnimation { let scaleAnimation = CABasicAnimation(keyPath:"transform.scale") scaleAnimation.duration = duration scaleAnimation.fromValue = 0 scaleAnimation.toValue = 1 return scaleAnimation } var opacityAnimation: CABasicAnimation { let opacityAnimation = CABasicAnimation(keyPath:"opacity") opacityAnimation.duration = duration opacityAnimation.fromValue = 1 opacityAnimation.toValue = 0 return opacityAnimation } }
apache-2.0
b88521b7b6b6902db1e40064da68992b
29.596491
95
0.716743
5.20597
false
false
false
false
moltin/ios-sdk
Sources/SDK/Requests/FlowRequest.swift
1
3658
// // FlowRequest.swift // moltin // // Created by Craig Tweedy on 20/03/2018. // import Foundation /// An entry point to make API calls relating to `Flow` and `Entry` objects public class FlowRequest: MoltinRequest { /// The API endpoint for this resource. public var endpoint: String = "/flows" /// The default collection handler type for `Flow` requests public typealias DefaultFlowCollectionRequestHandler = CollectionRequestHandler<[Flow]> /// The default object handler type for `Flow` requests public typealias DefaultFlowObjectRequestHandler = ObjectRequestHandler<Flow> /// The default collection handler type for `Entry` requests public typealias DefaultEntryCollectionRequestHandler = CollectionRequestHandler<[Entry]> /// The default object handler type for `Entry` requests public typealias DefaultEntryObjectRequestHandler = ObjectRequestHandler<Entry> /** Return all instances of type flow - parameters: - completionHandler: The handler to be called on success or failure */ public func all(completionHandler: @escaping DefaultFlowCollectionRequestHandler) -> MoltinRequest { return super.list(withPath: "\(self.endpoint)", completionHandler: completionHandler) } /** Return get an instance of flow by `id` - parameters: - forID: The ID of the object - completionHandler: The handler to be called on success or failure */ public func get(forID id: String, completionHandler: @escaping DefaultFlowObjectRequestHandler) -> MoltinRequest { return super.get(withPath: "\(self.endpoint)/\(id)", completionHandler: completionHandler) } /** Return all entries for the flow with the slug `slug` - parameters: - forSlug: The slug of the flow - completionHandler: The handler to be called on success or failure */ public func entries(forSlug slug: String, completionHandler: @escaping DefaultEntryCollectionRequestHandler) -> MoltinRequest { return super.get(withPath: "\(self.endpoint)/\(slug)/entries", completionHandler: completionHandler) } /** Return all custom entries for the flow with the slug `slug` - parameters: - forSlug: The slug of the flow - completionHandler: The handler to be called on success or failure */ public func entries<T>(forSlug slug: String, completionHandler: @escaping CollectionRequestHandler<T>) -> MoltinRequest { return super.get(withPath: "\(self.endpoint)/\(slug)", completionHandler: completionHandler) } /** Return an entry for the flow with the slug `slug` and an ID of `id` - parameters: - forSlug: The slug of the flow - forID: The ID of the entry - completionHandler: The handler to be called on success or failure */ public func entry(forSlug slug: String, forID id: String, completionHandler: @escaping DefaultEntryObjectRequestHandler) -> MoltinRequest { return super.get(withPath: "\(self.endpoint)/\(slug)/entries/\(id)", completionHandler: completionHandler) } /** Return a custom entry for the flow with the slug `slug` and an ID of `id` - parameters: - forSlug: The slug of the flow - forID: The ID of the entry - completionHandler: The handler to be called on success or failure */ public func entry<T: Codable>(forSlug slug: String, forID id: String, completionHandler: @escaping ObjectRequestHandler<T>) -> MoltinRequest { return super.get(withPath: "\(self.endpoint)/\(slug)/entries/\(id)", completionHandler: completionHandler) } }
mit
9099db5abc40b78715f057aff23f0f4a
38.76087
146
0.697102
4.832232
false
false
false
false
AimobierCocoaPods/OddityUI
Classes/OddityModal/Classes/Swaggers/ORM/About.swift
1
1184
// // About.swift // Journalism // // Created by Mister on 16/6/6. // Copyright © 2016年 aimobier. All rights reserved. // import RealmSwift /// 频道的数据模型 open class About: Object { open dynamic var nid = 0 // 相关新闻地址 open dynamic var url = "" // 相关新闻地址 open dynamic var title = "" // 相关新闻标题 open dynamic var from = "" // 新闻来源 open dynamic var rank = 0 //点赞数 open dynamic var pname = "" // 用户是否能对该条评论点赞,0、1 对应 可点、不可点 open dynamic var ptime = "" // 评论正文 open dynamic var img:String? = nil //创建时间 open dynamic var abs = "" //创建该评论的用户名 open dynamic var ptimes = Date() //创建时间 open dynamic var htmlTitle = "" // 相关新闻标题 open dynamic var isread = 0 // 是否阅读 override open static func primaryKey() -> String? { return "url" } } public extension About{ public func isRead(){ let realm = try! Realm() try! realm.write { self.isread = 1 } } }
mit
f354e31db71c38f4ebb41df63bb2df3c
20.510638
61
0.556874
3.623656
false
false
false
false
rsahara/dopamine
Dopamine/Optimizer/AdamOptimizer.swift
1
1805
// // AdamOptimizer.swift // Dopamine // // Created by Runo Sahara on 2017/05/02. // Copyright © 2017 Runo Sahara. All rights reserved. // // experimental #if false import Foundation // TODO: generalize/refactor public class AdamOptimizer: Optimizer { public init(learnRate: Float = 0.001, beta1: Float = 0.9, beta2: Float = 0.999) { _learnRate = learnRate _beta1 = beta1 _beta2 = beta2 _iterationNum = 0 _step = 0.0 } public func initialize(context: inout AnyObject?) { let m = FloatBuffer(1, 1024 * 1024) let v = FloatBuffer(1, 1024 * 1024) context = [m, v] as AnyObject } public func release(context: inout AnyObject?) { context = nil } public func updateIteration() { _iterationNum += 1 _step = _learnRate * sqrtf(1.0 - powf(_beta2, Float(_iterationNum))) / (1.0 - powf(_beta1, Float(_iterationNum))) // TODO: optimize } public func optimize(input: FloatBuffer, gradient: FloatBuffer, context: inout AnyObject?) { // TODO: optimize let contextArray = context as! Array<FloatBuffer> let m: FloatBuffer = contextArray[0] let v: FloatBuffer = contextArray[1] if (_iterationNum == 1) { m.resetLazy(like: input) v.resetLazy(like: input) m.fillZero() v.fillZero() } let temp = FloatBuffer(like: gradient) temp.copy(gradient) temp.sub(m) temp.mul(1.0 - _beta1) m.add(temp) temp.copy(gradient) temp.mul(gradient) temp.sub(v) temp.mul(1.0 - _beta2) v.add(temp) let temp2 = FloatBuffer(like: v) temp2.copy(v) temp2.sqrt() temp2.add(0.0000001) temp.copy(m) temp.mul(_step) temp.div(temp2) input.sub(temp) } // MARK: - Hidden private var _iterationNum: Int private var _step: Float private let _learnRate: Float private let _beta1: Float private let _beta2: Float } #endif
mit
d5997fa6b4b46959b691681e01a4127f
19.5
133
0.661308
2.832025
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderShowMenuAction.swift
1
12183
import UIKit /// Encapsulates a command to create and handle the extended menu for each post in Reader final class ReaderShowMenuAction { private let isLoggedIn: Bool init(loggedIn: Bool) { isLoggedIn = loggedIn } func execute(with post: ReaderPost, context: NSManagedObjectContext, siteTopic: ReaderSiteTopic? = nil, readerTopic: ReaderAbstractTopic? = nil, anchor: UIView, vc: UIViewController, source: ReaderPostMenuSource, followCommentsService: FollowCommentsService ) { // Create the action sheet let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.addCancelActionWithTitle(ReaderPostMenuButtonTitles.cancel, handler: nil) // Block button if shouldShowBlockSiteMenuItem(readerTopic: readerTopic, post: post) { alertController.addActionWithTitle(ReaderPostMenuButtonTitles.blockSite, style: .destructive, handler: { (action: UIAlertAction) in if let post: ReaderPost = ReaderActionHelpers.existingObject(for: post.objectID, in: context) { ReaderBlockSiteAction(asBlocked: true).execute(with: post, context: context, completion: { ReaderHelpers.dispatchSiteBlockedMessage(post: post, success: true) // Notify Reader Cards Stream so the post card is updated. NotificationCenter.default.post(name: .ReaderSiteBlocked, object: nil, userInfo: [ReaderNotificationKeys.post: post]) }, failure: { _ in ReaderHelpers.dispatchSiteBlockedMessage(post: post, success: false) }) } }) } // Report button if shouldShowReportPostMenuItem(readerTopic: readerTopic, post: post) { alertController.addActionWithTitle(ReaderPostMenuButtonTitles.reportPost, style: .default, handler: { (action: UIAlertAction) in if let post: ReaderPost = ReaderActionHelpers.existingObject(for: post.objectID, in: context) { ReaderReportPostAction().execute(with: post, context: context, origin: vc) } }) } // Notification if let siteTopic = siteTopic, isLoggedIn, post.isFollowing { let isSubscribedForPostNotifications = siteTopic.isSubscribedForPostNotifications let buttonTitle = isSubscribedForPostNotifications ? ReaderPostMenuButtonTitles.unsubscribe : ReaderPostMenuButtonTitles.subscribe alertController.addActionWithTitle(buttonTitle, style: .default, handler: { (action: UIAlertAction) in if let topic: ReaderSiteTopic = ReaderActionHelpers.existingObject(for: siteTopic.objectID, in: context) { let subscribe = !topic.isSubscribedForPostNotifications ReaderSubscribingNotificationAction().execute(for: topic.siteID, context: context, subscribe: subscribe, completion: { ReaderHelpers.dispatchToggleNotificationMessage(topic: topic, success: true) }, failure: { _ in ReaderHelpers.dispatchToggleNotificationMessage(topic: topic, success: false) }) } }) } // Following if isLoggedIn { let buttonTitle = post.isFollowing ? ReaderPostMenuButtonTitles.unfollow : ReaderPostMenuButtonTitles.follow alertController.addActionWithTitle(buttonTitle, style: .default, handler: { (action: UIAlertAction) in if let post: ReaderPost = ReaderActionHelpers.existingObject(for: post.objectID, in: context) { ReaderFollowAction().execute(with: post, context: context, completion: { follow in ReaderHelpers.dispatchToggleFollowSiteMessage(post: post, follow: follow, success: true) (vc as? ReaderStreamViewController)?.updateStreamHeaderIfNeeded() }, failure: { follow, _ in ReaderHelpers.dispatchToggleFollowSiteMessage(post: post, follow: follow, success: false) }) } }) } // Seen if post.isSeenSupported { alertController.addActionWithTitle(post.isSeen ? ReaderPostMenuButtonTitles.markUnseen : ReaderPostMenuButtonTitles.markSeen, style: .default, handler: { (action: UIAlertAction) in let event: WPAnalyticsEvent = post.isSeen ? .readerPostMarkUnseen : .readerPostMarkSeen WPAnalytics.track(event, properties: ["source": source.description]) if let post: ReaderPost = ReaderActionHelpers.existingObject(for: post.objectID, in: context) { ReaderSeenAction().execute(with: post, context: context, completion: { ReaderHelpers.dispatchToggleSeenMessage(post: post, success: true) // Notify Reader Stream so the post card is updated. NotificationCenter.default.post(name: .ReaderPostSeenToggled, object: nil, userInfo: [ReaderNotificationKeys.post: post]) }, failure: { _ in ReaderHelpers.dispatchToggleSeenMessage(post: post, success: false) }) } }) } // Visit alertController.addActionWithTitle(ReaderPostMenuButtonTitles.visit, style: .default, handler: { (action: UIAlertAction) in ReaderVisitSiteAction().execute(with: post, context: context, origin: vc) }) // Share alertController.addActionWithTitle(ReaderPostMenuButtonTitles.share, style: .default, handler: { (action: UIAlertAction) in ReaderShareAction().execute(with: post, context: context, anchor: anchor, vc: vc) }) // Comment Subscription (Follow Comments by Email & Notifications) if post.canSubscribeComments { let buttonTitle = post.isSubscribedComments ? ReaderPostMenuButtonTitles.unFollowConversation : ReaderPostMenuButtonTitles.followConversation alertController.addActionWithTitle( buttonTitle, style: .default, handler: { (action: UIAlertAction) in if let post: ReaderPost = ReaderActionHelpers.existingObject(for: post.objectID, in: context) { Self.trackToggleCommentSubscription(isSubscribed: post.isSubscribedComments, post: post, sourceViewController: vc) ReaderSubscribeCommentsAction().execute( with: post, context: context, followCommentsService: followCommentsService, sourceViewController: vc) { (vc as? ReaderDetailViewController)?.updateFollowButtonState() } } }) } if WPDeviceIdentification.isiPad() { alertController.modalPresentationStyle = .popover vc.present(alertController, animated: true) if let presentationController = alertController.popoverPresentationController { presentationController.permittedArrowDirections = .any presentationController.sourceView = anchor presentationController.sourceRect = anchor.bounds } } else { vc.present(alertController, animated: true) } } private func shouldShowBlockSiteMenuItem(readerTopic: ReaderAbstractTopic?, post: ReaderPost) -> Bool { guard let topic = readerTopic, isLoggedIn else { return false } return ReaderHelpers.isTopicTag(topic) || ReaderHelpers.topicIsDiscover(topic) || ReaderHelpers.topicIsFreshlyPressed(topic) || (ReaderHelpers.topicIsFollowing(topic) && !post.isFollowing) } private func shouldShowReportPostMenuItem(readerTopic: ReaderAbstractTopic?, post: ReaderPost) -> Bool { return shouldShowBlockSiteMenuItem(readerTopic: readerTopic, post: post) } private static func trackToggleCommentSubscription(isSubscribed: Bool, post: ReaderPost, sourceViewController: UIViewController) { var properties = [String: Any]() properties[WPAppAnalyticsKeyFollowAction] = isSubscribed ? "followed" : "unfollowed" properties["notifications_enabled"] = isSubscribed properties[WPAppAnalyticsKeyBlogID] = post.siteID properties[WPAppAnalyticsKeySource] = Self.sourceForTrackingEvents(sourceViewController: sourceViewController) WPAnalytics.trackReader(.readerMoreToggleFollowConversation, properties: properties) } private static func sourceForTrackingEvents(sourceViewController: UIViewController) -> String { if sourceViewController is ReaderDetailViewController { return "reader_post_details_comments" } else if sourceViewController is ReaderStreamViewController { return "reader" } return "unknown" } }
gpl-2.0
5f80821fe6bbd4fdcb3c35e5f21ba6f9
59.014778
173
0.4874
7.388114
false
false
false
false
interstateone/Fresh
Fresh/Components/Main Window/MainWireframe.swift
1
2612
// // MainWireframe.swift // Fresh // // Created by Brandon Evans on 2015-12-29. // Copyright © 2015 Brandon Evans. All rights reserved. // class MainWireframe: NSObject { let service = SoundCloudService() let audioPlayerService = AudioPlayerService() func presentMainWindow() { windowController.showWindow(nil) presentLogin() } // MARK: Transitions func presentSoundList() { windowController.transitionToSoundList() } func presentLogin() { windowController.transitionToLogin() } func showNowPlaying() { windowController.revealNowPlayingView() } func hideNowPlaying() { windowController.hideNowPlayingView() } // MARK: Constructors lazy var windowController: MainWindowController = { let windowController = MainWindowController(windowNibName: "MainWindow") windowController.loginViewController = self.loginViewController let listViewController = SoundListViewController(nibName: "SoundListView", bundle: nil)! let listPresenter = SoundListPresenter(view: listViewController, service: self.service, audioPlayerService: self.audioPlayerService) listPresenter.view = listViewController listViewController.presenter = listPresenter listPresenter.selectedSound.addObserver(listViewController, listViewController.dynamicType.selectedSoundChanged) windowController.listViewController = listViewController let nowPlayingViewController = NowPlayingViewController(nibName: "FSHNowPlayingView", bundle: nil)! let nowPlayingPresenter = NowPlayingPresenter(view: nowPlayingViewController, service: self.service, audioPlayerService: self.audioPlayerService) nowPlayingPresenter.view = nowPlayingViewController nowPlayingViewController.presenter = nowPlayingPresenter listPresenter.selectedSound.addObserver(nowPlayingPresenter, nowPlayingPresenter.dynamicType.selectedSoundChanged) windowController.nowPlayingViewController = nowPlayingViewController let presenter = MainWindowPresenter(view: windowController, wireframe: self, service: self.service) self.service.account.addObserver(presenter, presenter.dynamicType.accountChanged) listPresenter.selectedSound.addObserver(presenter, presenter.dynamicType.selectedSoundChanged) windowController.presenter = presenter return windowController }() lazy var loginViewController: FSHLoginViewController = { return FSHLoginViewController(nibName: "FSHLoginView", bundle: nil)! }() }
mit
14095710e5b8f3283e64bfb3ba557201
37.411765
153
0.748372
5.763797
false
false
false
false
szpnygo/firefox-ios
Utils/FaviconFetcher.swift
5
5271
import Storage import Shared private let queue = dispatch_queue_create("FaviconFetcher", DISPATCH_QUEUE_CONCURRENT) class FaviconFetcherErrorType: ErrorType { let description: String init(description: String) { self.description = description } } /* A helper class to find the favicon associated with a url. This will load the page and parse any icons it finds out of it * If that fails, it will attempt to find a favicon.ico in the root host domain */ class FaviconFetcher : NSObject, NSXMLParserDelegate { static let ExpirationTime = NSTimeInterval(60*60*24*7) // Only check for icons once a week private var siteUrl: NSURL // The url we're looking for favicons for private var _favicons = [Favicon]() // An internal cache of favicons found for this url class func getForUrl(url: NSURL, profile: Profile) -> Deferred<Result<[Favicon]>> { let f = FaviconFetcher(url: url) return f.loadFavicons(profile) } private init(url: NSURL) { siteUrl = url } private func loadFavicons(profile: Profile) -> Deferred<Result<[Favicon]>> { let deferred = Deferred<Result<[Favicon]>>() dispatch_async(queue) { _ in if self._favicons.count == 0 { // Initially look for tags in the page self.loadFromDoc() } // If that didn't find anything, look for a favicon.ico for this host if self._favicons.count == 0 { self.loadFromHost() } var filledCount = 0 for (i, icon) in enumerate(self._favicons) { // For each icon we set of an async load of the data (in order to get the width/height. self.getFavicon(icon, profile: profile).upon { result in if let icon = result.successValue { self._favicons[i] = icon } filledCount++ // When they've all completed, we can fill the deferred with the results if filledCount == self._favicons.count { self._favicons.sort({ (a, b) -> Bool in return a.width > b.width }) deferred.fill(Result(success: self._favicons)) } } } } return deferred } // Loads favicon.ico on the host domain for this url private func loadFromHost() { if let url = NSURL(scheme: siteUrl.scheme!, host: siteUrl.host, path: "/favicon.ico") { let icon = Favicon(url: url.absoluteString!, type: IconType.Guess) _favicons.append(icon) } } // Loads and parses an html document and tries to find any known favicon-type tags for the page private func loadFromDoc() { var err: NSError? if let data = NSData(contentsOfURL: siteUrl), let element = RXMLElement(fromHTMLData: data) { element.iterate("head.meta") { meta in if let refresh = meta.attribute("http-equiv"), let content = meta.attribute("content"), let index = content.rangeOfString("URL="), let url = NSURL(string: content.substringFromIndex(advance(index.startIndex,4))) { if refresh == "Refresh" { self.siteUrl = url self.loadFromDoc() return } } } element.iterate("head.link") { link in if var rel = link.attribute("rel") where (rel == "shortcut icon" || rel == "icon" || rel == "apple-touch-icon"), var href = link.attribute("href"), var url = NSURL(string: href, relativeToURL: self.siteUrl) { let icon = Favicon(url: url.absoluteString!, date: NSDate(), type: IconType.Icon) self._favicons.append(icon) } } } } private func getFavicon(icon: Favicon, profile: Profile) -> Deferred<Result<Favicon>> { let deferred = Deferred<Result<Favicon>>() let url = icon.url let manager = SDWebImageManager.sharedManager() let site = Site(url: siteUrl.absoluteString!, title: "") var fav = Favicon(url: url, type: IconType.Icon) if let url = url.asURL { manager.downloadImageWithURL(url, options: SDWebImageOptions.LowPriority, progress: nil, completed: { (img, err, cacheType, success, url) -> Void in fav = Favicon(url: url.absoluteString!, type: IconType.Icon) if let img = img { fav.width = Int(img.size.width) fav.height = Int(img.size.height) profile.favicons.addFavicon(fav, forSite: site) } else { fav.width = 0 fav.height = 0 } deferred.fill(Result(success: fav)) }) } else { return deferResult(FaviconFetcherErrorType(description: "Invalid url \(url)")) } return deferred } }
mpl-2.0
5e382de6079f71558be1ebed238cdded
37.474453
160
0.545627
4.885079
false
false
false
false
milseman/swift
test/SILGen/objc_metatypes.swift
13
2521
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: objc_interop import gizmo @objc class ObjCClass {} class A { // CHECK-LABEL: sil hidden @_T014objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F // CHECK-LABEL: sil hidden [thunk] @_T014objc_metatypes1AC3fooAA9ObjCClassCmAFmFTo @objc dynamic func foo(_ m: ObjCClass.Type) -> ObjCClass.Type { // CHECK: bb0([[M:%[0-9]+]] : $@objc_metatype ObjCClass.Type, [[SELF:%[0-9]+]] : $A): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $A // CHECK: [[M_AS_THICK:%[0-9]+]] = objc_to_thick_metatype [[M]] : $@objc_metatype ObjCClass.Type to $@thick ObjCClass.Type // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE_FOO:%[0-9]+]] = function_ref @_T014objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F // CHECK: [[NATIVE_RESULT:%[0-9]+]] = apply [[NATIVE_FOO]]([[M_AS_THICK]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@thick ObjCClass.Type, @guaranteed A) -> @thick ObjCClass.Type // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[OBJC_RESULT:%[0-9]+]] = thick_to_objc_metatype [[NATIVE_RESULT]] : $@thick ObjCClass.Type to $@objc_metatype ObjCClass.Type // CHECK: return [[OBJC_RESULT]] : $@objc_metatype ObjCClass.Type // CHECK: } // end sil function '_T014objc_metatypes1AC3fooAA9ObjCClassCmAFmFTo' return m } // CHECK-LABEL: sil hidden @_T014objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ // CHECK-LABEL: sil hidden [thunk] @_T014objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZTo // CHECK: bb0([[SELF:%[0-9]+]] : $@objc_metatype A.Type): // CHECK-NEXT: [[OBJC_SELF:%[0-9]+]] = objc_to_thick_metatype [[SELF]] : $@objc_metatype A.Type to $@thick A.Type // CHECK: [[BAR:%[0-9]+]] = function_ref @_T014objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[BAR]]([[OBJC_SELF]]) : $@convention(method) (@thick A.Type) -> () // CHECK-NEXT: return [[RESULT]] : $() @objc dynamic class func bar() { } @objc dynamic func takeGizmo(_ g: Gizmo.Type) { } // CHECK-LABEL: sil hidden @_T014objc_metatypes1AC7callFoo{{[_0-9a-zA-Z]*}}F func callFoo() { // Make sure we peephole Type/thick_to_objc_metatype. // CHECK-NOT: thick_to_objc_metatype // CHECK: metatype $@objc_metatype ObjCClass.Type foo(ObjCClass.self) // CHECK: return } }
apache-2.0
a831ecee04dd4a949b7b4041465fd194
51.520833
191
0.625942
3.081907
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieMath/Accelerate/CooleyTukey2D.swift
1
6733
// // CooleyTukey2D.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @inlinable @inline(__always) public func HalfRadix2CooleyTukey2D<T: BinaryFloatingPoint>(_ log2n: (Int, Int), _ input: UnsafePointer<T>, _ in_stride: Int, _ in_count: (Int, Int), _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) where T: ElementaryFunctions { let width = 1 << log2n.0 let height = 1 << log2n.1 let half_width = width >> 1 let in_width = in_count.0 let in_height = in_count.1 let in_row_stride = in_stride * in_width let out_row_stride = out_stride * half_width do { var input = input var out_real = out_real var out_imag = out_imag for _ in 0..<in_height { HalfRadix2CooleyTukey(log2n.0, input, in_stride, in_width, out_real, out_imag, out_stride) input += in_row_stride out_real += out_row_stride out_imag += out_row_stride } for _ in in_height..<height { var _r = out_real var _i = out_imag for _ in 0..<half_width { _r.pointee = 0 _i.pointee = 0 _r += out_stride _i += out_stride } out_real += out_row_stride out_imag += out_row_stride } } do { var out_real = out_real var out_imag = out_imag HalfRadix2CooleyTukey(log2n.1, out_real, out_row_stride) HalfRadix2CooleyTukey(log2n.1, out_imag, out_row_stride) for _ in 1..<half_width { out_real += out_stride out_imag += out_stride Radix2CooleyTukey(log2n.1, out_real, out_imag, out_row_stride) } } } @inlinable @inline(__always) public func HalfInverseRadix2CooleyTukey2D<T: BinaryFloatingPoint>(_ log2n: (Int, Int), _ in_real: UnsafePointer<T>, _ in_imag: UnsafePointer<T>, _ in_stride: Int, _ output: UnsafeMutablePointer<T>, _ out_stride: Int) where T: ElementaryFunctions { let width = 1 << log2n.0 let height = 1 << log2n.1 let half_width = width >> 1 do { var in_real = in_real var in_imag = in_imag var out_real = output var out_imag = output + out_stride let _out_stride = out_stride << 1 let in_row_stride = in_stride * half_width let out_row_stride = _out_stride * half_width HalfInverseRadix2CooleyTukey(log2n.1, in_real, in_real + in_row_stride, in_row_stride << 1, out_real, out_row_stride) HalfInverseRadix2CooleyTukey(log2n.1, in_imag, in_imag + in_row_stride, in_row_stride << 1, out_imag, out_row_stride) for _ in 1..<half_width { in_real += in_stride in_imag += in_stride out_real += _out_stride out_imag += _out_stride InverseRadix2CooleyTukey(log2n.1, in_real, in_imag, in_row_stride, height, out_real, out_imag, out_row_stride) } } do { var output = output let out_row_stride = out_stride * width for _ in 0..<height { HalfInverseRadix2CooleyTukey(log2n.0, output, out_stride) output += out_row_stride } } } @inlinable @inline(__always) public func separate_convolution_filter<T: BinaryFloatingPoint>(_ filter: [T], _ width: Int, _ height: Int) -> ([T], [T])? { precondition(width > 0, "invalid width.") precondition(height > 0, "invalid height.") precondition(width * height == filter.count, "mismatch filter count.") var horizontal = [T](repeating: 0, count: width) var vertical = [T](repeating: 0, count: height) filter.withUnsafeBufferPointer { guard let filter = $0.baseAddress else { return } return horizontal.withUnsafeMutableBufferPointer { guard let horizontal = $0.baseAddress else { return } return vertical.withUnsafeMutableBufferPointer { guard let vertical = $0.baseAddress else { return } var (i, m) = UnsafeBufferPointer(start: filter, count: width * height).enumerated().max { abs($0.element) < abs($1.element) }! guard m != 0 else { return } let j = i % width i /= width m = sqrt(abs(m)) do { var _filter = filter + i * width var _horizontal = horizontal for _ in 0..<width { _horizontal.pointee = _filter.pointee / m _filter += 1 _horizontal += 1 } } do { var _filter = filter + j let _horizontal = horizontal + j var _vertical = vertical for _ in 0..<height { _vertical.pointee = _filter.pointee / _horizontal.pointee _filter += width _vertical += 1 } } } } } let is_equal = zip(filter, vertical.flatMap { a in horizontal.map { a * $0 } }).allSatisfy { $0.almostEqual($1) } return is_equal ? (horizontal, vertical) : nil }
mit
15d44e3aad2d2efbc79323707a72b984
35.592391
273
0.54775
4.125613
false
false
false
false
lucas34/SwiftQueue
Sources/SwiftQueue/Constraint+Persister.swift
1
1962
// The MIT License (MIT) // // Copyright (c) 2022 Lucas Nelaupe // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation internal class PersisterConstraint: SimpleConstraint { private let serializer: JobInfoSerializer private let persister: JobPersister init(serializer: JobInfoSerializer, persister: JobPersister) { self.serializer = serializer self.persister = persister } override func willSchedule(queue: SqOperationQueue, operation: SqOperation) throws { let data = try serializer.serialize(info: operation.info) let name = operation.name ?? "" let queueName = queue.name ?? "" assertNotEmptyString(name) assertNotEmptyString(queueName) persister.put(queueName: queueName, taskId: name, data: data) } func remove(queueName: String, taskId: String) { persister.remove(queueName: queueName, taskId: taskId) } }
mit
3ccf7feecb93b9d280a62beb4f256f38
39.040816
88
0.733435
4.562791
false
false
false
false
tryswift/TryParsec
Sources/TryParsec/UnicodeScalarView+Helper.swift
1
2712
extension String.UnicodeScalarView: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self = value.unicodeScalars } public init(extendedGraphemeClusterLiteral value: String) { self = value.unicodeScalars } public init(unicodeScalarLiteral value: String) { self = value.unicodeScalars } } extension String.UnicodeScalarView: ExpressibleByArrayLiteral { public init(arrayLiteral elements: UnicodeScalar...) { self.init() self.append(contentsOf: elements) } } extension String.UnicodeScalarView: Equatable {} public func == (lhs: String.UnicodeScalarView, rhs: String.UnicodeScalarView) -> Bool { return String(lhs) == String(rhs) } // MARK: Functions public func isDigit(_ c: UnicodeScalar) -> Bool { return "0"..."9" ~= c } public func isHexDigit(_ c: UnicodeScalar) -> Bool { return "0"..."9" ~= c || "a"..."f" ~= c || "A"..."F" ~= c } public func isLowerAlphabet(_ c: UnicodeScalar) -> Bool { return "a"..."z" ~= c } public func isUpperAlphabet(_ c: UnicodeScalar) -> Bool { return "A"..."Z" ~= c } public func isAlphabet(_ c: UnicodeScalar) -> Bool { return isLowerAlphabet(c) || isUpperAlphabet(c) } private let _spaces: String.UnicodeScalarView = [ " ", "\t", "\n", "\r" ] public func isSpace(_ c: UnicodeScalar) -> Bool { return _spaces.contains(c) } /// UnicodeScalar validation using array of `ClosedInterval`. public func isInClosedIntervals(_ c: UnicodeScalar, _ closedIntervals: ClosedRange<UInt32>...) -> Bool { for closedInterval in closedIntervals { if closedInterval.contains(c.value) { return true } } return false } /// Removes head & tail whitespaces. public func trim(_ cs: String.UnicodeScalarView) -> String.UnicodeScalarView { return _trim(cs, true, true) } /// Removes head whitespace. public func trimStart(_ cs: String.UnicodeScalarView) -> String.UnicodeScalarView { return _trim(cs, true, false) } /// Removes tail whitespace. public func trimEnd(_ cs: String.UnicodeScalarView) -> String.UnicodeScalarView { return _trim(cs, false, true) } private func _trim(_ cs: String.UnicodeScalarView, _ trimsStart: Bool, _ trimsEnd: Bool) -> String.UnicodeScalarView { var startIndex = cs.startIndex var endIndex = cs.index(before: cs.endIndex) print("1") while trimsStart && isSpace(cs[startIndex]) { print("2") startIndex = cs.index(after: startIndex) } while trimsEnd && isSpace(cs[endIndex]) { print(cs[endIndex]) endIndex = cs.index(before: endIndex) } return String.UnicodeScalarView(cs[startIndex...endIndex]) }
mit
8b548fa53fe8c8324266b25592a78c34
22.37931
116
0.661504
3.988235
false
false
false
false
tcirwin/SignatureApp
SignatureApp/SignatureView.swift
1
1563
// // SignatureView.swift // SignatureApp // // Created by Therin Irwin on 8/31/14. // Copyright (c) 2014 Therin Irwin. All rights reserved. // import UIKit class SignatureView: UIView { // nil indicates that we need to move the pen var tracers: [CGPoint?] = [nil] override func drawRect(rect: CGRect) { let signature = UIBezierPath() var endLine = true for tracer in tracers { if let tracer = tracer { if endLine { signature.moveToPoint(tracer) endLine = false } else { signature.addLineToPoint(tracer) } } else { endLine = true } } UIColor.blackColor().setStroke() signature.stroke() } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { tracers.append(nil) handleTouch(touches, withEvent: event) } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { handleTouch(touches, withEvent: event) } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { handleTouch(touches, withEvent: event) tracers.append(nil) } func handleTouch(touches: Set<NSObject>, withEvent event: UIEvent!) { let touch: UITouch = touches.first as! UITouch tracers.append(touch.locationInView(self)) setNeedsDisplay() } }
mit
0210768b7ce3a8e4b919de026cde5929
26.421053
82
0.566219
4.765244
false
false
false
false
kolyasev/SwiftJSONRPC
Sources/SwiftJSONRPC/RequestExecutor/Request.swift
1
1394
// ---------------------------------------------------------------------------- // // Request.swift // // @author Denis Kolyasev <[email protected]> // // ---------------------------------------------------------------------------- public class Request { // MARK: - Properties public let id: String? public let method: String public let params: Params? // MARK: - Initialization init(id: String? = nil, method: String, params: Params?) { self.id = id self.method = method self.params = params } // MARK: - Functions public func buildBody() -> [String: Any] { var body: [String: Any] = [ JsonKeys.JsonRPC: RPCClient.Version, JsonKeys.Method: method ] if let id = id { body[JsonKeys.Id] = id } if let params = params { body[JsonKeys.Params] = params } return body } // MARK: - Constants private struct JsonKeys { static let JsonRPC = "jsonrpc" static let Method = "method" static let Params = "params" static let Result = "result" static let Error = "error" static let Code = "code" static let Message = "message" static let Data = "data" static let Id = "id" } // MARK: - Inner Types public typealias Params = Any }
mit
6692a8d986dda8607f531fa9d7002ddb
21.126984
79
0.477762
4.482315
false
false
false
false
skylib/SnapImagePicker
Pods/DORateLimit/DORateLimit/RateLimit.swift
1
9897
// // RateLimit.swift // RateLimitExample // // Created by Daniele Orrù on 28/06/15. // Copyright (c) 2015 Daniele Orru'. All rights reserved. // import Foundation // TODO: Merge RateLimitInfo with RateLimitInfo2 class RateLimitInfo: NSObject { let lastExecutionDate: Date let timer: Timer? let throttleInfo: ThrottleInfo init(lastExecutionDate: Date, timer: Timer? = nil, throttleInfo: ThrottleInfo) { self.lastExecutionDate = lastExecutionDate self.timer = timer self.throttleInfo = throttleInfo super.init() } } // TODO: Rename class class RateLimitInfo2: NSObject { let timer: Timer? let debounceInfo: DebounceInfo init(timer: Timer? = nil, debounceInfo: DebounceInfo) { self.timer = timer self.debounceInfo = debounceInfo super.init() } } // TODO: Merge ThrottleInfo with DebounceInfo class ThrottleInfo: NSObject { let key: String let threshold: TimeInterval let trailing: Bool let closure: () -> () init(key: String, threshold: TimeInterval, trailing: Bool, closure: @escaping () -> ()) { self.key = key self.threshold = threshold self.trailing = trailing self.closure = closure super.init() } } // TODO: Merge ThrottleInfo with DebounceInfo class DebounceInfo: NSObject { let key: String let threshold: TimeInterval let atBegin: Bool let closure: () -> () init(key: String, threshold: TimeInterval, atBegin: Bool, closure: @escaping () -> ()) { self.key = key self.threshold = threshold self.atBegin = atBegin self.closure = closure super.init() } } /** * Provide debounce and throttle functionality. */ open class RateLimit { // TODO: Rename queue with a generic name fileprivate static let debounceQueue = DispatchQueue(label: "org.orru.RateLimit", attributes: []) // TODO: merge rateLimitDictionary with rateLimitDictionary2 fileprivate static var rateLimitDictionary = [String : RateLimitInfo]() fileprivate static var rateLimitDictionary2 = [String : RateLimitInfo2]() /** Throttle call to a closure using a given threshold - parameter name: - parameter threshold: - parameter trailing: - parameter closure: */ open static func throttle(_ key: String, threshold: TimeInterval, trailing: Bool = false, closure: @escaping ()->()) { let now = Date() var canExecuteClosure = false if let rateLimitInfo = self.rateLimitInfoForKey(key) { let timeDifference = rateLimitInfo.lastExecutionDate.timeIntervalSince(now) if timeDifference < 0 && fabs(timeDifference) < threshold { if trailing && rateLimitInfo.timer == nil { let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.throttleTimerFired(_:)), userInfo: ["rateLimitInfo" : rateLimitInfo], repeats: false) let throttleInfo = ThrottleInfo(key: key, threshold: threshold, trailing: trailing, closure: closure) self.setRateLimitInfoForKey(RateLimitInfo(lastExecutionDate: rateLimitInfo.lastExecutionDate, timer: timer, throttleInfo: throttleInfo), forKey: key) } } else { canExecuteClosure = true } } else { canExecuteClosure = true } if canExecuteClosure { let throttleInfo = ThrottleInfo(key: key, threshold: threshold, trailing: trailing, closure: closure) self.setRateLimitInfoForKey(RateLimitInfo(lastExecutionDate: now, timer: nil, throttleInfo: throttleInfo), forKey: key) closure() } } @objc fileprivate static func throttleTimerFired(_ timer: Timer) { // TODO: use constant for "rateLimitInfo" if let userInfo = timer.userInfo as? [String : AnyObject], let rateLimitInfo = userInfo["rateLimitInfo"] as? RateLimitInfo { self.throttle(rateLimitInfo.throttleInfo.key, threshold: rateLimitInfo.throttleInfo.threshold, trailing: rateLimitInfo.throttleInfo.trailing, closure: rateLimitInfo.throttleInfo.closure) } } /** Debounce call to a closure using a given threshold - parameter key: - parameter threshold: - parameter atBegin: - parameter closure: */ open static func debounce(_ key: String, threshold: TimeInterval, atBegin: Bool = true, closure: @escaping ()->()) { var canExecuteClosure = false if let rateLimitInfo = self.rateLimitInfoForKey2(key) { if let timer = rateLimitInfo.timer , timer.isValid { timer.invalidate() let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) // TODO: use constant for "rateLimitInfo" let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.throttleTimerFired2(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setRateLimitInfoForKey2(RateLimitInfo2(timer: timer, debounceInfo: debounceInfo), forKey: key) } else { if (atBegin) { canExecuteClosure = true } else { let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) // TODO: use constant for "rateLimitInfo" let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.throttleTimerFired2(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setRateLimitInfoForKey2(RateLimitInfo2(timer: timer, debounceInfo: debounceInfo), forKey: key) } } } else { if (atBegin) { canExecuteClosure = true } else { let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) // TODO: use constant for "rateLimitInfo" let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.throttleTimerFired2(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setRateLimitInfoForKey2(RateLimitInfo2(timer: timer, debounceInfo: debounceInfo), forKey: key) } } if canExecuteClosure { let debounceInfo = DebounceInfo(key: key, threshold: threshold, atBegin: atBegin, closure: closure) // TODO: use constant for "rateLimitInfo" let timer = Timer.scheduledTimer(timeInterval: threshold, target: self, selector: #selector(RateLimit.throttleTimerFired2(_:)), userInfo: ["rateLimitInfo" : debounceInfo], repeats: false) self.setRateLimitInfoForKey2(RateLimitInfo2(timer: timer, debounceInfo: debounceInfo), forKey: key) closure() } } // TODO: Rename method @objc fileprivate static func throttleTimerFired2(_ timer: Timer) { // TODO: use constant for "rateLimitInfo" if let userInfo = timer.userInfo as? [String : AnyObject], let debounceInfo = userInfo["rateLimitInfo"] as? DebounceInfo , !debounceInfo.atBegin { debounceInfo.closure() } } open static func resetAllRateLimit() { debounceQueue.sync { for key in self.rateLimitDictionary.keys { if let rateLimitInfo = self.rateLimitDictionary[key], let timer = rateLimitInfo.timer , timer.isValid { timer.invalidate() } self.rateLimitDictionary[key] = nil } for key in self.rateLimitDictionary2.keys { if let rateLimitInfo = self.rateLimitDictionary2[key], let timer = rateLimitInfo.timer , timer.isValid { timer.invalidate() } self.rateLimitDictionary2[key] = nil } } } open static func resetRateLimitForKey(_ key: String) { debounceQueue.sync { if let rateLimitInfo = self.rateLimitDictionary[key], let timer = rateLimitInfo.timer , timer.isValid { timer.invalidate() } self.rateLimitDictionary[key] = nil if let rateLimitInfo = self.rateLimitDictionary2[key], let timer = rateLimitInfo.timer , timer.isValid { timer.invalidate() } self.rateLimitDictionary2[key] = nil } } // TODO: merge rateLimitInfoForKey with rateLimitInfoForKey2 fileprivate static func rateLimitInfoForKey(_ key: String) -> RateLimitInfo? { var rateLimitInfo: RateLimitInfo? debounceQueue.sync { rateLimitInfo = self.rateLimitDictionary[key] } return rateLimitInfo } // TODO: merge rateLimitInfoForKey with rateLimitInfoForKey2 fileprivate static func rateLimitInfoForKey2(_ key: String) -> RateLimitInfo2? { var rateLimitInfo: RateLimitInfo2? debounceQueue.sync { rateLimitInfo = self.rateLimitDictionary2[key] } return rateLimitInfo } // TODO: merge setRateLimitInfoForKey with setRateLimitInfoForKey2 fileprivate static func setRateLimitInfoForKey(_ rateLimitInfo: RateLimitInfo, forKey key: String) { debounceQueue.sync { self.rateLimitDictionary[key] = rateLimitInfo } } // TODO: merge setRateLimitInfoForKey with setRateLimitInfoForKey2 fileprivate static func setRateLimitInfoForKey2(_ rateLimitInfo: RateLimitInfo2, forKey key: String) { debounceQueue.sync { self.rateLimitDictionary2[key] = rateLimitInfo } } }
bsd-3-clause
36a736c08ba3b673fa2d3cfeccb30a0b
38.584
207
0.639652
4.741735
false
false
false
false
kolyasev/SwiftJSONRPC
Sources/SwiftJSONRPC/RequestExecutor/Response.swift
1
2090
// ---------------------------------------------------------------------------- // // Response.swift // // @author Denis Kolyasev <[email protected]> // // ---------------------------------------------------------------------------- public class Response { // MARK: - Properties public let id: String public let body: Body // MARK: - Initialization init(response: Any) throws { guard let json = (response as? [String: AnyObject]), let version = (json[JsonKeys.JsonRPC] as? String), (version == RPCClient.Version), let id = (json[JsonKeys.Id] as? String) else { throw ResponseError.invalidFormat } // Handle 'id' object self.id = id // Handle 'result' object if exists if let result = json[JsonKeys.Result] { // Create success result body self.body = .success(result: result) } else // Handle 'error' object if exists if let error = (json[JsonKeys.Error] as? [String: Any]), let code = (error[JsonKeys.Code] as? Int), let message = (error[JsonKeys.Message] as? String) { let data = error[JsonKeys.Data] // Init JSON-RPC error let error = RPCError(code: code, message: message, data: data) // Create error body self.body = .error(error: error) } else { throw ResponseError.invalidFormat } } // MARK: - Constants private struct JsonKeys { static let JsonRPC = "jsonrpc" static let Method = "method" static let Params = "params" static let Result = "result" static let Error = "error" static let Code = "code" static let Message = "message" static let Data = "data" static let Id = "id" } // MARK: - Inner Types public enum Body { case success(result: Result) case error(error: RPCError) } public typealias Result = Any } enum ResponseError: Error { case invalidFormat }
mit
bb65a66c563170b40df6899cace800ee
25.794872
96
0.515789
4.465812
false
false
false
false
MarkQSchultz/SwiftConstraints
SwiftConstraints/SwiftConstraints.swift
1
3004
// // SwiftConstraints.swift // SwiftConstraints // // Created by Mark Schultz on 6/4/14. // Copyright (c) 2014 QZero Labs, LLC. All rights reserved. // extension NSLayoutConstraint { class func constraintsThatFillWidthWithSubview(subview: UIView) -> NSLayoutConstraint[] { var constraints = NSLayoutConstraint[]() constraints += NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: subview.superview, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0.0) constraints += NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: subview.superview, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0.0) return constraints } class func constraintsThatFillHeightWithSubview(subview: UIView) -> NSLayoutConstraint[] { var constraints = NSLayoutConstraint[]() constraints += NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: subview.superview, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0) constraints += NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: subview.superview, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0) return constraints } class func constraintsThatFillSizeWithSubview(subview: UIView) -> NSLayoutConstraint[] { var constraints = NSLayoutConstraint[]() constraints += self.constraintsThatFillHeightWithSubview(subview) constraints += self.constraintsThatFillWidthWithSubview(subview) return constraints } convenience init(view: UIView, alignedWithOtherView otherView: UIView, onAttribute attribute: NSLayoutAttribute) { self.init( item: view, attribute: attribute, relatedBy: .Equal, toItem: otherView, attribute: attribute, multiplier: 1.0, constant: 0.0) } convenience init(subview: UIView, alignedWithSuperviewOnAttribute attribute: NSLayoutAttribute) { self.init(view: subview, alignedWithOtherView: subview.superview, onAttribute: attribute) } convenience init(horizontallyCenteredSubview subview: UIView) { self.init(subview: subview, alignedWithSuperviewOnAttribute: .CenterX) } convenience init(verticallyCenteredSubview subview: UIView) { self.init(subview: subview, alignedWithSuperviewOnAttribute: .CenterY) } }
mit
16dbb3bbfcf9ed65d775c48bb4eb9fd1
34.341176
118
0.635153
5.442029
false
false
false
false
mfitzpatrick79/BidHub-iOS
AuctionApp/Login/LoginViewController.swift
1
3108
// // LoginViewController.swift // AuctionApp // import UIKit import UserNotifications import AFViewShaker import OneSignal import PhoneNumberKit import Parse private var kAssociationKeyNextField: UInt8 = 0 extension UITextField { @IBOutlet var nextField: UITextField? { get { return objc_getAssociatedObject(self, &kAssociationKeyNextField) as? UITextField } set(newField) { objc_setAssociatedObject(self, &kAssociationKeyNextField, newField, .OBJC_ASSOCIATION_RETAIN) } } } class LoginViewController: UIViewController { @IBOutlet var nameTextField: UITextField! @IBOutlet var emailTextField: UITextField! @IBOutlet var telephoneTextField: UITextField! var viewShaker:AFViewShaker? override func viewDidLoad() { super.viewDidLoad() viewShaker = AFViewShaker(viewsArray: [nameTextField, emailTextField, telephoneTextField]) } @IBAction func textFieldShouldReturn(_ textField: UITextField) { textField.nextField?.becomeFirstResponder() } @IBAction func loginPressed(_ sender: AnyObject) { if nameTextField.text != "" && emailTextField.text != "" && telephoneTextField.text != "" { let user = PFUser() user["fullname"] = nameTextField.text!.lowercased() user.username = emailTextField.text!.lowercased() user.password = "test" user.email = emailTextField.text!.lowercased() user["telephone"] = telephoneTextField.text! user.signUpInBackground { (succeeded, error) in if succeeded == true { OneSignal.syncHashedEmail(user.email) OneSignal.promptForPushNotifications(userResponse: { accepted in print("User accepted notifications: \(accepted)") }) self.performSegue(withIdentifier: "loginToItemSegue", sender: nil) } else { let errorString = error?.localizedDescription print("Error Signing up: \(String(describing: errorString))", terminator: "") PFUser.logInWithUsername(inBackground: user.username!, password: user.password!, block: { (user, error) -> Void in if error == nil { OneSignal.syncHashedEmail(user?.email) OneSignal.promptForPushNotifications(userResponse: { accepted in print("User accepted notifications: \(accepted)") }) self.performSegue(withIdentifier: "loginToItemSegue", sender: nil) }else{ print("Error logging in ", terminator: "") self.viewShaker?.shake() } }) } } }else{ //Can't login with nothing set viewShaker?.shake() } } }
apache-2.0
141ece62b3cfbca3b389f7c054666719
35.564706
134
0.565315
5.661202
false
false
false
false
cohena100/Shimi
Carthage/Checkouts/SwiftyBeaver/Sources/BaseDestination.swift
1
16786
// // BaseDestination.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger (Twitter @skreutzb) on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation import Dispatch // store operating system / platform #if os(iOS) let OS = "iOS" #elseif os(OSX) let OS = "OSX" #elseif os(watchOS) let OS = "watchOS" #elseif os(tvOS) let OS = "tvOS" #elseif os(Linux) let OS = "Linux" #elseif os(FreeBSD) let OS = "FreeBSD" #elseif os(Windows) let OS = "Windows" #elseif os(Android) let OS = "Android" #else let OS = "Unknown" #endif /// destination which all others inherit from. do not directly use open class BaseDestination: Hashable, Equatable { /// output format pattern, see documentation for syntax open var format = "$DHH:mm:ss.SSS$d $C$L$c $N.$F:$l - $M" /// runs in own serial background thread for better performance open var asynchronously = true /// do not log any message which has a lower level than this one open var minLevel = SwiftyBeaver.Level.verbose /// set custom log level words for each level open var levelString = LevelString() /// set custom log level colors for each level open var levelColor = LevelColor() public struct LevelString { public var verbose = "VERBOSE" public var debug = "DEBUG" public var info = "INFO" public var warning = "WARNING" public var error = "ERROR" } // For a colored log level word in a logged line // empty on default public struct LevelColor { public var verbose = "" // silver public var debug = "" // green public var info = "" // blue public var warning = "" // yellow public var error = "" // red } var reset = "" var escape = "" var filters = [FilterType]() let formatter = DateFormatter() // each destination class must have an own hashValue Int lazy public var hashValue: Int = self.defaultHashValue open var defaultHashValue: Int {return 0} // each destination instance must have an own serial queue to ensure serial output // GCD gives it a prioritization between User Initiated and Utility var queue: DispatchQueue? //dispatch_queue_t? var debugPrint = false // set to true to debug the internal filter logic of the class public init() { let uuid = NSUUID().uuidString let queueLabel = "swiftybeaver-queue-" + uuid queue = DispatchQueue(label: queueLabel, target: queue) } /// send / store the formatted log message to the destination /// returns the formatted log message for processing by inheriting method /// and for unit tests (nil if error) open func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { if format.hasPrefix("$J") { return messageToJSON(level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) } else { return formatMessage(format, level: level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) } } //////////////////////////////// // MARK: Format //////////////////////////////// /// returns the log message based on the format pattern func formatMessage(_ format: String, level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String { var text = "" let phrases: [String] = format.components(separatedBy: "$") for phrase in phrases where !phrase.isEmpty { let firstChar = phrase[phrase.startIndex] let rangeAfterFirstChar = phrase.index(phrase.startIndex, offsetBy: 1)..<phrase.endIndex let remainingPhrase = phrase[rangeAfterFirstChar] switch firstChar { case "L": text += levelWord(level) + remainingPhrase case "M": text += msg + remainingPhrase case "T": text += thread + remainingPhrase case "N": // name of file without suffix text += fileNameWithoutSuffix(file) + remainingPhrase case "n": // name of file with suffix text += fileNameOfFile(file) + remainingPhrase case "F": text += function + remainingPhrase case "l": text += String(line) + remainingPhrase case "D": // start of datetime format text += formatDate(remainingPhrase) case "d": text += remainingPhrase case "Z": // start of datetime format in UTC timezone text += formatDate(remainingPhrase, timeZone: "UTC") case "z": text += remainingPhrase case "C": // color code ("" on default) text += escape + colorForLevel(level) + remainingPhrase case "c": text += reset + remainingPhrase case "X": // add the context if let cx = context { text += String(describing: cx).trimmingCharacters(in: .whitespacesAndNewlines) + remainingPhrase } /* if let contextString = context as? String { text += contextString + remainingPhrase }*/ default: text += phrase } } return text } /// returns the log payload as optional JSON string func messageToJSON(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { var dict: [String: Any] = [ "timestamp": Date().timeIntervalSince1970, "level": level.rawValue, "message": msg, "thread": thread, "file": file, "function": function, "line": line ] if let cx = context { dict["context"] = cx } return jsonStringFromDict(dict) } /// returns the string of a level func levelWord(_ level: SwiftyBeaver.Level) -> String { var str = "" switch level { case SwiftyBeaver.Level.debug: str = levelString.debug case SwiftyBeaver.Level.info: str = levelString.info case SwiftyBeaver.Level.warning: str = levelString.warning case SwiftyBeaver.Level.error: str = levelString.error default: // Verbose is default str = levelString.verbose } return str } /// returns color string for level func colorForLevel(_ level: SwiftyBeaver.Level) -> String { var color = "" switch level { case SwiftyBeaver.Level.debug: color = levelColor.debug case SwiftyBeaver.Level.info: color = levelColor.info case SwiftyBeaver.Level.warning: color = levelColor.warning case SwiftyBeaver.Level.error: color = levelColor.error default: color = levelColor.verbose } return color } /// returns the filename of a path func fileNameOfFile(_ file: String) -> String { let fileParts = file.components(separatedBy: "/") if let lastPart = fileParts.last { return lastPart } return "" } /// returns the filename without suffix (= file ending) of a path func fileNameWithoutSuffix(_ file: String) -> String { let fileName = fileNameOfFile(file) if !fileName.isEmpty { let fileNameParts = fileName.components(separatedBy: ".") if let firstPart = fileNameParts.first { return firstPart } } return "" } /// returns a formatted date string /// optionally in a given abbreviated timezone like "UTC" func formatDate(_ dateFormat: String, timeZone: String = "") -> String { if !timeZone.isEmpty { formatter.timeZone = TimeZone(abbreviation: timeZone) } formatter.dateFormat = dateFormat //let dateStr = formatter.string(from: NSDate() as Date) let dateStr = formatter.string(from: Date()) return dateStr } /// returns the json-encoded string value /// after it was encoded by jsonStringFromDict func jsonStringValue(_ jsonString: String?, key: String) -> String { guard let str = jsonString else { return "" } // remove the leading {"key":" from the json string and the final } let offset = key.characters.count + 5 let endIndex = str.index(str.startIndex, offsetBy: str.characters.count - 2) let range = str.index(str.startIndex, offsetBy: offset)..<endIndex return str[range] } /// turns dict into JSON-encoded string func jsonStringFromDict(_ dict: [String: Any]) -> String? { var jsonString: String? // try to create JSON string do { let jsonData = try JSONSerialization.data(withJSONObject: dict, options: []) jsonString = String(data: jsonData, encoding: .utf8) } catch { print("SwiftyBeaver could not create JSON from dict.") } return jsonString } //////////////////////////////// // MARK: Filters //////////////////////////////// /// Add a filter that determines whether or not a particular message will be logged to this destination public func addFilter(_ filter: FilterType) { filters.append(filter) } /// Remove a filter from the list of filters public func removeFilter(_ filter: FilterType) { let index = filters.index { return ObjectIdentifier($0) == ObjectIdentifier(filter) } guard let filterIndex = index else { return } filters.remove(at: filterIndex) } /// Answer whether the destination has any message filters /// returns boolean and is used to decide whether to resolve /// the message before invoking shouldLevelBeLogged func hasMessageFilters() -> Bool { return !getFiltersTargeting(Filter.TargetType.Message(.Equals([], true)), fromFilters: self.filters).isEmpty } /// checks if level is at least minLevel or if a minLevel filter for that path does exist /// returns boolean and can be used to decide if a message should be logged or not func shouldLevelBeLogged(_ level: SwiftyBeaver.Level, path: String, function: String, message: String? = nil) -> Bool { if filters.isEmpty { if level.rawValue >= minLevel.rawValue { if debugPrint { print("filters is empty and level >= minLevel") } return true } else { if debugPrint { print("filters is empty and level < minLevel") } return false } } let (matchedExclude, allExclude) = passedExcludedFilters(level, path: path, function: function, message: message) if allExclude > 0 && matchedExclude != allExclude { if debugPrint { print("filters is not empty and message was excluded") } return false } let (matchedRequired, allRequired) = passedRequiredFilters(level, path: path, function: function, message: message) let (matchedNonRequired, allNonRequired) = passedNonRequiredFilters(level, path: path, function: function, message: message) if allRequired > 0 { if matchedRequired == allRequired { return true } } else { // no required filters are existing so at least 1 optional needs to match if allNonRequired > 0 { if matchedNonRequired > 0 { return true } } else if allExclude == 0 { // no optional is existing, so all is good return true } } if level.rawValue < minLevel.rawValue { if debugPrint { print("filters is not empty and level < minLevel") } return false } return true } func getFiltersTargeting(_ target: Filter.TargetType, fromFilters: [FilterType]) -> [FilterType] { return fromFilters.filter { filter in return filter.getTarget() == target } } /// returns a tuple of matched and all filters func passedRequiredFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let requiredFilters = self.filters.filter { filter in return filter.isRequired() && !filter.isExcluded() } let matchingFilters = applyFilters(requiredFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(requiredFilters.count) required filters") } return (matchingFilters, requiredFilters.count) } /// returns a tuple of matched and all filters func passedNonRequiredFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let nonRequiredFilters = self.filters.filter { filter in return !filter.isRequired() && !filter.isExcluded() } let matchingFilters = applyFilters(nonRequiredFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(nonRequiredFilters.count) non-required filters") } return (matchingFilters, nonRequiredFilters.count) } /// returns a tuple of matched and all exclude filters func passedExcludedFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let excludeFilters = self.filters.filter { filter in return filter.isExcluded() } let matchingFilters = applyFilters(excludeFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(excludeFilters.count) exclude filters") } return (matchingFilters, excludeFilters.count) } func applyFilters(_ targetFilters: [FilterType], level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Int { return targetFilters.filter { filter in let passes: Bool if !filter.reachedMinLevel(level) { return false } switch filter.getTarget() { case .Path(_): passes = filter.apply(path) case .Function(_): passes = filter.apply(function) case .Message(_): guard let message = message else { return false } passes = filter.apply(message) } return passes }.count } /** Triggered by main flush() method on each destination. Runs in background thread. Use for destinations that buffer log items, implement this function to flush those buffers to their final destination (web server...) */ func flush() { // no implementation in base destination needed } } public func == (lhs: BaseDestination, rhs: BaseDestination) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
mit
ebb219a3da9fc871682fc41eb1761406
33.89605
120
0.557522
5.174168
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Home/Buildings/Buildings/Cells/BuildingMapCell.swift
1
2845
// // BuildingMapCell.swift // PennMobile // // Created by dominic on 6/21/18. // Copyright © 2018 PennLabs. All rights reserved. // import UIKit import MapKit class BuildingMapCell: BuildingCell { static let identifier = "BuildingMapCell" static let cellHeight: CGFloat = 240 var building: BuildingMapDisplayable! { didSet { setupCell(with: building) } } fileprivate let safeInsetValue: CGFloat = 14 fileprivate var safeArea: UIView! fileprivate var mapView: MKMapView! // MARK: - Init override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Setup Cell extension BuildingMapCell { fileprivate func setupCell(with building: BuildingMapDisplayable) { mapView.setRegion(building.getRegion(), animated: false) mapView.addAnnotation(building.getAnnotation()) } } // MARK: - Initialize and Prepare UI extension BuildingMapCell { fileprivate func prepareUI() { prepareSafeArea() prepareMapView() } // MARK: Safe Area fileprivate func prepareSafeArea() { safeArea = getSafeAreaView() addSubview(safeArea) NSLayoutConstraint.activate([ safeArea.leadingAnchor.constraint(equalTo: leadingAnchor, constant: safeInsetValue * 2), safeArea.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -safeInsetValue * 2), safeArea.topAnchor.constraint(equalTo: topAnchor, constant: safeInsetValue), safeArea.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -safeInsetValue) ]) } // MARK: Map View fileprivate func prepareMapView() { mapView = getMapView() addSubview(mapView) NSLayoutConstraint.activate([ mapView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor), mapView.topAnchor.constraint(equalTo: safeArea.topAnchor), mapView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor), mapView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor) ]) } fileprivate func getSafeAreaView() -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view } fileprivate func getMapView() -> MKMapView { let mv = MKMapView(frame: safeArea.frame) mv.translatesAutoresizingMaskIntoConstraints = false mv.layer.cornerRadius = 10.0 mv.isScrollEnabled = false mv.setRegion(PennCoordinate.shared.getDefaultRegion(at: .close), animated: false) return mv } }
mit
3ced5f4be7a7eddb1010a1fac212c555
28.936842
103
0.671589
4.989474
false
false
false
false
AnthonyMDev/AmazonS3RequestManager
Source/Region.swift
2
2813
// // Region.swift // // Created by Anthony Miller on 1/17/17. // Copyright (c) 2017 App-Order, LLC. All rights reserved. // import Foundation /** MARK: Amazon S3 Regions The possible Amazon Web Service regions for the client. - USStandard: N. Virginia or Pacific Northwest - USWest1: Oregon - USWest2: N. California - EUWest1: Ireland - EUCentral1: Frankfurt - APSoutheast1: Singapore - APSoutheast2: Sydney - APNortheast1: Toyko - APNortheast2: Seoul - SAEast1: Sao Paulo */ public enum Region: Equatable { case USStandard, USWest1, USWest2, EUWest1, EUCentral1, APSoutheast1, APSoutheast2, APNortheast1, APNortheast2, SAEast1, custom(hostName: String, endpoint: String) var hostName: String { switch self { case .USStandard: return "us-east-1" case .USWest1: return "us-west-1" case .USWest2: return "us-west-2" case .EUWest1: return "eu-west-1" case .EUCentral1: return "eu-central-1" case .APSoutheast1: return "ap-southeast-1" case .APSoutheast2: return "ap-southeast-2" case .APNortheast1: return "ap-northeast-1" case .APNortheast2: return "ap-northeast-2" case .SAEast1: return "sa-east-1" case .custom(let hostName, _): return hostName } } var endpoint: String { switch self { case .USStandard: return "s3.amazonaws.com" case .USWest1: return "s3-us-west-1.amazonaws.com" case .USWest2: return "s3-us-west-2.amazonaws.com" case .EUWest1: return "s3-eu-west-1.amazonaws.com" case .EUCentral1: return "s3-eu-central-1.amazonaws.com" case .APSoutheast1: return "s3-ap-southeast-1.amazonaws.com" case .APSoutheast2: return "s3-ap-southeast-2.amazonaws.com" case .APNortheast1: return "s3-ap-northeast-1.amazonaws.com" case .APNortheast2: return "s3-ap-northeast-2.amazonaws.com" case .SAEast1: return "s3-sa-east-1.amazonaws.com" case .custom(_, let endpoint): return endpoint } } } public func ==(lhs: Region, rhs: Region) -> Bool { switch (lhs, rhs) { case (.USStandard, .USStandard), (.USWest1, .USWest1), (.USWest2, .USWest2), (.EUWest1, .EUWest1), (.EUCentral1, .EUCentral1), (.APSoutheast1, .APSoutheast1), (.APSoutheast2, .APSoutheast2), (.APNortheast1, .APNortheast1), (.APNortheast2, .APNortheast2), (.SAEast1, .SAEast1): return true case (.custom(let host1, let endpoint1), .custom(let host2, let endpoint2)): return host1 == host2 && endpoint1 == endpoint2 default: return false } }
mit
825623c3cec4407032a71e8f44f25d17
29.247312
80
0.605759
3.344828
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Healthcare
iOS/Healthcare/Views/RatingCollectionViewCell.swift
1
2612
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit /** CollectionViewCell consisting of a number label that varies in size if it is the most centered cell */ class RatingCollectionViewCell: UICollectionViewCell { var numberLabel: UILabel! /** Init method to initialize the UICollectionViewCell with a number label - parameter frame: size of the cell - returns: UICollectionViewCell object */ override init(frame: CGRect) { super.init(frame: frame) numberLabel = UILabel() numberLabel.textColor = UIColor(red: 128/255.0, green: 128/255.0, blue: 128/255.0, alpha: 1.0) numberLabel.font = UIFont(name: "RobotoSlab-Regular", size: 30) self.contentView.addSubview(numberLabel) setUpAutoLayoutConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Method to increase number size and animate with a popping effect */ func setAsHighlightedCell() { self.numberLabel.textColor = UIColor.whiteColor() self.numberLabel.font = UIFont(name: "RobotoSlab-Bold", size: 65) self.numberLabel.transform = CGAffineTransformScale(self.numberLabel.transform, 0.5, 0.5) UIView.animateWithDuration(0.3, animations: { self.numberLabel.transform = CGAffineTransformMakeScale(1.0,1.0) }) } /** Returns cells back to their original state and smaller size. */ func setAsNormalCell() { self.numberLabel.textColor = UIColor(red: 128/255.0, green: 128/255.0, blue: 128/255.0, alpha: 1.0) self.numberLabel.font = UIFont(name: "RobotoSlab-Regular", size: 30) self.numberLabel.transform = CGAffineTransformScale(self.numberLabel.transform, 2.0, 2.0) UIView.animateWithDuration(0.1, animations: { self.numberLabel.transform = CGAffineTransformMakeScale(1.0,1.0) }) } func setUpAutoLayoutConstraints() { self.numberLabel.translatesAutoresizingMaskIntoConstraints = false self.addConstraint(NSLayoutConstraint( item:self.numberLabel, attribute:.CenterX, relatedBy:.Equal, toItem:self, attribute:.CenterX, multiplier:1, constant:0)) self.addConstraint(NSLayoutConstraint( item:self.numberLabel, attribute:.CenterY, relatedBy:.Equal, toItem:self, attribute:.CenterY, multiplier:1, constant:0)) } }
epl-1.0
76b9388cfed02af421d285f5b2c19ab8
33.813333
107
0.65607
4.654189
false
false
false
false
tgu/HAP
Sources/HAP/Security/Cryptographer.swift
1
4209
import Evergreen import Foundation import HKDF fileprivate let logger = getLogger("hap.encryption") class UpgradeResponse: Response { let cryptographer: Cryptographer init(cryptographer: Cryptographer) { self.cryptographer = cryptographer super.init(status: .ok) } } // 5.5.2 Session Security // (...) // Each HTTP message is split into frames no larger than 1024 bytes. Each frame has the following format: // // <2:AAD for little endian length of encrypted data (n) in bytes> // <n:encrypted data according to AEAD algorithm, up to 1024 bytes> // <16:authTag according to AEAD algorithm> class Cryptographer { enum Error: Swift.Error { case invalidArgument case indexOutOfBounds } var encryptCount: UInt64 = 0 var decryptCount: UInt64 = 0 let decryptKey: Data let encryptKey: Data init(sharedKey: Data) { logger.debug("Shared key: \(sharedKey.hex)") decryptKey = HKDF.deriveKey(algorithm: .sha512, seed: sharedKey, info: "Control-Write-Encryption-Key".data(using: .utf8), salt: "Control-Salt".data(using: .utf8), count: 32) encryptKey = HKDF.deriveKey(algorithm: .sha512, seed: sharedKey, info: "Control-Read-Encryption-Key".data(using: .utf8), salt: "Control-Salt".data(using: .utf8), count: 32) logger.debug("Decrypt key: \(self.decryptKey.hex)") logger.debug("Encrypt key: \(self.encryptKey.hex)") } func decrypt(_ data: Data) throws -> Data { guard !data.isEmpty else { throw Error.invalidArgument } logger.info("Decrypt message #\(self.decryptCount), length: \(data.count)") logger.debug("Message cipher: \(data.hex)") var buffer = Data() var position = data.startIndex repeat { defer { decryptCount += 1 } let lengthBytes = data[position..<(position + 2)] let length = Int(UInt16(data: lengthBytes)) guard position + 2 + length + 16 <= data.endIndex else { throw Error.indexOutOfBounds } let nonce = decryptCount.bigEndian.bytes let cipher = data[(position + 2)..<(position + 2 + length + 16)] logger.debug("Ciphertext: \(cipher.hex), Nonce: \(nonce.hex), Length: \(length)") buffer += try ChaCha20Poly1305.decrypt(cipher: cipher, additional: lengthBytes, nonce: nonce, key: decryptKey) data.formIndex(&position, offsetBy: 2 + length + 16) } while position < data.endIndex logger.debug("Message data: \(data.hex)") return buffer } func encrypt(_ data: Data) throws -> Data { logger.info("Encrypt message #\(self.encryptCount), length: \(data.count)") logger.debug("Message data: \(data.hex)") var buffer = Data() var position = data.startIndex repeat { defer { encryptCount += 1 } let length = min(data.endIndex - position, 1024) let chunk = data[position..<(position + length)] let nonce = encryptCount.bigEndian.bytes let lengthBytes = UInt16(length).bigEndian.bytes logger.debug("Chunk: \(chunk.hex), Nonce: \(nonce.hex), Length: \(lengthBytes.hex)") let encrypted = try ChaCha20Poly1305.encrypt(message: chunk, additional: lengthBytes, nonce: nonce, key: encryptKey) buffer += lengthBytes + encrypted data.formIndex(&position, offsetBy: length) } while position < data.endIndex logger.debug("Cipher: \(buffer.hex)") return buffer } }
mit
143c4d552ebc245a7c43309e8198b0f5
41.515152
105
0.535044
4.810286
false
false
false
false
ndouglas/SwiftNetService
SwiftNetServiceTests/ServiceDelegateTests.swift
1
4006
// // ServiceDelegateTests.swift // SwiftNetService // // Created by Nathan Douglas on 11/5/15. // Copyright © 2015 Nathan Douglas. All rights reserved. // import XCTest import ReactiveCocoa @testable import SwiftNetService extension TestService { func resolveAndFulfillExpectation(expectation: XCTestExpectation, timeout: NSTimeInterval) { if self.browser == nil { self.browser = NSNetServiceBrowser() self.clientDelegate = BrowserDelegate() self.browser!.delegate = self.clientDelegate } self.clientDelegate?.servicesSignalProducer .reduceToServiceMatchingTestService(self) .flatMap(FlattenStrategy.Latest) { service -> ResolutionSignalProducerType in ServiceDelegate().resolveNetService(service, timeout: timeout) } .startWithCompleted({ expectation.fulfill() }) if !self.clientDelegate!.isSearching { self.browser!.searchForServicesOfType(self.type, inDomain: "local") } } func lookupAndFulfillExpectation(expectation: XCTestExpectation, timeout: NSTimeInterval) { if self.browser == nil { self.browser = NSNetServiceBrowser() self.clientDelegate = BrowserDelegate() self.browser!.delegate = self.clientDelegate } self.clientDelegate?.servicesSignalProducer .reduceToServiceMatchingTestService(self) .flatMap(FlattenStrategy.Latest) { service -> DictionarySignalProducerType in ServiceDelegate().lookupTXTRecordForNetService(service) } .startWithCompleted({ expectation.fulfill() }) if !self.clientDelegate!.isSearching { self.browser!.searchForServicesOfType(self.type, inDomain: "local") } } } class ServiceDelegateTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testServiceResolution() { // We're going to publish a net service and see if we find and resolve it. // Let's start up that service. let myTestService = TestService(port: 2015) let expectation = self.expectationWithDescription("published") myTestService.publishAndFulfillExpectation(expectation) self.waitForExpectationsWithTimeout(2.5, handler: nil) // The service was created and published successfully. // Next, let's start up a browser and try to find the service. let expectation2 = self.expectationWithDescription("found") myTestService.discoverAndFulfillExpectation(expectation2) self.waitForExpectationsWithTimeout(2.5, handler: nil) // The service was discovered. let expectation3 = self.expectationWithDescription("resolved") myTestService.resolveAndFulfillExpectation(expectation3, timeout: 15.0) self.waitForExpectationsWithTimeout(15.0, handler: nil) } func testServiceTXTRecordLookup() { // We're going to publish a net service and see if we find and resolve it. // Let's start up that service. let myTestService = TestService(port: 2015) let expectation = self.expectationWithDescription("published") myTestService.publishAndFulfillExpectation(expectation) self.waitForExpectationsWithTimeout(2.5, handler: nil) // The service was created and published successfully. // Next, let's start up a browser and try to find the service. let expectation2 = self.expectationWithDescription("found") myTestService.discoverAndFulfillExpectation(expectation2) self.waitForExpectationsWithTimeout(2.5, handler: nil) // The service was discovered. let expectation3 = self.expectationWithDescription("lookedup") myTestService.lookupAndFulfillExpectation(expectation3, timeout: 15.0) self.waitForExpectationsWithTimeout(15.0, handler: nil) } }
unlicense
f6385bf57200d72626ad6e3177c35b46
39.05
154
0.684894
5.06962
false
true
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
SechQueryComposer/SechQueryComposer/ViewController.swift
1
5502
// // ViewController.swift // SechQueryComposer // // Copyright © 2015 Peter Stoehr. All rights reserved. // import Cocoa class ViewController: NSViewController, NSTextFieldDelegate { @IBOutlet weak var mainTopicMatrx: NSMatrix! @IBOutlet weak var processBar: NSProgressIndicator! @IBOutlet weak var recommendButton: NSButton! @IBOutlet weak var isMainWidthCons: NSLayoutConstraint! @IBOutlet weak var resultTable: NSTableView! @IBOutlet weak var kw00: NSTextField! @IBOutlet weak var kw01: NSTextField! @IBOutlet weak var kw02: NSTextField! @IBOutlet weak var kw03: NSTextField! let cntKWS = 4 var isMainWidth = CGFloat(0.0) var recommendCTRL : RecommendationCTRL! var selectedRow = 0 // ################################ @IBAction func searchPressed(sender: NSButton) { let recData : ([String], Int?) if (checkForURL() == false) { print("Invalid URL") return } sender.hidden = true processBar.hidden = false processBar.startAnimation(self) recData = createRecommendInfo() recommendCTRL.getRecommendsForKeyWords(recData, dataSource: resultTable.dataSource() as! RecommendationDataSource){() -> Void in dispatch_async(dispatch_get_main_queue(), { self.resultTable.reloadData() self.recommendButton.hidden = false self.processBar.hidden = true self.processBar.stopAnimation(self) self.resultTable.enabled = true })} } private func createRecommendInfo() -> ([String], Int?) { var keyWords : [String] = [] var validKWS = 0; var isMainTopicIDX : Int? = nil var kwf = self.valueForKey("kw0\(validKWS)") as! NSTextField while((kwf.enabled) && (kwf.stringValue != "") && (validKWS < cntKWS-1)) { keyWords.append(kwf.stringValue) validKWS += 1 kwf = self.valueForKey("kw0\(validKWS)") as! NSTextField } if (validKWS >= 3) { isMainTopicIDX = mainTopicMatrx.selectedRow } return (keyWords, isMainTopicIDX) } // ################################ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. processBar.hidden = true isMainWidth = isMainWidthCons.constant isMainWidthCons.constant = 0.0 kw00.enabled = true kw00.selectable = true kw00.delegate = self for i in 1 ..< cntKWS { let kwf = self.valueForKey("kw0\(i)") as? NSTextField kwf!.enabled = false //kwf!.selectable = false kwf!.delegate = self } let dele = resultTable.delegate() as! RecommendationDelegate dele.viewCtrl = self resultTable.enabled = false resultTable.doubleAction = Selector("performSegue:") // Create the CTRLs recommendCTRL = RecommendationCTRL() } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } func performSegue(table : NSTableView) { let ds = resultTable.dataSource() as! RecommendationDataSource selectedRow = table.selectedRow NSWorkspace.sharedWorkspace().openURL(NSURL(string: ds.data[selectedRow].uri)!) //performSegueWithIdentifier("toWebView", sender: self) } override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "toWebView") { let ds = resultTable.dataSource() as! RecommendationDataSource let destCtrl = segue.destinationController as! WebViewCTRL destCtrl.url = ds.data[selectedRow].uri destCtrl.title = ds.data[selectedRow].title } } // Delegates fur Textfields override func controlTextDidEndEditing(obj: NSNotification) { if (kw03.stringValue == "") && (mainTopicMatrx.cellAtRow(3, column: 0) == mainTopicMatrx.selectedCell()) { mainTopicMatrx.selectCellAtRow(0, column: 0) } } override func controlTextDidChange(notification: NSNotification) { var firstEmpty = 1 while (firstEmpty < cntKWS) { let kwf = self.valueForKey("kw0\(firstEmpty)") as? NSTextField if (kwf!.stringValue == "") { break } firstEmpty += 1 } for i in 0 ..< cntKWS { let kwf = self.valueForKey("kw0\(i)") as? NSTextField kwf!.enabled = (i <= firstEmpty) } if (firstEmpty >= 3) { isMainWidthCons.constant = isMainWidth } else { isMainWidthCons.constant = 0 } mainTopicMatrx.cellAtRow(3, column: 0)?.enabled = (kw03.stringValue != "") } // TBDs func checkForURL() -> Bool { let p = Preferences() let urlStr = p.url let url = NSURL(string: urlStr) if (url == nil) {return false} let req = NSURLRequest(URL: url!) return NSURLConnection.canHandleRequest(req) } }
mit
dcfa0f268954087c155a28e41f26191c
28.10582
136
0.562625
4.738157
false
false
false
false
niklassaers/SnapTagsView
SnapTagsView/LessBuggyCollectionViewFlowLayout.swift
6
2123
import Foundation /* There is a bug in flow layout where it will not correctly lay out cells that are offscreen, but cache the error, and use that cache to show it incorrectly when coming on-screen again */ open class LessBuggyCollectionViewFlowLayout : UICollectionViewFlowLayout { override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if var attributes = super.layoutAttributesForElements(in: rect) { var i = 0 var fixInvaliidLayout = false for attribute in attributes { defer { i += 1 } if attribute.frame.origin.x == 0 && attribute.frame.origin.y == 0 { fixInvaliidLayout = true let attribute = attribute.copy() as! UICollectionViewLayoutAttributes attribute.frame.origin.y = sectionInset.top attributes[i] = attribute } } if fixInvaliidLayout == true { let sortedAttributes = attributes.sorted(by: { (a, b) -> Bool in if (a.indexPath as NSIndexPath).section == (b.indexPath as NSIndexPath).section { return (a.indexPath as NSIndexPath).item < (b.indexPath as NSIndexPath).row } return (a.indexPath as NSIndexPath).section < (b.indexPath as NSIndexPath).section }) var pos = sectionInset.left as CGFloat let relaidOutAttributes : [UICollectionViewLayoutAttributes] = sortedAttributes.map { inAttribute in let attribute = inAttribute.copy() as! UICollectionViewLayoutAttributes attribute.frame.origin.x = pos pos += attribute.frame.size.width + minimumInteritemSpacing return attribute } return relaidOutAttributes } return attributes } return nil } }
bsd-3-clause
d4ea571896ee0e388975c09cd0a50100
39.826923
116
0.557701
5.880886
false
false
false
false
paketehq/ios
Pakete/ColorPalette.swift
1
597
// // ColorPalette.swift // Pakete // // Created by Royce Albert Dy on 31/03/2016. // Copyright © 2016 Pakete. All rights reserved. // import UIKit struct ColorPalette { static let Matisse = UIColor(red:26.0/255.0, green:99.0/255.0, blue:167.0/255.0, alpha:1.00) static let Raven = UIColor(red:0.41, green:0.45, blue:0.49, alpha:1.00) static let BlackHaze = UIColor(red:0.97, green:0.97, blue:0.97, alpha:1) static let LavenderGray = UIColor(red:0.78, green:0.78, blue:0.80, alpha:1.00) static let SeaGreenMedium = UIColor(red:0.11, green:0.70, blue:0.38, alpha:1.00) }
mit
565a0284f23d5a448e112e2444250aa7
34.058824
96
0.676174
2.614035
false
false
false
false
ECP-CANDLE/Supervisor
workflows/cp-leaveout/swift/cpl-upf-workflow.swift
1
5865
/* CPL-UPF-WORKFLOW.SWIFT run with: 'swift-t workflow.swift <FILE SETTINGS>' FILE SETTINGS: These are mandatory: --plan_json=<FILE> : The JSON plan for topN_to_uno --dataframe_csv=<FILE> : The CSV data file for topN_to_uno --db_file=<FILE> : The SQLite DB file --benchmark_data=<DIR> : Location of Bencharks/Pilot1/Uno. Used by data_setup to set softlinks to Uno cache and uno_auc_model.txt --f : The UPF file --parent_stage_directory: The root experiment directory for the this runs parent stage. Child stages will look here for initial model weights by appending run/<parent_node_id> to this parent directory */ import assert; import io; import files; import python; import string; import sys; import plangen; import unix; // BEGIN WORKFLOW ARGUMENTS int stage = string2int(argv("stage")); string runtype; if (argv_contains("r")) { runtype = "plangen.RunType.RESTART"; } else { runtype = "plangen.RunType.RUN_ALL"; } file upf = input(argv("f")); string plan_json = argv("plan_json"); string dataframe_csv = argv("dataframe_csv"); string db_file = argv("db_file"); string benchmark_data = argv("benchmark_data"); string parent_stage_directory = argv("parent_stage_directory", ""); string turbine_output = getenv("TURBINE_OUTPUT"); # These 3 are used in obj_py so we need to initialize them here int benchmark_timeout = toint(getenv("BENCHMARK_TIMEOUT")); string model_name = getenv("MODEL_NAME"); string exp_id = getenv("EXPID"); // initial epochs int epochs = 6; // END WORKFLOW ARGUMENTS // For compatibility with obj(): global const string FRAMEWORK = "keras"; (string h_json) read_history(string node) { string history_file = "%s/run/%s/history.txt" % (turbine_output, node); if (file_exists(history_file)) { h_json = read(input(history_file)); } else { h_json = "{}"; } } /** RUN SINGLE: Set up and run a single model via obj(), plus the SQL ops */ (string r, string ins) run_single(string node, string plan_id) { json_fragment = make_json_fragment(node); json = "{\"node\": \"%s\", %s}" % (node, json_fragment); json2 = replace_all(json, "\n", " ", 0); db_start_result = plangen_start(db_file, plan_json, node, plan_id, runtype); ins = json2; assert(db_start_result != "EXCEPTION", "Exception in plangen_start()!"); if (db_start_result == "0") { r = obj(json2, node) => string hist_json = read_history(node); db_stop_result = plangen_stop(db_file, node, plan_id, hist_json) => assert(db_stop_result != "EXCEPTION", "Exception in plangen_stop()!") => printf("stop_subplan result: %s", db_stop_result); } else { printf("plan node already marked complete: %s result=%s", node, db_start_result) => r = "error"; } } /** MAKE JSON FRAGMENT: Construct the JSON parameter fragment for the model */ (string result) make_json_fragment(string this) { int this_ep; if (stage > 1) { this_ep = max_integer(epochs %/ float2int(pow_integer(2, (stage - 1))), 1); } else { this_ep = epochs; } //"pre_module": "data_setup", json_fragment = ---- "pre_module": "data_setup", "post_module": "data_setup", "plan": "%s", "config_file": "uno_auc_model.txt", "cache": "cache/top6_auc", "dataframe_from": "%s", "save_weights": "model.h5", "gpus": "0", "epochs": %i, "use_exported_data": "topN.uno.h5", "benchmark_data": "%s" ---- % (plan_json, dataframe_csv, this_ep, benchmark_data); if (stage > 1) { n = strlen(this); parent = substring(this, 0, n-2); result = json_fragment + ---- , "initial_weights": "%s/run/%s/model.h5" ---- % (parent_stage_directory, parent); } else { result = json_fragment; } } printf("CP LEAVEOUT UPF WORKFLOW START- UPF: %s, STAGE: %i", filename(upf), stage); (void o) write_lines(string lines[], string f) { string lines_string = join(lines,"\n"); fname = "%s/%s" % (turbine_output, f); file out <fname> = write(lines_string) => o = propagate(); } main() { string check = check_plangen() => printf("python result: import plangen: '%s'", check) => assert(check == "OK", "could not import plangen, check PYTHONPATH!"); string plan_id; if (stage > 1) { int b; file pif = input("%s/plan_id.txt" % parent_stage_directory); string parent_db_fname = "%s/%s" % (parent_stage_directory, basename_string(db_file)); if (file_exists(parent_db_fname)) { file parent_db = input(parent_db_fname); file dbf <db_file> = cp(parent_db) => b = 0; } else { b = 0; } // wait for db file to be copied to experiment directory // b waits for dbf to be created if its needs to be wait(b) { plan_id = trim(read(pif)); } } else { plan_id = init_plangen(db_file, plan_json, runtype); } // string plan_id = init_plangen(db_file, plan_json, runtype); printf("DB plan_id: %s", plan_id) => assert(plan_id != "EXCEPTION", "Plan prep failed!"); // If the plan already exists and we are not doing a restart, abort assert(plan_id != "-1", "Plan already exists!"); // Read unrolled parameter file string upf_lines[] = file_lines(upf); // Resultant output values: string results[]; // Evaluate each parameter set foreach params,i in upf_lines { // printf("params: %s", params); result, inputs = run_single(params, plan_id); results[i] = "%s|%s|%s" % (params, replace_all(inputs, "\n", " ", 0), result); } // string result = join(results, ";") => file out<"%s/plan_id.txt" % turbine_output> = write("%s\n" % plan_id); write_lines(results, "results.txt") => printf("CP LEAVEOUT WORKFLOW: RESULTS: COMPLETE"); }
mit
d6c553bb4bb86fa5d926ce541707e6c6
28.472362
111
0.609548
3.16343
false
false
false
false
Tyr0/PushUp-Proximity
PushUp Proximity/ViewController.swift
1
1554
// // ViewController.swift // PushUp Proximity // // Created by Tyler Calderone on 6/10/14. // Copyright (c) 2014 Tyler Calderone. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var textLabel: UILabel? var count:UInt = 0 { didSet { textLabel!.text = String(self.count) } } override func viewDidLoad() { super.viewDidLoad() // register for proximity state changes NSNotificationCenter.defaultCenter().addObserver(self, selector: "proximityChanged:", name: "UIDeviceProximityStateDidChangeNotification", object: nil) // enable proximity monitoring UIDevice.currentDevice().proximityMonitoringEnabled = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: NSNotificationCenter Observers func proximityChanged(notification: NSNotification) { // if proximity is currently down, increment count if (UIDevice.currentDevice().proximityState) { count++ } } // MARK: Interface Builder Methods @IBAction func resetCounter(sender: AnyObject?) { count = 0; } // MARK: Teardown deinit { // stop proximity monitoring UIDevice.currentDevice().proximityMonitoringEnabled = false // stop observing notifications NSNotificationCenter.defaultCenter().removeObserver(self) } }
mit
740999e631d3627e033240ca7b0ff23b
24.9
159
0.649292
5.414634
false
false
false
false
manavgabhawala/swift
test/SILGen/witnesses.swift
1
32703
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s infix operator <~> {} func archetype_method<T: X>(x: T, y: T) -> T { var x = x var y = y return x.selfTypes(x: y) } // CHECK-LABEL: sil hidden @_T09witnesses16archetype_method{{[_0-9a-zA-Z]*}}F{{.*}} : $@convention(thin) <T where T : X> (@in T, @in T) -> @out T { // CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes!1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0 // CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0 // CHECK: } func archetype_generic_method<T: X>(x: T, y: Loadable) -> Loadable { var x = x return x.generic(x: y) } // CHECK-LABEL: sil hidden @_T09witnesses24archetype_generic_method{{[_0-9a-zA-Z]*}}F{{.*}} : $@convention(thin) <T where T : X> (@in T, Loadable) -> Loadable { // CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic!1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0 // CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0 // CHECK: } // CHECK-LABEL: sil hidden @_T09witnesses32archetype_associated_type_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : WithAssoc> (@in T, @in T.AssocType) -> @out T // CHECK: apply %{{[0-9]+}}<T> func archetype_associated_type_method<T: WithAssoc>(x: T, y: T.AssocType) -> T { return x.useAssocType(x: y) } protocol StaticMethod { static func staticMethod() } // CHECK-LABEL: sil hidden @_T09witnesses23archetype_static_method{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : StaticMethod> (@in T) -> () func archetype_static_method<T: StaticMethod>(x: T) { // CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod!1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> () // CHECK: apply [[METHOD]]<T> T.staticMethod() } protocol Existentiable { func foo() -> Loadable func generic<T>() -> T } func protocol_method(x: Existentiable) -> Loadable { return x.foo() } // CHECK-LABEL: sil hidden @_T09witnesses15protocol_methodAA8LoadableVAA13Existentiable_p1x_tF : $@convention(thin) (@in Existentiable) -> Loadable { // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1 // CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}}) // CHECK: } func protocol_generic_method(x: Existentiable) -> Loadable { return x.generic() } // CHECK-LABEL: sil hidden @_T09witnesses23protocol_generic_methodAA8LoadableVAA13Existentiable_p1x_tF : $@convention(thin) (@in Existentiable) -> Loadable { // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1 // CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}}) // CHECK: } @objc protocol ObjCAble { func foo() } // CHECK-LABEL: sil hidden @_T09witnesses20protocol_objc_methodyAA8ObjCAble_p1x_tF : $@convention(thin) (@owned ObjCAble) -> () // CHECK: witness_method [volatile] $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign func protocol_objc_method(x: ObjCAble) { x.foo() } struct Loadable {} protocol AddrOnly {} protocol Classes : class {} protocol X { mutating func selfTypes(x: Self) -> Self mutating func loadable(x: Loadable) -> Loadable mutating func addrOnly(x: AddrOnly) -> AddrOnly mutating func generic<A>(x: A) -> A mutating func classes<A2: Classes>(x: A2) -> A2 static func <~>(_ x: Self, y: Self) -> Self } protocol Y {} protocol WithAssoc { associatedtype AssocType func useAssocType(x: AssocType) -> Self } protocol ClassBounded : class { func selfTypes(x: Self) -> Self } struct ConformingStruct : X { mutating func selfTypes(x: ConformingStruct) -> ConformingStruct { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformingStruct, @inout ConformingStruct) -> @out ConformingStruct { // CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct): // CHECK-NEXT: %3 = load [trivial] %1 : $*ConformingStruct // CHECK-NEXT: // function_ref // CHECK-NEXT: %4 = function_ref @_T09witnesses16ConformingStructV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct // CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct // CHECK-NEXT: store %5 to [trivial] %0 : $*ConformingStruct // CHECK-NEXT: %7 = tuple () // CHECK-NEXT: return %7 : $() // CHECK-NEXT: } mutating func loadable(x: Loadable) -> Loadable { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XA2aDP8loadable{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Loadable, @inout ConformingStruct) -> Loadable { // CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %2 = function_ref @_T09witnesses16ConformingStructV8loadable{{[_0-9a-zA-Z]*}}F : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable // CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable // CHECK-NEXT: return %3 : $Loadable // CHECK-NEXT: } mutating func addrOnly(x: AddrOnly) -> AddrOnly { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XA2aDP8addrOnly{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly { // CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_T09witnesses16ConformingStructV8addrOnly{{[_0-9a-zA-Z]*}}F : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly // CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() // CHECK-NEXT: } mutating func generic<C>(x: C) -> C { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0 { // CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_T09witnesses16ConformingStructV7generic{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0 // CHECK-NEXT: %4 = apply %3<τ_0_0>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0 // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() // CHECK-NEXT: } mutating func classes<C2: Classes>(x: C2) -> C2 { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XA2aDP7classes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0 { // CHECK: bb0(%0 : $τ_0_0, %1 : $*ConformingStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %2 = function_ref @_T09witnesses16ConformingStructV7classes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0 // CHECK-NEXT: %3 = apply %2<τ_0_0>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0 // CHECK-NEXT: return %3 : $τ_0_0 // CHECK-NEXT: } } func <~>(_ x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16ConformingStructVAA1XA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> @out ConformingStruct { // CHECK: bb0([[ARG1:%.*]] : $*ConformingStruct, [[ARG2:%.*]] : $*ConformingStruct, [[ARG3:%.*]] : $*ConformingStruct, [[ARG4:%.*]] : $@thick ConformingStruct.Type): // CHECK-NEXT: [[LOADED_ARG2:%.*]] = load [trivial] [[ARG2]] : $*ConformingStruct // CHECK-NEXT: [[LOADED_ARG3:%.*]] = load [trivial] [[ARG3]] : $*ConformingStruct // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FUNC:%.*]] = function_ref @_T09witnesses3ltgoiAA16ConformingStructVAD_ADtF : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct // CHECK-NEXT: [[FUNC_RESULT:%.*]] = apply [[FUNC]]([[LOADED_ARG2]], [[LOADED_ARG3]]) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct // CHECK-NEXT: store [[FUNC_RESULT]] to [trivial] [[ARG1]] : $*ConformingStruct // CHECK-NEXT: %9 = tuple () // CHECK-NEXT: return %9 : $() // CHECK-NEXT: } final class ConformingClass : X { func selfTypes(x: ConformingClass) -> ConformingClass { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses15ConformingClassCAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformingClass, @inout ConformingClass) -> @out ConformingClass { // CHECK: bb0([[ARG1:%.*]] : $*ConformingClass, [[ARG2:%.*]] : $*ConformingClass, [[ARG3:%.*]] : $*ConformingClass): // -- load and copy_value 'self' from inout witness 'self' parameter // CHECK: [[ARG3_LOADED:%.*]] = load [copy] [[ARG3]] : $*ConformingClass // CHECK: [[ARG2_LOADED:%.*]] = load [take] [[ARG2]] : $*ConformingClass // CHECK: [[FUNC:%.*]] = function_ref @_T09witnesses15ConformingClassC9selfTypes{{[_0-9a-zA-Z]*}}F // CHECK: [[BORROWED_ARG3_LOADED:%.*]] = begin_borrow [[ARG3_LOADED]] // CHECK: [[FUNC_RESULT:%.*]] = apply [[FUNC]]([[ARG2_LOADED]], [[BORROWED_ARG3_LOADED]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass // CHECK: store [[FUNC_RESULT]] to [init] [[ARG1]] : $*ConformingClass // CHECK: end_borrow [[BORROWED_ARG3_LOADED]] from [[ARG3_LOADED]] // CHECK: destroy_value [[ARG3_LOADED]] // CHECK: } // end sil function '_T09witnesses15ConformingClassCAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW' func loadable(x: Loadable) -> Loadable { return x } func addrOnly(x: AddrOnly) -> AddrOnly { return x } func generic<D>(x: D) -> D { return x } func classes<D2: Classes>(x: D2) -> D2 { return x } } func <~>(_ x: ConformingClass, y: ConformingClass) -> ConformingClass { return x } extension ConformingClass : ClassBounded { } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses15ConformingClassCAA0C7BoundedA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass { // CHECK: bb0([[C0:%.*]] : $ConformingClass, [[C1:%.*]] : $ConformingClass): // CHECK-NEXT: [[C1_COPY:%.*]] = copy_value [[C1]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @_T09witnesses15ConformingClassC9selfTypes{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: [[BORROWED_C1_COPY:%.*]] = begin_borrow [[C1_COPY]] // CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[BORROWED_C1_COPY]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass // CHECK-NEXT: end_borrow [[BORROWED_C1_COPY]] from [[C1_COPY]] // CHECK-NEXT: destroy_value [[C1_COPY]] // CHECK-NEXT: return [[RESULT]] : $ConformingClass // CHECK-NEXT: } struct ConformingAOStruct : X { var makeMeAO : AddrOnly mutating func selfTypes(x: ConformingAOStruct) -> ConformingAOStruct { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18ConformingAOStructVAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct { // CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_T09witnesses18ConformingAOStructV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct // CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() // CHECK-NEXT: } func loadable(x: Loadable) -> Loadable { return x } func addrOnly(x: AddrOnly) -> AddrOnly { return x } func generic<D>(x: D) -> D { return x } func classes<D2: Classes>(x: D2) -> D2 { return x } } func <~>(_ x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x } struct ConformsWithMoreGeneric : X, Y { mutating func selfTypes<E>(x: E) -> E { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XA2aDP9selfTypes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in ConformsWithMoreGeneric, @inout ConformsWithMoreGeneric) -> @out ConformsWithMoreGeneric { // CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_T09witnesses23ConformsWithMoreGenericV9selfTypes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } func loadable<F>(x: F) -> F { return x } mutating func addrOnly<G>(x: G) -> G { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XA2aDP8addrOnly{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in AddrOnly, @inout ConformsWithMoreGeneric) -> @out AddrOnly { // CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_T09witnesses23ConformsWithMoreGenericV8addrOnly{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } mutating func generic<H>(x: H) -> H { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 { // CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*ConformsWithMoreGeneric): // CHECK-NEXT: // function_ref // CHECK-NEXT: %3 = function_ref @_T09witnesses23ConformsWithMoreGenericV7generic{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: %4 = apply %3<τ_0_0>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } mutating func classes<I>(x: I) -> I { return x } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XA2aDP7classes{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformsWithMoreGeneric) -> @owned τ_0_0 { // CHECK: bb0(%0 : $τ_0_0, %1 : $*ConformsWithMoreGeneric): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $τ_0_0 // CHECK-NEXT: store %0 to [init] [[SELF_BOX]] : $*τ_0_0 // CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes // CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_T09witnesses23ConformsWithMoreGenericV7classes{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<τ_0_0>([[RESULT_BOX]], [[SELF_BOX]], %1) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0 // CHECK-NEXT: [[RESULT:%.*]] = load [take] [[RESULT_BOX]] : $*τ_0_0 // CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*τ_0_0 // CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*τ_0_0 // CHECK-NEXT: return [[RESULT]] : $τ_0_0 // CHECK-NEXT: } } func <~> <J: Y, K: Y>(_ x: J, y: K) -> K { return y } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses23ConformsWithMoreGenericVAA1XA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method) (@in ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @thick ConformsWithMoreGeneric.Type) -> @out ConformsWithMoreGeneric { // CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_T09witnesses3ltgoi{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1 // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } protocol LabeledRequirement { func method(x: Loadable) } struct UnlabeledWitness : LabeledRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16UnlabeledWitnessVAA18LabeledRequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Loadable, @in_guaranteed UnlabeledWitness) -> () func method(x _: Loadable) {} } protocol LabeledSelfRequirement { func method(x: Self) } struct UnlabeledSelfWitness : LabeledSelfRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses20UnlabeledSelfWitnessVAA07LabeledC11RequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in UnlabeledSelfWitness, @in_guaranteed UnlabeledSelfWitness) -> () func method(x _: UnlabeledSelfWitness) {} } protocol UnlabeledRequirement { func method(x _: Loadable) } struct LabeledWitness : UnlabeledRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses14LabeledWitnessVAA20UnlabeledRequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Loadable, @in_guaranteed LabeledWitness) -> () func method(x: Loadable) {} } protocol UnlabeledSelfRequirement { func method(_: Self) } struct LabeledSelfWitness : UnlabeledSelfRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18LabeledSelfWitnessVAA09UnlabeledC11RequirementA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in LabeledSelfWitness, @in_guaranteed LabeledSelfWitness) -> () func method(_ x: LabeledSelfWitness) {} } protocol ReadOnlyRequirement { var prop: String { get } static var prop: String { get } } struct ImmutableModel: ReadOnlyRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses14ImmutableModelVAA19ReadOnlyRequirementA2aDP4propSSfgTW : $@convention(witness_method) (@in_guaranteed ImmutableModel) -> @owned String let prop: String = "a" // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses14ImmutableModelVAA19ReadOnlyRequirementA2aDP4propSSfgZTW : $@convention(witness_method) (@thick ImmutableModel.Type) -> @owned String static let prop: String = "b" } protocol FailableRequirement { init?(foo: Int) } protocol NonFailableRefinement: FailableRequirement { init(foo: Int) } protocol IUOFailableRequirement { init!(foo: Int) } struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16NonFailableModelVAA0C11Requirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out Optional<NonFailableModel> // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16NonFailableModelVAA0bC10Refinement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out NonFailableModel // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16NonFailableModelVAA22IUOFailableRequirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out Optional<NonFailableModel> init(foo: Int) {} } struct FailableModel: FailableRequirement, IUOFailableRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses13FailableModelVAA0B11Requirement{{[_0-9a-zA-Z]*}}fCTW // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses13FailableModelVAA22IUOFailableRequirement{{[_0-9a-zA-Z]*}}fCTW // CHECK: bb0([[SELF:%[0-9]+]] : $*Optional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type): // CHECK: [[FN:%.*]] = function_ref @_T09witnesses13FailableModelV{{[_0-9a-zA-Z]*}}fC // CHECK: [[INNER:%.*]] = apply [[FN]]( // CHECK: store [[INNER]] to [trivial] [[SELF]] // CHECK: return init?(foo: Int) {} } struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16IUOFailableModelVAA21NonFailableRefinement{{[_0-9a-zA-Z]*}}fCTW // CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type): // CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type // CHECK: [[INIT:%[0-9]+]] = function_ref @_T09witnesses16IUOFailableModelV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thin IUOFailableModel.Type) -> Optional<IUOFailableModel> // CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(method) (Int, @thin IUOFailableModel.Type) -> Optional<IUOFailableModel> // CHECK: bb2([[RESULT:%.*]] : $IUOFailableModel): // CHECK: store [[RESULT]] to [trivial] [[SELF]] : $*IUOFailableModel // CHECK: return init!(foo: Int) { return nil } } protocol FailableClassRequirement: class { init?(foo: Int) } protocol NonFailableClassRefinement: FailableClassRequirement { init(foo: Int) } protocol IUOFailableClassRequirement: class { init!(foo: Int) } final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21NonFailableClassModelCAA0cD11Requirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel> // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21NonFailableClassModelCAA0bcD10Refinement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned NonFailableClassModel // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21NonFailableClassModelCAA011IUOFailableD11Requirement{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel> init(foo: Int) {} } final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18FailableClassModelCAA0bC11Requirement{{[_0-9a-zA-Z]*}}fCTW // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses18FailableClassModelCAA011IUOFailableC11Requirement{{[_0-9a-zA-Z]*}}fCTW // CHECK: [[FUNC:%.*]] = function_ref @_T09witnesses18FailableClassModelC{{[_0-9a-zA-Z]*}}fC // CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1) // CHECK: return [[INNER]] : $Optional<FailableClassModel> init?(foo: Int) {} } final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21IUOFailableClassModelCAA011NonFailableC10Refinement{{[_0-9a-zA-Z]*}}fCTW // CHECK: bb0({{.*}}): // CHECK: [[FUNC:%.*]] = function_ref @_T09witnesses21IUOFailableClassModelCSQyACGSi3foo_tcfC : $@convention(method) (Int, @thick IUOFailableClassModel.Type) -> @owned Optional<IUOFailableClassModel> // CHECK: [[VALUE:%.*]] = apply [[FUNC]]({{.*}}) // CHECK: switch_enum [[VALUE]] : $Optional<IUOFailableClassModel>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NONEBB:bb[0-9]+]] // // CHECK: [[NONEBB]]: // CHECK: unreachable // // CHECK: [[SOMEBB]]([[RESULT:%.*]] : $IUOFailableClassModel) // CHECK: return [[RESULT]] : $IUOFailableClassModel // CHECK: } // end sil function '_T09witnesses21IUOFailableClassModelCAA011NonFailableC10Refinement{{[_0-9a-zA-Z]*}}fCTW' // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21IUOFailableClassModelCAA0bC11Requirement{{[_0-9a-zA-Z]*}}fCTW init!(foo: Int) {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses21IUOFailableClassModelCAA08FailableC11Requirement{{[_0-9a-zA-Z]*}}fCTW // CHECK: [[FUNC:%.*]] = function_ref @_T09witnesses21IUOFailableClassModelC{{[_0-9a-zA-Z]*}}fC // CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1) // CHECK: return [[INNER]] : $Optional<IUOFailableClassModel> } protocol HasAssoc { associatedtype Assoc } protocol GenericParameterNameCollisionProtocol { func foo<T>(_ x: T) associatedtype Assoc2 func bar<T>(_ x: (T) -> Assoc2) } struct GenericParameterNameCollision<T: HasAssoc> : GenericParameterNameCollisionProtocol { // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2A8HasAssocRzlAaEP3fooyqd__lFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@in τ_1_0, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () { // CHECK: bb0(%0 : $*τ_1_0, %1 : $*GenericParameterNameCollision<τ_0_0>): // CHECK: apply {{%.*}}<τ_0_0, τ_1_0> func foo<U>(_ x: U) {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2A8HasAssocRzlAaEP3bary6Assoc2Qzqd__clFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@owned @callee_owned (@in τ_1_0) -> @out τ_0_0.Assoc, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () { // CHECK: bb0(%0 : $@callee_owned (@in τ_1_0) -> @out τ_0_0.Assoc, %1 : $*GenericParameterNameCollision<τ_0_0>): // CHECK: apply {{%.*}}<τ_0_0, τ_1_0> func bar<V>(_ x: (V) -> T.Assoc) {} } protocol PropertyRequirement { var width: Int { get set } static var height: Int { get set } var depth: Int { get set } } class PropertyRequirementBase { var width: Int = 12 static var height: Int = 13 } class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement { var depth: Int = 14 // Make sure the contravariant return type in materializeForSet works correctly // If the witness is in a base class of the conforming class, make sure we have a bit_cast in there: // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses34PropertyRequirementWitnessFromBaseCAA0bC0A2aDP5widthSifmTW : {{.*}} { // CHECK: bb0({{.*}} : $Builtin.RawPointer, {{.*}} : $*Builtin.UnsafeValueBuffer, [[ARG2:%.*]] : $*PropertyRequirementWitnessFromBase): // CHECK-NEXT: [[ARG2_LOADED:%[0-9][0-9]*]] = load [copy] [[ARG2]] // CHECK-NEXT: [[CAST_ARG2_LOADED:%[0-9][0-9]*]] = upcast [[ARG2_LOADED]] : $PropertyRequirementWitnessFromBase to $PropertyRequirementBase // CHECK-NEXT: [[BORROWED_CAST_ARG2_LOADED:%[0-9][0-9]*]] = begin_borrow [[CAST_ARG2_LOADED]] : $PropertyRequirementBase // CHECK-NEXT: [[METH:%.*]] = class_method [[BORROWED_CAST_ARG2_LOADED]] : $PropertyRequirementBase, #PropertyRequirementBase.width!materializeForSet.1 // CHECK-NEXT: [[RES:%.*]] = apply [[METH]]({{.*}}, {{.*}}, [[BORROWED_CAST_ARG2_LOADED]]) : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed PropertyRequirementBase) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0 // CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1 // CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CADR]] : {{.*}}) // CHECK-NEXT: end_borrow [[BORROWED_CAST_ARG2_LOADED]] from [[CAST_ARG2_LOADED]] // CHECK-NEXT: destroy_value [[ARG2_LOADED]] // CHECK-NEXT: return [[TUPLE]] // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses34PropertyRequirementWitnessFromBaseCAA0bC0A2aDP6heightSifmZTW : {{.*}} { // CHECK: [[OBJ:%.*]] = upcast %2 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type // CHECK: [[METH:%.*]] = function_ref @_T09witnesses23PropertyRequirementBaseC6heightSifmZ // CHECK-NEXT: [[RES:%.*]] = apply [[METH]] // CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0 // CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1 // CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CADR]] : {{.*}}) // CHECK-NEXT: return [[TUPLE]] // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses34PropertyRequirementWitnessFromBaseCAA0bC0A2aDP5depthSifmTW // CHECK: bb0({{.*}} : $Builtin.RawPointer, {{.*}} : $*Builtin.UnsafeValueBuffer, [[ARG2:%.*]] : $*PropertyRequirementWitnessFromBase): // CHECK: [[ARG2_LOADED:%[0-9][0-9]*]] = load [copy] [[ARG2]] // CHECK: [[METH:%.*]] = class_method [[ARG2_LOADED]] : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!materializeForSet.1 // CHECK-NEXT: [[BORROWED_ARG2_LOADED:%.*]] = begin_borrow [[ARG2_LOADED]] // CHECK-NEXT: [[RES:%.*]] = apply [[METH]]({{.*}}, {{.*}}, [[BORROWED_ARG2_LOADED]]) : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed PropertyRequirementWitnessFromBase) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK-NEXT: tuple_extract // CHECK-NEXT: tuple_extract // CHECK-NEXT: [[RES:%.*]] = tuple // CHECK-NEXT: end_borrow [[BORROWED_ARG2_LOADED]] from [[ARG2_LOADED]] // CHECK-NEXT: destroy_value [[ARG2_LOADED]] // CHECK-NEXT: return [[RES]] } protocol Crashable { func crash() } class CrashableBase { func crash() {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T09witnesses16GenericCrashableCyxGAA0C0AAlAaEP5crashyyFTW : $@convention(witness_method) <τ_0_0> (@in_guaranteed GenericCrashable<τ_0_0>) -> () // CHECK: bb0(%0 : $*GenericCrashable<τ_0_0>): // CHECK-NEXT: [[BOX:%.*]] = alloc_stack $GenericCrashable<τ_0_0> // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]] : $*GenericCrashable<τ_0_0> // CHECK-NEXT: [[SELF:%.*]] = load [take] [[BOX]] : $*GenericCrashable<τ_0_0> // CHECK-NEXT: [[BASE:%.*]] = upcast [[SELF]] : $GenericCrashable<τ_0_0> to $CrashableBase // CHECK-NEXT: [[BORROWED_BASE:%.*]] = begin_borrow [[BASE]] // CHECK-NEXT: [[FN:%.*]] = class_method [[BORROWED_BASE]] : $CrashableBase, #CrashableBase.crash!1 : (CrashableBase) -> () -> (), $@convention(method) (@guaranteed CrashableBase) -> () // CHECK-NEXT: apply [[FN]]([[BORROWED_BASE]]) : $@convention(method) (@guaranteed CrashableBase) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: end_borrow [[BORROWED_BASE]] from [[BASE]] // CHECK-NEXT: destroy_value [[SELF]] : $GenericCrashable<τ_0_0> // CHECK-NEXT: dealloc_stack [[BOX]] : $*GenericCrashable<τ_0_0> // CHECK-NEXT: return [[RESULT]] : $() class GenericCrashable<T> : CrashableBase, Crashable {}
apache-2.0
f6a36fcf2da6530217e6bbc42b9bd7ed
61.028571
343
0.663504
3.209639
false
false
false
false
amomchilov/ZipNsequence
Zip7Sequence.swift
1
7776
/// Creates a sequence of tuples built out of 7 underlying sequences. /// /// In the `Zip7Sequence` instance returned by this function, the elements of /// the *i*th tuple are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the 7 sequences passed to `zip(_:_:_:_:_:_:_:)` are different lengths, the /// resulting sequence is the same length as the shortest sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The sequence or collection in position 1 of each tuple. /// - sequence2: The sequence or collection in position 2 of each tuple. /// - sequence3: The sequence or collection in position 3 of each tuple. /// - sequence4: The sequence or collection in position 4 of each tuple. /// - sequence5: The sequence or collection in position 5 of each tuple. /// - sequence6: The sequence or collection in position 6 of each tuple. /// - sequence7: The sequence or collection in position 7 of each tuple. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. public func zip< Sequence1 : Sequence, Sequence2 : Sequence, Sequence3 : Sequence, Sequence4 : Sequence, Sequence5 : Sequence, Sequence6 : Sequence, Sequence7 : Sequence >( _ sequence1: Sequence1, _ sequence2: Sequence2, _ sequence3: Sequence3, _ sequence4: Sequence4, _ sequence5: Sequence5, _ sequence6: Sequence6, _ sequence7: Sequence7 ) -> Zip7Sequence< Sequence1, Sequence2, Sequence3, Sequence4, Sequence5, Sequence6, Sequence7 > { return Zip7Sequence( _sequence1: sequence1, _sequence2: sequence2, _sequence3: sequence3, _sequence4: sequence4, _sequence5: sequence5, _sequence6: sequence6, _sequence7: sequence7 ) } /// An iterator for `Zip7Sequence`. public struct Zip7Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol, Iterator3 : IteratorProtocol, Iterator4 : IteratorProtocol, Iterator5 : IteratorProtocol, Iterator6 : IteratorProtocol, Iterator7 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = ( Iterator1.Element, Iterator2.Element, Iterator3.Element, Iterator4.Element, Iterator5.Element, Iterator6.Element, Iterator7.Element ) /// Creates an instance around the underlying iterators. internal init( _ iterator1: Iterator1, _ iterator2: Iterator2, _ iterator3: Iterator3, _ iterator4: Iterator4, _ iterator5: Iterator5, _ iterator6: Iterator6, _ iterator7: Iterator7 ) { _baseStream1 = iterator1 _baseStream2 = iterator2 _baseStream3 = iterator3 _baseStream4 = iterator4 _baseStream5 = iterator5 _baseStream6 = iterator6 _baseStream7 = iterator7 } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next(), let element3 = _baseStream3.next(), let element4 = _baseStream4.next(), let element5 = _baseStream5.next(), let element6 = _baseStream6.next(), let element7 = _baseStream7.next() else { _reachedEnd = true return nil } return ( element1, element2, element3, element4, element5, element6, element7 ) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _baseStream3: Iterator3 internal var _baseStream4: Iterator4 internal var _baseStream5: Iterator5 internal var _baseStream6: Iterator6 internal var _baseStream7: Iterator7 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip7Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip7Sequence` instance, /// use the `zip(_:_:_:_:_:_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// - SeeAlso: `zip(_:_:_:_:_:_:_:)` public struct Zip7Sequence< Sequence1 : Sequence, Sequence2 : Sequence, Sequence3 : Sequence, Sequence4 : Sequence, Sequence5 : Sequence, Sequence6 : Sequence, Sequence7 : Sequence > : Sequence { public typealias Stream1 = Sequence1.Iterator public typealias Stream2 = Sequence2.Iterator public typealias Stream3 = Sequence3.Iterator public typealias Stream4 = Sequence4.Iterator public typealias Stream5 = Sequence5.Iterator public typealias Stream6 = Sequence6.Iterator public typealias Stream7 = Sequence7.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip7Iterator< Stream1, Stream2, Stream3, Stream4, Stream5, Stream6, Stream7 > @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init( _sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2, _sequence3 sequence3: Sequence3, _sequence4 sequence4: Sequence4, _sequence5 sequence5: Sequence5, _sequence6 sequence6: Sequence6, _sequence7 sequence7: Sequence7 ) { _sequence1 = sequence1 _sequence2 = sequence2 _sequence3 = sequence3 _sequence4 = sequence4 _sequence5 = sequence5 _sequence6 = sequence6 _sequence7 = sequence7 } /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator(), _sequence3.makeIterator(), _sequence4.makeIterator(), _sequence5.makeIterator(), _sequence6.makeIterator(), _sequence7.makeIterator() ) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 internal let _sequence3: Sequence3 internal let _sequence4: Sequence4 internal let _sequence5: Sequence5 internal let _sequence6: Sequence6 internal let _sequence7: Sequence7 }
apache-2.0
1527aadee57d5df9333a433f6197b793
28.911538
81
0.663066
3.949213
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Common/UI/Cells/ReceiptCell.swift
2
3011
// // ReceiptCell.swift // SmartReceipts // // Created by Bogdan Evsenev on 12/08/2018. // Copyright © 2018 Will Baumann. All rights reserved. // import UIKit import RxSwift class ReceiptCell: SyncableTableCell { @IBOutlet private weak var priceLabel: UILabel! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var imageButton: UIButton! @IBOutlet private weak var categoryLabel: UILabel! private let bag = DisposeBag() var onImageTap: VoidBlock? override func awakeFromNib() { super.awakeFromNib() imageButton.rx.tap .subscribe(onNext: { [weak self] in self?.onImageTap?() }).disposed(by: bag) imageButton.layer.cornerRadius = Constants.imageRadius imageButton.layer.masksToBounds = true } override func prepareForReuse() { super.prepareForReuse() imageButton.setImage(Constants.cameraImage, for: .normal) } @discardableResult func configure(receipt: WBReceipt) -> Self { priceLabel.text = receipt.formattedPrice() nameLabel.text = receipt.name categoryLabel.text = receipt.category?.name var image: UIImage? let path = receipt.imageFilePath(for: receipt.trip) if receipt.hasImage() { image = UIImage(contentsOfFile: path) } else if receipt.hasPDF() { image = generatePDFIcon(url: URL(fileURLWithPath: path)) } updateState(receipt: receipt) guard let buttonImage = image else { return self } imageButton.setImage(buttonImage.withRenderingMode(.alwaysOriginal), for: .normal) return self } private func updateState(receipt: WBReceipt) { var state: ModelSyncState = .disabled if SyncProvider.current != .none { if receipt.attachemntType != .none { state = receipt.isSynced(syncProvider: .last) ? .synced : .notSynced } else { state = .modelState(modelChangeDate: receipt.lastLocalModificationTime) } } setState(state) } private func generatePDFIcon(url: URL) -> UIImage? { guard let document = CGPDFDocument(url as CFURL) else { return nil } guard let page = document.page(at: 1) else { return nil } let pageRect = page.getBoxRect(.mediaBox) let renderer = UIGraphicsImageRenderer(size: pageRect.size) let img = renderer.image { ctx in UIColor.white.set() ctx.fill(pageRect) ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height) ctx.cgContext.scaleBy(x: 1.0, y: -1.0) ctx.cgContext.drawPDFPage(page) } return img } } private extension ReceiptCell { struct Constants { static let imageRadius: CGFloat = 9 static let cameraImage = #imageLiteral(resourceName: "camera-icon") } }
agpl-3.0
fc7c85d75cd5f8d6016c24b4f6940509
30.354167
90
0.615282
4.659443
false
false
false
false
tbkka/swift-protobuf
Tests/SwiftProtobufTests/Test_JSON.swift
3
58778
// Tests/SwiftProtobufTests/Test_JSON.swift - Exercise JSON coding // // Copyright (c) 2014 - 2019 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// JSON is a major new feature for Proto3. This test suite exercises /// the JSON coding for all primitive types, including boundary and error /// cases. /// // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobuf class Test_JSON: XCTestCase, PBTestHelpers { typealias MessageTestType = Proto3Unittest_TestAllTypes private func configureLargeObject(_ o: inout MessageTestType) { o.optionalInt32 = 1 o.optionalInt64 = 2 o.optionalUint32 = 3 o.optionalUint64 = 4 o.optionalSint32 = 5 o.optionalSint64 = 6 o.optionalFixed32 = 7 o.optionalFixed64 = 8 o.optionalSfixed32 = 9 o.optionalSfixed64 = 10 o.optionalFloat = 11 o.optionalDouble = 12 o.optionalBool = true o.optionalString = "abc" o.optionalBytes = Data([65, 66]) var nested = MessageTestType.NestedMessage() nested.bb = 7 o.optionalNestedMessage = nested var foreign = Proto3Unittest_ForeignMessage() foreign.c = 88 o.optionalForeignMessage = foreign var importMessage = ProtobufUnittestImport_ImportMessage() importMessage.d = -9 o.optionalImportMessage = importMessage o.optionalNestedEnum = .baz o.optionalForeignEnum = .foreignBaz var publicImportMessage = ProtobufUnittestImport_PublicImportMessage() publicImportMessage.e = -999999 o.optionalPublicImportMessage = publicImportMessage o.repeatedInt32 = [1, 2] o.repeatedInt64 = [3, 4] o.repeatedUint32 = [5, 6] o.repeatedUint64 = [7, 8] o.repeatedSint32 = [9, 10] o.repeatedSint64 = [11, 12] o.repeatedFixed32 = [13, 14] o.repeatedFixed64 = [15, 16] o.repeatedSfixed32 = [17, 18] o.repeatedSfixed64 = [19, 20] o.repeatedFloat = [21, 22] o.repeatedDouble = [23, 24] o.repeatedBool = [true, false] o.repeatedString = ["abc", "def"] o.repeatedBytes = [Data(), Data([65, 66])] var nested2 = nested nested2.bb = -7 o.repeatedNestedMessage = [nested, nested2] var foreign2 = foreign foreign2.c = -88 o.repeatedForeignMessage = [foreign, foreign2] var importMessage2 = importMessage importMessage2.d = 999999 o.repeatedImportMessage = [importMessage, importMessage2] o.repeatedNestedEnum = [.bar, .baz] o.repeatedForeignEnum = [.foreignBar, .foreignBaz] var publicImportMessage2 = publicImportMessage publicImportMessage2.e = 999999 o.oneofUint32 = 99 } func testMultipleFields() { let expected: String = ("{" + "\"optionalInt32\":1," + "\"optionalInt64\":\"2\"," + "\"optionalUint32\":3," + "\"optionalUint64\":\"4\"," + "\"optionalSint32\":5," + "\"optionalSint64\":\"6\"," + "\"optionalFixed32\":7," + "\"optionalFixed64\":\"8\"," + "\"optionalSfixed32\":9," + "\"optionalSfixed64\":\"10\"," + "\"optionalFloat\":11.0," + "\"optionalDouble\":12.0," + "\"optionalBool\":true," + "\"optionalString\":\"abc\"," + "\"optionalBytes\":\"QUI=\"," + "\"optionalNestedMessage\":{\"bb\":7}," + "\"optionalForeignMessage\":{\"c\":88}," + "\"optionalImportMessage\":{\"d\":-9}," + "\"optionalNestedEnum\":\"BAZ\"," + "\"optionalForeignEnum\":\"FOREIGN_BAZ\"," + "\"optionalPublicImportMessage\":{\"e\":-999999}," + "\"repeatedInt32\":[1,2]," + "\"repeatedInt64\":[\"3\",\"4\"]," + "\"repeatedUint32\":[5,6]," + "\"repeatedUint64\":[\"7\",\"8\"]," + "\"repeatedSint32\":[9,10]," + "\"repeatedSint64\":[\"11\",\"12\"]," + "\"repeatedFixed32\":[13,14]," + "\"repeatedFixed64\":[\"15\",\"16\"]," + "\"repeatedSfixed32\":[17,18]," + "\"repeatedSfixed64\":[\"19\",\"20\"]," + "\"repeatedFloat\":[21.0,22.0]," + "\"repeatedDouble\":[23.0,24.0]," + "\"repeatedBool\":[true,false]," + "\"repeatedString\":[\"abc\",\"def\"]," + "\"repeatedBytes\":[\"\",\"QUI=\"]," + "\"repeatedNestedMessage\":[{\"bb\":7},{\"bb\":-7}]," + "\"repeatedForeignMessage\":[{\"c\":88},{\"c\":-88}]," + "\"repeatedImportMessage\":[{\"d\":-9},{\"d\":999999}]," + "\"repeatedNestedEnum\":[\"BAR\",\"BAZ\"]," + "\"repeatedForeignEnum\":[\"FOREIGN_BAR\",\"FOREIGN_BAZ\"]," + "\"oneofUint32\":99" + "}") assertJSONEncode(expected, configure: configureLargeObject) } // See if we can crash the JSON parser by trying every possible // truncation of the large message above. func testTruncation() throws { var m = MessageTestType() configureLargeObject(&m) let s = try m.jsonString() var truncated = "" for c in s { truncated.append(c) do { _ = try MessageTestType(jsonString: truncated) } catch _ { continue } } } func testOptionalInt32() { assertJSONEncode("{\"optionalInt32\":1}") {(o: inout MessageTestType) in o.optionalInt32 = 1 } assertJSONEncode("{\"optionalInt32\":2147483647}") {(o: inout MessageTestType) in o.optionalInt32 = Int32.max } assertJSONEncode("{\"optionalInt32\":-2147483648}") {(o: inout MessageTestType) in o.optionalInt32 = Int32.min } // 32-bit overflow assertJSONDecodeFails("{\"optionalInt32\":2147483648}") // Explicit 'null' is permitted, proto3 decodes it to default value assertJSONDecodeSucceeds("{\"optionalInt32\":null}") {(o:MessageTestType) in o.optionalInt32 == 0} // Quoted or unquoted numbers, positive, negative, or zero assertJSONDecodeSucceeds("{\"optionalInt32\":1}") {(o:MessageTestType) in o.optionalInt32 == 1} assertJSONDecodeSucceeds("{\"optionalInt32\":\"1\"}") {(o:MessageTestType) in o.optionalInt32 == 1} assertJSONDecodeSucceeds("{\"optionalInt32\":\"\\u0030\"}") {(o:MessageTestType) in o.optionalInt32 == 0} assertJSONDecodeSucceeds("{\"optionalInt32\":\"\\u0031\"}") {(o:MessageTestType) in o.optionalInt32 == 1} assertJSONDecodeSucceeds("{\"optionalInt32\":\"\\u00310\"}") {(o:MessageTestType) in o.optionalInt32 == 10} assertJSONDecodeSucceeds("{\"optionalInt32\":0}") {(o:MessageTestType) in o.optionalInt32 == 0} assertJSONDecodeSucceeds("{\"optionalInt32\":\"0\"}") {(o:MessageTestType) in o.optionalInt32 == 0} assertJSONDecodeSucceeds("{\"optionalInt32\":-0}") {(o:MessageTestType) in o.optionalInt32 == 0} assertJSONDecodeSucceeds("{\"optionalInt32\":\"-0\"}") {(o:MessageTestType) in o.optionalInt32 == 0} assertJSONDecodeSucceeds("{\"optionalInt32\":-1}") {(o:MessageTestType) in o.optionalInt32 == -1} assertJSONDecodeSucceeds("{\"optionalInt32\":\"-1\"}") {(o:MessageTestType) in o.optionalInt32 == -1} // JSON RFC does not accept leading zeros assertJSONDecodeFails("{\"optionalInt32\":00000000000000000000001}") assertJSONDecodeFails("{\"optionalInt32\":\"01\"}") assertJSONDecodeFails("{\"optionalInt32\":-01}") assertJSONDecodeFails("{\"optionalInt32\":\"-00000000000000000000001\"}") // Exponents are okay, as long as result is integer assertJSONDecodeSucceeds("{\"optionalInt32\":2.147483647e9}") {(o:MessageTestType) in o.optionalInt32 == Int32.max} assertJSONDecodeSucceeds("{\"optionalInt32\":-2.147483648e9}") {(o:MessageTestType) in o.optionalInt32 == Int32.min} assertJSONDecodeSucceeds("{\"optionalInt32\":1e3}") {(o:MessageTestType) in o.optionalInt32 == 1000} assertJSONDecodeSucceeds("{\"optionalInt32\":100e-2}") {(o:MessageTestType) in o.optionalInt32 == 1} assertJSONDecodeFails("{\"optionalInt32\":1e-1}") // Reject malformed input assertJSONDecodeFails("{\"optionalInt32\":\\u0031}") assertJSONDecodeFails("{\"optionalInt32\":\"\\u0030\\u0030\"}") assertJSONDecodeFails("{\"optionalInt32\":\" 1\"}") assertJSONDecodeFails("{\"optionalInt32\":\"1 \"}") assertJSONDecodeFails("{\"optionalInt32\":\"01\"}") assertJSONDecodeFails("{\"optionalInt32\":true}") assertJSONDecodeFails("{\"optionalInt32\":0x102}") assertJSONDecodeFails("{\"optionalInt32\":{}}") assertJSONDecodeFails("{\"optionalInt32\":[]}") // Try to get the library to access past the end of the string... assertJSONDecodeFails("{\"optionalInt32\":0") assertJSONDecodeFails("{\"optionalInt32\":-0") assertJSONDecodeFails("{\"optionalInt32\":0.1") assertJSONDecodeFails("{\"optionalInt32\":0.") assertJSONDecodeFails("{\"optionalInt32\":1") assertJSONDecodeFails("{\"optionalInt32\":\"") assertJSONDecodeFails("{\"optionalInt32\":\"1") assertJSONDecodeFails("{\"optionalInt32\":\"1\"") assertJSONDecodeFails("{\"optionalInt32\":1.") assertJSONDecodeFails("{\"optionalInt32\":1e") assertJSONDecodeFails("{\"optionalInt32\":1e1") assertJSONDecodeFails("{\"optionalInt32\":-1") assertJSONDecodeFails("{\"optionalInt32\":123e") assertJSONDecodeFails("{\"optionalInt32\":123.") assertJSONDecodeFails("{\"optionalInt32\":123") } func testOptionalUInt32() { assertJSONEncode("{\"optionalUint32\":1}") {(o: inout MessageTestType) in o.optionalUint32 = 1 } assertJSONEncode("{\"optionalUint32\":4294967295}") {(o: inout MessageTestType) in o.optionalUint32 = UInt32.max } assertJSONDecodeFails("{\"optionalUint32\":4294967296}") // Explicit 'null' is permitted, decodes to default assertJSONDecodeSucceeds("{\"optionalUint32\":null}") {$0.optionalUint32 == 0} // Quoted or unquoted numbers, positive, negative, or zero assertJSONDecodeSucceeds("{\"optionalUint32\":1}") {$0.optionalUint32 == 1} assertJSONDecodeSucceeds("{\"optionalUint32\":\"1\"}") {$0.optionalUint32 == 1} assertJSONDecodeSucceeds("{\"optionalUint32\":0}") {$0.optionalUint32 == 0} assertJSONDecodeSucceeds("{\"optionalUint32\":\"0\"}") {$0.optionalUint32 == 0} // Protobuf JSON does not accept leading zeros assertJSONDecodeFails("{\"optionalUint32\":01}") assertJSONDecodeFails("{\"optionalUint32\":\"01\"}") // But it does accept exponential (as long as result is integral) assertJSONDecodeSucceeds("{\"optionalUint32\":4.294967295e9}") {$0.optionalUint32 == UInt32.max} assertJSONDecodeSucceeds("{\"optionalUint32\":1e3}") {$0.optionalUint32 == 1000} assertJSONDecodeSucceeds("{\"optionalUint32\":1.2e3}") {$0.optionalUint32 == 1200} assertJSONDecodeSucceeds("{\"optionalUint32\":1000e-2}") {$0.optionalUint32 == 10} assertJSONDecodeSucceeds("{\"optionalUint32\":1.0}") {$0.optionalUint32 == 1} assertJSONDecodeSucceeds("{\"optionalUint32\":1.000000e2}") {$0.optionalUint32 == 100} assertJSONDecodeFails("{\"optionalUint32\":1e-3}") assertJSONDecodeFails("{\"optionalUint32\":1") assertJSONDecodeFails("{\"optionalUint32\":\"") assertJSONDecodeFails("{\"optionalUint32\":\"1") assertJSONDecodeFails("{\"optionalUint32\":\"1\"") assertJSONDecodeFails("{\"optionalUint32\":1.11e1}") // Reject malformed input assertJSONDecodeFails("{\"optionalUint32\":true}") assertJSONDecodeFails("{\"optionalUint32\":-1}") assertJSONDecodeFails("{\"optionalUint32\":\"-1\"}") assertJSONDecodeFails("{\"optionalUint32\":0x102}") assertJSONDecodeFails("{\"optionalUint32\":{}}") assertJSONDecodeFails("{\"optionalUint32\":[]}") } func testOptionalInt64() throws { // Protoc JSON always quotes Int64 values assertJSONEncode("{\"optionalInt64\":\"9007199254740992\"}") {(o: inout MessageTestType) in o.optionalInt64 = 0x20000000000000 } assertJSONEncode("{\"optionalInt64\":\"9007199254740991\"}") {(o: inout MessageTestType) in o.optionalInt64 = 0x1fffffffffffff } assertJSONEncode("{\"optionalInt64\":\"-9007199254740992\"}") {(o: inout MessageTestType) in o.optionalInt64 = -0x20000000000000 } assertJSONEncode("{\"optionalInt64\":\"-9007199254740991\"}") {(o: inout MessageTestType) in o.optionalInt64 = -0x1fffffffffffff } assertJSONEncode("{\"optionalInt64\":\"9223372036854775807\"}") {(o: inout MessageTestType) in o.optionalInt64 = Int64.max } assertJSONEncode("{\"optionalInt64\":\"-9223372036854775808\"}") {(o: inout MessageTestType) in o.optionalInt64 = Int64.min } assertJSONEncode("{\"optionalInt64\":\"1\"}") {(o: inout MessageTestType) in o.optionalInt64 = 1 } assertJSONEncode("{\"optionalInt64\":\"-1\"}") {(o: inout MessageTestType) in o.optionalInt64 = -1 } // 0 is default, so proto3 omits it var a = MessageTestType() a.optionalInt64 = 0 XCTAssertEqual(try a.jsonString(), "{}") // Decode should work even with unquoted large numbers assertJSONDecodeSucceeds("{\"optionalInt64\":9223372036854775807}") {$0.optionalInt64 == Int64.max} assertJSONDecodeFails("{\"optionalInt64\":9223372036854775808}") assertJSONDecodeSucceeds("{\"optionalInt64\":-9223372036854775808}") {$0.optionalInt64 == Int64.min} assertJSONDecodeFails("{\"optionalInt64\":-9223372036854775809}") // Protobuf JSON does not accept leading zeros assertJSONDecodeFails("{\"optionalInt64\": \"01\" }") assertJSONDecodeSucceeds("{\"optionalInt64\": \"1\" }") {$0.optionalInt64 == 1} assertJSONDecodeFails("{\"optionalInt64\": \"-01\" }") assertJSONDecodeSucceeds("{\"optionalInt64\": \"-1\" }") {$0.optionalInt64 == -1} assertJSONDecodeSucceeds("{\"optionalInt64\": \"0\" }") {$0.optionalInt64 == 0} // Protobuf JSON does accept exponential format for integer fields assertJSONDecodeSucceeds("{\"optionalInt64\":1e3}") {$0.optionalInt64 == 1000} assertJSONDecodeSucceeds("{\"optionalInt64\":\"9223372036854775807\"}") {$0.optionalInt64 == Int64.max} assertJSONDecodeSucceeds("{\"optionalInt64\":-9.223372036854775808e18}") {$0.optionalInt64 == Int64.min} assertJSONDecodeFails("{\"optionalInt64\":9.223372036854775808e18}") // Out of range // Explicit 'null' is permitted, decodes to default (in proto3) assertJSONDecodeSucceeds("{\"optionalInt64\":null}") {$0.optionalInt64 == 0} assertJSONDecodeSucceeds("{\"optionalInt64\":2147483648}") {$0.optionalInt64 == 2147483648} assertJSONDecodeSucceeds("{\"optionalInt64\":2147483648}") {$0.optionalInt64 == 2147483648} assertJSONDecodeFails("{\"optionalInt64\":1") assertJSONDecodeFails("{\"optionalInt64\":\"") assertJSONDecodeFails("{\"optionalInt64\":\"1") assertJSONDecodeFails("{\"optionalInt64\":\"1\"") } func testOptionalUInt64() { assertJSONEncode("{\"optionalUint64\":\"1\"}") {(o: inout MessageTestType) in o.optionalUint64 = 1 } assertJSONEncode("{\"optionalUint64\":\"4294967295\"}") {(o: inout MessageTestType) in o.optionalUint64 = UInt64(UInt32.max) } assertJSONEncode("{\"optionalUint64\":\"18446744073709551615\"}") {(o: inout MessageTestType) in o.optionalUint64 = UInt64.max } // Parse unquoted 64-bit integers assertJSONDecodeSucceeds("{\"optionalUint64\":18446744073709551615}") {$0.optionalUint64 == UInt64.max} // Accept quoted 64-bit integers with backslash escapes in them assertJSONDecodeSucceeds("{\"optionalUint64\":\"184467\\u00344073709551615\"}") {$0.optionalUint64 == UInt64.max} // Reject unquoted 64-bit integers with backslash escapes assertJSONDecodeFails("{\"optionalUint64\":184467\\u00344073709551615}") // Reject out-of-range integers, whether or not quoted assertJSONDecodeFails("{\"optionalUint64\":\"18446744073709551616\"}") assertJSONDecodeFails("{\"optionalUint64\":18446744073709551616}") assertJSONDecodeFails("{\"optionalUint64\":\"184467440737095516109\"}") assertJSONDecodeFails("{\"optionalUint64\":184467440737095516109}") // Explicit 'null' is permitted, decodes to default assertJSONDecodeSucceeds("{\"optionalUint64\":null}") {$0.optionalUint64 == 0} // Quoted or unquoted numbers, positive or zero assertJSONDecodeSucceeds("{\"optionalUint64\":1}") {$0.optionalUint64 == 1} assertJSONDecodeSucceeds("{\"optionalUint64\":\"1\"}") {$0.optionalUint64 == 1} assertJSONDecodeSucceeds("{\"optionalUint64\":0}") {$0.optionalUint64 == 0} assertJSONDecodeSucceeds("{\"optionalUint64\":\"0\"}") {$0.optionalUint64 == 0} // Protobuf JSON does not accept leading zeros assertJSONDecodeFails("{\"optionalUint64\":01}") assertJSONDecodeFails("{\"optionalUint64\":\"01\"}") // But it does accept exponential (as long as result is integral) assertJSONDecodeSucceeds("{\"optionalUint64\":4.294967295e9}") {$0.optionalUint64 == UInt64(UInt32.max)} assertJSONDecodeSucceeds("{\"optionalUint64\":1e3}") {$0.optionalUint64 == 1000} assertJSONDecodeSucceeds("{\"optionalUint64\":1.2e3}") {$0.optionalUint64 == 1200} assertJSONDecodeSucceeds("{\"optionalUint64\":1000e-2}") {$0.optionalUint64 == 10} assertJSONDecodeSucceeds("{\"optionalUint64\":1.0}") {$0.optionalUint64 == 1} assertJSONDecodeSucceeds("{\"optionalUint64\":1.000000e2}") {$0.optionalUint64 == 100} assertJSONDecodeFails("{\"optionalUint64\":1e-3}") assertJSONDecodeFails("{\"optionalUint64\":1.11e1}") // Reject truncated JSON (ending at the beginning, end, or middle of the number assertJSONDecodeFails("{\"optionalUint64\":") assertJSONDecodeFails("{\"optionalUint64\":1") assertJSONDecodeFails("{\"optionalUint64\":\"") assertJSONDecodeFails("{\"optionalUint64\":\"1") assertJSONDecodeFails("{\"optionalUint64\":\"1\"") // Reject malformed input assertJSONDecodeFails("{\"optionalUint64\":true}") assertJSONDecodeFails("{\"optionalUint64\":-1}") assertJSONDecodeFails("{\"optionalUint64\":\"-1\"}") assertJSONDecodeFails("{\"optionalUint64\":0x102}") assertJSONDecodeFails("{\"optionalUint64\":{}}") assertJSONDecodeFails("{\"optionalUint64\":[]}") } private func assertRoundTripJSON(file: XCTestFileArgType = #file, line: UInt = #line, configure: (inout MessageTestType) -> Void) { var original = MessageTestType() configure(&original) do { let json = try original.jsonString() do { let decoded = try MessageTestType(jsonString: json) XCTAssertEqual(original, decoded, file: file, line: line) } catch let e { XCTFail("Failed to decode \(e): \(json)", file: file, line: line) } } catch let e { XCTFail("Failed to encode \(e)", file: file, line: line) } } func testOptionalDouble() throws { assertJSONEncode("{\"optionalDouble\":1.0}") {(o: inout MessageTestType) in o.optionalDouble = 1.0 } assertJSONEncode("{\"optionalDouble\":\"Infinity\"}") {(o: inout MessageTestType) in o.optionalDouble = Double.infinity } assertJSONEncode("{\"optionalDouble\":\"-Infinity\"}") {(o: inout MessageTestType) in o.optionalDouble = -Double.infinity } assertJSONDecodeSucceeds("{\"optionalDouble\":\"Inf\"}") {$0.optionalDouble == Double.infinity} assertJSONDecodeSucceeds("{\"optionalDouble\":\"-Inf\"}") {$0.optionalDouble == -Double.infinity} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1\"}") {$0.optionalDouble == 1} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.0\"}") {$0.optionalDouble == 1.0} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5\"}") {$0.optionalDouble == 1.5} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e1\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5E1\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1\\u002e5e1\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.\\u0035e1\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5\\u00651\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e\\u002b1\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e+\\u0031\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e+1\"}") {$0.optionalDouble == 15} assertJSONDecodeSucceeds("{\"optionalDouble\":\"15e-1\"}") {$0.optionalDouble == 1.5} assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.0e0\"}") {$0.optionalDouble == 1.0} assertJSONDecodeSucceeds("{\"optionalDouble\":\"0\"}") {$0.optionalDouble == 0.0} assertJSONDecodeSucceeds("{\"optionalDouble\":0}") {$0.optionalDouble == 0.0} // We preserve signed zero when decoding let d1 = try MessageTestType(jsonString: "{\"optionalDouble\":\"-0\"}") XCTAssertEqual(d1.optionalDouble, 0.0) XCTAssertEqual(d1.optionalDouble.sign, .minus) let d2 = try MessageTestType(jsonString: "{\"optionalDouble\":-0}") XCTAssertEqual(d2.optionalDouble, 0.0) XCTAssertEqual(d2.optionalDouble.sign, .minus) // But re-encoding treats the field as defaulted, so the sign gets lost assertJSONDecodeSucceeds("{\"optionalDouble\":\"-0\"}") {$0.optionalDouble == 0.0} assertJSONDecodeSucceeds("{\"optionalDouble\":-0}") {$0.optionalDouble == 0.0} // Malformed numbers should fail assertJSONDecodeFails("{\"optionalDouble\":Infinity}") assertJSONDecodeFails("{\"optionalDouble\":-Infinity}") // Must be quoted assertJSONDecodeFails("{\"optionalDouble\":\"inf\"}") assertJSONDecodeFails("{\"optionalDouble\":\"-inf\"}") assertJSONDecodeFails("{\"optionalDouble\":NaN}") assertJSONDecodeFails("{\"optionalDouble\":\"nan\"}") assertJSONDecodeFails("{\"optionalDouble\":\"1.0.0\"}") assertJSONDecodeFails("{\"optionalDouble\":00.1}") assertJSONDecodeFails("{\"optionalDouble\":\"00.1\"}") assertJSONDecodeFails("{\"optionalDouble\":.1}") assertJSONDecodeFails("{\"optionalDouble\":\".1\"}") assertJSONDecodeFails("{\"optionalDouble\":1.}") assertJSONDecodeFails("{\"optionalDouble\":\"1.\"}") assertJSONDecodeFails("{\"optionalDouble\":1e}") assertJSONDecodeFails("{\"optionalDouble\":\"1e\"}") assertJSONDecodeFails("{\"optionalDouble\":1e+}") assertJSONDecodeFails("{\"optionalDouble\":\"1e+\"}") assertJSONDecodeFails("{\"optionalDouble\":1e3.2}") assertJSONDecodeFails("{\"optionalDouble\":\"1e3.2\"}") assertJSONDecodeFails("{\"optionalDouble\":1.0.0}") // A wide range of numbers should exactly round-trip assertRoundTripJSON {$0.optionalDouble = 0.1} assertRoundTripJSON {$0.optionalDouble = 0.01} assertRoundTripJSON {$0.optionalDouble = 0.001} assertRoundTripJSON {$0.optionalDouble = 0.0001} assertRoundTripJSON {$0.optionalDouble = 0.00001} assertRoundTripJSON {$0.optionalDouble = 0.000001} assertRoundTripJSON {$0.optionalDouble = 1e-10} assertRoundTripJSON {$0.optionalDouble = 1e-20} assertRoundTripJSON {$0.optionalDouble = 1e-30} assertRoundTripJSON {$0.optionalDouble = 1e-40} assertRoundTripJSON {$0.optionalDouble = 1e-50} assertRoundTripJSON {$0.optionalDouble = 1e-60} assertRoundTripJSON {$0.optionalDouble = 1e-100} assertRoundTripJSON {$0.optionalDouble = 1e-200} assertRoundTripJSON {$0.optionalDouble = Double.pi} assertRoundTripJSON {$0.optionalDouble = 123456.789123456789123} assertRoundTripJSON {$0.optionalDouble = 1.7976931348623157e+308} assertRoundTripJSON {$0.optionalDouble = 2.22507385850720138309e-308} } func testOptionalFloat() throws { assertJSONEncode("{\"optionalFloat\":1.0}") {(o: inout MessageTestType) in o.optionalFloat = 1.0 } assertJSONEncode("{\"optionalFloat\":-1.0}") {(o: inout MessageTestType) in o.optionalFloat = -1.0 } assertJSONEncode("{\"optionalFloat\":\"Infinity\"}") {(o: inout MessageTestType) in o.optionalFloat = Float.infinity } assertJSONEncode("{\"optionalFloat\":\"-Infinity\"}") {(o: inout MessageTestType) in o.optionalFloat = -Float.infinity } assertJSONDecodeSucceeds("{\"optionalFloat\":\"Inf\"}") {$0.optionalFloat == Float.infinity} assertJSONDecodeSucceeds("{\"optionalFloat\":\"-Inf\"}") {$0.optionalFloat == -Float.infinity} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1\"}") {$0.optionalFloat == 1} assertJSONDecodeSucceeds("{\"optionalFloat\":\"-1\"}") {$0.optionalFloat == -1} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.0\"}") {$0.optionalFloat == 1.0} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5\"}") {$0.optionalFloat == 1.5} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e1\"}") {$0.optionalFloat == 15} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1\\u002e5e1\"}") {$0.optionalFloat == 15} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.\\u0035e1\"}") {$0.optionalFloat == 15} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5\\u00651\"}") {$0.optionalFloat == 15} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e\\u002b1\"}") {$0.optionalFloat == 15} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e+\\u0031\"}") {$0.optionalFloat == 15} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e+1\"}") {$0.optionalFloat == 15} assertJSONDecodeSucceeds("{\"optionalFloat\":\"15e-1\"}") {$0.optionalFloat == 1.5} assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.0e0\"}") {$0.optionalFloat == 1.0} assertJSONDecodeSucceeds("{\"optionalFloat\":1.0e0}") {$0.optionalFloat == 1.0} assertJSONDecodeSucceeds("{\"optionalFloat\":\"0\"}") {$0.optionalFloat == 0.0} assertJSONDecodeSucceeds("{\"optionalFloat\":0}") {$0.optionalFloat == 0.0} // We preserve signed zero when decoding let d1 = try MessageTestType(jsonString: "{\"optionalFloat\":\"-0\"}") XCTAssertEqual(d1.optionalFloat, 0.0) XCTAssertEqual(d1.optionalFloat.sign, .minus) let d2 = try MessageTestType(jsonString: "{\"optionalFloat\":-0}") XCTAssertEqual(d2.optionalFloat, 0.0) XCTAssertEqual(d2.optionalFloat.sign, .minus) // But re-encoding treats the field as defaulted, so the sign gets lost assertJSONDecodeSucceeds("{\"optionalFloat\":\"-0\"}") {$0.optionalFloat == 0.0} assertJSONDecodeSucceeds("{\"optionalFloat\":-0}") {$0.optionalFloat == 0.0} // Malformed numbers should fail assertJSONDecodeFails("{\"optionalFloat\":Infinity}") assertJSONDecodeFails("{\"optionalFloat\":-Infinity}") // Must be quoted assertJSONDecodeFails("{\"optionalFloat\":NaN}") assertJSONDecodeFails("{\"optionalFloat\":\"nan\"}") assertJSONDecodeFails("{\"optionalFloat\":\"1.0.0\"}") assertJSONDecodeFails("{\"optionalFloat\":1.0.0}") assertJSONDecodeFails("{\"optionalFloat\":00.1}") assertJSONDecodeFails("{\"optionalFloat\":\"00.1\"}") assertJSONDecodeFails("{\"optionalFloat\":.1}") assertJSONDecodeFails("{\"optionalFloat\":\".1\"}") assertJSONDecodeFails("{\"optionalFloat\":\"1") assertJSONDecodeFails("{\"optionalFloat\":\"") assertJSONDecodeFails("{\"optionalFloat\":1") assertJSONDecodeFails("{\"optionalFloat\":1.") assertJSONDecodeFails("{\"optionalFloat\":1.}") assertJSONDecodeFails("{\"optionalFloat\":\"1.\"}") assertJSONDecodeFails("{\"optionalFloat\":1e}") assertJSONDecodeFails("{\"optionalFloat\":\"1e\"}") assertJSONDecodeFails("{\"optionalFloat\":1e+}") assertJSONDecodeFails("{\"optionalFloat\":\"1e+\"}") assertJSONDecodeFails("{\"optionalFloat\":1e3.2}") assertJSONDecodeFails("{\"optionalFloat\":\"1e3.2\"}") // Out-of-range numbers should fail assertJSONDecodeFails("{\"optionalFloat\":1e39}") // A wide range of numbers should exactly round-trip assertRoundTripJSON {$0.optionalFloat = 0.1} assertRoundTripJSON {$0.optionalFloat = 0.01} assertRoundTripJSON {$0.optionalFloat = 0.001} assertRoundTripJSON {$0.optionalFloat = 0.0001} assertRoundTripJSON {$0.optionalFloat = 0.00001} assertRoundTripJSON {$0.optionalFloat = 0.000001} assertRoundTripJSON {$0.optionalFloat = 1.00000075e-36} assertRoundTripJSON {$0.optionalFloat = 1e-10} assertRoundTripJSON {$0.optionalFloat = 1e-20} assertRoundTripJSON {$0.optionalFloat = 1e-30} assertRoundTripJSON {$0.optionalFloat = Float(1e-40)} assertRoundTripJSON {$0.optionalFloat = Float(1e-50)} assertRoundTripJSON {$0.optionalFloat = Float(1e-60)} assertRoundTripJSON {$0.optionalFloat = Float(1e-100)} assertRoundTripJSON {$0.optionalFloat = Float(1e-200)} assertRoundTripJSON {$0.optionalFloat = Float.pi} assertRoundTripJSON {$0.optionalFloat = 123456.789123456789123} assertRoundTripJSON {$0.optionalFloat = 1999.9999999999} assertRoundTripJSON {$0.optionalFloat = 1999.9} assertRoundTripJSON {$0.optionalFloat = 1999.99} assertRoundTripJSON {$0.optionalFloat = 1999.99} assertRoundTripJSON {$0.optionalFloat = 3.402823567e+38} assertRoundTripJSON {$0.optionalFloat = 1.1754944e-38} } func testOptionalDouble_NaN() throws { // The helper functions don't work with NaN because NaN != NaN var o = Proto3Unittest_TestAllTypes() o.optionalDouble = Double.nan let encoded = try o.jsonString() XCTAssertEqual(encoded, "{\"optionalDouble\":\"NaN\"}") let o2 = try Proto3Unittest_TestAllTypes(jsonString: encoded) XCTAssert(o2.optionalDouble.isNaN == .some(true)) } func testOptionalFloat_NaN() throws { // The helper functions don't work with NaN because NaN != NaN var o = Proto3Unittest_TestAllTypes() o.optionalFloat = Float.nan let encoded = try o.jsonString() XCTAssertEqual(encoded, "{\"optionalFloat\":\"NaN\"}") do { let o2 = try Proto3Unittest_TestAllTypes(jsonString: encoded) XCTAssert(o2.optionalFloat.isNaN == .some(true)) } catch let e { XCTFail("Couldn't decode: \(e) -- \(encoded)") } } func testOptionalDouble_roundtrip() throws { for _ in 0..<10000 { let d = drand48() assertRoundTripJSON {$0.optionalDouble = d} } } func testOptionalFloat_roundtrip() throws { for _ in 0..<10000 { let f = Float(drand48()) assertRoundTripJSON {$0.optionalFloat = f} } } func testOptionalBool() throws { assertJSONEncode("{\"optionalBool\":true}") {(o: inout MessageTestType) in o.optionalBool = true } // False is default, so should not serialize in proto3 var o = MessageTestType() o.optionalBool = false XCTAssertEqual(try o.jsonString(), "{}") } func testOptionalString() { assertJSONEncode("{\"optionalString\":\"hello\"}") {(o: inout MessageTestType) in o.optionalString = "hello" } // Start of the C1 range assertJSONEncode("{\"optionalString\":\"~\\u007F\\u0080\\u0081\"}") {(o: inout MessageTestType) in o.optionalString = "\u{7e}\u{7f}\u{80}\u{81}" } // End of the C1 range assertJSONEncode("{\"optionalString\":\"\\u009E\\u009F ¡¢£\"}") {(o: inout MessageTestType) in o.optionalString = "\u{9e}\u{9f}\u{a0}\u{a1}\u{a2}\u{a3}" } // Empty string is default, so proto3 omits it var a = MessageTestType() a.optionalString = "" XCTAssertEqual(try a.jsonString(), "{}") // Example from RFC 7159: G clef coded as escaped surrogate pair assertJSONDecodeSucceeds("{\"optionalString\":\"\\uD834\\uDD1E\"}") {$0.optionalString == "𝄞"} // Ditto, with lowercase hex assertJSONDecodeSucceeds("{\"optionalString\":\"\\ud834\\udd1e\"}") {$0.optionalString == "𝄞"} // Same character represented directly assertJSONDecodeSucceeds("{\"optionalString\":\"𝄞\"}") {$0.optionalString == "𝄞"} // Various broken surrogate forms assertJSONDecodeFails("{\"optionalString\":\"\\uDD1E\\uD834\"}") assertJSONDecodeFails("{\"optionalString\":\"\\uDD1E\"}") assertJSONDecodeFails("{\"optionalString\":\"\\uD834\"}") assertJSONDecodeFails("{\"optionalString\":\"\\uDD1E\\u1234\"}") } func testOptionalString_controlCharacters() { // This is known to fail on Swift Linux 4.1 and earlier, // so skip it there. // See https://bugs.swift.org/browse/SR-4218 for details. #if !os(Linux) || swift(>=4.2) // Verify that all C0 controls are correctly escaped assertJSONEncode("{\"optionalString\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\"}") {(o: inout MessageTestType) in o.optionalString = "\u{00}\u{01}\u{02}\u{03}\u{04}\u{05}\u{06}\u{07}" } assertJSONEncode("{\"optionalString\":\"\\b\\t\\n\\u000B\\f\\r\\u000E\\u000F\"}") {(o: inout MessageTestType) in o.optionalString = "\u{08}\u{09}\u{0a}\u{0b}\u{0c}\u{0d}\u{0e}\u{0f}" } assertJSONEncode("{\"optionalString\":\"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\"}") {(o: inout MessageTestType) in o.optionalString = "\u{10}\u{11}\u{12}\u{13}\u{14}\u{15}\u{16}\u{17}" } assertJSONEncode("{\"optionalString\":\"\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F\"}") {(o: inout MessageTestType) in o.optionalString = "\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f}" } #endif } func testOptionalBytes() throws { // Empty bytes is default, so proto3 omits it var a = MessageTestType() a.optionalBytes = Data() XCTAssertEqual(try a.jsonString(), "{}") assertJSONEncode("{\"optionalBytes\":\"AA==\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([0]) } assertJSONEncode("{\"optionalBytes\":\"AAA=\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([0, 0]) } assertJSONEncode("{\"optionalBytes\":\"AAAA\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([0, 0, 0]) } assertJSONEncode("{\"optionalBytes\":\"/w==\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([255]) } assertJSONEncode("{\"optionalBytes\":\"//8=\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([255, 255]) } assertJSONEncode("{\"optionalBytes\":\"////\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([255, 255, 255]) } assertJSONEncode("{\"optionalBytes\":\"QQ==\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([65]) } assertJSONDecodeFails("{\"optionalBytes\":\"QQ=\"}") assertJSONDecodeSucceeds("{\"optionalBytes\":\"QQ\"}") { $0.optionalBytes == Data([65]) } assertJSONEncode("{\"optionalBytes\":\"QUI=\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([65, 66]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"QUI\"}") { $0.optionalBytes == Data([65, 66]) } assertJSONEncode("{\"optionalBytes\":\"QUJD\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([65, 66, 67]) } assertJSONEncode("{\"optionalBytes\":\"QUJDRA==\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([65, 66, 67, 68]) } assertJSONDecodeFails("{\"optionalBytes\":\"QUJDRA===\"}") assertJSONDecodeFails("{\"optionalBytes\":\"QUJDRA=\"}") assertJSONDecodeSucceeds("{\"optionalBytes\":\"QUJDRA\"}") { $0.optionalBytes == Data([65, 66, 67, 68]) } assertJSONEncode("{\"optionalBytes\":\"QUJDREU=\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([65, 66, 67, 68, 69]) } assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREU==\"}") assertJSONDecodeSucceeds("{\"optionalBytes\":\"QUJDREU\"}") { $0.optionalBytes == Data([65, 66, 67, 68, 69]) } assertJSONEncode("{\"optionalBytes\":\"QUJDREVG\"}") {(o: inout MessageTestType) in o.optionalBytes = Data([65, 66, 67, 68, 69, 70]) } assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG=\"}") assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG==\"}") assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG===\"}") assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG====\"}") // Google's parser accepts and ignores spaces: assertJSONDecodeSucceeds("{\"optionalBytes\":\" Q U J D R E U \"}") { $0.optionalBytes == Data([65, 66, 67, 68, 69]) } // Accept both RFC4648 Section 4 "base64" and Section 5 // "URL-safe base64" variants, but reject mixed coding: assertJSONDecodeSucceeds("{\"optionalBytes\":\"-_-_\"}") { $0.optionalBytes == Data([251, 255, 191]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"+/+/\"}") { $0.optionalBytes == Data([251, 255, 191]) } assertJSONDecodeFails("{\"optionalBytes\":\"-_+/\"}") assertJSONDecodeFails("{\"optionalBytes\":\"-_+\\/\"}") } func testOptionalBytes_escapes() { // Many JSON encoders escape "/": assertJSONDecodeSucceeds("{\"optionalBytes\":\"\\/w==\"}") { $0.optionalBytes == Data([255]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"\\/w\"}") { $0.optionalBytes == Data([255]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"\\/\\/\"}") { $0.optionalBytes == Data([255]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"a\\/\"}") { $0.optionalBytes == Data([107]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"ab\\/\"}") { $0.optionalBytes == Data([105, 191]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"abc\\/\"}") { $0.optionalBytes == Data([105, 183, 63]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"\\/a\"}") { $0.optionalBytes == Data([253]) } assertJSONDecodeSucceeds("{\"optionalBytes\":\"\\/\\/\\/\\/\"}") { $0.optionalBytes == Data([255, 255, 255]) } // Most backslash escapes decode to values that are // not legal in base-64 encoded strings assertJSONDecodeFails("{\"optionalBytes\":\"a\\b\"}") assertJSONDecodeFails("{\"optionalBytes\":\"a\\f\"}") assertJSONDecodeFails("{\"optionalBytes\":\"a\\n\"}") assertJSONDecodeFails("{\"optionalBytes\":\"a\\r\"}") assertJSONDecodeFails("{\"optionalBytes\":\"a\\t\"}") assertJSONDecodeFails("{\"optionalBytes\":\"a\\\"\"}") // TODO: For completeness, we should support \u1234 escapes // assertJSONDecodeSucceeds("{\"optionalBytes\":\"\u0061\u0062\"}") // assertJSONDecodeFails("{\"optionalBytes\":\"\u1234\u5678\"}") } func testOptionalBytes_roundtrip() throws { for i in UInt8(0)...UInt8(255) { let d = Data([i]) let message = Proto3Unittest_TestAllTypes.with { $0.optionalBytes = d } let text = try message.jsonString() let decoded = try Proto3Unittest_TestAllTypes(jsonString: text) XCTAssertEqual(decoded, message) XCTAssertEqual(message.optionalBytes[0], i) } } func testOptionalNestedMessage() { assertJSONEncode("{\"optionalNestedMessage\":{\"bb\":1}}") {(o: inout MessageTestType) in var sub = Proto3Unittest_TestAllTypes.NestedMessage() sub.bb = 1 o.optionalNestedMessage = sub } } func testOptionalNestedEnum() { assertJSONEncode("{\"optionalNestedEnum\":\"FOO\"}") {(o: inout MessageTestType) in o.optionalNestedEnum = Proto3Unittest_TestAllTypes.NestedEnum.foo } assertJSONDecodeSucceeds("{\"optionalNestedEnum\":1}") {$0.optionalNestedEnum == .foo} // Out-of-range values should be serialized to an int assertJSONEncode("{\"optionalNestedEnum\":123}") {(o: inout MessageTestType) in o.optionalNestedEnum = .UNRECOGNIZED(123) } // TODO: Check whether Google's spec agrees that unknown Enum tags // should fail to parse assertJSONDecodeFails("{\"optionalNestedEnum\":\"UNKNOWN\"}") } func testRepeatedInt32() { assertJSONEncode("{\"repeatedInt32\":[1]}") {(o: inout MessageTestType) in o.repeatedInt32 = [1] } assertJSONEncode("{\"repeatedInt32\":[1,2]}") {(o: inout MessageTestType) in o.repeatedInt32 = [1, 2] } assertEncode([250, 1, 2, 1, 2]) {(o: inout MessageTestType) in // Proto3 seems to default to packed for repeated int fields o.repeatedInt32 = [1, 2] } assertJSONDecodeSucceeds("{\"repeatedInt32\":null}") {$0.repeatedInt32 == []} assertJSONDecodeSucceeds("{\"repeatedInt32\":[]}") {$0.repeatedInt32 == []} assertJSONDecodeSucceeds("{\"repeatedInt32\":[1]}") {$0.repeatedInt32 == [1]} assertJSONDecodeSucceeds("{\"repeatedInt32\":[1,2]}") {$0.repeatedInt32 == [1, 2]} } func testRepeatedString() { assertJSONEncode("{\"repeatedString\":[\"\"]}") {(o: inout MessageTestType) in o.repeatedString = [""] } assertJSONEncode("{\"repeatedString\":[\"abc\",\"\"]}") {(o: inout MessageTestType) in o.repeatedString = ["abc", ""] } assertJSONDecodeSucceeds("{\"repeatedString\":null}") {$0.repeatedString == []} assertJSONDecodeSucceeds("{\"repeatedString\":[]}") {$0.repeatedString == []} assertJSONDecodeSucceeds(" { \"repeatedString\" : [ \"1\" , \"2\" ] } ") { $0.repeatedString == ["1", "2"] } } func testRepeatedNestedMessage() { assertJSONEncode("{\"repeatedNestedMessage\":[{\"bb\":1}]}") {(o: inout MessageTestType) in var sub = Proto3Unittest_TestAllTypes.NestedMessage() sub.bb = 1 o.repeatedNestedMessage = [sub] } assertJSONEncode("{\"repeatedNestedMessage\":[{\"bb\":1},{\"bb\":2}]}") {(o: inout MessageTestType) in var sub1 = Proto3Unittest_TestAllTypes.NestedMessage() sub1.bb = 1 var sub2 = Proto3Unittest_TestAllTypes.NestedMessage() sub2.bb = 2 o.repeatedNestedMessage = [sub1, sub2] } assertJSONDecodeSucceeds("{\"repeatedNestedMessage\": []}") { $0.repeatedNestedMessage == [] } } func testRepeatedEnum() { assertJSONEncode("{\"repeatedNestedEnum\":[\"FOO\"]}") {(o: inout MessageTestType) in o.repeatedNestedEnum = [.foo] } assertJSONEncode("{\"repeatedNestedEnum\":[\"FOO\",\"BAR\"]}") {(o: inout MessageTestType) in o.repeatedNestedEnum = [.foo, .bar] } assertJSONDecodeSucceeds("{\"repeatedNestedEnum\":[\"FOO\",0,1,\"BAR\",-1]}") {(o:MessageTestType) in o.repeatedNestedEnum == [.foo, .zero, .foo, .bar, .neg] } assertJSONDecodeFails("{\"repeatedNestedEnum\":[null]}") assertJSONDecodeFails("{\"repeatedNestedEnum\":\"FOO\"}") assertJSONDecodeFails("{\"repeatedNestedEnum\":0}") assertJSONDecodeSucceeds("{\"repeatedNestedEnum\":null}") {(o:MessageTestType) in o.repeatedNestedEnum == [] } assertJSONDecodeSucceeds("{\"repeatedNestedEnum\":[]}") {(o:MessageTestType) in o.repeatedNestedEnum == [] } } // TODO: Test other repeated field types func testOneof() { assertJSONEncode("{\"oneofUint32\":1}") {(o: inout MessageTestType) in o.oneofUint32 = 1 } assertJSONEncode("{\"oneofString\":\"abc\"}") {(o: inout MessageTestType) in o.oneofString = "abc" } assertJSONEncode("{\"oneofNestedMessage\":{\"bb\":1}}") {(o: inout MessageTestType) in var sub = Proto3Unittest_TestAllTypes.NestedMessage() sub.bb = 1 o.oneofNestedMessage = sub } assertJSONDecodeFails("{\"oneofString\": 1}") assertJSONDecodeFails("{\"oneofUint32\":1,\"oneofString\":\"abc\"}") assertJSONDecodeFails("{\"oneofString\":\"abc\",\"oneofUint32\":1}") } func testEmptyMessage() { assertJSONDecodeSucceeds("{}") {MessageTestType -> Bool in true} assertJSONDecodeFails("") assertJSONDecodeFails("{") assertJSONDecodeFails("}") } } class Test_JSONPacked: XCTestCase, PBTestHelpers { typealias MessageTestType = Proto3Unittest_TestPackedTypes func testPackedFloat() { assertJSONEncode("{\"packedFloat\":[1.0]}") {(o: inout MessageTestType) in o.packedFloat = [1] } assertJSONEncode("{\"packedFloat\":[1.0,0.25,0.125]}") {(o: inout MessageTestType) in o.packedFloat = [1, 0.25, 0.125] } assertJSONDecodeSucceeds("{\"packedFloat\":[1,0.25,125e-3]}") { $0.packedFloat == [1, 0.25, 0.125] } assertJSONDecodeSucceeds("{\"packedFloat\":null}") {$0.packedFloat == []} assertJSONDecodeSucceeds("{\"packedFloat\":[]}") {$0.packedFloat == []} assertJSONDecodeSucceeds("{\"packedFloat\":[\"1\"]}") {$0.packedFloat == [1]} assertJSONDecodeSucceeds("{\"packedFloat\":[\"1\",2]}") {$0.packedFloat == [1, 2]} } func testPackedDouble() { assertJSONEncode("{\"packedDouble\":[1.0]}") {(o: inout MessageTestType) in o.packedDouble = [1] } assertJSONEncode("{\"packedDouble\":[1.0,0.25,0.125]}") {(o: inout MessageTestType) in o.packedDouble = [1, 0.25, 0.125] } assertJSONDecodeSucceeds("{\"packedDouble\":[1,0.25,125e-3]}") { $0.packedDouble == [1, 0.25, 0.125] } assertJSONDecodeSucceeds("{\"packedDouble\":null}") {$0.packedDouble == []} assertJSONDecodeSucceeds("{\"packedDouble\":[]}") {$0.packedDouble == []} assertJSONDecodeSucceeds("{\"packedDouble\":[\"1\"]}") {$0.packedDouble == [1]} assertJSONDecodeSucceeds("{\"packedDouble\":[\"1\",2]}") {$0.packedDouble == [1, 2]} } func testPackedInt32() { assertJSONEncode("{\"packedInt32\":[1]}") {(o: inout MessageTestType) in o.packedInt32 = [1] } assertJSONEncode("{\"packedInt32\":[1,2]}") {(o: inout MessageTestType) in o.packedInt32 = [1, 2] } assertJSONEncode("{\"packedInt32\":[-2147483648,2147483647]}") {(o: inout MessageTestType) in o.packedInt32 = [Int32.min, Int32.max] } assertJSONDecodeSucceeds("{\"packedInt32\":null}") {$0.packedInt32 == []} assertJSONDecodeSucceeds("{\"packedInt32\":[]}") {$0.packedInt32 == []} assertJSONDecodeSucceeds("{\"packedInt32\":[\"1\"]}") {$0.packedInt32 == [1]} assertJSONDecodeSucceeds("{\"packedInt32\":[\"1\",\"2\"]}") {$0.packedInt32 == [1, 2]} assertJSONDecodeSucceeds(" { \"packedInt32\" : [ \"1\" , \"2\" ] } ") {$0.packedInt32 == [1, 2]} } func testPackedInt64() { assertJSONEncode("{\"packedInt64\":[\"1\"]}") {(o: inout MessageTestType) in o.packedInt64 = [1] } assertJSONEncode("{\"packedInt64\":[\"9223372036854775807\",\"-9223372036854775808\"]}") { (o: inout MessageTestType) in o.packedInt64 = [Int64.max, Int64.min] } assertJSONDecodeSucceeds("{\"packedInt64\":null}") {$0.packedInt64 == []} assertJSONDecodeSucceeds("{\"packedInt64\":[]}") {$0.packedInt64 == []} assertJSONDecodeSucceeds("{\"packedInt64\":[1]}") {$0.packedInt64 == [1]} assertJSONDecodeSucceeds("{\"packedInt64\":[1,2]}") {$0.packedInt64 == [1, 2]} assertJSONDecodeFails("{\"packedInt64\":[null]}") } func testPackedUInt32() { assertJSONEncode("{\"packedUint32\":[1]}") {(o: inout MessageTestType) in o.packedUint32 = [1] } assertJSONEncode("{\"packedUint32\":[0,4294967295]}") {(o: inout MessageTestType) in o.packedUint32 = [UInt32.min, UInt32.max] } assertJSONDecodeSucceeds("{\"packedUint32\":null}") {$0.packedUint32 == []} assertJSONDecodeSucceeds("{\"packedUint32\":[]}") {$0.packedUint32 == []} assertJSONDecodeSucceeds("{\"packedUint32\":[1]}") {$0.packedUint32 == [1]} assertJSONDecodeSucceeds("{\"packedUint32\":[1,2]}") {$0.packedUint32 == [1, 2]} assertJSONDecodeFails("{\"packedUint32\":[null]}") assertJSONDecodeFails("{\"packedUint32\":[-1]}") assertJSONDecodeFails("{\"packedUint32\":[1.2]}") } func testPackedUInt64() { assertJSONEncode("{\"packedUint64\":[\"1\"]}") {(o: inout MessageTestType) in o.packedUint64 = [1] } assertJSONEncode("{\"packedUint64\":[\"0\",\"18446744073709551615\"]}") { (o: inout MessageTestType) in o.packedUint64 = [UInt64.min, UInt64.max] } assertJSONDecodeSucceeds("{\"packedUint64\":null}") {$0.packedUint64 == []} assertJSONDecodeSucceeds("{\"packedUint64\":[]}") {$0.packedUint64 == []} assertJSONDecodeSucceeds("{\"packedUint64\":[1]}") {$0.packedUint64 == [1]} assertJSONDecodeSucceeds("{\"packedUint64\":[1,2]}") {$0.packedUint64 == [1, 2]} assertJSONDecodeFails("{\"packedUint64\":[null]}") assertJSONDecodeFails("{\"packedUint64\":[-1]}") assertJSONDecodeFails("{\"packedUint64\":[1.2]}") } func testPackedSInt32() { assertJSONEncode("{\"packedSint32\":[1]}") {(o: inout MessageTestType) in o.packedSint32 = [1] } assertJSONEncode("{\"packedSint32\":[-2147483648,2147483647]}") {(o: inout MessageTestType) in o.packedSint32 = [Int32.min, Int32.max] } assertJSONDecodeSucceeds("{\"packedSint32\":null}") {$0.packedSint32 == []} assertJSONDecodeSucceeds("{\"packedSint32\":[]}") {$0.packedSint32 == []} assertJSONDecodeSucceeds("{\"packedSint32\":[1]}") {$0.packedSint32 == [1]} assertJSONDecodeSucceeds("{\"packedSint32\":[1,2]}") {$0.packedSint32 == [1, 2]} assertJSONDecodeFails("{\"packedSint32\":[null]}") assertJSONDecodeFails("{\"packedSint32\":[1.2]}") } func testPackedSInt64() { assertJSONEncode("{\"packedSint64\":[\"1\"]}") {(o: inout MessageTestType) in o.packedSint64 = [1] } assertJSONEncode("{\"packedSint64\":[\"-9223372036854775808\",\"9223372036854775807\"]}") { (o: inout MessageTestType) in o.packedSint64 = [Int64.min, Int64.max] } assertJSONDecodeSucceeds("{\"packedSint64\":null}") {$0.packedSint64 == []} assertJSONDecodeSucceeds("{\"packedSint64\":[]}") {$0.packedSint64 == []} assertJSONDecodeSucceeds("{\"packedSint64\":[1]}") {$0.packedSint64 == [1]} assertJSONDecodeSucceeds("{\"packedSint64\":[1,2]}") {$0.packedSint64 == [1, 2]} assertJSONDecodeFails("{\"packedSint64\":[null]}") assertJSONDecodeFails("{\"packedSint64\":[1.2]}") } func testPackedFixed32() { assertJSONEncode("{\"packedFixed32\":[1]}") {(o: inout MessageTestType) in o.packedFixed32 = [1] } assertJSONEncode("{\"packedFixed32\":[0,4294967295]}") {(o: inout MessageTestType) in o.packedFixed32 = [UInt32.min, UInt32.max] } assertJSONDecodeSucceeds("{\"packedFixed32\":null}") {$0.packedFixed32 == []} assertJSONDecodeSucceeds("{\"packedFixed32\":[]}") {$0.packedFixed32 == []} assertJSONDecodeSucceeds("{\"packedFixed32\":[1]}") {$0.packedFixed32 == [1]} assertJSONDecodeSucceeds("{\"packedFixed32\":[1,2]}") {$0.packedFixed32 == [1, 2]} assertJSONDecodeFails("{\"packedFixed32\":[null]}") assertJSONDecodeFails("{\"packedFixed32\":[-1]}") assertJSONDecodeFails("{\"packedFixed32\":[1.2]}") } func testPackedFixed64() { assertJSONEncode("{\"packedFixed64\":[\"1\"]}") {(o: inout MessageTestType) in o.packedFixed64 = [1] } assertJSONEncode("{\"packedFixed64\":[\"0\",\"18446744073709551615\"]}") { (o: inout MessageTestType) in o.packedFixed64 = [UInt64.min, UInt64.max] } assertJSONDecodeSucceeds("{\"packedFixed64\":null}") {$0.packedFixed64 == []} assertJSONDecodeSucceeds("{\"packedFixed64\":[]}") {$0.packedFixed64 == []} assertJSONDecodeSucceeds("{\"packedFixed64\":[1]}") {$0.packedFixed64 == [1]} assertJSONDecodeSucceeds("{\"packedFixed64\":[1,2]}") {$0.packedFixed64 == [1, 2]} assertJSONDecodeFails("{\"packedFixed64\":[null]}") assertJSONDecodeFails("{\"packedFixed64\":[-1]}") assertJSONDecodeFails("{\"packedFixed64\":[1.2]}") } func testPackedSFixed32() { assertJSONEncode("{\"packedSfixed32\":[1]}") {(o: inout MessageTestType) in o.packedSfixed32 = [1] } assertJSONEncode("{\"packedSfixed32\":[-2147483648,2147483647]}") {(o: inout MessageTestType) in o.packedSfixed32 = [Int32.min, Int32.max] } assertJSONDecodeSucceeds("{\"packedSfixed32\":null}") {$0.packedSfixed32 == []} assertJSONDecodeSucceeds("{\"packedSfixed32\":[]}") {$0.packedSfixed32 == []} assertJSONDecodeSucceeds("{\"packedSfixed32\":[1]}") {$0.packedSfixed32 == [1]} assertJSONDecodeSucceeds("{\"packedSfixed32\":[1,2]}") {$0.packedSfixed32 == [1, 2]} assertJSONDecodeFails("{\"packedSfixed32\":[null]}") assertJSONDecodeFails("{\"packedSfixed32\":[1.2]}") } func testPackedSFixed64() { assertJSONEncode("{\"packedSfixed64\":[\"1\"]}") {(o: inout MessageTestType) in o.packedSfixed64 = [1] } assertJSONEncode("{\"packedSfixed64\":[\"-9223372036854775808\",\"9223372036854775807\"]}") { (o: inout MessageTestType) in o.packedSfixed64 = [Int64.min, Int64.max] } assertJSONDecodeSucceeds("{\"packedSfixed64\":null}") {$0.packedSfixed64 == []} assertJSONDecodeSucceeds("{\"packedSfixed64\":[]}") {$0.packedSfixed64 == []} assertJSONDecodeSucceeds("{\"packedSfixed64\":[1]}") {$0.packedSfixed64 == [1]} assertJSONDecodeSucceeds("{\"packedSfixed64\":[1,2]}") {$0.packedSfixed64 == [1, 2]} assertJSONDecodeFails("{\"packedSfixed64\":[null]}") assertJSONDecodeFails("{\"packedSfixed64\":[1.2]}") } func testPackedBool() { assertJSONEncode("{\"packedBool\":[true]}") {(o: inout MessageTestType) in o.packedBool = [true] } assertJSONEncode("{\"packedBool\":[true,false]}") { (o: inout MessageTestType) in o.packedBool = [true,false] } assertJSONDecodeSucceeds("{\"packedBool\":null}") {$0.packedBool == []} assertJSONDecodeSucceeds("{\"packedBool\":[]}") {$0.packedBool == []} assertJSONDecodeFails("{\"packedBool\":[null]}") assertJSONDecodeFails("{\"packedBool\":[1,0]}") assertJSONDecodeFails("{\"packedBool\":[\"true\"]}") assertJSONDecodeFails("{\"packedBool\":[\"false\"]}") } } class Test_JSONrepeated: XCTestCase, PBTestHelpers { typealias MessageTestType = Proto3Unittest_TestUnpackedTypes func testPackedInt32() { assertJSONEncode("{\"repeatedInt32\":[1]}") {(o: inout MessageTestType) in o.repeatedInt32 = [1] } assertJSONEncode("{\"repeatedInt32\":[1,2]}") {(o: inout MessageTestType) in o.repeatedInt32 = [1, 2] } assertEncode([8, 1, 8, 2]) {(o: inout MessageTestType) in o.repeatedInt32 = [1, 2] } assertJSONDecodeSucceeds("{\"repeatedInt32\":null}") {$0.repeatedInt32 == []} assertJSONDecodeSucceeds("{\"repeatedInt32\":[]}") {$0.repeatedInt32 == []} assertJSONDecodeSucceeds("{\"repeatedInt32\":[1]}") {$0.repeatedInt32 == [1]} assertJSONDecodeSucceeds("{\"repeatedInt32\":[1,2]}") {$0.repeatedInt32 == [1, 2]} } }
apache-2.0
83463765647018b74e54bf4f44f56447
49.700604
140
0.597053
5.08806
false
true
false
false
MattiaPrimavera/iOS-Development---PPM
tme4/Quizz-programmatically/Quizz-programmatically/DBQuestionAnswers.swift
1
1423
// // DBQuestionAnswers.swift // Quizz-programmatically // // Created by m2sar on 25/10/2016. // Copyright © 2016 UPMC. All rights reserved. // import Foundation class DBQuestionAnswers{ private var current = 0 // Q1, A1, Seen(Boolean), Hard(Boolean) private var questions = [ ("Q1", "A1", false, false), ("Q2", "A2", false, false), ("Q3", "A3", false, true), ("Q4", "A4", false, false), ("Q5", "A5", false, true) ] init(){} func getCurrent () -> (String, String, Bool, Bool) { return questions[current] } func setCurrentToShown () { questions[current].2 = true } func getPrevious (modeBalaiseOn: Bool) -> (String, String, Bool, Bool) { // Circle loop through array repeat{ current = (current - 1) % (questions.count) if(current < 0){ current *= -1 } if(questions[current].3 == modeBalaiseOn){ return questions[current] } }while true } func getNext (modeBalaiseOn: Bool) -> (String, String, Bool, Bool) { // Circle loop through array repeat{ current = (current + 1) % (questions.count) if(questions[current].3 == modeBalaiseOn){ return questions[current] } }while true } }
apache-2.0
929b0e49810a8cb7c6701ebe74c72687
24.392857
76
0.513361
3.874659
false
false
false
false
abouzek/hn_browser
HNBrowser/HNBFlexibleHeightBar.swift
1
1875
// // HNBMainFlexibleHeightBar.swift // HNBrowser // // Created by Alan Bouzek on 11/18/15. // Copyright © 2015 abouzek. All rights reserved. // import UIKit import BLKFlexibleHeightBar class HNBFlexibleHeightBar: BLKFlexibleHeightBar { internal var title: String? internal var label: UILabel! init(title: String, frame: CGRect) { super.init(frame: frame) self.setupWithTitle(title) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func setupWithTitle(title: String) { self.minimumBarHeight = 20 self.backgroundColor = HNBConstants.HN_ORANGE self.behaviorDefiner = SquareCashStyleBehaviorDefiner() self.behaviorDefiner = self.behaviorDefiner self.label = UILabel() self.label.text = title self.label.font = UIFont.systemFontOfSize(20) self.label.textColor = HNBConstants.HN_WHITE self.label.sizeToFit() self.addSubview(label) let initialLayoutAttributes = BLKFlexibleHeightBarSubviewLayoutAttributes() initialLayoutAttributes.size = label.frame.size initialLayoutAttributes.center = CGPoint(x: CGRectGetMidX(self.bounds), y: CGRectGetMidY(self.bounds) + 10.0) label.addLayoutAttributes(initialLayoutAttributes, forProgress: 0) let finalLayoutAttributes = BLKFlexibleHeightBarSubviewLayoutAttributes(existingLayoutAttributes: initialLayoutAttributes) finalLayoutAttributes.alpha = 0 let translation = CGAffineTransformMakeTranslation(0, -30) let scale = CGAffineTransformMakeScale(0.2, 0.2) finalLayoutAttributes.transform = CGAffineTransformConcat(scale, translation) label.addLayoutAttributes(finalLayoutAttributes, forProgress: 1) } }
mit
db861259f85d5b2e5bf1cc391391dc85
34.358491
130
0.698506
4.732323
false
false
false
false
Hanse00/SwiftSound
SwiftSound/SwiftSound/ViewController.swift
1
1136
// // ViewController.swift // SwiftSound // // Created by Philip Hansen on 03/11/15. // Copyright © 2015 Philip Hansen. Licensed under the MIT Licnse. // See the LICENSE file in the repository root for details. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var textField: NSTextField! @IBOutlet weak var slider: NSSlider! var track: Track! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. track = Track(path: "beatbox.mp3") updateUI() } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } @IBAction func mute(sender: AnyObject) { track.volume = 0 NSLog("Mute clicked!") updateUI() } @IBAction func updateVolume(sender: AnyObject) { track.volume = sender.floatValue NSLog("Volume set to: \(track.volume)") updateUI() } func updateUI() { textField.floatValue = track.volume slider.floatValue = track.volume } }
mit
6badba4753454eb70ef199adbe79d49f
22.163265
66
0.612335
4.468504
false
false
false
false
CosmicMind/MaterialKit
Sources/iOS/SearchBar.swift
1
7294
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(SearchBarDelegate) public protocol SearchBarDelegate { /** A delegation method that is executed when the textField changed. - Parameter searchBar: A SearchBar. - Parameter didChange textField: A UITextField. - Parameter with text: An optional String. */ @objc optional func searchBar(searchBar: SearchBar, didChange textField: UITextField, with text: String?) /** A delegation method that is executed when the textField will clear. - Parameter searchBar: A SearchBar. - Parameter willClear textField: A UITextField. - Parameter with text: An optional String. */ @objc optional func searchBar(searchBar: SearchBar, willClear textField: UITextField, with text: String?) /** A delegation method that is executed when the textField is cleared. - Parameter searchBar: A SearchBar. - Parameter didClear textField: A UITextField. - Parameter with text: An optional String. */ @objc optional func searchBar(searchBar: SearchBar, didClear textField: UITextField, with text: String?) } open class SearchBar: Bar { /// The UITextField for the searchBar. @IBInspectable open let textField = UITextField() /// Reference to the clearButton. open fileprivate(set) var clearButton: IconButton! /// A reference to the delegate. open weak var delegate: SearchBarDelegate? /// Handle the clearButton manually. @IBInspectable open var isClearButtonAutoHandleEnabled = true { didSet { clearButton.removeTarget(self, action: #selector(handleClearButton), for: .touchUpInside) if isClearButtonAutoHandleEnabled { clearButton.addTarget(self, action: #selector(handleClearButton), for: .touchUpInside) } } } /// TintColor for searchBar. @IBInspectable open override var tintColor: UIColor? { get { return textField.tintColor } set(value) { textField.tintColor = value } } /// TextColor for searchBar. @IBInspectable open var textColor: UIColor? { get { return textField.textColor } set(value) { textField.textColor = value } } /// Sets the textField placeholder value. @IBInspectable open var placeholder: String? { didSet { if let v = placeholder { textField.attributedPlaceholder = NSAttributedString(string: v, attributes: [.foregroundColor: placeholderColor]) } } } /// Placeholder text @IBInspectable open var placeholderColor = Color.darkText.others { didSet { if let v = placeholder { textField.attributedPlaceholder = NSAttributedString(string: v, attributes: [.foregroundColor: placeholderColor]) } } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) } open override func layoutSubviews() { super.layoutSubviews() guard willLayout else { return } layoutTextField() layoutLeftView() layoutClearButton() } open override func prepare() { super.prepare() prepareTextField() prepareClearButton() } } extension SearchBar { /// Layout the textField. open func layoutTextField() { textField.frame = contentView.bounds } /// Layout the leftView. open func layoutLeftView() { guard let v = textField.leftView else { return } let h = textField.frame.height v.frame = CGRect(x: 4, y: 4, width: h, height: h - 8) (v as? UIImageView)?.contentMode = .scaleAspectFit } /// Layout the clearButton. open func layoutClearButton() { let h = textField.frame.height clearButton.frame = CGRect(x: textField.frame.width - h - 4, y: 4, width: h, height: h - 8) } } fileprivate extension SearchBar { /// Clears the textField text. @objc func handleClearButton() { guard nil == textField.delegate?.textFieldShouldClear || true == textField.delegate?.textFieldShouldClear?(textField) else { return } let t = textField.text delegate?.searchBar?(searchBar: self, willClear: textField, with: t) textField.text = nil delegate?.searchBar?(searchBar: self, didClear: textField, with: t) } // Live updates the search results. @objc func handleEditingChanged(textField: UITextField) { delegate?.searchBar?(searchBar: self, didChange: textField, with: textField.text) } } fileprivate extension SearchBar { /// Prepares the textField. func prepareTextField() { textField.contentScaleFactor = Screen.scale textField.font = RobotoFont.regular(with: 17) textField.backgroundColor = Color.clear textField.clearButtonMode = .whileEditing textField.addTarget(self, action: #selector(handleEditingChanged(textField:)), for: .editingChanged) tintColor = placeholderColor textColor = Color.darkText.primary placeholder = "Search" contentView.addSubview(textField) } /// Prepares the clearButton. func prepareClearButton() { clearButton = IconButton(image: Icon.cm.close, tintColor: placeholderColor) clearButton.contentEdgeInsets = .zero isClearButtonAutoHandleEnabled = true textField.clearButtonMode = .never textField.rightViewMode = .whileEditing textField.rightView = clearButton } }
bsd-3-clause
d321b8d5a11f01f1999a84c95bc7bafb
30.038298
128
0.708253
4.687661
false
false
false
false
MomentaBV/CwlUtils
Sources/CwlUtils/CwlWrappers.swift
1
3607
// // CwlWrappers.swift // CwlUtils // // Created by Matt Gallagher on 2015/02/03. // Copyright © 2015 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation /// A class wrapper around a type (usually a value type) so it can be moved without copying but also so that it can be passed through Objective-C parameters. public class Box<T> { public let value: T public init(_ t: T) { value = t } } //// A class wrapper around a type (usually a value type) so changes to it can be shared (usually as an ad hoc communication channel). NOTE: this version is *not* threadsafe, use AtomicBox for that. public final class MutableBox<T> { public var value: T public init(_ t: T) { value = t } } // A class wrapper around a type (usually a value type) so changes to it can be shared in a thread-safe manner (usually as an ad hoc communication channel). /// "Atomic" in this sense refers to the semantics, not the implementation. This uses a pthread mutex, not CAS-style atomic operations. public final class AtomicBox<T> { private var mutex = PThreadMutex() private var internalValue: T public init(_ t: T) { internalValue = t } public var value: T { get { mutex.unbalancedLock() defer { mutex.unbalancedUnlock() } return internalValue } set { mutex.unbalancedLock() defer { mutex.unbalancedUnlock() } internalValue = newValue } } @discardableResult public func mutate(_ f: (inout T) -> Void) -> T { mutex.unbalancedLock() defer { mutex.unbalancedUnlock() } f(&internalValue) return internalValue } } /// A wrapper around a type (usually a class type) so it can be weakly referenced from an Array or other strong container. public struct Weak<T: AnyObject> { public weak var value: T? public init(_ value: T?) { self.value = value } public func contains(_ other: T) -> Bool { if let v = value { return v === other } else { return false } } } /// A wrapper around a type (usually a class type) so it can be referenced unowned from an Array or other strong container. public struct Unowned<T: AnyObject> { public unowned let value: T public init(_ value: T) { self.value = value } } /// A enum wrapper around a type (usually a class type) so its ownership can be set at runtime. public enum PossiblyWeak<T: AnyObject> { case strong(T) case weak(Weak<T>) public init(strong value: T) { self = PossiblyWeak<T>.strong(value) } public init(weak value: T) { self = PossiblyWeak<T>.weak(Weak(value)) } public var value: T? { switch self { case .strong(let t): return t case .weak(let weakT): return weakT.value } } public func contains(_ other: T) -> Bool { switch self { case .strong(let t): return t === other case .weak(let weakT): if let wt = weakT.value { return wt === other } return false } } }
isc
a588671448d82fe17d5522c76f8f6a50
27.619048
198
0.69939
3.552709
false
false
false
false
cacawai/Tap2Read
tap2read/tap2read/SwipeableVC.swift
1
15357
// // SwipeableVC.swift // tap2read // // Created by 徐新元 on 16/7/28. // Copyright © 2016年 Last4 Team. All rights reserved. // import UIKit import UIColor_FlatColors import SnapKit import ReactiveUI import ZLSwipeableViewSwift import Cartography import SCLAlertView import pop class SwipeableVC: UIViewController, UIViewControllerPreviewingDelegate, LanguageBarDelegate,CategoryBarDelegate { let borderColor = UIColor.init(white: 0.3, alpha: 1.0) var currentLanguage:String = ConfigMgr.sharedInstance.currentLanguage() var currentCardIndex = 0 var cardIndex = 0 var cardModels:[CardModel] = [CardModel]() var cardCount = 0 @IBOutlet weak var swipeableView: ZLSwipeableView! @IBOutlet weak var cardModelTypeSwitchBtn: CardModelTypeSwitchBtn! //Top Bar @IBOutlet weak var categoryBar: CategoryBar! @IBOutlet weak var topBar: UIView! //Bottom Bar @IBOutlet weak var languageBar: LanguageBar! @IBOutlet weak var bottomBar: UIView! @IBOutlet weak var upArrowImageView: UIImageView! @IBOutlet weak var createNewCardBtn: UIButton! //MARK:- ViewController life cycle override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() self.cardModelTypeSwitchBtn.layer.cornerRadius = 24 self.cardModelTypeSwitchBtn.layer.borderWidth = 2.0 self.cardModelTypeSwitchBtn.layer.borderColor = borderColor.cgColor self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true if #available(iOS 9.0, *) { self.registerForPreviewing(with: self, sourceView: self.cardModelTypeSwitchBtn) } else { // Fallback on earlier versions } CardModelMgr.sharedInstance.reloadCardModels() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() swipeableView.nextView = { return self.nextCardView() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) self.prepareCardModels() self.prepareSwipableView() self.prepareLanguageBar() self.prepareCategoryBar() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.readByIndex(index: self.currentCardIndex) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } //MARK:- Cards func prepareCardModels() { cardIndex = 0 currentCardIndex = 0 cardModels = CardModelMgr.sharedInstance.cardModels cardCount = cardModels.count } func prepareSwipableView() { cardModelTypeSwitchBtn.updateBtnByCategoryModel(category: CardModelMgr.sharedInstance.getCurrentCategoryModel()) swipeableView.shouldSwipeView = { _, _, _ in true } swipeableView.numberOfActiveView = UInt(min(3, self.cardModels.count)) swipeableView.discardViews() swipeableView.loadViews() if swipeableView.didTap == nil { swipeableView.didTap = {view, location in print("Did tap at location \(location)") self.readByIndex(index: self.currentCardIndex) } } if swipeableView.didEnd == nil { swipeableView.didEnd = {view, location in print("Did end swiping view at location: \(location)") self.currentCardIndex += 1 if self.currentCardIndex >= self.cardCount{ self.currentCardIndex = 0 } self.readByIndex(index: self.currentCardIndex) self.swipeableView.isUserInteractionEnabled = false DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.swipeableView.isUserInteractionEnabled = true } self.upArrowImageView.alpha = 0.7 } } self.createNewCardBtn.isHidden = cardCount > 0 } func prepareLanguageBar() { languageBar.languageBarDelegate = self let rotationAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY) rotationAnimation?.springSpeed = 0.1 rotationAnimation?.fromValue = self.upArrowImageView.layer.position.y rotationAnimation?.toValue = self.upArrowImageView.layer.position.y - 4 rotationAnimation?.autoreverses = true rotationAnimation?.repeatForever = true self.upArrowImageView.layer.pop_add(rotationAnimation, forKey: "rotation") } func nextCardView() -> UIView? { if cardIndex >= self.cardModels.count { return nil } let cardModel = cardModels[cardIndex] let cardView = BaseCardView(frame: swipeableView.bounds) var contentView:BaseCardView if cardModel.categoryId == CategoryIdNumber || cardModel.categoryId == CategoryIdLetter{ contentView = Bundle.main.loadNibNamed("NumberCardView", owner: self, options: nil)?.first! as! NumberCardView }else { contentView = Bundle.main.loadNibNamed("CardContentView", owner: self, options: nil)?.first! as! CardContentView } contentView.loadData(cardModel: cardModel, language: currentLanguage) cardView.addSubview(contentView) constrain(contentView, cardView) { view1, view2 in view1.left == view2.left view1.top == view2.top view1.width == cardView.bounds.width view1.height == cardView.bounds.height } // contentView.snp.makeConstraints { (make) in // make.edges.equalTo(cardView).inset(UIEdgeInsetsMake(10, 0, 10, 0)) // } self.cardIndex += 1 if self.cardIndex >= self.cardCount{ self.cardIndex = 0 } return cardView } func readByIndex(index:NSInteger) { if index < self.cardModels.count { self.read(cardModel: self.cardModels[index]) } } func read(cardModel: CardModel) { let title = cardModel.titleWithLanguage(language: currentLanguage) if cardModel.categoryId == CategoryIdLetter { TTSMgr.sharedInstance.readText(title, language:"en-US") }else{ TTSMgr.sharedInstance.readText(title) } } func reloadCards() { cardIndex = 0 currentCardIndex = 0 cardModels = CardModelMgr.sharedInstance.cardModels cardCount = cardModels.count cardModelTypeSwitchBtn.updateBtnByCategoryModel(category: CardModelMgr.sharedInstance.getCurrentCategoryModel()) swipeableView.numberOfActiveView = UInt(min(3, self.cardModels.count)) swipeableView.discardViews() swipeableView.loadViews() } //MARK:- Switch card model types @IBAction func onClickCardModelTypeSwitchBtn(_ sender: Any) { CardModelMgr.sharedInstance.switchToNextCategory() self.reloadCards() self.readByIndex(index: self.currentCardIndex) // let storyboad = UIStoryboard(name: "Main", bundle: Bundle.main) // let categoryVC = storyboad.instantiateViewController(withIdentifier: "CategoryVC") as! CategoryVC // categoryVC.loadData(categories: CardModelMgr.sharedInstance.categoryModels) // let transition = CATransition() // transition.duration = 0.3 // transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // transition.type = kCATransitionFade // self.navigationController?.view.layer.add(transition, forKey: nil) // self.navigationController?.pushViewController(categoryVC, animated: true) // self.present(categoryVC, animated: true, completion: nil) // let animation = POPSpringAnimation(propertyNamed: kPOPViewSize) // animation?.fromValue = CGSize(width: self.cardModelTypeSwitchBtn.imageView!.frame.size.width*1.1, height: self.cardModelTypeSwitchBtn.imageView!.frame.size.height*1.1) // animation?.toValue = CGSize(width: self.cardModelTypeSwitchBtn.imageView!.frame.size.width, height: self.cardModelTypeSwitchBtn.imageView!.frame.size.height) // self.cardModelTypeSwitchBtn.imageView!.pop_add(animation, forKey: "size") } //MARK:- Settings @IBAction func onClickSettingsBtn(_ sender: Any) { self.onSettingsSelected() } func onSettingsSelected() { // if CardModelMgr.sharedInstance.cardModelType == .Number{ // self.gotoNumberSettings() // }else if CardModelMgr.sharedInstance.cardModelType == .Image{ let category = CardModelMgr.sharedInstance.getCurrentCategoryModel() // if category.categoryId! > 10000 { // if cardCount == 0 { // let storyboad = UIStoryboard(name: "Main", bundle: Bundle.main) // let createVC = storyboad.instantiateViewController(withIdentifier: "CreateCardVC") as! CreateCardVC // createVC.whatToCreate = .Card // self.navigationController?.pushViewController(createVC, animated: true) // }else{ // let storyboad = UIStoryboard(name: "Main", bundle: Bundle.main) // let categoryVC = storyboad.instantiateViewController(withIdentifier: "CategoryVC") as! CategoryVC // categoryVC.isEditMode = true // categoryVC.loadData(cards:self.cardModels, category:category) // self.navigationController?.pushViewController(categoryVC, animated: true) // } // }else { let storyboad = UIStoryboard(name: "Main", bundle: Bundle.main) let categoryVC = storyboad.instantiateViewController(withIdentifier: "CategoryVC") as! CategoryVC categoryVC.loadData(categories: CardModelMgr.sharedInstance.categoryModels) self.navigationController?.pushViewController(categoryVC, animated: true) // } // } // let animation = POPSpringAnimation(propertyNamed: kPOPViewSize) // animation?.fromValue = CGSize(width: 44*1.1, height: 44*1.1) // animation?.toValue = CGSize(width: 44, height: 44) // self.settingsBtn.pop_add(animation, forKey: "size") } // func gotoNumberSettings() { // let alert = SCLAlertView() // // let textFieldStart = alert.addTextField(NSLocalizedString("from_number", comment: "")) // let textFieldEnd = alert.addTextField(NSLocalizedString("to_number", comment: "")) // // textFieldStart.keyboardType = UIKeyboardType.numberPad // textFieldEnd.keyboardType = UIKeyboardType.numberPad // // alert.addButton(NSLocalizedString("ok", comment: ""), action: { // if (textFieldStart.text?.isEmpty)! { // // SCLAlertView().showError("请输入起始数字", subTitle: "") // return // } // if (textFieldEnd.text?.isEmpty)! { // // SCLAlertView().showError("请输入结束数字", subTitle: "") // return // } // CardModelMgr.sharedInstance.loadNumberCards(from: Int(textFieldStart.text!)!, to: Int(textFieldEnd.text!)!) // self.reloadCards() // }) // // [alert addButton:@"Show Name" actionBlock:^(void) { // // NSLog(@"Text value: %@", textField.text); // // }]; // alert.showEdit(NSLocalizedString("set_number_range", comment: ""), subTitle: "", closeButtonTitle: NSLocalizedString("cancel", comment: ""), duration: 0, colorStyle: UInt(SCLAlertViewStyle.edit.hashValue), colorTextButton: 0xFFFFFF, circleIconImage: nil, animationStyle: SCLAnimationStyle.topToBottom) // } // MARK:- CategoryBar func prepareCategoryBar() { categoryBar.categoryBarDelegate = self categoryBar.loadData(categories: CardModelMgr.sharedInstance.categoryModels) } func onCategorySelected(index: NSInteger!) { CardModelMgr.sharedInstance.setCurrentCategoryIndex(index:index) self.reloadCards() self.readByIndex(index: self.currentCardIndex) } // MARK:- LanguageBar @IBAction func onSwipeLanguageBarUp(_ sender: Any) { //Slide animation let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter) animation?.toValue = CGPoint(x: self.bottomBar.center.x, y: self.view.frame.size.height - self.bottomBar.frame.size.height/2) self.bottomBar.pop_add(animation, forKey: "up") //Alpha animation let alphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) alphaAnimation?.toValue = 0.0 alphaAnimation?.toValue = 1.0 self.languageBar.pop_add(alphaAnimation, forKey: "fadeIn") //Alpha animation let upArrowAlphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) upArrowAlphaAnimation?.fromValue = 1.0 upArrowAlphaAnimation?.toValue = 0.0 self.upArrowImageView.pop_add(upArrowAlphaAnimation, forKey: "fadeOut") } func onLanguaeSelected(language: String) { //Slide animation // let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter) // animation?.toValue = CGPoint(x: self.bottomBar.center.x, y: self.view.frame.size.height + self.bottomBar.frame.size.height/2) // self.bottomBar.pop_add(animation, forKey: "down") // // //Alpha animation // let alphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) // alphaAnimation?.fromValue = 0.0 // alphaAnimation?.toValue = 0.7 // self.upArrowImageView.pop_add(alphaAnimation, forKey: "fadeIn") // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { self.changeLanguage(language: language) // } } func changeLanguage(language: String) { currentLanguage = language TTSMgr.sharedInstance.configSpeech("", postUtteranceDelay: 0.0, speechRate: 0.28, pitchMultiplier: 1.0, language: currentLanguage) swipeableView.discardViews() cardIndex = currentCardIndex swipeableView.loadViews() self.readByIndex(index: self.currentCardIndex) cardModelTypeSwitchBtn.updateBtnByCategoryModel(category: CardModelMgr.sharedInstance.getCurrentCategoryModel()) categoryBar.reloadData() } func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let storyboad = UIStoryboard(name: "Main", bundle: Bundle.main) let categoryVC = storyboad.instantiateViewController(withIdentifier: "CategoryVC") as! CategoryVC categoryVC.loadData(categories: CardModelMgr.sharedInstance.categoryModels) return categoryVC } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { self.navigationController?.pushViewController(viewControllerToCommit, animated: true) // self.show(viewControllerToCommit, sender: self.cardModelTypeSwitchBtn) } }
mit
0c27d8bbdba3e101c0d1f4e07891e982
41.087912
311
0.661684
4.716749
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/GoldenQuranSwift/LanguageManager.swift
1
4553
// // LanguageManager.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 3/7/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import Foundation import UIKit enum LanguageType:String { case ar = "ar" case en = "en" } struct LanguageManager { static func deviceLanguage() -> String { let languages = UserDefaults.standard.object(forKey: Constants.iOS_LANGUAGES_KEY) as! NSArray return languages.firstObject as! String } static func changeLanguageTo( lang: LanguageType) { UserDefaults.standard.set([lang.rawValue,deviceLanguage()], forKey: Constants.iOS_LANGUAGES_KEY) UserDefaults.standard.synchronize() if lang == .ar { UIView.appearance().semanticContentAttribute = .forceRightToLeft } else { UIView.appearance().semanticContentAttribute = .forceLeftToRight } LocalizerHelper.DoTheSwizzling() } } extension UIApplication { func isAr() -> Bool{ return UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft } func isEn() -> Bool { return UIApplication.shared.userInterfaceLayoutDirection != .rightToLeft } var cstm_userInterfaceLayoutDirection : UIUserInterfaceLayoutDirection { get { var direction = UIUserInterfaceLayoutDirection.leftToRight if LanguageManager.deviceLanguage() == "ar" { direction = .rightToLeft } return direction } } } /* These methods to replace the original functions for localization It will fix the locations strings, UILable text alignment direction https://github.com/MoathOthman/Localization102/tree/swift3 https://medium.com/@dark_torch/working-with-localization-in-swift-4a87f0d393a4#.bxwjrxawt */ extension UILabel { public func cstmlayoutSubviews() { self.cstmlayoutSubviews() if self.textAlignment == .center { return } if self.tag <= 0 { if UIApplication.isAr() { if self.textAlignment == .right { return } } else { if self.textAlignment == .left { return } } } if self.tag <= 0 { if UIApplication.isAr() { self.textAlignment = .right } else { self.textAlignment = .left } } } } extension Bundle { func specialLocalizedStringForKey(key: String, value: String?, table tableName: String?) -> String { let currentLanguage = LanguageManager.deviceLanguage() var bundle = Bundle() if let _path = Bundle.main.path(forResource: currentLanguage, ofType: "lproj") { bundle = Bundle(path: _path)! } else { let _path = Bundle.main.path(forResource: "Base", ofType: "lproj")! bundle = Bundle(path: _path)! } return (bundle.specialLocalizedStringForKey(key: key, value: value, table: tableName)) } } /// Exchange the implementation of two methods for the same Class func MethodSwizzleGivenClassName(cls: AnyClass, originalSelector: Selector, overrideSelector: Selector) { let origMethod: Method = class_getInstanceMethod(cls, originalSelector); let overrideMethod: Method = class_getInstanceMethod(cls, overrideSelector); if (class_addMethod(cls, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) { class_replaceMethod(cls, overrideSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); } else { method_exchangeImplementations(origMethod, overrideMethod); } } class LocalizerHelper: NSObject { class func DoTheSwizzling() { MethodSwizzleGivenClassName(cls: Bundle.self, originalSelector: #selector(Bundle.localizedString), overrideSelector: #selector(Bundle.specialLocalizedStringForKey(key:value:table:))) MethodSwizzleGivenClassName(cls: UIApplication.self, originalSelector: #selector(getter: UIApplication.userInterfaceLayoutDirection), overrideSelector: #selector(getter: UIApplication.cstm_userInterfaceLayoutDirection)) MethodSwizzleGivenClassName(cls: UILabel.self, originalSelector: #selector(UILabel.layoutSubviews), overrideSelector: #selector(UILabel.cstmlayoutSubviews)) } }
mit
fb763437bece4177748d0b094ee1a300
31.748201
227
0.646309
4.905172
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Home/HomeFeedItem.swift
1
4997
// // Copyright (c) 2019 Google Inc. // // 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 FirebaseFirestore public struct HomeFeedItem { public var title: String public var message: String public var timestamp: Date public var category: String public var color: String public var active: Bool public var emergency: Bool } extension HomeFeedItem { public init?(dictionary: [String: Any]) { guard let title = dictionary["title"] as? String, let message = dictionary["message"] as? String, let timestamp = dictionary["timeStamp"] as? Timestamp, let category = dictionary["category"] as? String, let color = dictionary["color"] as? String, let active = dictionary["active"] as? Bool, let emergency = dictionary["emergency"] as? Bool else { return nil } self.title = title self.message = message self.timestamp = timestamp.dateValue() self.category = category self.color = color self.active = active self.emergency = emergency } } public class RemoteHomeFeedItemDataSource { public private(set) var feedItems: [HomeFeedItem] = [] public var activeFeedItems: [HomeFeedItem] { let currentTimestamp = Date() return feedItems.filter { currentTimestamp > $0.timestamp } .sorted { (lhs, rhs) -> Bool in return lhs.timestamp <= rhs.timestamp } } private var firestoreListener: ListenerRegistration? private let firestore: Firestore public init(firestore: Firestore) { self.firestore = firestore } public convenience init() { self.init(firestore: Firestore.firestore()) } public func syncFeedItems(_ callback: @escaping ([HomeFeedItem]) -> Void) { firestoreListener = firestore.feed.addSnapshotListener { (snapshot, error) in if let error = error { print("Error fetching feed items: \(error)") return } guard let snapshot = snapshot else { print("Unexpectedly found nil snapshot when fetching feed items") return } var feedItems: [HomeFeedItem] = [] for document in snapshot.documents { if let item = HomeFeedItem(dictionary: document.data()) { feedItems.append(item) } } self.feedItems = feedItems self.cacheAttributedStrings() callback(feedItems) } } public func stopSyncing() { firestoreListener?.remove() firestoreListener = nil } // Avoids a crash. Not sure why. Has something to do with NSAttributedString using WebKit // to create attributed strings from HTML. private func cacheAttributedStrings() { for item in feedItems { _ = InfoDetail.attributedText(detail: item.message) } } } class FeedSectionDataSource { private let remoteDataSource: RemoteHomeFeedItemDataSource init(remoteDataSource: RemoteHomeFeedItemDataSource) { self.remoteDataSource = remoteDataSource } var numberOfItems: Int { // Always show at least one cell. return max(remoteDataSource.activeFeedItems.count, 1) } func itemAtIndex(_ index: Int) -> HomeFeedItem { return remoteDataSource.activeFeedItems[index] } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard !remoteDataSource.activeFeedItems.isEmpty else { return noAnnouncementsCell(collectionView: collectionView, indexPath: indexPath) } let cell = collectionView.dequeueReusableCell( withReuseIdentifier: HomeFeedItemCollectionViewCell.reuseIdentifier(), for: indexPath ) as! HomeFeedItemCollectionViewCell let feedItem = itemAtIndex(indexPath.item) cell.populate(feedItem: feedItem) return cell } private func noAnnouncementsCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: NoAnnouncementsCollectionViewCell.reuseIdentifier(), for: indexPath ) as! NoAnnouncementsCollectionViewCell return cell } func sizeForItem(index: Int, maxWidth: CGFloat) -> CGSize { guard !remoteDataSource.activeFeedItems.isEmpty else { let height = NoAnnouncementsCollectionViewCell.height return CGSize(width: maxWidth, height: height) } let item = itemAtIndex(index) return HomeFeedItemCollectionViewCell.sizeForContents(item, maxWidth: maxWidth) } }
apache-2.0
225350f6bf20c7f966215f49da11a1a5
29.10241
91
0.69962
4.63114
false
false
false
false
AxziplinNet/AxziplinNet
Source/Delegate.swift
1
38636
// // SessionDelegate.swift // AxziplinNet // // Created by devedbox on 2017/4/19. // Copyright © 2017年 devedbox. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// Custom session delegate class for URLSession's callbacks and operations. public final class SessionDelegate: NSObject { // MARK: - URLSessionDelegate closures. /// Closure for `urlSession(_:didBecomeInvalidWithError:)` function in protocol `URLSessionDelegate`. public var sessionDidBecomeInvalid: SessionDidBecomeInvalid? /// Closure for `urlSession(_:didReceive:completionHandler:)` function in protocol `URLSessionDelegate`. public var sessionDidReceiveChallenge: SessionDidReceiveChallenge? #if !os(macOS) /// Closure for `urlSessionDidFinishEvents(forBackgroundURLSession:)` function in protocol `URLSessionDelegate`. public var sessionDidFinishedEvents: SessionDidFinishedEvents? #endif /// Closure for `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` function in protocol `URLSessionTaskDelegate`. public var taskOfSessionWillPerformHTTPRedirection: TaskOfSessionWillPerformHTTPRedirection? /// Closure for `urlSession(_:task:didReceive:completionHandler:)` function in protocol `URLSessionTaskDelegate`. public var taskOfSessionDidReceiveChallenge: TaskOfSessionDidReceiveChallenge? /// Closure for `urlSession(_:task:needNewBodyStream:)` function in protocol `URLSessionTaskDelegate`. public var taskOfSessionNeedNewBodyStream: TaskOfSessionNeedNewBodyStream? /// Closure for `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` function in protocol `URLSessionTaskDelegate`. public var taskOfSessionDidSendData: TaskOfSessionDidSendData? /// Closure for `urlSession(_:task:didFinishCollecting:)` function in protocol `URLSessionTaskDelegate`. @available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) public var taskOfSessionDidFinishCollecting: TaskOfSessionDidFinishCollecting? { get { return _taskOfSessionDidFinishCollecting as? TaskOfSessionDidFinishCollecting } set { _taskOfSessionDidFinishCollecting = newValue } } /// Closure for `urlSession(_:task:didComplete:)` function in protocol `URLSessionTaskDelegate`. public var taskOfSessionDidComplete: TaskOfSessionDidComplete? /// Closure for `urlSession(_:dataTask:didReceive:completionHandler:)` function in protocol `URLSessionDataDelegate`. public var dataTaskOfSessionDidReceiveResponse: DataTaskOfSessionDidReceiveResponse? /// Closure for `urlSession(_:dataTask:didBecome:)` function in protocol `URLSessionDataDelegate`. public var dataTaskOfSessionDidBecomeDownloadTask: DataTaskOfSessionDidBecomeDownloadTask? /// Closure for `urlSession(_:dataTask:didBecome:)` function in protocol `URLSessionDataDelegate`. @available(iOS 9.0, OSX 10.11, *) public var dataTaskOfSessionDidBecomeStreamTask: DataTaskOfSessionDidBecomeStreamTask? { get { return _dataTaskOfSessionDidBecomeStreamTask as? DataTaskOfSessionDidBecomeStreamTask } set { _dataTaskOfSessionDidBecomeStreamTask = newValue } } /// Closure for `urlSession(_:dataTask:didReceive:)` function in protocol `URLSessionDataDelegate`. public var dataTaskOfSessionDidReceiveData: DataTaskOfSessionDidReceiveData? /// Closure for `urlSession(_:dataTask:willCacheResponse:)` function in protocol `URLSessionDataDelegate`. public var dataTaskOfSessionWillCacheResponse: DataTaskOfSessionWillCacheResponse? /// Closure for `urlSession(_:downloadTask:didFinishDownloadingTo:)` function in protocol `URLSessionDownloadDelegate`. public var downloadTaskOfSessionDidFinishDownloading: DownloadTaskOfSessionDidFinishDownloading? /// Closure for `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` function in protocol `URLSessionDownloadDelegate`. public var downloadTaskOfSessionDidWriteData: DownloadTaskOfSessionDidWriteData? /// Closure for `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` function in protocol `URLSessionDownloadDelegate`. public var downloadTaskOfSessionDidResume: DownloadTaskOfSessionDidResume? /// Closure for `urlSession(_:readClosedFor:)` function in protocol `URLSessionStreamDelegate`. @available(iOS 9.0, OSX 10.11, *) public var streamTaskOfSessionReadClosed: StreamTaskOfSessionReadClosed? { get { return _streamTaskOfSessionReadClosed as? StreamTaskOfSessionReadClosed } set { _streamTaskOfSessionReadClosed = newValue } } /// Closure for `urlSession(_:writeClosedFor:)` function in protocol `URLSessionStreamDelegate`. @available(iOS 9.0, OSX 10.11, *) public var streamTaskOfSessionWriteClosed: StreamTaskOfSessionWriteClosed? { get { return _streamTaskOfSessionWriteClosed as? StreamTaskOfSessionWriteClosed } set { _streamTaskOfSessionWriteClosed = newValue } } /// Closure for `urlSession(_:betterRouteDiscoveredFor:)` function in protocol `URLSessionStreamDelegate`. @available(iOS 9.0, OSX 10.11, *) public var streamTaskOfSessionBetterRouteDiscovered: StreamTaskOfSessionBetterRouteDiscovered? { get { return _streamTaskOfSessionBetterRouteDiscovered as? StreamTaskOfSessionBetterRouteDiscovered } set { _streamTaskOfSessionBetterRouteDiscovered = newValue } } /// Closure for `urlSession(_streamTask:didBecome:outputStream:)` function in protocol `URLSessionStreamDelegate`. @available(iOS 9.0, OSX 10.11, *) public var streamTaskOfSessionDidBecomeInOutStream: StreamTaskOfSessionDidBecomeInOutStream? { get { return _streamTaskOfSessionDidBecomeInOutStream as? StreamTaskOfSessionDidBecomeInOutStream } set { _streamTaskOfSessionDidBecomeInOutStream = newValue } } private var _taskOfSessionDidFinishCollecting: Any? private var _dataTaskOfSessionDidBecomeStreamTask: Any? private var _streamTaskOfSessionReadClosed: Any? private var _streamTaskOfSessionWriteClosed: Any? private var _streamTaskOfSessionBetterRouteDiscovered: Any? private var _streamTaskOfSessionDidBecomeInOutStream: Any? // MARK: URLCredential /// public var credentialOfChallenge: ((URLSession, URLSessionTask?, URLAuthenticationChallenge) -> URLCredential?)? } extension SessionDelegate { public typealias SessionDidBecomeInvalid = ((URLSession, Error?) -> Swift.Void) public typealias SessionDidReceiveChallenge = ((URLSession, URLAuthenticationChallenge, (@escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)) -> Swift.Void) public typealias SessionDidFinishedEvents = ((URLSession) -> Swift.Void) public typealias TaskOfSessionWillPerformHTTPRedirection = ((URLSessionTask, URLSession, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Swift.Void) -> Swift.Void) public typealias TaskOfSessionDidReceiveChallenge = ((URLSessionTask, URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) -> Swift.Void) public typealias TaskOfSessionNeedNewBodyStream = ((URLSessionTask, URLSession, @escaping (InputStream?) -> Swift.Void) -> Swift.Void) public typealias TaskOfSessionDidSendData = ((URLSessionTask, URLSession, Int64, Int64, Int64) -> Swift.Void) public typealias TaskOfSessionDidFinishCollecting = ((URLSessionTask, URLSession, URLSessionTaskMetrics) -> Swift.Void) public typealias TaskOfSessionDidComplete = ((URLSessionTask, URLSession, Error?) -> Swift.Void) public typealias DataTaskOfSessionDidReceiveResponse = ((URLSessionDataTask, URLSession, URLResponse, @escaping (URLSession.ResponseDisposition) -> Swift.Void) -> Swift.Void) public typealias DataTaskOfSessionDidBecomeDownloadTask = ((URLSessionDataTask, URLSession, URLSessionDownloadTask) -> Swift.Void) public typealias DataTaskOfSessionDidBecomeStreamTask = ((URLSessionDataTask, URLSession, URLSessionStreamTask) -> Swift.Void) public typealias DataTaskOfSessionDidReceiveData = ((URLSessionDataTask, URLSession, Data) -> Swift.Void) public typealias DataTaskOfSessionWillCacheResponse = ((URLSessionDataTask, URLSession, CachedURLResponse, @escaping (CachedURLResponse?) -> Swift.Void) -> Swift.Void) public typealias DownloadTaskOfSessionDidFinishDownloading = ((URLSessionDownloadTask, URLSession, URL) -> Swift.Void) public typealias DownloadTaskOfSessionDidWriteData = ((URLSessionDownloadTask, URLSession, Int64, Int64, Int64) -> Swift.Void) public typealias DownloadTaskOfSessionDidResume = ((URLSessionDownloadTask, URLSession, Int64, Int64) -> Swift.Void) public typealias StreamTaskOfSessionReadClosed = ((URLSessionStreamTask, URLSession) -> Swift.Void) public typealias StreamTaskOfSessionWriteClosed = ((URLSessionStreamTask, URLSession) -> Swift.Void) public typealias StreamTaskOfSessionBetterRouteDiscovered = ((URLSessionStreamTask, URLSession) -> Swift.Void) public typealias StreamTaskOfSessionDidBecomeInOutStream = ((URLSessionStreamTask, URLSession, InputStream, OutputStream) -> Swift.Void) } // MARK: URLSessionDelegate extension SessionDelegate: URLSessionDelegate { /// Tells the URL session that the session has been invalidated. /// If you invalidate a session by calling its finishTasksAndInvalidate() method, the session waits until after the final task in the session finishes or fails before calling this delegate method. If you call the invalidateAndCancel() method, the session calls this delegate method immediately. /// - Parameters: /// - session: The session object that was invalidated. /// - error: The error that caused invalidation, or nil if the invalidation was explicit. public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { sessionDidBecomeInvalid?(session, error) } /// Requests credentials from the delegate in response to a session-level authentication request from the remote server. /// This method is called in two situations: /// /// - When a remote server asks for client certificates or Windows NT LAN Manager (NTLM) authentication, /// to allow your app to provide appropriate credentials /// - When a session first establishes a connection to a remote server that uses SSL or TLS, /// to allow your app to verify the server’s certificate chain /// /// If you do not implement this method, the session calls its delegate’s urlSession(_:task:didReceive:completionHandler:) method instead. /// /// - Note: This method handles only the NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate, /// NSURLAuthenticationMethodClientCertificate, and NSURLAuthenticationMethodServerTrust authentication types. For all other authentication /// schemes, the session calls only the urlSession(_:task:didReceive:completionHandler:) method. /// - Parameters: /// - session: The session containing the task that requested authentication. /// - challenge: An object that contains the request for authentication. /// - completionHandler: A handler that your delegate method must call. Its parameters are: /// - disposition—One of several constants that describes how the challenge should be handled. /// - credential—The credential that should be used for authentication if disposition is /// NSURLSessionAuthChallengeUseCredential, otherwise NULL. public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) { // Using did receive challenge closure. if let _challenge = sessionDidReceiveChallenge { _challenge(session, challenge, completionHandler) return } // Run default configuration of challenge: // Cancel challenge if failed many times. guard challenge.previousFailureCount == 0 else { challenge.sender?.cancel(challenge) completionHandler(.cancelAuthenticationChallenge, nil) return } // Using the credential of custom closure results by user. if let _credentialGetter = credentialOfChallenge { if let _credential = _credentialGetter(session, nil, challenge) { completionHandler(.useCredential, _credential) } return } // Performing default handling without credential. completionHandler(.performDefaultHandling, nil) } #if !os(macOS) /// Tells the delegate that all messages enqueued for a session have been delivered. /// In iOS, when a background transfer completes or requires credentials, if your app is no longer running, your app is automatically relaunched in the background, and the app’s UIApplicationDelegate is sent an application(_:handleEventsForBackgroundURLSession:completionHandler:) message. This call contains the identifier of the session that caused your app to be launched. Your app should then store that completion handler before creating a background configuration object with the same identifier, and creating a session with that configuration. The newly created session is automatically reassociated with ongoing background activity. /// When your app later receives a URLSessionDidFinishEventsForBackgroundURLSession: message, this indicates that all messages previously enqueued for this session have been delivered, and that it is now safe to invoke the previously stored completion handler or to begin any internal updates that may result in invoking the completion handler. /// - Important: /// Because the provided completion handler is part of UIKit, you must call it on your main thread. For example: /// - Listing 1: /// ``` /// [[NSOperationQueue mainQueue] addOperationWithBlock:^{ /// storedHandler(); /// }]; /// ``` /// - Parameters: /// - session: The session that no longer has any outstanding requests. public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { sessionDidFinishedEvents?(session) } #endif } // MARK: URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Tells the delegate that the remote server requested an HTTP redirect. /// This method is called only for tasks in default and ephemeral sessions. Tasks in background sessions automatically follow redirects. /// - Parameters: /// - session: The session containing the task whose request resulted in a redirect. /// - task: The task whose request resulted in a redirect. /// - response: An object containing the server’s response to the original request. /// - request: A URL request object filled out with the new location. /// - completionHandler: A block that your handler should call with either the value of the request parameter, /// a modified URL request object, or NULL to refuse the redirect and return the body of the redirect response. public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Swift.Void) { if let willPerformHTTPRedirection = taskOfSessionWillPerformHTTPRedirection { willPerformHTTPRedirection(task, session, response, request, completionHandler) return; } completionHandler(request) } /// Requests credentials from the delegate in response to an authentication request from the remote server. /// This method handles task-level authentication challenges. The URLSessionDelegate protocol also provides a session-level authentication /// delegate method. The method called depends on the type of authentication challenge: /// /// - For session-level challenges—NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate, /// NSURLAuthenticationMethodClientCertificate, or NSURLAuthenticationMethodServerTrust—the NSURLSession object calls the session /// delegate’s urlSession(_:didReceive:completionHandler:) method. If your app does not provide a session delegate method, the /// NSURLSession object calls the task delegate’s urlSession(_:task:didReceive:completionHandler:) method to handle the challenge. /// - For non-session-level challenges (all others), the NSURLSession object calls the session delegate’s /// urlSession(_:task:didReceive:completionHandler:) method to handle the challenge. If your app provides a session delegate and you need /// to handle authentication, then you must either handle the authentication at the task level or provide a task-level handler that calls /// the per-session handler explicitly. The session delegate’s urlSession(_:didReceive:completionHandler:) method is not called for non- /// session-level challenges. /// /// - Parameters: /// - session: The session containing the task whose request requires authentication. /// - task: The task whose request requires authentication. /// - challenge: An object that contains the request for authentication. /// - completionHandler: A handler that your delegate method must call. Its parameters are: /// - disposition—One of several constants that describes how the challenge should be handled. /// - credential—The credential that should be used for authentication if disposition is /// NSURLSessionAuthChallengeUseCredential; otherwise, NULL. public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) { taskOfSessionDidReceiveChallenge?(task, session, challenge, completionHandler) } /// Tells the delegate when a task requires a new request body stream to send to the remote server. /// This delegate method is called under two circumstances: /// /// - To provide the initial request body stream if the task was created with uploadTask(withStreamedRequest:) /// - To provide a replacement request body stream if the task needs to resend a request that has a body stream because of an /// authentication challenge or other recoverable server error. /// /// - Note: You do not need to implement this if your code provides the request body using a file URL or an NSData object. /// - Parameters: /// - session: The session containing the task that needs a new body stream. /// - task: The task that needs a new body stream. /// - completionHandler: A completion handler that your delegate method should call with the new body stream. public func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Swift.Void) { if let needNewBodyStream = taskOfSessionNeedNewBodyStream { needNewBodyStream(task, session, completionHandler) return } completionHandler(nil) } /// Periodically informs the delegate of the progress of sending body content to the server. /// - Parameters: /// - session: The session containing the data task. /// - task: The data task. /// - bytesSent: The number of bytes sent since the last time this delegate method was called. /// - totalBytesSent: The total number of bytes sent so far. /// - totalBytesExpectedToSend: The expected length of the body data. The URL loading system can determine the length of the upload /// data in three ways: /// - From the length of the NSData object provided as the upload body. /// - From the length of the file on disk provided as the upload body of an upload task (not a download /// task). /// - From the Content-Length in the request object, if you explicitly set it. /// Otherwise, the value is NSURLSessionTransferSizeUnknown (-1) if you provided a stream or body data /// object, or zero (0) if you did not. public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { taskOfSessionDidSendData?(task, session, bytesSent, totalBytesSent, totalBytesExpectedToSend) } /// Tells the delegate that the session finished collecting metrics for the task. /// - Parameters: /// - session: The session collecting the metrics. /// - task: The task whose metrics have been collected. /// - metrics: The collected metrics. @available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { taskOfSessionDidFinishCollecting?(task, session, metrics) } /// Tells the delegate that the task finished transferring data. /// Server errors are not reported through the error parameter. The only errors your delegate receives through the error parameter are client-side errors, such as being unable to resolve the hostname or connect to the host. /// - Parameters: /// - session: The session containing the task whose request finished transferring data. /// - task: The task whose request finished transferring data. /// - error: If an error occurred, an error object indicating how the transfer failed, otherwise NULL. public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { taskOfSessionDidComplete?(task, session, error) } } // MARK: URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { /// Tells the delegate that the data task received the initial reply (headers) from the server. /// This method is optional unless you need to support the (relatively obscure) multipart/x-mixed-replace content type. With that content type, the server sends a series of parts, each of which is intended to replace the previous part. The session calls this method at the beginning of each part, and you should then display, discard, or otherwise process the previous part, as appropriate. /// If you do not provide this delegate method, the session always allows the task to continue. /// - Parameters: /// - session: The session containing the data task that received an initial reply. /// - dataTask: The data task that received an initial reply. /// - response: A URL response object populated with headers. /// - completionHandler: A completion handler that your code calls to continue the transfer, passing a constant /// to indicate whether the transfer should continue as a data task or should become a download task. /// - If you pass allow, the task continues normally. /// - If you pass cancel, the task is canceled. /// - If you pass becomeDownload as the disposition, your delegate’s urlSession(_:dataTask:didBecome:) /// method is called to provide you with the new download task that supersedes the current task. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Swift.Void) { if let didReceiveResponse = dataTaskOfSessionDidReceiveResponse { didReceiveResponse(dataTask, session, response, completionHandler) return } completionHandler(.allow) } /// Tells the delegate that the data task was changed to a download task. /// When the delegate’s URLSession:dataTask:didReceiveResponse:completionHandler: method decides to change the disposition from a data request to a download, the session calls this delegate method to provide you with the new download task. After this call, the session delegate receives no further delegate method calls related to the original data task. /// - Parameters: /// - session: The session containing the task that was replaced by a download task. /// - dataTask: The data task that was replaced by a download task. /// - downloadTask: The new download task that replaced the data task. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { dataTaskOfSessionDidBecomeDownloadTask?(dataTask, session, downloadTask) } /// Tells the delegate that the data task was changed to a streamtask. /// When the delegate’s URLSession:dataTask:didReceiveResponse:completionHandler: method decides to change the disposition from a data request to a stream, the session calls this delegate method to provide you with the new stream task. After this call, the session delegate receives no further delegate method calls related to the original data task. /// For requests that were pipelined, the stream task will only allow reading, and the object will immediately send the delegate message urlSession(_:writeClosedFor:). Pipelining can be disabled for all requests in a session by setting the httpShouldUsePipelining property on its URLSessionConfiguration object, or for individual requests by setting the httpShouldUsePipelining property on an NSURLRequest object. /// - Parameters: /// - session: The session containing the task that was replaced by a stream task. /// - dataTask: The data task that was replaced by a stream task. /// - streamTask: The new stream task that replaced the data task. @available(iOS 9.0, OSX 10.11, *) public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome streamTask: URLSessionStreamTask) { dataTaskOfSessionDidBecomeStreamTask?(dataTask, session, streamTask) } /// Tells the delegate that the data task has received some of the expected data. /// Because the NSData object is often pieced together from a number of different data objects, whenever possible, use NSData’s enumerateBytes(_:) method to iterate through the data rather than using the bytes method (which flattens the NSData object into a single memory block). /// This delegate method may be called more than once, and each call provides only data received since the previous call. The app is responsible for accumulating this data if needed. /// - Parameters: /// - session: The session containing the data task that provided data. /// - dataTask: The data task that provided data. /// - data: A data object containing the transferred data. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { dataTaskOfSessionDidReceiveData?(dataTask, session, data) } /// Asks the delegate whether the data (or upload) task should store the response in the cache. /// The session calls this delegate method after the task finishes receiving all of the expected data. If you do not implement this method, the default behavior is to use the caching policy specified in the session’s configuration object. The primary purpose of this method is to prevent caching of specific URLs or to modify the userInfo dictionary associated with the URL response. /// This method is called only if the URLProtocol handling the request decides to cache the response. As a rule, responses are cached only when all of the following are true: /// - The request is for an HTTP or HTTPS URL (or your own custom networking protocol that supports caching). /// - The request was successful (with a status code in the 200–299 range). /// - The provided response came from the server, rather than out of the cache. /// - The session configuration’s cache policy allows caching. /// - The provided NSURLRequest object's cache policy (if applicable) allows caching. /// - The cache-related headers in the server’s response (if present) allow caching. /// - The response size is small enough to reasonably fit within the cache. (For example, if you provide a disk cache, the response must be no larger than about 5% of the disk cache size.) /// - Parameters: /// - session: The session containing the data (or upload) task. /// - dataTask: The data (or upload) task. /// - proposedResponse: The default caching behavior. This behavior is determined based on the current /// caching policy and the values of certain received headers, such as the Pragma and Cache-Control headers. /// - completionHandler: A block that your handler must call, providing either the original proposed response, a modified /// version of that response, or NULL to prevent caching the response. If your delegate implements this method, /// it must call this completion handler; otherwise, your app leaks memory. public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Swift.Void) { if let willCacheResponse = dataTaskOfSessionWillCacheResponse { willCacheResponse(dataTask, session, proposedResponse, completionHandler) return } completionHandler(proposedResponse) } } // MARK: URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { /// Tells the delegate that a download task has finished downloading. /// - Parameters: /// - session: The session containing the download task that finished. /// - downloadTask: The download task that finished. /// - location: A file URL for the temporary file. Because the file is temporary, you must /// either open the file for reading or move it to a permanent location in your /// app’s sandbox container directory before returning from this delegate method. /// /// If you choose to open the file for reading, you should do the actual reading /// in another thread to avoid blocking the delegate queue. public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { downloadTaskOfSessionDidFinishDownloading?(downloadTask, session, location) } /// Periodically informs the delegate about the download’s progress. /// - Parameters: /// - session: The session containing the download task. /// - downloadTask: The download task. /// - bytesWritten: The number of bytes transferred since the last time this delegate method was called. /// - totalBytesWritten: The total number of bytes transferred so far. /// - totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length header. /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { downloadTaskOfSessionDidWriteData?(downloadTask, session, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } /// Tells the delegate that the download task has resumed downloading. /// If a resumable download task is canceled or fails, you can request a resumeData object that provides enough information to restart the download in the future. Later, you can call downloadTask(withResumeData:) or downloadTask(withResumeData:completionHandler:) with that data. /// When you call those methods, you get a new download task. As soon as you resume that task, the session calls its delegate’s URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes: method with that new task to indicate that the download is resumed. /// - Parameters: /// - session: The session containing the download task that finished. /// - downloadTask: The download task that resumed. See explanation in the discussion. /// - fileOffset: If the file's cache policy or last modified date prevents reuse of the existing /// content, then this value is zero. Otherwise, this value is an integer representing /// the number of bytes on disk that do not need to be retrieved again. /// - Note: In some situations, it may be possible for the transfer to resume earlier in the file /// than where the previous transfer ended. /// - expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. If this header /// was not provided, the value is NSURLSessionTransferSizeUnknown. public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { downloadTaskOfSessionDidResume?(downloadTask, session, fileOffset, expectedTotalBytes) } } // MARK: URLSessionStreamDelegate @available(iOS 9.0, OSX 10.11, *) extension SessionDelegate: URLSessionStreamDelegate { /// Tells the delegate that the read side of the underlying socket has been closed. /// This method may be called even if no reads are currently in progress. This method does not indicate that the stream reached end-of-file (EOF), such that no more data can be read. /// - Parameters: /// - session: The session containing the stream task that closed reads. /// - streamTask: The stream task that closed reads. public func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { streamTaskOfSessionReadClosed?(streamTask, session) } /// Tells the delegate that the write side of the underlying socket has been closed. /// This method may be called even if no writes are currently in progress. /// - Parameters: /// - session: The session containing the stream task that closed writes. /// - streamTask: The stream task that closed writes. public func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { streamTaskOfSessionWriteClosed?(streamTask, session) } /// Tells the delegate that a better route to the host has been detected for the stream. /// This method is called when the URL loading system determines that a better route to the endpoint host is available. For example, this method may be called when a Wi-Fi interface becomes available. /// You should consider completing pending work and creating a new stream task in order to take advantage of better routes when they become available. /// - Parameters: /// - session: The session of the stream task that discovered a better route. /// - streamTask: The stream task that discovered a better route. public func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { streamTaskOfSessionBetterRouteDiscovered?(streamTask, session) } /// Tells the delegate that the stream task has been completed as a result of the stream task calling the captureStreams() method. /// This delegate method will only be called after all enqueued reads and writes for the stream task have been completed. /// - Parameters: /// - session: The session of the stream task that has been completed. /// - streamTask: The stream task that has been completed. /// - inputStream: The created input stream. This InputStream object is unopened. /// - outputStream: The created output stream. This OutputStream object is unopened public func urlSession(_ session: URLSession, streamTask: URLSessionStreamTask, didBecome inputStream: InputStream, outputStream: OutputStream) { streamTaskOfSessionDidBecomeInOutStream?(streamTask, session, inputStream, outputStream) } }
mit
a6977a36a7b3ee47fa72dc3ae593ce72
75.250988
644
0.719747
5.50478
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/Migrations/87-88/BlogToBlogMigration87to88.swift
1
1550
import CoreData class BlogToBlogMigration87to88: NSEntityMigrationPolicy { override func createRelationships(forDestination dInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws { try super.createRelationships(forDestination: dInstance, in: mapping, manager: manager) let gutenbergEnabledFlag = UserPersistentStoreFactory.instance().object(forKey: "kUserDefaultsGutenbergEditorEnabled") as? Bool let isGutenbergEnabled = gutenbergEnabledFlag ?? false let editor = isGutenbergEnabled ? "gutenberg" : "aztec" dInstance.setValue(editor, forKey: "mobileEditor") if gutenbergEnabledFlag != nil { let url = dInstance.value(forKey: "url") as? String ?? "" let perSiteEnabledKey = "com.wordpress.gutenberg-autoenabled-"+url UserPersistentStoreFactory.instance().set(true, forKey: perSiteEnabledKey) } } override func end(_ mapping: NSEntityMapping, manager: NSMigrationManager) throws { NotificationCenter.default.observeOnce(forName: .applicationLaunchCompleted, object: nil, queue: .main, using: { (_) in let context = ContextManager.shared.mainContext let service = EditorSettingsService(managedObjectContext: context) let isGutenbergEnabled = UserPersistentStoreFactory.instance().object(forKey: "kUserDefaultsGutenbergEditorEnabled") as? Bool ?? false service.migrateGlobalSettingToRemote(isGutenbergEnabled: isGutenbergEnabled) }) } }
gpl-2.0
f13ed4cdf66552af7ec37ee0635027ff
52.448276
147
0.727742
4.682779
false
false
false
false
WERUreo/werureo-slackbots
Sources/App/Slack/SlackRequest.swift
1
1408
// // SlackRequest.swift // slack-commands // // Created by Keli'i Martin on 1/1/17. // // import Foundation import Vapor struct SlackRequest { //////////////////////////////////////////////////////////// // MARK: - Properties //////////////////////////////////////////////////////////// var channelID: String = "" var responseURL: String = "" var channelName: String = "" var token: String = "" var userID: String = "" var userName: String = "" var text: String? var command: String = "" var teamID: String = "" var teamDomain: String = "" //////////////////////////////////////////////////////////// // MARK: - Initializers //////////////////////////////////////////////////////////// init(node: Node?) throws { guard let node = node else { return } self.channelID = try node.extract("channel_id") self.responseURL = try node.extract("response_url") self.channelName = try node.extract("channel_name") self.token = try node.extract("token") self.userID = try node.extract("user_id") self.userName = try node.extract("user_name") self.text = try node.extract("text") self.command = try node.extract("command") self.teamID = try node.extract("team_id") self.teamDomain = try node.extract("team_domain") } }
mit
5e0ee79895a189f2cca1934a936b1909
26.607843
64
0.480114
4.571429
false
false
false
false
elationfoundation/Reporta-iOS
IWMF/TableViewCell/CheckInDetailTableViewCell.swift
1
1247
// // CheckInLocationTableViewCell.swift // IWMF // // // // import Foundation import UIKit class CheckInDetailTableViewCell: UITableViewCell, UITextViewDelegate { @IBOutlet weak var textView: UITextView! var identity : String! = "" var value : NSString! = "" var title : String! = "" override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func intialize() { textView.selectable = false if value != nil{ if value.length > 0{ self.textView.text = value as String self.textView.textColor = UIColor.blackColor() }else{ self.textView.text = title self.textView.textColor = UIColor.lightGrayColor() } }else{ self.textView.text = title self.textView.textColor = UIColor.lightGrayColor() } self.textView.font = Utility.setFont() } func textViewDidBeginEditing(textView: UITextView) { } func textViewDidEndEditing(textView: UITextView) { } }
gpl-3.0
205a5451f3203dcfc2e295b42ff2187b
23.96
75
0.573376
4.948413
false
false
false
false
azimin/Rainbow
Rainbow/ColorWheelBasicActions.swift
1
2612
// // ColorWheelBasicActions.swift // Rainbow // // Created by Alex Zimin on 05/04/16. // Copyright © 2016 Alex Zimin. All rights reserved. // import Foundation struct ColorWheelAction { let colorWheel: ColorWheelType.Type init(colorWheel: ColorWheelType.Type) { self.colorWheel = colorWheel } init() { self.init(colorWheel: RYBColorWheel.self) } static func takeSameStyleOfColor(color originColor: Color, forColorOnAngle color: Color) -> Color { let angle = RGBColorWheel.angleForColor(color) return RGBColorWheel.colorAtAngle(originColor, angle: angle) } // Hight contrast func complementary(color: Color) -> (original: Color, complementary: Color) { let angle = colorWheel.angleForColor(color) let complementaryColor = colorWheel.colorAtAngle(color, angle: angle + 180) return (color, complementaryColor) } // Для генерации ... цвета надо использовать деаметриально противоположный // // Two less contrast colors func splitComplementary(color: Color, movementAngle: Int = 30) -> (original: Color, complementaryRight: Color, complementaryLeft: Color) { let angle = colorWheel.angleForColor(color) let firstColor = colorWheel.colorAtAngle(color, angle: angle + (180 - movementAngle)) let secondColor = colorWheel.colorAtAngle(color, angle: angle + (180 + movementAngle)) return (color, firstColor, secondColor) } func rectangle(firstColor: Color, movementAngle: Int = 30) -> (firstPair: (Color, Color), secondPair: (Color, Color)) { let angle = colorWheel.angleForColor(firstColor) let secondAngle = angle + movementAngle let secondColor = colorWheel.colorAtAngle(firstColor, angle: secondAngle) let firstPair = complementary(firstColor) let secondPair = complementary(secondColor) return (firstPair, secondPair) } // Narby colors func analogous(color: Color, movementAngle: Int = 30) -> (middle: Color, left: Color, right: Color) { let angle = colorWheel.angleForColor(color) let leftColor = colorWheel.colorAtAngle(color, angle: angle - 30) let rightColor = colorWheel.colorAtAngle(color, angle: angle + 30) return (color, leftColor, rightColor) } // Equal space on wheel func triadic(color: Color) -> (original: Color, left: Color, right: Color) { let angle = colorWheel.angleForColor(color) let leftColor = colorWheel.colorAtAngle(color, angle: angle - 120) let rightColor = colorWheel.colorAtAngle(color, angle: angle + 120) return (color, leftColor, rightColor) } }
mit
37db1fad057cdf9edfc6fa415418be6b
36.514706
140
0.718431
3.971963
false
false
false
false
MrBendel/InfinityScrollView
APLoopingScrollView/APLoopingScrollView/Examples/Examples.swift
2
4505
// // Examples.swift // APLoopingScrollView // // Created by Andrew Poes on 9/14/15. // Copyright © 2015 Andrew Poes. All rights reserved. // import UIKit class ExampleHorz: UIViewController, APLoopingScrollViewDataSource, APLoopingScrollViewDelegate { @IBOutlet var backButton: UIButton? @IBOutlet var loopingScrollView: LoopingScrollViewWithScaling? var cacheCount = 0 var cellColors = [UIColor.cyanColor().colorWithAlphaComponent(0.5), UIColor.yellowColor().colorWithAlphaComponent(0.5),UIColor.greenColor().colorWithAlphaComponent(0.5),UIColor.grayColor().colorWithAlphaComponent(0.5)] override func viewDidLoad() { super.viewDidLoad() if let loopingScrollView = self.loopingScrollView { let frame = loopingScrollView.frame loopingScrollView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.3) loopingScrollView.delegate = self loopingScrollView.dataSource = self loopingScrollView.scrollDirection = .Horizontal loopingScrollView.itemSize = CGSize(width: CGRectGetHeight(frame) * 0.5, height: CGRectGetHeight(frame) * 0.5) loopingScrollView.itemSpacing = 6 loopingScrollView.edgeScale = 0.9 loopingScrollView.pagingEnabled = true } } @IBAction func handleClearData(sender: UIButton) { self.cacheCount += 1 self.loopingScrollView?.reloadData() } func loopingScrollViewTotalItems(scrollView: APLoopingScrollView) -> Int { return 10 } func loopingScrollView(scrollView: APLoopingScrollView, viewForIndex index: Int) -> UIView { let itemSize = scrollView.itemSize let cell = ExampleCell(frame: CGRect(origin: CGPointZero, size: itemSize)) cell.text = "\(index)" let colorIndex = self.cacheCount%self.cellColors.count cell.backgroundColor = self.cellColors[colorIndex] return cell } @IBAction func backButtonTouchUpInside(sender: UIButton?) { self.navigationController?.popViewControllerAnimated(true) } } class ExampleVert: UIViewController, APLoopingScrollViewDataSource, APLoopingScrollViewDelegate { @IBOutlet var backButton: UIButton? @IBOutlet var loopingScrollView: APLoopingScrollView? var cacheCount = 0 var cellColors = [UIColor.cyanColor().colorWithAlphaComponent(0.5), UIColor.yellowColor().colorWithAlphaComponent(0.5),UIColor.greenColor().colorWithAlphaComponent(0.5),UIColor.grayColor().colorWithAlphaComponent(0.5)] override func viewDidLoad() { super.viewDidLoad() if let loopingScrollView = self.loopingScrollView { let frame = loopingScrollView.frame loopingScrollView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.3) loopingScrollView.delegate = self loopingScrollView.dataSource = self loopingScrollView.scrollDirection = .Vertical loopingScrollView.itemSize = CGSize(width: CGRectGetWidth(frame) * 0.5, height: CGRectGetWidth(frame) * 0.5) loopingScrollView.itemSpacing = 6 loopingScrollView.pagingEnabled = false } } @IBAction func handleClearData(sender: UIButton) { self.cacheCount += 1 self.loopingScrollView?.reloadData() } func loopingScrollViewTotalItems(scrollView: APLoopingScrollView) -> Int { return 10 } func loopingScrollView(scrollView: APLoopingScrollView, viewForIndex index: Int) -> UIView { let itemSize = scrollView.itemSize let cell = ExampleCell(frame: CGRect(origin: CGPointZero, size: itemSize)) cell.text = "\(index)" let colorIndex = self.cacheCount%self.cellColors.count cell.backgroundColor = self.cellColors[colorIndex] return cell } @IBAction func backButtonTouchUpInside(sender: UIButton?) { self.navigationController?.popViewControllerAnimated(true) } } class ExampleCell: UIView { var label: UILabel? override init(frame: CGRect) { super.init(frame: frame) let label = UILabel(frame: self.bounds) label.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.5) label.textColor = UIColor.whiteColor() label.font = UIFont.systemFontOfSize(48, weight: UIFontWeightBlack) self.addSubview(label) self.label = label } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var text: String? { set { self.label?.text = newValue self.label?.sizeToFit() self.label?.center = CGPoint(x: CGRectGetWidth(self.frame) * 0.5, y: CGRectGetHeight(self.frame) * 0.5) } get { return self.label?.text } } }
mit
e55d8f3bfbe5af95bb6c8a43cf6b5c43
32.864662
220
0.736901
4.549495
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/BookDetail/Views/ProgressView.swift
1
1427
// // ProgressView.swift // zhuishushenqi // // Created by yung on 2017/4/28. // Copyright © 2017年 QS. All rights reserved. // /* { "desc":"正在缓存中", "total":100, "now":0 } */ import UIKit class ProgressView: UIView { var dict:[String:Any]? { didSet{ if let tip = dict { setTips(dict: tip) } } } private var tipLabel:UILabel! override init(frame: CGRect) { super.init(frame: frame) setupSubview() } func setupSubview(){ tipLabel = UILabel() tipLabel.frame = CGRect(x: 15, y: 0, width: self.bounds.width, height: 20) tipLabel.textColor = UIColor.white tipLabel.font = UIFont.systemFont(ofSize: 11) addSubview(tipLabel) } func setTips(dict:[String:Any]){ let desc = dict["desc"] ?? "" let total:Int = dict["total"] as? Int ?? -1 let now:Int = dict["now"] as? Int ?? 0 var tip = "" if total == -1 { tip = "\(desc)" }else{ tip = "\(desc)(\(now + 1)/\(total))" } if now >= total { tip = "缓存完成...(\(now)/\(total))" } DispatchQueue.main.async { self.tipLabel.text = tip } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
45b504679f0ea6bdded4f1cb3c41fcd7
20.96875
82
0.497155
3.873278
false
false
false
false
adamontherun/economist
EconomistNotes/RecentNotesTableViewController.swift
1
2552
// // RecentNotesTableViewController.swift // EconomistNotes // // Created by adam smith on 7/25/16. // Copyright © 2016 adam smith. All rights reserved. // import UIKit /// Displays all notes written by the user in reverse chronological order of the date they were written. NOTE: UITableViewController+FetchedResultsControllerDelegate.swift extends UITableViewController to adopt NSFetchedResultsControllerDelegate delegate methods final class RecentNotesTableViewController: UITableViewController { var fetchedResultsController:NSFetchedResultsController? // MARK: View Controller Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() configureTableViewAppearance() fetchedResultsController = Note.MR_fetchAllSortedBy("publishDate", ascending: false, withPredicate: nil, groupBy: nil, delegate: self) } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let count = fetchedResultsController?.sections?[0].numberOfObjects { return count } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.RecentNoteCell.rawValue, forIndexPath: indexPath) as! NoteTableViewCell if let note = fetchedResultsController?.objectAtIndexPath(indexPath) as? Note { cell.configure(withNote: note) } return cell } // MARK: - Table View Configuration Methods private func configureTableViewAppearance() { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 140 tableView.hideUnusedCells() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == SegueIdentifier.SegueFromRecentNotesViewControllerToNoteViewController.rawValue { guard let indexPath = tableView.indexPathForSelectedRow, let noteViewController = segue.destinationViewController as? NoteViewController else { return } let note = fetchedResultsController?.objectAtIndexPath(indexPath) as? Note noteViewController.note = note } } }
mit
54a35d4326a4df942987c7bae6c04ad5
32.565789
262
0.684437
6.298765
false
true
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Account/Controllers/SignUpController.swift
1
989
// // SignUpController.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/11/6. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class SignUpController: GroupTableController, SignActionPresenter { override func initSubviews() { tableView.backgroundColor = .white let headerView = AccountHeaderView() tableView.tableHeaderView = headerView let footerView = PasswordSignInFooterView() tableView.tableFooterView = footerView tableView.separatorStyle = .none rows = [ [ Row<AccountCell>(viewData: NoneItem()), Row<VerificationCodeCell>(viewData: NoneItem()), Row<AdjustedPasswordCell>(viewData: NoneItem()) ] ] } @objc func signInAction() { } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.sizeFooterToFit() } }
mit
fba5df1c827208fda693671419aff5d5
22.190476
67
0.60883
5.236559
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/Sku/SkuVC.swift
1
2123
// // SkuVC.swift // UIScrollViewDemo // // Created by 黄渊 on 2022/10/28. // Copyright © 2022 伯驹 黄. All rights reserved. // import Foundation final class SkuVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // 强制设置为darkMode if #available(iOS 13.0, *) { overrideUserInterfaceStyle = .dark } view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalToSuperview() } loadData() } func loadData() { DispatchQueue.global().async { guard let dataFilePath = Bundle.main.path(forResource: "variants", ofType: "json") else { return } do { let data = try Data(contentsOf: URL(fileURLWithPath: dataFilePath)) let model = try JSONDecoder().decode(GoodsModel.self, from: data) self.viewModel.updateRows(with: model) } catch let error { print(error) } DispatchQueue.main.async { self.tableView.reloadData() } } } private lazy var tableView: UITableView = { let tableView = UITableView() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 100 tableView.separatorStyle = .none tableView.keyboardDismissMode = .onDrag tableView.register(cellType: SKUCell.self) tableView.register(cellType: GoodsInfoCell.self) tableView.dataSource = viewModel return tableView }() private lazy var viewModel: SkuViewModel = { let viewModel = SkuViewModel() viewModel.isGraph = title == "图解法" return viewModel }() } extension SkuVC: SKUCellDelegate { func skuCellItemDidSelect(_ cell: SKUCell) { guard let goodsModel = cell.cellModel?.selectedGoods else { return } viewModel.refreshInfoRow(with: goodsModel) tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none) } }
mit
f789b420552680ef068400c77c501c28
28.521127
110
0.607347
4.731377
false
false
false
false
Gujci/RESTAPI
RESTAPI/Utils.swift
1
3310
// // API+Utils.swift // // Created by Gujgiczer Máté on 23/03/16. // import Foundation extension String { mutating func insert(_ string: Character, before substring: String) { guard let index = self.range(of: substring)?.lowerBound else { return } insert(string, at: index) } mutating func insert(_ string: Character, after substring: String) { guard let index = self.range(of: substring)?.upperBound else { return } insert(string, at: index) } } extension Dictionary: Queryable { public func queryString(forKey key: String) -> [URLQueryItem] { return self.keys.compactMap { dkey in guard let item = self[dkey] else { return nil } if let qItem = item as? Queryable { let result = qItem.queryString(forKey: "\(dkey)") return result.compactMap { it in var chainedKey = it.name chainedKey.insert("[", before: "\(dkey)") chainedKey.insert("]", after: "\(dkey)") guard let value = it.value else { return nil } return URLQueryItem(name: "\(key)\(chainedKey)", value: "\(value)") } } else { return [URLQueryItem(name: "\(key)[\(dkey)]", value: "\(item)")] } }.reduce([], +) } } extension Array: Queryable { public func queryString(forKey key: String) -> [URLQueryItem] { return self.map() { item in return URLQueryItem(name: "\(key)[]", value: "\(item)") } } } extension String: Queryable { public func queryString(forKey key: String) -> [URLQueryItem] { return [URLQueryItem(name: key, value: self)] } } extension URL { init(string: String, query: Dictionary<String, Queryable>?) { if query == nil { self.init(string: string)! return } var components = URLComponents(string: string) var querryItems = components?.queryItems ?? Array<URLQueryItem>() query?.forEach() { querryItems.append(contentsOf: $0.value.queryString(forKey: $0.0)) } components?.queryItems = querryItems self.init(string: components!.url!.absoluteString)! } init(url: URL, query: Dictionary<String, Queryable>?) { var components = URLComponents(url: url, resolvingAgainstBaseURL: false) var querryItems = components?.queryItems ?? Array<URLQueryItem>() query?.forEach() { querryItems.append(contentsOf: $0.1.queryString(forKey: $0.0)) } components?.queryItems = querryItems self.init(string: components!.url!.absoluteString)! } } extension Date { static var timestamp: Double { get { return Date().timeIntervalSince1970 * 1000 } } } func + <K, V>(left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> { var map = Dictionary<K, V>() for (k, v) in left { map[k] = v } for (k, v) in right { map[k] = v } return map } func += <K, V> (left: inout Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> { for (k, v) in right { left[k] = v } return left }
mit
c8bde6d723fc008ac6f6abd70d5b2471
28.535714
92
0.558646
4.161006
false
false
false
false
Karumi/BothamNetworking
BothamNetworking/Dictionary.swift
1
769
// // Dictionary.swift // BothamNetworking // // Created by Pedro Vicente Gomez on 29/12/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation extension Dictionary { init<S: Sequence>(_ seq: S) where S.Iterator.Element == (Key, Value) { self.init() for (k, v) in seq { self[k] = v } } } func += <KeyType, ValueType> (left: inout [KeyType: ValueType]?, right: [KeyType: ValueType]) { if left == nil { left = [KeyType: ValueType]() } for (k, v) in right { left?.updateValue(v, forKey: k) } } func += <KeyType, ValueType> (left: inout [KeyType: ValueType], right: [KeyType: ValueType]) { for (k, v) in right { left.updateValue(v, forKey: k) } }
apache-2.0
3897c34ad85da0bf61e165eb7aa35957
22.272727
95
0.574219
3.39823
false
false
false
false
Zewo/Core
Sources/Axis/Stream/Stream.swift
3
3139
public enum StreamError : Error { case closedStream case timeout } public protocol InputStream { var closed: Bool { get } func open(deadline: Double) throws func close() func read(into readBuffer: UnsafeMutableBufferPointer<Byte>, deadline: Double) throws -> UnsafeBufferPointer<Byte> func read(upTo byteCount: Int, deadline: Double) throws -> Buffer func read(exactly byteCount: Int, deadline: Double) throws -> Buffer } extension InputStream { public func read(upTo byteCount: Int, deadline: Double) throws -> Buffer { guard byteCount > 0 else { return Buffer() } var bytes = [Byte](repeating: 0, count: byteCount) let bytesRead = try bytes.withUnsafeMutableBufferPointer { try read(into: $0, deadline: deadline).count } return Buffer(bytes[0..<bytesRead]) } public func read(exactly byteCount: Int, deadline: Double) throws -> Buffer { guard byteCount > 0 else { return Buffer() } var bytes = [Byte](repeating: 0, count: byteCount) try bytes.withUnsafeMutableBufferPointer { pointer in var address = pointer.baseAddress! var remaining = byteCount while remaining > 0 { let chunk = try read(into: UnsafeMutableBufferPointer(start: address, count: remaining), deadline: deadline) guard chunk.count > 0 else { throw StreamError.closedStream } address = address.advanced(by: chunk.count) remaining -= chunk.count } } return Buffer(bytes) } /// Drains the `Stream` and returns the contents in a `Buffer`. At the end of this operation the stream will be closed. public func drain(deadline: Double) throws -> Buffer { var buffer = Buffer() while !self.closed, let chunk = try? self.read(upTo: 2048, deadline: deadline), chunk.count > 0 { buffer.append(chunk) } return buffer } } public protocol OutputStream { var closed: Bool { get } func open(deadline: Double) throws func close() func write(_ buffer: UnsafeBufferPointer<Byte>, deadline: Double) throws func write(_ buffer: Buffer, deadline: Double) throws func write(_ buffer: BufferRepresentable, deadline: Double) throws func flush(deadline: Double) throws } extension OutputStream { public func write(_ buffer: Buffer, deadline: Double) throws { guard !buffer.isEmpty else { return } try buffer.bytes.withUnsafeBufferPointer { try write($0, deadline: deadline) } } public func write(_ converting: BufferRepresentable, deadline: Double) throws { try write(converting.buffer, deadline: deadline) } public func write(_ bytes: [Byte], deadline: Double) throws { guard !bytes.isEmpty else { return } try bytes.withUnsafeBufferPointer { try self.write($0, deadline: deadline) } } } public typealias Stream = InputStream & OutputStream
mit
572d2e3e033f040be306138108bdc0a6
30.079208
124
0.625996
4.836672
false
false
false
false
grpc/grpc-swift
Sources/GRPC/_FakeResponseStream.swift
1
13228
/* * Copyright 2020, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import NIOCore import NIOEmbedded import NIOHPACK public enum FakeRequestPart<Request> { case metadata(HPACKHeaders) case message(Request) case end } extension FakeRequestPart: Equatable where Request: Equatable {} /// Sending on a fake response stream would have resulted in a protocol violation (such as /// sending initial metadata multiple times or sending messages after the stream has closed). public struct FakeResponseProtocolViolation: Error, Hashable { /// The reason that sending the message would have resulted in a protocol violation. public var reason: String init(_ reason: String) { self.reason = reason } } /// A fake response stream into which users may inject response parts for use in unit tests. /// /// Users may not interact with this class directly but may do so via one of its subclasses /// `FakeUnaryResponse` and `FakeStreamingResponse`. public class _FakeResponseStream<Request, Response> { private enum StreamEvent { case responsePart(_GRPCClientResponsePart<Response>) case error(Error) } /// The channel to use for communication. internal let channel: EmbeddedChannel /// A buffer to hold responses in before the proxy is activated. private var responseBuffer: CircularBuffer<StreamEvent> /// The current state of the proxy. private var activeState: ActiveState /// The state of sending response parts. private var sendState: SendState private enum ActiveState { case inactive case active } private enum SendState { // Nothing has been sent; we can send initial metadata to become 'sending' or trailing metadata // to start 'closing'. case idle // We're sending messages. We can send more messages in this state or trailing metadata to // transition to 'closing'. case sending // We're closing: we've sent trailing metadata, we may only send a status now to close. case closing // Closed, nothing more can be sent. case closed } internal init(requestHandler: @escaping (FakeRequestPart<Request>) -> Void) { self.activeState = .inactive self.sendState = .idle self.responseBuffer = CircularBuffer() self.channel = EmbeddedChannel(handler: WriteCapturingHandler(requestHandler: requestHandler)) } /// Activate the test proxy; this should be called internal func activate() { switch self.activeState { case .inactive: // Activate the channel. This will allow any request parts to be sent. self.channel.pipeline.fireChannelActive() // Unbuffer any response parts. while !self.responseBuffer.isEmpty { self.write(self.responseBuffer.removeFirst()) } // Now we're active. self.activeState = .active case .active: () } } /// Write or buffer the response part, depending on the our current state. internal func _sendResponsePart(_ part: _GRPCClientResponsePart<Response>) throws { try self.send(.responsePart(part)) } internal func _sendError(_ error: Error) throws { try self.send(.error(error)) } private func send(_ event: StreamEvent) throws { switch self.validate(event) { case .valid: self.writeOrBuffer(event) case let .validIfSentAfter(extraPart): self.writeOrBuffer(extraPart) self.writeOrBuffer(event) case let .invalid(reason): throw FakeResponseProtocolViolation(reason) } } /// Validate events the user wants to send on the stream. private func validate(_ event: StreamEvent) -> Validation { switch (event, self.sendState) { case (.responsePart(.initialMetadata), .idle): self.sendState = .sending return .valid case (.responsePart(.initialMetadata), .sending), (.responsePart(.initialMetadata), .closing), (.responsePart(.initialMetadata), .closed): // We can only send initial metadata from '.idle'. return .invalid(reason: "Initial metadata has already been sent") case (.responsePart(.message), .idle): // This is fine: we don't force the user to specify initial metadata so we send some on their // behalf. self.sendState = .sending return .validIfSentAfter(.responsePart(.initialMetadata([:]))) case (.responsePart(.message), .sending): return .valid case (.responsePart(.message), .closing), (.responsePart(.message), .closed): // We can't send messages once we're closing or closed. return .invalid(reason: "Messages can't be sent after the stream has been closed") case (.responsePart(.trailingMetadata), .idle), (.responsePart(.trailingMetadata), .sending): self.sendState = .closing return .valid case (.responsePart(.trailingMetadata), .closing), (.responsePart(.trailingMetadata), .closed): // We're already closing or closed. return .invalid(reason: "Trailing metadata can't be sent after the stream has been closed") case (.responsePart(.status), .idle), (.error, .idle), (.responsePart(.status), .sending), (.error, .sending), (.responsePart(.status), .closed), (.error, .closed): // We can only error/close if we're closing (i.e. have already sent trailers which we enforce // from the API in the subclasses). return .invalid(reason: "Status/error can only be sent after trailing metadata has been sent") case (.responsePart(.status), .closing), (.error, .closing): self.sendState = .closed return .valid } } private enum Validation { /// Sending the part is valid. case valid /// Sending the part, if it is sent after the given part. case validIfSentAfter(_ part: StreamEvent) /// Sending the part would be a protocol violation. case invalid(reason: String) } private func writeOrBuffer(_ event: StreamEvent) { switch self.activeState { case .inactive: self.responseBuffer.append(event) case .active: self.write(event) } } private func write(_ part: StreamEvent) { switch part { case let .error(error): self.channel.pipeline.fireErrorCaught(error) case let .responsePart(responsePart): // We tolerate errors here: an error will be thrown if the write results in an error which // isn't caught in the channel. Errors in the channel get funnelled into the transport held // by the actual call object and handled there. _ = try? self.channel.writeInbound(responsePart) } } } // MARK: - Unary Response /// A fake unary response to be used with a generated test client. /// /// Users typically create fake responses via helper methods on their generated test clients /// corresponding to the RPC which they intend to test. /// /// For unary responses users may call one of two functions for each RPC: /// - `sendMessage(_:initialMetadata:trailingMetadata:status)`, or /// - `sendError(status:trailingMetadata)` /// /// `sendMessage` sends a normal unary response with the provided message and allows the caller to /// also specify initial metadata, trailing metadata and the status. Both metadata arguments are /// empty by default and the status defaults to one with an 'ok' status code. /// /// `sendError` may be used to terminate an RPC without providing a response. As for `sendMessage`, /// the `trailingMetadata` defaults to being empty. public class FakeUnaryResponse<Request, Response>: _FakeResponseStream<Request, Response> { override public init(requestHandler: @escaping (FakeRequestPart<Request>) -> Void = { _ in }) { super.init(requestHandler: requestHandler) } /// Send a response message to the client. /// /// - Parameters: /// - response: The message to send. /// - initialMetadata: The initial metadata to send. By default the metadata will be empty. /// - trailingMetadata: The trailing metadata to send. By default the metadata will be empty. /// - status: The status to send. By default this has an '.ok' status code. /// - Throws: FakeResponseProtocolViolation if sending the message would violate the gRPC /// protocol, e.g. sending messages after the RPC has ended. public func sendMessage( _ response: Response, initialMetadata: HPACKHeaders = [:], trailingMetadata: HPACKHeaders = [:], status: GRPCStatus = .ok ) throws { try self._sendResponsePart(.initialMetadata(initialMetadata)) try self._sendResponsePart(.message(.init(response, compressed: false))) try self._sendResponsePart(.trailingMetadata(trailingMetadata)) try self._sendResponsePart(.status(status)) } /// Send an error to the client. /// /// - Parameters: /// - error: The error to send. /// - trailingMetadata: The trailing metadata to send. By default the metadata will be empty. public func sendError(_ error: Error, trailingMetadata: HPACKHeaders = [:]) throws { try self._sendResponsePart(.trailingMetadata(trailingMetadata)) try self._sendError(error) } } // MARK: - Streaming Response /// A fake streaming response to be used with a generated test client. /// /// Users typically create fake responses via helper methods on their generated test clients /// corresponding to the RPC which they intend to test. /// /// For streaming responses users have a number of methods available to them: /// - `sendInitialMetadata(_:)` /// - `sendMessage(_:)` /// - `sendEnd(status:trailingMetadata:)` /// - `sendError(_:trailingMetadata)` /// /// `sendInitialMetadata` may be called to send initial metadata to the client, however, it /// must be called first in order for the metadata to be sent. If it is not called, empty /// metadata will be sent automatically if necessary. /// /// `sendMessage` may be called to send a response message on the stream. This may be called /// multiple times. Messages will be ignored if this is called after `sendEnd` or `sendError`. /// /// `sendEnd` indicates that the response stream has closed. It – or `sendError` - must be called /// once. The `status` defaults to a value with the `ok` code and `trailingMetadata` is empty by /// default. /// /// `sendError` may be called at any time to indicate an error on the response stream. /// Like `sendEnd`, `trailingMetadata` is empty by default. public class FakeStreamingResponse<Request, Response>: _FakeResponseStream<Request, Response> { override public init(requestHandler: @escaping (FakeRequestPart<Request>) -> Void = { _ in }) { super.init(requestHandler: requestHandler) } /// Send initial metadata to the client. /// /// Note that calling this function is not required; empty initial metadata will be sent /// automatically if necessary. /// /// - Parameter metadata: The metadata to send /// - Throws: FakeResponseProtocolViolation if sending initial metadata would violate the gRPC /// protocol, e.g. sending metadata too many times, or out of order. public func sendInitialMetadata(_ metadata: HPACKHeaders) throws { try self._sendResponsePart(.initialMetadata(metadata)) } /// Send a response message to the client. /// /// - Parameter response: The response to send. /// - Throws: FakeResponseProtocolViolation if sending the message would violate the gRPC /// protocol, e.g. sending messages after the RPC has ended. public func sendMessage(_ response: Response) throws { try self._sendResponsePart(.message(.init(response, compressed: false))) } /// Send the RPC status and trailing metadata to the client. /// /// - Parameters: /// - status: The status to send. By default the status code will be '.ok'. /// - trailingMetadata: The trailing metadata to send. Empty by default. /// - Throws: FakeResponseProtocolViolation if ending the RPC would violate the gRPC /// protocol, e.g. sending end after the RPC has already completed. public func sendEnd(status: GRPCStatus = .ok, trailingMetadata: HPACKHeaders = [:]) throws { try self._sendResponsePart(.trailingMetadata(trailingMetadata)) try self._sendResponsePart(.status(status)) } /// Send an error to the client. /// /// - Parameters: /// - error: The error to send. /// - trailingMetadata: The trailing metadata to send. By default the metadata will be empty. /// - Throws: FakeResponseProtocolViolation if sending the error would violate the gRPC /// protocol, e.g. erroring after the RPC has already completed. public func sendError(_ error: Error, trailingMetadata: HPACKHeaders = [:]) throws { try self._sendResponsePart(.trailingMetadata(trailingMetadata)) try self._sendError(error) } }
apache-2.0
f41173c70276080d42b2b297070116ca
36.785714
100
0.702079
4.446873
false
false
false
false
Quaggie/Quaggify
Quaggify/PlaylistCell.swift
1
3136
// // PlaylistCell.swift // Quaggify // // Created by Jonathan Bijos on 01/02/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit class PlaylistCell: CollectionViewCell { var omitName = false var playlist: Playlist? { didSet { guard let playlist = playlist else { return } if let smallerImage = playlist.images?[safe: 1], let imgUrlString = smallerImage.url, let url = URL(string: imgUrlString) { imageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "placeholder"), options: [.transition(.fade(0.2))]) } else if let smallerImage = playlist.images?[safe: 0], let imgUrlString = smallerImage.url, let url = URL(string: imgUrlString) { imageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "placeholder"), options: [.transition(.fade(0.2))]) } else { imageView.image = #imageLiteral(resourceName: "placeholder") } if let playlistName = playlist.name { titleLabel.text = playlistName } else { titleLabel.text = "Unkown Playlist" } if let id = playlist.owner?.id, let totalTracks = playlist.tracks?.total { subTitleLabel.isHidden = false if omitName { subTitleLabel.text = "\(totalTracks) \(totalTracks == 1 ? "song" : "songs")".uppercased() } else { subTitleLabel.text = "\(id) ・ \(totalTracks) \(totalTracks == 1 ? "song" : "songs")".uppercased() } } else { subTitleLabel.isHidden = true } } } let imageView: UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFill iv.clipsToBounds = true return iv }() let stackView: UIStackView = { let sv = UIStackView() sv.axis = .vertical sv.alignment = .fill sv.distribution = .fillEqually sv.backgroundColor = .clear sv.spacing = 4 return sv }() let titleLabel: UILabel = { let label = UILabel() label.textColor = ColorPalette.white label.font = Font.montSerratBold(size: 16) label.textAlignment = .left label.translatesAutoresizingMaskIntoConstraints = false return label }() let subTitleLabel: UILabel = { let label = UILabel() label.textColor = ColorPalette.lightGray label.font = Font.montSerratRegular(size: 12) label.textAlignment = .left label.translatesAutoresizingMaskIntoConstraints = false return label }() override func setupViews() { super.setupViews() addSubview(imageView) addSubview(stackView) stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(subTitleLabel) imageView.anchorCenterYToSuperview() imageView.anchor(nil, left: leftAnchor, bottom: nil, right: nil, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 0, widthConstant: 64, heightConstant: 64) stackView.anchor(imageView.topAnchor, left: imageView.rightAnchor, bottom: imageView.bottomAnchor, right: rightAnchor, topConstant: 8, leftConstant: 8, bottomConstant: 8, rightConstant: 8, widthConstant: 0, heightConstant: 0) } }
mit
8de673f77d62329c629c9fda84f3763d
31.978947
229
0.664539
4.456615
false
false
false
false
goktugyil/EZSwiftExtensions
EZSwiftExtensionsTests/DateTests.swift
1
14290
// // DateTests.swift // EZSwiftExtensions // // Created by Valentino Urbano on 28/01/16. // Copyright © 2016 Goktug Yilmaz. All rights reserved. // import XCTest @testable import EZSwiftExtensions class DateTests: XCTestCase { // note that Date uses UTC in Date(timeIntervalSince1970: _) var dateString: String! var invalidDateString: String! var date: Date! var timeZoneOffset: TimeInterval! let format = "yyyy-MM-dd'T'HH:mm:ssxxxxx" override func setUp() { super.setUp() self.dateString = "2015-11-14T16:05:11+00:00" // time of the first commit of EZSwiftExtension :clap::clap: self.invalidDateString = "9999-99-99T99:99:99+00:00" self.date = Date(fromString: self.dateString, format: self.format)! NSTimeZone.default = TimeZone(abbreviation: "SGT")! // set timezone to be SGT self.timeZoneOffset = TimeInterval(NSTimeZone.local.secondsFromGMT()) } func testDateFromString() { guard let dateFromString = Date(fromString: self.dateString, format: self.format) else { XCTFail("Date From String Couldn't be initialized.") return } NSTimeZone.default = TimeZone(abbreviation: "UTC")! // set timezone to be UTC to match with original string XCTAssertEqual(dateFromString.toString(format: self.format), date.toString(format: self.format)) // TODO why is there a need for ! for self.dateString XCTAssertNil(Date(fromString: self.invalidDateString, format: format), "Date From String initialized, but source string was invalid.") let dateFromFalseStr = Date(fromString: "lol", format: "haha") XCTAssertNil(dateFromFalseStr) } func testDateFormatterCacheDictionary() { let formatter1 = "yyyy-MM-dd" let formatter2 = "yyyy-MM-dd'T'HH:mm:ssxxxxx" let _ = createDateFormatter(for: formatter1) let _ = createDateFormatter(for: formatter2) let size = DateFormattersManager.dateFormatters.getSize() XCTAssertEqual(size, 2) var hasFormatter = DateFormattersManager.dateFormatters.containValue(for: formatter1) XCTAssertTrue(hasFormatter) hasFormatter = DateFormattersManager.dateFormatters.containValue(for: formatter2) XCTAssertTrue(hasFormatter) } ///EZSE: CreateDateFormatter if formatter doesn't exist in Dict. private func createDateFormatter(for format: String) -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = format DateFormattersManager.dateFormatters.setValue(for: format, value: formatter) return formatter } func testHTTPDateString() { // Given let fromStartOfDay = TimeInterval(16 * 3600 + 5 * 60 + 11) // seconds from start of day let fromStartOfMin = TimeInterval(11) // seconds from start of minute // When let correctDateString = "2015-11-14" let correctTimeString = "16:05:11" let correctZoneString = "+00:00" let rfc1123 = Date(httpDateString: "Sat, 14 Nov 2015 \(correctTimeString) GMT") let rfc850 = Date(httpDateString: "Saturday, 14-Nov-15 \(correctTimeString) GMT") let asctime = Date(httpDateString: "Sun Nov 14 \(correctTimeString) 2015") let iso8601DateOnly = Date(httpDateString: correctDateString) let iso8601DateHrMinOnly = Date(httpDateString: "\(correctDateString)T16:05\(correctZoneString)") let iso8601DateHrMinSecOnly = Date(httpDateString: "\(correctDateString)T\(correctTimeString)\(correctZoneString)") let iso8601DateHrMinSecMs = Date(httpDateString: "\(correctDateString)T\(correctTimeString).123\(correctZoneString)") // random nanosecond value 123 let invalid = Date(httpDateString: "\(correctDateString) \(correctTimeString)") // Test XCTAssertEqual(rfc1123, self.date) XCTAssertEqual(rfc850, self.date) XCTAssertEqual(asctime?.addingTimeInterval(self.timeZoneOffset), self.date) XCTAssertEqual(iso8601DateOnly?.addingTimeInterval(self.timeZoneOffset), self.date.addingTimeInterval(-fromStartOfDay)) XCTAssertEqual(iso8601DateHrMinOnly, self.date.addingTimeInterval(-fromStartOfMin)) XCTAssertEqual(iso8601DateHrMinSecOnly, self.date) XCTAssertEqual(iso8601DateHrMinSecMs, Date(timeIntervalSince1970: 1447517111.123)) // TODO: find method that can add milliseconds to Date object XCTAssertNil(invalid) } func testDateToString() { let date = Date(timeIntervalSince1970: 0) let format = "yyyy-MM-dd" let formatter = DateFormatter() formatter.dateFormat = format let dateString = formatter.string(from: date) XCTAssertEqual(date.toString(format: format), dateString) } func testDaysInBetween() { // Given let date1 = Date(timeIntervalSince1970: 0) let date2 = Date(timeIntervalSinceReferenceDate: 0) let expectedResult: Double = 978_307_200 / 86_400 // When let actualResult = floor(date1.daysInBetweenDate(date2)) // Test XCTAssertEqual(actualResult, expectedResult) } func testHoursInBetween() { // Given let date1 = Date(timeIntervalSince1970: 0) let date2 = Date(timeIntervalSinceReferenceDate: 0) let expectedResult: Double = 978_307_200 / 3_600 // When let actualResult = date1.hoursInBetweenDate(date2) // Test XCTAssertEqual(actualResult, expectedResult) } func testMinutesInBetween() { // Given let date1 = Date(timeIntervalSince1970: 0) let date2 = Date(timeIntervalSinceReferenceDate: 0) let expectedResult: Double = 978_307_200 / 60 // When let actualResult = date1.minutesInBetweenDate(date2) // Test XCTAssertEqual(actualResult, expectedResult) } func testSecondsInBetween() { // Given let date1 = Date(timeIntervalSince1970: 0) let date2 = Date(timeIntervalSinceReferenceDate: 0) let expectedResult: Double = 978_307_200 // When let actualResult = date1.secondsInBetweenDate(date2) // Test XCTAssertEqual(actualResult, expectedResult) } func testTimePassedBetweenDates() { // Given let years = Date(timeIntervalSince1970: 0) let months = Date(timeIntervalSinceNow: -8_388_608) let days = Date(timeIntervalSinceNow: -262_144) let hours = Date(timeIntervalSinceNow: -65_536) let minutes = Date(timeIntervalSinceNow: -2_048) let now = Date() // Test XCTAssertTrue(years.timePassed().contains("years")) XCTAssertTrue(months.timePassed().contains("months")) XCTAssertTrue(days.timePassed().contains("days")) XCTAssertTrue(hours.timePassed().contains("hours")) XCTAssertTrue(minutes.timePassed().contains("minutes")) XCTAssertTrue(now.timePassed().contains("now") || now.timePassed().contains("seconds")) let today = Date() XCTAssertEqual(today.timePassed(), "Just now") let yesterday = Calendar.current.date(byAdding: .day, value: -1,to: today) XCTAssertEqual(yesterday?.timePassed(), "1 day ago") let fiveSecondsAgo = Calendar.current.date(byAdding: .second, value: -5,to: today) XCTAssertEqual(fiveSecondsAgo?.timePassed(), "5 seconds ago") let oneSecondAgo = Calendar.current.date(byAdding: .second, value: -1, to: today) XCTAssertEqual(oneSecondAgo?.timePassed(), "1 second ago") let sixHoursAgo = Calendar.current.date(byAdding: .hour, value: -6,to: today) XCTAssertEqual(sixHoursAgo?.timePassed(), "6 hours ago") let twoMonthsAgo = Calendar.current.date(byAdding: .month, value: -2,to: today) XCTAssertEqual(twoMonthsAgo?.timePassed(), "2 months ago") let fifteenYearsAgo = Calendar.current.date(byAdding: .year, value: -15,to: today) XCTAssertEqual(fifteenYearsAgo?.timePassed(), "15 years ago") } func testTimePassedEnumBetweenDates() { let today = Date() let timePassedToday: TimePassed = today.timePassed() XCTAssertEqual(timePassedToday, TimePassed.now) let fifteenYearsAgo = Calendar.current.date(byAdding: .year, value: -15, to: today) let timePassedFifteenYearsAgo: TimePassed = fifteenYearsAgo!.timePassed() XCTAssertEqual(timePassedFifteenYearsAgo, TimePassed.year(15)) let twoMonthsAgo = Calendar.current.date(byAdding: .month, value: -2, to: today) let timePassedTwoMonthsAgo: TimePassed = twoMonthsAgo!.timePassed() XCTAssertEqual(timePassedTwoMonthsAgo, TimePassed.month(2)) let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today) let timePassedYesterday: TimePassed = yesterday!.timePassed() XCTAssertEqual(timePassedYesterday, TimePassed.day(1)) let sixHoursAgo = Calendar.current.date(byAdding: .hour, value: -6, to: today) let timePassedSixHoursAgo: TimePassed = sixHoursAgo!.timePassed() XCTAssertEqual(timePassedSixHoursAgo, TimePassed.hour(6)) let thirteenMinutesAgo = Calendar.current.date(byAdding: .minute, value: -13, to: today) let timePassedThirteenMinutesAgo: TimePassed = thirteenMinutesAgo!.timePassed() XCTAssertEqual(timePassedThirteenMinutesAgo, TimePassed.minute(13)) let fiveSecondsAgo = Calendar.current.date(byAdding: .second, value: -5, to: today) let timePassedFiveSecondsAgo: TimePassed = fiveSecondsAgo!.timePassed() XCTAssertEqual(timePassedFiveSecondsAgo, TimePassed.second(5)) let oneSecondAgo = Calendar.current.date(byAdding: .second, value: -1, to: today) let timePassedOneSecondAgo: TimePassed = oneSecondAgo!.timePassed() XCTAssertEqual(timePassedOneSecondAgo, TimePassed.second(1)) } func testIsPast() { let beginningOfUnixTime = Date(timeIntervalSince1970: 0) XCTAssertTrue(beginningOfUnixTime.isPast) let today = Date() let yesterday = Calendar.current.date(byAdding: .day, value: -1,to: today) XCTAssertTrue((yesterday?.isPast)!) let tomorrow = Calendar.current.date(byAdding: .day, value: 1,to: today) XCTAssertFalse((tomorrow?.isPast)!) } func testIsFuture() { let distantFuture = Date(httpDateString: "Sun Nov 6 08:49:37 5000") XCTAssertTrue((distantFuture?.isFuture)!) let today = Date() let yesterday = Calendar.current.date(byAdding: .day, value: -1,to: today) XCTAssertFalse((yesterday?.isFuture)!) let tomorrow = Calendar.current.date(byAdding: .day, value: 1,to: today) XCTAssertTrue((tomorrow?.isFuture)!) } func testIsToday() { let today = Date() XCTAssertTrue(today.isToday) let beginningOfUnixTime = Date(timeIntervalSince1970: 0) XCTAssertFalse(beginningOfUnixTime.isToday) } func testIsTomorrow() { let today = Date() XCTAssertFalse(today.isTomorrow) let tomorrow = Calendar.current.date(byAdding: .day, value: 1,to: today) XCTAssertTrue((tomorrow?.isTomorrow)!) } func testIsYesterday() { let today = Date() XCTAssertFalse(today.isYesterday) let yesterday = Calendar.current.date(byAdding: .day, value: -1,to: today) XCTAssertTrue((yesterday?.isYesterday)!) } func testIsThisWeek() { let today = Date() XCTAssertTrue(today.isThisWeek) let yesterday = Calendar.current.date(byAdding: .day, value: -1,to: today) XCTAssertTrue((yesterday?.isThisWeek)!) let tomorrow = Calendar.current.date(byAdding: .day, value: 1,to: today) XCTAssertTrue((tomorrow?.isThisWeek)!) XCTAssertFalse(Date.distantPast.isThisWeek) } func testIsThisMonth() { let today = Date() XCTAssertTrue(today.isThisMonth) // Its difficult to unit test (by checking a few days prior) because builds might fail // on the first day of every month. let aFewSecondsBefore = Calendar.current.date(byAdding: .second, value: -5,to: today) XCTAssertTrue((aFewSecondsBefore?.isThisMonth)!) let aFewSecondsAfter = Calendar.current.date(byAdding: .second, value: -5,to: today) XCTAssertTrue((aFewSecondsAfter?.isThisMonth)!) XCTAssertFalse(Date.distantPast.isThisMonth) } func testEra() { XCTAssertEqual(date.era, Calendar.current.component(Calendar.Component.era, from: date)) } func testYear() { XCTAssertEqual(self.date.year, 2015) } func testMonth() { XCTAssertEqual(self.date.month, 11) } func testMonthAsString() { XCTAssertEqual(self.date.monthAsString, "November") } func testWeekDay() { XCTAssertEqual(self.date.weekday, "Sunday") NSTimeZone.default = TimeZone(abbreviation: "UTC")! } func testDay() { XCTAssertEqual(self.date.day, 15) NSTimeZone.default = TimeZone(abbreviation: "UTC")! XCTAssertEqual(self.date.day, 14) } func testHour() { XCTAssertEqual(self.date.hour, 0) NSTimeZone.default = TimeZone(abbreviation: "UTC")! XCTAssertEqual(self.date.hour, 16) } func testMinute() { XCTAssertEqual(self.date.minute, 5) } func testSecond() { XCTAssertEqual(self.date.second, 11) } func testNanoSecond() { XCTAssertEqual(self.date.nanosecond, 0) let today = Date() XCTAssert(today.nanosecond == Calendar.current.component(.nanosecond, from: today)) } #if os(iOS) || os(tvOS) func testISO8601() { XCTAssertEqual(self.date.iso8601, "2015-11-14T16:05:11Z") } #endif }
mit
52f9b77f7aef3bff8dc78ca15fe803eb
37.723577
158
0.6512
4.593057
false
true
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/PaginatedFeed.swift
3
603
// // PaginatedFeed.swift // edX // // Created by Ehmad Zubair Chughtai on 24/08/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit //Not conforming to GeneratorType protocol because next() returns -> A NOT ->A? class PaginatedFeed<A> { private let generator : Int -> A private var page = 0 init(f : Int -> A) { self.generator = f } func next() -> A? { page += 1 let result = generator(page) return result } func current() -> A { let result = generator(page) return result } }
apache-2.0
c615b77aedd438b695b51fbae96550d1
17.272727
79
0.558872
3.890323
false
false
false
false
50WDLARP/app
SonicIOS/Controllers/ConnectedViewController.swift
1
1388
// // ConnectedViewController.swift // Cool Beans // // Created by Kyle on 11/14/14. // Copyright (c) 2014 Kyle Weiner. All rights reserved. // import UIKit class ConnectedViewController: UIViewController, PTDBeanDelegate { var connectedBean: PTDBean? @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var sonicView: SonicView! // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() // Update the name label. sonicView.nameLabel.text = connectedBean?.name sonicView.connectedBean = connectedBean } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) connectedBean?.readTemperature() } // MARK: Actions func updateAcc(){ connectedBean?.readTemperature() connectedBean?.readAccelerationAxes() } // MARK: PTDBeanDelegate func bean(bean: PTDBean!, serialDataReceived data:NSData) { let theString:NSString = NSString(data: data, encoding: NSASCIIStringEncoding)! let distFloat = theString.floatValue * 340.0 / 2 / 1e6 sonicView.distance.text = distFloat.description print(theString) } // MARK: Helper func updatesonicView() { } func updateBean() { connectedBean?.setLedColor(sonicView.containerView.backgroundColor) } }
mit
12a07854facaebe024f70d81436d4403
21.403226
87
0.657781
4.580858
false
false
false
false
jopamer/swift
test/IRGen/mixed_mode_class_with_unimportable_fields.swift
1
5122
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/UsingObjCStuff.swiftmodule -module-name UsingObjCStuff -I %t -I %S/Inputs/mixed_mode -swift-version 5 %S/Inputs/mixed_mode/UsingObjCStuff.swift // RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 4 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V4 -DWORD=i%target-ptrsize // RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 5 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V5 -DWORD=i%target-ptrsize // REQUIRES: objc_interop import UsingObjCStuff public class SubButtHolder: ButtHolder { final var w: Float = 0 override public func virtual() {} public func subVirtual() {} } public class SubSubButtHolder: SubButtHolder { public override func virtual() {} public override func subVirtual() {} } // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$S4main17accessFinalFields2ofyp_ypt14UsingObjCStuff10ButtHolderC_tF" public func accessFinalFields(of holder: ButtHolder) -> (Any, Any) { // ButtHolder.y cannot be imported in Swift 4 mode, so make sure we use field // offset globals here. // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1xSivpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1zSSvpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // ButtHolder.y is correctly imported in Swift 5 mode, so we can use fixed offsets. // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* %2, i32 0, i32 1 // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* %2, i32 0, i32 3 return (holder.x, holder.z) } // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$S4main17accessFinalFields5ofSubyp_ypyptAA0F10ButtHolderC_tF" public func accessFinalFields(ofSub holder: SubButtHolder) -> (Any, Any, Any) { // We should use the runtime-adjusted ivar offsets since we may not have // a full picture of the layout in mixed Swift language version modes. // ButtHolder.y cannot be imported in Swift 4 mode, so make sure we use field // offset globals here. // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1xSivpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1zSSvpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S4main13SubButtHolderC1wSfvpWvd" // CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8* // CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]] // ButtHolder.y is correctly imported in Swift 5 mode, so we can use fixed offsets. // CHECK-V5: [[SELF:%.*]] = bitcast %T4main13SubButtHolderC* %3 to %T14UsingObjCStuff10ButtHolderC* // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* [[SELF]], i32 0, i32 1 // CHECK-V5: [[SELF:%.*]] = bitcast %T4main13SubButtHolderC* %3 to %T14UsingObjCStuff10ButtHolderC* // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* [[SELF]], i32 0, i32 3 // CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T4main13SubButtHolderC, %T4main13SubButtHolderC* %3, i32 0, i32 4 return (holder.x, holder.z, holder.w) } // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$S4main12invokeMethod2onyAA13SubButtHolderC_tF" public func invokeMethod(on holder: SubButtHolder) { // CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 10 // CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 13 // CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]] // CHECK: call swiftcc void [[IMPL]] holder.virtual() // CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 15 // CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 18 // CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]] // CHECK: call swiftcc void [[IMPL]] holder.subVirtual() } // CHECK-V4-LABEL: define private void @initialize_metadata_SubButtHolder // CHECK-V4: call void @swift_initClassMetadata( // CHECK-V4-LABEL: define private void @initialize_metadata_SubSubButtHolder // CHECK-V4: call void @swift_initClassMetadata(
apache-2.0
9319e6d080ed7b5531227e41e86aa587
50.737374
229
0.679032
3.439893
false
false
false
false
pixlwave/Countout
Sources/AdaptiveSplitView.swift
1
1589
import SwiftUI struct AdaptiveSplitView: View { @ObservedObject var appearance = Appearance.shared @Environment(\.horizontalSizeClass) var horizontalSizeClass @State private var isPresentingAppearance = false var appearanceOverlayButton: some View { Button { isPresentingAppearance = true } label: { Image(systemName: "paintbrush") .font(.body) .padding(5) .background(.thickMaterial, in: Circle()) } } var body: some View { if horizontalSizeClass == .compact { MainView() .overlay(appearanceOverlayButton .offset(x: -23, y: 13), alignment: .topTrailing) .sheet(isPresented: $isPresentingAppearance) { AppearanceView() } } else { NavigationView { TimersView() .navigationTitle("Timers") MainView() .navigationBarTitleDisplayMode(.inline) .navigationViewStyle(.columns) .toolbar { ToolbarItem { Button { isPresentingAppearance = true } label: { Image(systemName: "paintbrush") } } } .sheet(isPresented: $isPresentingAppearance) { AppearanceView() } } } } }
mpl-2.0
2c89e91ece48fe1672bd8a535a60e008
32.808511
77
0.462555
6.45935
false
false
false
false
nextgenappsllc/NGAEssentials
NGAEssentials/Classes/StringExtension.swift
1
25375
// // StringExtension.swift // NGAFramework // // Created by Jose Castellanos on 3/13/16. // Copyright © 2016 NextGen Apps LLC. All rights reserved. // import Foundation import CryptoSwift public extension String { public func containsString(_ str:String, caseInsensitive:Bool = false) -> Bool { // var temp = false // let nsStr = caseInsensitive ? str.lowercased() : str // let newSelf:NSString = caseInsensitive ? self.lowercased() as NSString : self as NSString // temp = newSelf.contains(nsStr) // return temp return caseInsensitive ? self.lowercased().contains(str.lowercased()) : self.contains(str) } public func stringByAddingPathComponent(_ pathComp: String?) -> String? { if let comp = pathComp { return (self as NSString).appendingPathComponent(comp) } else {return self} } public var characterArray:[Character] {get{return Array(characters)}} public var substrings:[String] {get {return characterArray.mapToNewArray(iteratorBlock: { (element) -> String? in return String(element) })}} public subscript (i: Int) -> String? { get{return substrings.itemAtIndex(i)} mutating set { var arr = substrings let _=arr.safeSet(i, toElement: newValue) self = arr.joined(separator: "") } } public subscript (r: Range<Int>) -> String { var range = r let letterCount = characters.count if range.upperBound > letterCount { range = (range.lowerBound..<letterCount) } // return substring[characters.index(startIndex, offsetBy: range.lowerBound)..<characters.index(startIndex, offsetBy: range.upperBound)] return String(self[characters.index(startIndex, offsetBy: range.lowerBound)..<characters.index(startIndex, offsetBy: range.upperBound)]) // var range = r // let letterCount = characters.count // if range.upperBound > letterCount { range.upperBound = letterCount } // return substring(with: characters.index(startIndex, offsetBy: range.lowerBound)..<characters.index(startIndex, offsetBy: range.upperBound)) } public func abbreviatedStringWithMaxCharacters(_ maxChars:Int = 3) -> String { var temp = self let components = temp.components(separatedBy: " ") if components.count > 1 { temp = "" for str in components { if !str.isEmpty() { temp += str[0] ?? "" } } } temp = temp[0..<maxChars] return temp } public var length:Int {get {return self.characters.count}} public var isValidEmailFormat:Bool { get{ let components = self.components(separatedBy: "@") return components.count == 2 && components.last?.components(separatedBy: ".").count ?? 0 >= 2 } } public static func doesExist(_ str:String?) -> Bool {return !(str?.isEmpty() ?? true)} public static func isNotEmpty(_ str:String?) -> Bool { return doesExist(str) } public static func isEmptyOrNil(_ str:String?) -> Bool { return !isNotEmpty(str) } public var url:URL? {get{return URL(string: self)}} public var fileUrl:URL? {get{return URL(fileURLWithPath: self)}} public static func largerContainsSmaller(string1 str1:String?, string2 str2:String?, caseInsensitive:Bool = true) -> Bool { if !doesExist(str1) || !doesExist(str2) {return false} let largerString:String ; let smallerString:String if str1!.length < str2!.length {largerString = str2!; smallerString = str1!} else {largerString = str1!; smallerString = str2!} return largerString.containsString(smallerString, caseInsensitive: caseInsensitive) } public func appendIfNotNil(_ str:String?, separator:String? = nil) -> String { guard let str = str else {return self} return surround(prefix: nil, postfix: "\(separator ?? "")\(str)") } public func prependIfNotNil(_ str:String?, separator:String? = nil) -> String { return surround(prefix: "\(separator ?? "")\(str ?? "")", postfix: nil) } public func surround(prefix pre:String?, postfix post:String?) -> String{ return "\(pre ?? "")\(self)\(post ?? "")" } public func regexNumberOfMatches(_ pattern:String, patternOptions:NSRegularExpression.Options = NSRegularExpression.Options.init(rawValue: 0), matchingOptions:NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions.init(rawValue: 0)) -> Int? { do { let regex = try NSRegularExpression(pattern: pattern, options: patternOptions) return regex.numberOfMatches(in: self, options: matchingOptions, range: NSMakeRange(0, self.characters.count)) } catch { return nil } } public func regexMatchExists(_ pattern:String, patternOptions:NSRegularExpression.Options = NSRegularExpression.Options.init(rawValue: 0), matchingOptions:NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions.init(rawValue: 0)) -> Bool { return regexNumberOfMatches(pattern, patternOptions: patternOptions, matchingOptions: matchingOptions) ?? 0 > 0 } //TODO rename to isBlank public func isEmpty() -> Bool { return self.trim().length == 0 } public func urlEncode() -> String { let charactersToEscape = "\\!*'();:@&=+$,/?%#[]\" " let allowedCharacters = CharacterSet(charactersIn: charactersToEscape).inverted return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? self } fileprivate static let xmlEscapeCharMap = [["&":"&amp;"],["<":"&lt;"], [">": "&gt;"], ["'":"&pos;"], ["\"":"&quo;"]] public func xmlEncode() -> String { var str = self for charDictionary in String.xmlEscapeCharMap { for (key, value) in charDictionary { str = str.replacingOccurrences(of: key, with: value) } } return str } public func xmlDecode() -> String { var str = self for charDictionary in String.xmlEscapeCharMap.reversed() { for (key, value) in charDictionary.invert() { str = str.replacingOccurrences(of: key, with: value) } } return str } // public func htmlDecode() -> String? { // guard let encodedData = dataUsingEncoding(NSUTF8StringEncoding) else {return nil} // let attributedOptions : [String: AnyObject] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding] // return try? NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil).string // } public func htmlDecode() -> String { var result = "" var position = startIndex // Find the next '&' and copy the characters preceding it to `result`: while let ampRange = self.range(of: "&", range: position ..< endIndex) { result.append(String(self[position ..< ampRange.lowerBound])) position = ampRange.lowerBound // Find the next ';' and copy everything from '&' to ';' into `entity` if let semiRange = self.range(of: ";", range: position ..< endIndex) { let entity = self[position ..< semiRange.upperBound] position = semiRange.upperBound if let decoded = HTMLEntities.decode(String(entity)) { // Replace by decoded character: result.append(decoded) } else { // Invalid entity, copy verbatim: result.append(String(entity)) } } else { // No matching ';'. break } } result.append(String(self[position ..< endIndex])) return result } public func crc32CheckSum() -> String? { let s = self.crc32() if let i = UInt(s, radix: 16) { return "\(i)" } return nil } public func trim() -> String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } public mutating func trimInPlace() { self = trim() } public static func fromAny(_ obj:Any?) -> String? { return obj as? String } public func toDateWithFormat(_ format:String) -> Date? { return Date.date(from: self, withFormat: format) } public func toAttributedString(_ attributes:[NSAttributedStringKey:Any]?) -> NSAttributedString { return NSAttributedString(string: self, attributes: attributes) } public func toAttributedString(font:UIFont?, color: UIColor?) -> NSAttributedString { var attributes = [NSAttributedStringKey:Any]() attributes[NSAttributedStringKey.font] = font attributes[NSAttributedStringKey.foregroundColor] = color return toAttributedString(attributes) } public static func repeatedStringOfSize(_ s:Int, repeatedString:String = " ") -> String { var str = "" s.times { (i) in str += repeatedString } return str } public static let degrees = "°" /** Encrypts the string with the given 32 bit key. If you would like to use a passphrase instead of the key then use the md5 hash of the passphrase to ensure it is 32 bit like in the following example. ```` let key = "passphrase".md5() let encryptionResult = "encrypt me!".AES256Encrypt(key: key) ```` - Parameter key: The key to use for encryption. **Must be 32 bits in length.** - Returns: A tuple containing the hex string values on the initialization vector and the encrypted data. */ public func AES256Encrypt(key:String)->(iv:String, encrypted:String?){ let _key = key.utf8.map{$0} as Array<UInt8> let _iv = AES.randomIV(AES.blockSize) var t:(iv:String, encrypted:String?) = (_iv.toHexString(), nil) guard _key.count == 32, let aes = try? AES.init(key: _key, blockMode: .CBC(iv: _iv)), let encrypted = try? aes.encrypt(Array(self.utf8)) else {return t} t.encrypted = encrypted.toHexString() return t } /** Decrypts the string with the given 32 bit key and initialization vector. If you would like to use a passphrase instead of the key then use the md5 hash of the passphrase to ensure it is 32 bit like in the following example. ```` let key = "passphrase".md5() let encryptionResult = "encrypt me!".AES256Encrypt(key: key) let decrypted = encryptionResult.encrypted?.AES256Decrypt(key: key, iv: encryptionResult.iv) ```` - Parameter key: The key to use for encryption. **Must be 32 bits in length.** - Parameter iv: The initialization vector used to encrypt the data as a hex string. - Returns: A decrypted string if successful */ public func AES256Decrypt(key:String, iv:String) -> String?{ let _key = key.utf8.map{$0} as Array<UInt8> let _iv = iv.convertFromHex() guard _key.count == 32, let aes = try? AES(key: _key, blockMode: .CBC(iv: _iv)), let decrypted = try? aes.decrypt(self.convertFromHex()) else {return nil} return String(data: Data(decrypted), encoding: .utf8) } /** Converts the string into an array of numbers corresponding to the hex value. So the string "ff00" would get converted to [255, 0]. - Returns: An array of 8 bit unsigned integers (bytes). */ //DEPRECATE public func convertFromHex() -> [UInt8]{ return hexToBytes() } /** Converts the a hexadecimal string to a corresponding array of bytes. So the string "ff00" would get converted to [255, 0]. Supports odd number of characters by interpreting the last character as its' hex value ("f" produces [16] as if it was "0f"). - Returns: An array of 8 bit unsigned integers (bytes). */ public func hexToBytes() -> [UInt8]{ var bytes:[UInt8] = [] do{ try self.streamHexBytes { (byte) in bytes.append(byte) } }catch _{ return [] } return bytes } // Allows str.hexToBytes() and Array<UInt8>(hex: str) to share the same code // Old functionality returns a blank array upon encountering a non hex character so this method must throw in order to replicate that in methods relying on this method. (ex. "ffn" should return [] instead of [255]) // Changed NSError to custom Error enum public func streamHexBytes(_ block:(UInt8)->Void) throws{ var buffer:UInt8? var skip = hasPrefix("0x") ? 2 : 0 for char in unicodeScalars.lazy { guard skip == 0 else { skip -= 1 continue } guard char.value >= 48 && char.value <= 102 else {throw HexError.invalidCharacter} let v:UInt8 let c:UInt8 = UInt8(char.value) switch c{ case let c where c <= 57: v = c - 48 case let c where c >= 65 && c <= 70: v = c - 55 case let c where c >= 97: v = c - 87 default: throw HexError.invalidCharacter } if let b = buffer { block(b << 4 | v) buffer = nil } else { buffer = v } } if let b = buffer{block(b)} } // public func streamHexBytes(_ block:(UInt8)->Void) throws{ // let unicodeHexMap:[UnicodeScalar:UInt8] = ["0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"a":10,"b":11,"c":12,"d":13,"e":14,"f":15,"A":10,"B":11,"C":12,"D":13,"E":14,"F":15] // var buffer:UInt8? // var skip = hasPrefix("0x") ? 2 : 0 // for char in unicodeScalars.lazy { // guard skip == 0 else { // skip -= 1 // continue // } // guard let value = unicodeHexMap[char] else { // throw HexError.invalidCharacter // } // if let b = buffer { // block(b << 4 | value) // buffer = nil // } else { // buffer = value // } // } // if let b = buffer{block(b)} // } private enum HexError:Error { case invalidCharacter } } private struct HTMLEntities { static let characterEntities : [String: Character] = [ // XML predefined entities: "&quot;" : "\"", "&amp;" : "&", "&apos;" : "'", "&lt;" : "<", "&gt;" : ">", // HTML character entity references: "&nbsp;" : "\u{00A0}", "&iexcl;" : "\u{00A1}", "&cent;" : "\u{00A2}", "&pound;" : "\u{00A3}", "&curren;" : "\u{00A4}", "&yen;" : "\u{00A5}", "&brvbar;" : "\u{00A6}", "&sect;" : "\u{00A7}", "&uml;" : "\u{00A8}", "&copy;" : "\u{00A9}", "&ordf;" : "\u{00AA}", "&laquo;" : "\u{00AB}", "&not;" : "\u{00AC}", "&shy;" : "\u{00AD}", "&reg;" : "\u{00AE}", "&macr;" : "\u{00AF}", "&deg;" : "\u{00B0}", "&plusmn;" : "\u{00B1}", "&sup2;" : "\u{00B2}", "&sup3;" : "\u{00B3}", "&acute;" : "\u{00B4}", "&micro;" : "\u{00B5}", "&para;" : "\u{00B6}", "&middot;" : "\u{00B7}", "&cedil;" : "\u{00B8}", "&sup1;" : "\u{00B9}", "&ordm;" : "\u{00BA}", "&raquo;" : "\u{00BB}", "&frac14;" : "\u{00BC}", "&frac12;" : "\u{00BD}", "&frac34;" : "\u{00BE}", "&iquest;" : "\u{00BF}", "&Agrave;" : "\u{00C0}", "&Aacute;" : "\u{00C1}", "&Acirc;" : "\u{00C2}", "&Atilde;" : "\u{00C3}", "&Auml;" : "\u{00C4}", "&Aring;" : "\u{00C5}", "&AElig;" : "\u{00C6}", "&Ccedil;" : "\u{00C7}", "&Egrave;" : "\u{00C8}", "&Eacute;" : "\u{00C9}", "&Ecirc;" : "\u{00CA}", "&Euml;" : "\u{00CB}", "&Igrave;" : "\u{00CC}", "&Iacute;" : "\u{00CD}", "&Icirc;" : "\u{00CE}", "&Iuml;" : "\u{00CF}", "&ETH;" : "\u{00D0}", "&Ntilde;" : "\u{00D1}", "&Ograve;" : "\u{00D2}", "&Oacute;" : "\u{00D3}", "&Ocirc;" : "\u{00D4}", "&Otilde;" : "\u{00D5}", "&Ouml;" : "\u{00D6}", "&times;" : "\u{00D7}", "&Oslash;" : "\u{00D8}", "&Ugrave;" : "\u{00D9}", "&Uacute;" : "\u{00DA}", "&Ucirc;" : "\u{00DB}", "&Uuml;" : "\u{00DC}", "&Yacute;" : "\u{00DD}", "&THORN;" : "\u{00DE}", "&szlig;" : "\u{00DF}", "&agrave;" : "\u{00E0}", "&aacute;" : "\u{00E1}", "&acirc;" : "\u{00E2}", "&atilde;" : "\u{00E3}", "&auml;" : "\u{00E4}", "&aring;" : "\u{00E5}", "&aelig;" : "\u{00E6}", "&ccedil;" : "\u{00E7}", "&egrave;" : "\u{00E8}", "&eacute;" : "\u{00E9}", "&ecirc;" : "\u{00EA}", "&euml;" : "\u{00EB}", "&igrave;" : "\u{00EC}", "&iacute;" : "\u{00ED}", "&icirc;" : "\u{00EE}", "&iuml;" : "\u{00EF}", "&eth;" : "\u{00F0}", "&ntilde;" : "\u{00F1}", "&ograve;" : "\u{00F2}", "&oacute;" : "\u{00F3}", "&ocirc;" : "\u{00F4}", "&otilde;" : "\u{00F5}", "&ouml;" : "\u{00F6}", "&divide;" : "\u{00F7}", "&oslash;" : "\u{00F8}", "&ugrave;" : "\u{00F9}", "&uacute;" : "\u{00FA}", "&ucirc;" : "\u{00FB}", "&uuml;" : "\u{00FC}", "&yacute;" : "\u{00FD}", "&thorn;" : "\u{00FE}", "&yuml;" : "\u{00FF}", "&OElig;" : "\u{0152}", "&oelig;" : "\u{0153}", "&Scaron;" : "\u{0160}", "&scaron;" : "\u{0161}", "&Yuml;" : "\u{0178}", "&fnof;" : "\u{0192}", "&circ;" : "\u{02C6}", "&tilde;" : "\u{02DC}", "&Alpha;" : "\u{0391}", "&Beta;" : "\u{0392}", "&Gamma;" : "\u{0393}", "&Delta;" : "\u{0394}", "&Epsilon;" : "\u{0395}", "&Zeta;" : "\u{0396}", "&Eta;" : "\u{0397}", "&Theta;" : "\u{0398}", "&Iota;" : "\u{0399}", "&Kappa;" : "\u{039A}", "&Lambda;" : "\u{039B}", "&Mu;" : "\u{039C}", "&Nu;" : "\u{039D}", "&Xi;" : "\u{039E}", "&Omicron;" : "\u{039F}", "&Pi;" : "\u{03A0}", "&Rho;" : "\u{03A1}", "&Sigma;" : "\u{03A3}", "&Tau;" : "\u{03A4}", "&Upsilon;" : "\u{03A5}", "&Phi;" : "\u{03A6}", "&Chi;" : "\u{03A7}", "&Psi;" : "\u{03A8}", "&Omega;" : "\u{03A9}", "&alpha;" : "\u{03B1}", "&beta;" : "\u{03B2}", "&gamma;" : "\u{03B3}", "&delta;" : "\u{03B4}", "&epsilon;" : "\u{03B5}", "&zeta;" : "\u{03B6}", "&eta;" : "\u{03B7}", "&theta;" : "\u{03B8}", "&iota;" : "\u{03B9}", "&kappa;" : "\u{03BA}", "&lambda;" : "\u{03BB}", "&mu;" : "\u{03BC}", "&nu;" : "\u{03BD}", "&xi;" : "\u{03BE}", "&omicron;" : "\u{03BF}", "&pi;" : "\u{03C0}", "&rho;" : "\u{03C1}", "&sigmaf;" : "\u{03C2}", "&sigma;" : "\u{03C3}", "&tau;" : "\u{03C4}", "&upsilon;" : "\u{03C5}", "&phi;" : "\u{03C6}", "&chi;" : "\u{03C7}", "&psi;" : "\u{03C8}", "&omega;" : "\u{03C9}", "&thetasym;" : "\u{03D1}", "&upsih;" : "\u{03D2}", "&piv;" : "\u{03D6}", "&ensp;" : "\u{2002}", "&emsp;" : "\u{2003}", "&thinsp;" : "\u{2009}", "&zwnj;" : "\u{200C}", "&zwj;" : "\u{200D}", "&lrm;" : "\u{200E}", "&rlm;" : "\u{200F}", "&ndash;" : "\u{2013}", "&mdash;" : "\u{2014}", "&lsquo;" : "\u{2018}", "&rsquo;" : "\u{2019}", "&sbquo;" : "\u{201A}", "&ldquo;" : "\u{201C}", "&rdquo;" : "\u{201D}", "&bdquo;" : "\u{201E}", "&dagger;" : "\u{2020}", "&Dagger;" : "\u{2021}", "&bull;" : "\u{2022}", "&hellip;" : "\u{2026}", "&permil;" : "\u{2030}", "&prime;" : "\u{2032}", "&Prime;" : "\u{2033}", "&lsaquo;" : "\u{2039}", "&rsaquo;" : "\u{203A}", "&oline;" : "\u{203E}", "&frasl;" : "\u{2044}", "&euro;" : "\u{20AC}", "&image;" : "\u{2111}", "&weierp;" : "\u{2118}", "&real;" : "\u{211C}", "&trade;" : "\u{2122}", "&alefsym;" : "\u{2135}", "&larr;" : "\u{2190}", "&uarr;" : "\u{2191}", "&rarr;" : "\u{2192}", "&darr;" : "\u{2193}", "&harr;" : "\u{2194}", "&crarr;" : "\u{21B5}", "&lArr;" : "\u{21D0}", "&uArr;" : "\u{21D1}", "&rArr;" : "\u{21D2}", "&dArr;" : "\u{21D3}", "&hArr;" : "\u{21D4}", "&forall;" : "\u{2200}", "&part;" : "\u{2202}", "&exist;" : "\u{2203}", "&empty;" : "\u{2205}", "&nabla;" : "\u{2207}", "&isin;" : "\u{2208}", "&notin;" : "\u{2209}", "&ni;" : "\u{220B}", "&prod;" : "\u{220F}", "&sum;" : "\u{2211}", "&minus;" : "\u{2212}", "&lowast;" : "\u{2217}", "&radic;" : "\u{221A}", "&prop;" : "\u{221D}", "&infin;" : "\u{221E}", "&ang;" : "\u{2220}", "&and;" : "\u{2227}", "&or;" : "\u{2228}", "&cap;" : "\u{2229}", "&cup;" : "\u{222A}", "&int;" : "\u{222B}", "&there4;" : "\u{2234}", "&sim;" : "\u{223C}", "&cong;" : "\u{2245}", "&asymp;" : "\u{2248}", "&ne;" : "\u{2260}", "&equiv;" : "\u{2261}", "&le;" : "\u{2264}", "&ge;" : "\u{2265}", "&sub;" : "\u{2282}", "&sup;" : "\u{2283}", "&nsub;" : "\u{2284}", "&sube;" : "\u{2286}", "&supe;" : "\u{2287}", "&oplus;" : "\u{2295}", "&otimes;" : "\u{2297}", "&perp;" : "\u{22A5}", "&sdot;" : "\u{22C5}", "&lceil;" : "\u{2308}", "&rceil;" : "\u{2309}", "&lfloor;" : "\u{230A}", "&rfloor;" : "\u{230B}", "&lang;" : "\u{2329}", "&rang;" : "\u{232A}", "&loz;" : "\u{25CA}", "&spades;" : "\u{2660}", "&clubs;" : "\u{2663}", "&hearts;" : "\u{2665}", "&diams;" : "\u{2666}", ] // Convert the number in the string to the corresponding // Unicode character, e.g. // decodeNumeric("64", 10) --> "@" // decodeNumeric("20ac", 16) --> "€" fileprivate static func decodeNumeric(_ string : String, base : Int32) -> Character? { let code = UInt32(strtoul(string, nil, base)) guard let scalar = UnicodeScalar(code) else {return nil} return Character(scalar) } // Decode the HTML character entity to the corresponding // Unicode character, return `nil` for invalid input. // decode("&#64;") --> "@" // decode("&#x20ac;") --> "€" // decode("&lt;") --> "<" // decode("&foo;") --> nil fileprivate static func decode(_ entity : String) -> Character? { if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){ return decodeNumeric(String(entity[entity.index(entity.startIndex, offsetBy: 3)...]), base: 16) // return decodeNumeric(entity.substring(from: entity.characters.index(entity.startIndex, offsetBy: 3)), base: 16) } else if entity.hasPrefix("&#") { return decodeNumeric(String(entity[entity.index(entity.startIndex, offsetBy: 2)...]), base: 10) // return decodeNumeric(entity.substring(from: entity.characters.index(entity.startIndex, offsetBy: 2)), base: 10) } else { return HTMLEntities.characterEntities[entity] } } }
mit
8cdd3af354d9e27725b357599b9f82ca
35.293276
265
0.477709
3.674004
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Stats/Insights/SiteStatsInsightsViewModel.swift
1
29370
import Foundation import WordPressFlux /// The view model used by Stats Insights. /// class SiteStatsInsightsViewModel: Observable { // MARK: - Properties let changeDispatcher = Dispatcher<Void>() private weak var siteStatsInsightsDelegate: SiteStatsInsightsDelegate? private let insightsStore = StoreContainer.shared.statsInsights private var insightsReceipt: Receipt? private var insightsChangeReceipt: Receipt? private var insightsToShow = [InsightType]() private var periodReceipt: Receipt? private typealias Style = WPStyleGuide.Stats // MARK: - Constructor init(insightsToShow: [InsightType], insightsDelegate: SiteStatsInsightsDelegate) { self.siteStatsInsightsDelegate = insightsDelegate self.insightsToShow = insightsToShow insightsChangeReceipt = insightsStore.onChange { [weak self] in self?.emitChange() } } func fetchInsights() { insightsReceipt = insightsStore.query(.insights) } // MARK: - Refresh Data func refreshInsights() { if !insightsStore.isFetchingOverview { ActionDispatcher.dispatch(InsightAction.refreshInsights) } } // MARK: - Table Model func tableViewModel() -> ImmuTable { var tableRows = [ImmuTableRow]() if insightsToShow.isEmpty || (insightsStore.fetchingFailed(for: .insights) && !containsCachedData()) { return ImmuTable.Empty } insightsToShow.forEach { insightType in let errorBlock = { return StatsErrorRow(rowStatus: .error, statType: .insights) } switch insightType { case .customize: tableRows.append(CustomizeInsightsRow(siteStatsInsightsDelegate: siteStatsInsightsDelegate)) case .latestPostSummary: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsLatestPostSummary, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .latestPostSummary, type: .insights, status: insightsStore.lastPostSummaryStatus, block: { return LatestPostSummaryRow(summaryData: insightsStore.getLastPostInsight(), chartData: insightsStore.getPostStats(), siteStatsInsightsDelegate: siteStatsInsightsDelegate) }, loading: { return StatsGhostChartImmutableRow() }, error: errorBlock)) case .allTimeStats: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsAllTime, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .allTimeStats, type: .insights, status: insightsStore.allTimeStatus, block: { return TwoColumnStatsRow(dataRows: createAllTimeStatsRows(), statSection: .insightsAllTime, siteStatsInsightsDelegate: nil) }, loading: { return StatsGhostTwoColumnImmutableRow() }, error: errorBlock)) case .followersTotals: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsFollowerTotals, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .followersTotals, type: .insights, status: insightsStore.followersTotalsStatus, block: { return TwoColumnStatsRow(dataRows: createTotalFollowersRows(), statSection: .insightsFollowerTotals, siteStatsInsightsDelegate: nil) }, loading: { return StatsGhostTwoColumnImmutableRow() }, error: errorBlock)) case .mostPopularTime: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsMostPopularTime, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .mostPopularTime, type: .insights, status: insightsStore.annualAndMostPopularTimeStatus, block: { return TwoColumnStatsRow(dataRows: createMostPopularStatsRows(), statSection: .insightsMostPopularTime, siteStatsInsightsDelegate: nil) }, loading: { return StatsGhostTwoColumnImmutableRow() }, error: errorBlock)) case .tagsAndCategories: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsTagsAndCategories, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .tagsAndCategories, type: .insights, status: insightsStore.tagsAndCategoriesStatus, block: { return TopTotalsInsightStatsRow(itemSubtitle: StatSection.insightsTagsAndCategories.itemSubtitle, dataSubtitle: StatSection.insightsTagsAndCategories.dataSubtitle, dataRows: createTagsAndCategoriesRows(), siteStatsInsightsDelegate: siteStatsInsightsDelegate) }, loading: { return StatsGhostTopImmutableRow() }, error: errorBlock)) case .annualSiteStats: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsAnnualSiteStats, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .annualSiteStats, type: .insights, status: insightsStore.annualAndMostPopularTimeStatus, block: { return TwoColumnStatsRow(dataRows: createAnnualRows(), statSection: .insightsAnnualSiteStats, siteStatsInsightsDelegate: siteStatsInsightsDelegate) }, loading: { return StatsGhostTwoColumnImmutableRow() }, error: errorBlock)) case .comments: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsCommentsPosts, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .comments, type: .insights, status: insightsStore.commentsInsightStatus, block: { return createCommentsRow() }, loading: { return StatsGhostTabbedImmutableRow() }, error: errorBlock)) case .followers: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsFollowersWordPress, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .followers, type: .insights, status: insightsStore.followersTotalsStatus, block: { return createFollowersRow() }, loading: { return StatsGhostTabbedImmutableRow() }, error: errorBlock)) case .todaysStats: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsTodaysStats, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .todaysStats, type: .insights, status: insightsStore.todaysStatsStatus, block: { return TwoColumnStatsRow(dataRows: createTodaysStatsRows(), statSection: .insightsTodaysStats, siteStatsInsightsDelegate: nil) }, loading: { return StatsGhostTwoColumnImmutableRow() }, error: errorBlock)) case .postingActivity: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsPostingActivity, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .postingActivity, type: .insights, status: insightsStore.postingActivityStatus, block: { return createPostingActivityRow() }, loading: { return StatsGhostPostingActivitiesImmutableRow() }, error: errorBlock)) case .publicize: tableRows.append(InsightCellHeaderRow(statSection: StatSection.insightsPublicize, siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(blocks(for: .publicize, type: .insights, status: insightsStore.publicizeFollowersStatus, block: { return TopTotalsInsightStatsRow(itemSubtitle: StatSection.insightsPublicize.itemSubtitle, dataSubtitle: StatSection.insightsPublicize.dataSubtitle, dataRows: createPublicizeRows(), siteStatsInsightsDelegate: nil) }, loading: { return StatsGhostTopImmutableRow() }, error: errorBlock)) default: break } } tableRows.append(TableFooterRow()) tableRows.append(AddInsightRow(dataRow: createAddInsightRow(), siteStatsInsightsDelegate: siteStatsInsightsDelegate)) tableRows.append(TableFooterRow()) return ImmuTable(sections: [ ImmuTableSection( rows: tableRows) ]) } func isFetchingOverview() -> Bool { return insightsStore.isFetchingOverview } func fetchingFailed() -> Bool { return insightsStore.fetchingFailed(for: .insights) } func containsCachedData() -> Bool { return insightsStore.containsCachedData(for: insightsToShow) } func yearlyPostingActivity(from date: Date = Date()) -> [[PostingStreakEvent]] { return insightsStore.getYearlyPostingActivityFrom(date: date) } func annualInsightsYear() -> Int? { return insightsStore.getAnnualAndMostPopularTime()?.annualInsightsYear } func updateInsightsToShow(insights: [InsightType]) { insightsToShow = insights } } // MARK: - Private Extension private extension SiteStatsInsightsViewModel { struct AllTimeStats { static let postsTitle = NSLocalizedString("Posts", comment: "All Time Stats 'Posts' label") static let viewsTitle = NSLocalizedString("Views", comment: "All Time Stats 'Views' label") static let visitorsTitle = NSLocalizedString("Visitors", comment: "All Time Stats 'Visitors' label") static let bestViewsEverTitle = NSLocalizedString("Best views ever", comment: "All Time Stats 'Best views ever' label") } struct MostPopularStats { static let bestDay = NSLocalizedString("Best Day", comment: "'Best Day' label for Most Popular stat.") static let bestHour = NSLocalizedString("Best Hour", comment: "'Best Hour' label for Most Popular stat.") } struct FollowerTotals { static let total = NSLocalizedString("Total", comment: "Label for total followers") static let wordPress = NSLocalizedString("WordPress.com", comment: "Label for WordPress.com followers") static let email = NSLocalizedString("Email", comment: "Label for email followers") static let social = NSLocalizedString("Social", comment: "Follower Totals label for social media followers") } struct TodaysStats { static let viewsTitle = NSLocalizedString("Views", comment: "Today's Stats 'Views' label") static let visitorsTitle = NSLocalizedString("Visitors", comment: "Today's Stats 'Visitors' label") static let likesTitle = NSLocalizedString("Likes", comment: "Today's Stats 'Likes' label") static let commentsTitle = NSLocalizedString("Comments", comment: "Today's Stats 'Comments' label") } func createAllTimeStatsRows() -> [StatsTwoColumnRowData] { guard let allTimeInsight = insightsStore.getAllTimeStats() else { return [] } let totalCounts = allTimeInsight.viewsCount + allTimeInsight.visitorsCount + allTimeInsight.postsCount + allTimeInsight.bestViewsPerDayCount guard totalCounts > 0 else { return [] } var dataRows = [StatsTwoColumnRowData]() dataRows.append(StatsTwoColumnRowData.init(leftColumnName: AllTimeStats.viewsTitle, leftColumnData: allTimeInsight.viewsCount.abbreviatedString(), rightColumnName: AllTimeStats.visitorsTitle, rightColumnData: allTimeInsight.visitorsCount.abbreviatedString())) dataRows.append(StatsTwoColumnRowData.init(leftColumnName: AllTimeStats.postsTitle, leftColumnData: allTimeInsight.postsCount.abbreviatedString(), rightColumnName: AllTimeStats.bestViewsEverTitle, rightColumnData: allTimeInsight.bestViewsPerDayCount.abbreviatedString())) return dataRows } func createMostPopularStatsRows() -> [StatsTwoColumnRowData] { guard let mostPopularStats = insightsStore.getAnnualAndMostPopularTime(), var mostPopularWeekday = mostPopularStats.mostPopularDayOfWeek.weekday, let mostPopularHour = mostPopularStats.mostPopularHour.hour, mostPopularStats.mostPopularDayOfWeekPercentage > 0 else { return [] } var calendar = Calendar.init(identifier: .gregorian) calendar.locale = Locale.autoupdatingCurrent // Back up mostPopularWeekday by 1 to get correct index for standaloneWeekdaySymbols. mostPopularWeekday = mostPopularWeekday == 0 ? calendar.standaloneWeekdaySymbols.count - 1 : mostPopularWeekday - 1 let dayString = calendar.standaloneWeekdaySymbols[mostPopularWeekday] guard let timeModifiedDate = calendar.date(bySettingHour: mostPopularHour, minute: 0, second: 0, of: Date()) else { return [] } let timeFormatter = DateFormatter() timeFormatter.setLocalizedDateFormatFromTemplate("h a") let timeString = timeFormatter.string(from: timeModifiedDate) return [StatsTwoColumnRowData.init(leftColumnName: MostPopularStats.bestDay, leftColumnData: dayString, rightColumnName: MostPopularStats.bestHour, rightColumnData: timeString.uppercased())] } func createTotalFollowersRows() -> [StatsTwoColumnRowData] { let totalDotComFollowers = insightsStore.getDotComFollowers()?.dotComFollowersCount ?? 0 let totalEmailFollowers = insightsStore.getEmailFollowers()?.emailFollowersCount ?? 0 var totalPublicize = 0 if let publicize = insightsStore.getPublicize(), !publicize.publicizeServices.isEmpty { totalPublicize = publicize.publicizeServices.compactMap({$0.followers}).reduce(0, +) } let totalFollowers = totalDotComFollowers + totalEmailFollowers + totalPublicize guard totalFollowers > 0 else { return [] } var dataRows = [StatsTwoColumnRowData]() dataRows.append(StatsTwoColumnRowData.init(leftColumnName: FollowerTotals.total, leftColumnData: totalFollowers.abbreviatedString(), rightColumnName: FollowerTotals.wordPress, rightColumnData: totalDotComFollowers.abbreviatedString())) dataRows.append(StatsTwoColumnRowData.init(leftColumnName: FollowerTotals.email, leftColumnData: totalEmailFollowers.abbreviatedString(), rightColumnName: FollowerTotals.social, rightColumnData: totalPublicize.abbreviatedString())) return dataRows } func createPublicizeRows() -> [StatsTotalRowData] { guard let services = insightsStore.getPublicize()?.publicizeServices else { return [] } return services.map { return StatsTotalRowData(name: $0.name, data: $0.followers.abbreviatedString(), socialIconURL: $0.iconURL, statSection: .insightsPublicize) } } func createTodaysStatsRows() -> [StatsTwoColumnRowData] { guard let todaysStats = insightsStore.getTodaysStats() else { return [] } let totalCounts = todaysStats.viewsCount + todaysStats.visitorsCount + todaysStats.likesCount + todaysStats.commentsCount guard totalCounts > 0 else { return [] } var dataRows = [StatsTwoColumnRowData]() dataRows.append(StatsTwoColumnRowData.init(leftColumnName: TodaysStats.viewsTitle, leftColumnData: todaysStats.viewsCount.abbreviatedString(), rightColumnName: TodaysStats.visitorsTitle, rightColumnData: todaysStats.visitorsCount.abbreviatedString())) dataRows.append(StatsTwoColumnRowData.init(leftColumnName: TodaysStats.likesTitle, leftColumnData: todaysStats.likesCount.abbreviatedString(), rightColumnName: TodaysStats.commentsTitle, rightColumnData: todaysStats.commentsCount.abbreviatedString())) return dataRows } func createPostingActivityRow() -> PostingActivityRow { var monthsData = [[PostingStreakEvent]]() if let twoMonthsAgo = Calendar.current.date(byAdding: .month, value: -2, to: Date()) { monthsData.append(insightsStore.getMonthlyPostingActivityFor(date: twoMonthsAgo)) } if let oneMonthAgo = Calendar.current.date(byAdding: .month, value: -1, to: Date()) { monthsData.append(insightsStore.getMonthlyPostingActivityFor(date: oneMonthAgo)) } monthsData.append(insightsStore.getMonthlyPostingActivityFor(date: Date())) return PostingActivityRow(monthsData: monthsData, siteStatsInsightsDelegate: siteStatsInsightsDelegate) } func createTagsAndCategoriesRows() -> [StatsTotalRowData] { guard let tagsAndCategories = insightsStore.getTopTagsAndCategories()?.topTagsAndCategories else { return [] } return tagsAndCategories.map { let viewsCount = $0.viewsCount ?? 0 return StatsTotalRowData(name: $0.name, data: viewsCount.abbreviatedString(), dataBarPercent: Float(viewsCount) / Float(tagsAndCategories.first?.viewsCount ?? 1), icon: StatsDataHelper.tagsAndCategoriesIconForKind($0.kind), showDisclosure: true, disclosureURL: $0.url, childRows: StatsDataHelper.childRowsForItems($0.children), statSection: .insightsTagsAndCategories) } } func createAnnualRows() -> [StatsTwoColumnRowData] { guard let annualInsights = insightsStore.getAnnualAndMostPopularTime(), annualInsights.annualInsightsTotalPostsCount > 0 else { return [] } var dataRows = [StatsTwoColumnRowData]() dataRows.append(StatsTwoColumnRowData.init(leftColumnName: AnnualSiteStats.year, leftColumnData: String(annualInsights.annualInsightsYear), rightColumnName: AnnualSiteStats.totalPosts, rightColumnData: annualInsights.annualInsightsTotalPostsCount.abbreviatedString())) dataRows.append(StatsTwoColumnRowData.init(leftColumnName: AnnualSiteStats.totalComments, leftColumnData: annualInsights.annualInsightsTotalCommentsCount.abbreviatedString(), rightColumnName: AnnualSiteStats.commentsPerPost, rightColumnData: Int(round(annualInsights.annualInsightsAverageCommentsCount)).abbreviatedString())) dataRows.append(StatsTwoColumnRowData.init(leftColumnName: AnnualSiteStats.totalLikes, leftColumnData: annualInsights.annualInsightsTotalLikesCount.abbreviatedString(), rightColumnName: AnnualSiteStats.likesPerPost, rightColumnData: Int(round(annualInsights.annualInsightsAverageLikesCount)).abbreviatedString())) dataRows.append(StatsTwoColumnRowData.init(leftColumnName: AnnualSiteStats.totalWords, leftColumnData: annualInsights.annualInsightsTotalWordsCount.abbreviatedString(), rightColumnName: AnnualSiteStats.wordsPerPost, rightColumnData: Int(round(annualInsights.annualInsightsAverageWordsCount)).abbreviatedString())) return dataRows } func createCommentsRow() -> TabbedTotalsStatsRow { return TabbedTotalsStatsRow(tabsData: [tabDataForCommentType(.insightsCommentsAuthors), tabDataForCommentType(.insightsCommentsPosts)], siteStatsInsightsDelegate: siteStatsInsightsDelegate, showTotalCount: false) } func tabDataForCommentType(_ commentType: StatSection) -> TabData { let commentsInsight = insightsStore.getTopCommentsInsight() var rowItems: [StatsTotalRowData] = [] // Ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/11713 // For now, don't show `View more` for Insights Comments. // To accomplish this, return only the max number of rows displayed on the Insights card, // as `View more` is added if the number of rows exceeds the max. switch commentType { case .insightsCommentsAuthors: let authors = commentsInsight?.topAuthors.prefix(StatsDataHelper.maxRowsToDisplay) ?? [] rowItems = authors.map { StatsTotalRowData(name: $0.name, data: $0.commentCount.abbreviatedString(), userIconURL: $0.iconURL, showDisclosure: false, statSection: .insightsCommentsAuthors) } case .insightsCommentsPosts: let posts = commentsInsight?.topPosts.prefix(StatsDataHelper.maxRowsToDisplay) ?? [] rowItems = posts.map { StatsTotalRowData(name: $0.name, data: $0.commentCount.abbreviatedString(), showDisclosure: true, disclosureURL: $0.postURL, statSection: .insightsCommentsPosts) } default: break } return TabData(tabTitle: commentType.tabTitle, itemSubtitle: commentType.itemSubtitle, dataSubtitle: commentType.dataSubtitle, dataRows: rowItems) } func createFollowersRow() -> TabbedTotalsStatsRow { return TabbedTotalsStatsRow(tabsData: [tabDataForFollowerType(.insightsFollowersWordPress), tabDataForFollowerType(.insightsFollowersEmail)], siteStatsInsightsDelegate: siteStatsInsightsDelegate, showTotalCount: true) } func tabDataForFollowerType(_ followerType: StatSection) -> TabData { let tabTitle = followerType.tabTitle var followers: [StatsFollower]? var totalFollowers: Int? switch followerType { case .insightsFollowersWordPress: followers = insightsStore.getDotComFollowers()?.topDotComFollowers totalFollowers = insightsStore.getDotComFollowers()?.dotComFollowersCount case .insightsFollowersEmail: followers = insightsStore.getEmailFollowers()?.topEmailFollowers totalFollowers = insightsStore.getEmailFollowers()?.emailFollowersCount default: break } let totalCount = String(format: followerType.totalFollowers, (totalFollowers ?? 0).abbreviatedString()) let followersData = followers?.compactMap { return StatsTotalRowData(name: $0.name, data: $0.subscribedDate.relativeStringInPast(), userIconURL: $0.avatarURL, statSection: followerType) } return TabData(tabTitle: tabTitle, itemSubtitle: followerType.itemSubtitle, dataSubtitle: followerType.dataSubtitle, totalCount: totalCount, dataRows: followersData ?? []) } func createAddInsightRow() -> StatsTotalRowData { return StatsTotalRowData(name: StatSection.insightsAddInsight.title, data: "", icon: Style.imageForGridiconType(.plus, withTint: .darkGrey), statSection: .insightsAddInsight) } } extension SiteStatsInsightsViewModel: AsyncBlocksLoadable { typealias RowType = InsightType var currentStore: StatsInsightsStore { return insightsStore } }
gpl-2.0
719c8dfce4e1b443362791da68bf52f1
49.989583
151
0.55063
6.248936
false
true
false
false
ulidev/JMButtonLoader
JMButtonLoader/JMButtonLoader/ViewController.swift
1
801
// // ViewController.swift // JMButtonLoader // // Created by Joan Molinas on 17/6/15. // Copyright © 2015 Joan. All rights reserved. // import UIKit class ViewController: UIViewController, ButtonLoaderDelegate { @IBOutlet weak var buttonLoader: JMButtonLoader! var counter : Int = 0 override func viewDidLoad() { super.viewDidLoad() buttonLoader.delegate = self } func buttonTapped() { counter = 0 let _ = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("update:"), userInfo: nil, repeats: true) } func update(timer : NSTimer) { counter++ if(counter == 4) { timer.invalidate() buttonLoader.stopButton() } } }
mit
8e873b81fa1dbb6cc759dd313e98c396
19
134
0.5925
4.444444
false
false
false
false
jiaxw32/ZRSwiftKit
ZRSwiftKit/Demo/FaceIt/EmotionViewController.swift
1
1609
// // EmotionViewController.swift // ZRSwiftKit // // Created by jiaxw-mac on 2017/9/26. // Copyright © 2017年 jiaxw32. All rights reserved. // import UIKit class EmotionViewController: UIViewController { let emotionMap: [String: FacialExpresison] = [ "sad" : FacialExpresison(eyes: .closed, mouth: .frown), "worried" : FacialExpresison(eyes: .open, mouth: .smirk), "happy" : FacialExpresison(eyes: .open, mouth: .smile) ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var destViewController = segue.destination if let navigationViewController = destViewController as? UINavigationController { destViewController = navigationViewController.visibleViewController ?? destViewController } if let emotionViewController = destViewController as? FaceItViewController, let identifier = segue.identifier { if let faceExpression = emotionMap[identifier] { emotionViewController.faceExpression = faceExpression } emotionViewController.navigationItem.title = identifier } } @IBAction func actionCancel(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } }
mit
650b42dee803c0f6cde642d9b1068934
29.301887
101
0.655044
4.751479
false
false
false
false
cheeyi/ProjectSora
ProjectSora/OnboardViewController.swift
1
3306
// // OnboardViewController.swift // ProjectSora // // Created by Chee Yi Ong on 11/29/15. // Copyright © 2015 Expedia MSP. All rights reserved. // import Foundation import Onboard class OnboardViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().statusBarStyle = .LightContent // Hardcode this first to see onboarding every time NSUserDefaults.standardUserDefaults().setBool(false, forKey: "kUserHasOnboardedKey") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let userHasOnboarded = NSUserDefaults.standardUserDefaults().boolForKey("kUserHasOnboardedKey") if !userHasOnboarded { // Handle onboarding // Set up onboarding content pages let firstPage = OnboardingContentViewController(title: "Welcome", body: "This app is going to rock your world", image: UIImage(named: "umbrella-icon"), buttonText: nil) { () -> Void in // Do something here when users press the button, like ask for location services permissions, register for push notifications } let secondPage = OnboardingContentViewController(title: "Getting to Know You", body: "We'll start by asking you some questions. Be honest!", image: UIImage(named: "umbrella-icon"), buttonText: nil) { () -> Void in } let thirdPage = OnboardingContentViewController(title: "Understanding You", body: "The app learns and understands what you like", image: UIImage(named: "umbrella-icon"), buttonText: nil) { () -> Void in } let fourthPage = OnboardingContentViewController(title: "Assisting You", body: "We then suggest full holiday packages based on your interests", image: UIImage(named: "umbrella-icon"), buttonText: "Let's get started!") { () -> Void in NSUserDefaults.standardUserDefaults().setBool(true, forKey: "kUserHasOnboardedKey") // Perform segue to survey questions } // Set up onboarding view controller let onboardingVC = OnboardingViewController(backgroundImage: UIImage(named: "haystack"), contents: [firstPage, secondPage, thirdPage, fourthPage]) onboardingVC.allowSkipping = true onboardingVC.skipHandler = {() -> Void in // Copy completion block from last onboarding content VC's button completion above, and put it under the completion block below NSUserDefaults.standardUserDefaults().setBool(true, forKey: "kUserHasOnboardedKey") self.dismissViewControllerAnimated(true, completion: nil) } // Present onboarding view controller modally self.modalTransitionStyle = UIModalTransitionStyle.CoverVertical self.modalPresentationStyle = .CurrentContext self.presentViewController(onboardingVC, animated: true, completion: nil) } NSUserDefaults.standardUserDefaults().synchronize() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
mit
05ed152f9a8a79eb1dd77591d0b5bcf7
47.617647
245
0.658396
5.480929
false
false
false
false
abertelrud/swift-package-manager
Sources/PackageGraph/Pubgrub/PubgrubDependencyResolver.swift
2
64026
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Dispatch import class Foundation.NSLock import OrderedCollections import PackageModel import TSCBasic /// The solver that is able to transitively resolve a set of package constraints /// specified by a root package. public struct PubgrubDependencyResolver { /// The type of the constraints the resolver operates on. public typealias Constraint = PackageContainerConstraint /// the mutable state that get computed internal final class State { /// The root package reference. let root: DependencyResolutionNode /// The list of packages that are overridden in the graph. A local package reference will /// always override any other kind of package reference and branch-based reference will override /// version-based reference. let overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)] /// A collection of all known incompatibilities matched to the packages they /// refer to. This means an incompatibility can occur several times. public private(set) var incompatibilities: [DependencyResolutionNode: [Incompatibility]] = [:] /// The current best guess for a solution satisfying all requirements. public private(set) var solution: PartialSolution private let lock = NSLock() init(root: DependencyResolutionNode, overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)] = [:], solution: PartialSolution = PartialSolution()) { self.root = root self.overriddenPackages = overriddenPackages self.solution = solution } func addIncompatibility(_ incompatibility: Incompatibility, at location: LogLocation) { self.lock.withLock { // log("incompat: \(incompatibility) \(location)") for package in incompatibility.terms.map({ $0.node }) { if let incompats = self.incompatibilities[package] { if !incompats.contains(incompatibility) { self.incompatibilities[package]!.append(incompatibility) } } else { self.incompatibilities[package] = [incompatibility] } } } } /// Find all incompatibilities containing a positive term for a given package. func positiveIncompatibilities(for node: DependencyResolutionNode) -> [Incompatibility]? { self.lock.withLock { guard let all = self.incompatibilities[node] else { return nil } return all.filter { $0.terms.first { $0.node == node }!.isPositive } } } func decide(_ node: DependencyResolutionNode, at version: Version) { let term = Term(node, .exact(version)) self.lock.withLock { assert(term.isValidDecision(for: self.solution)) self.solution.decide(node, at: version) } } func derive(_ term: Term, cause: Incompatibility) { self.lock.withLock { self.solution.derive(term, cause: cause) } } func backtrack(toDecisionLevel: Int) { self.lock.withLock { self.solution.backtrack(toDecisionLevel: toDecisionLevel) } } } /// Reference to the pins store, if provided. private let pinsMap: PinsStore.PinsMap /// The container provider used to load package containers. private let provider: ContainerProvider /// Reference to the package container provider. private let packageContainerProvider: PackageContainerProvider /// Should resolver prefetch the containers. private let prefetchBasedOnResolvedFile: Bool /// Update containers while fetching them. private let skipDependenciesUpdates: Bool /// Resolver delegate private let delegate: DependencyResolverDelegate? public init( provider: PackageContainerProvider, pinsMap: PinsStore.PinsMap = [:], skipDependenciesUpdates: Bool = false, prefetchBasedOnResolvedFile: Bool = false, observabilityScope: ObservabilityScope, delegate: DependencyResolverDelegate? = nil ) { self.packageContainerProvider = provider self.pinsMap = pinsMap self.skipDependenciesUpdates = skipDependenciesUpdates self.prefetchBasedOnResolvedFile = prefetchBasedOnResolvedFile self.provider = ContainerProvider( provider: self.packageContainerProvider, skipUpdate: self.skipDependenciesUpdates, pinsMap: self.pinsMap, observabilityScope: observabilityScope ) self.delegate = delegate } /// Execute the resolution algorithm to find a valid assignment of versions. public func solve(constraints: [Constraint]) -> Result<[DependencyResolver.Binding], Error> { // the graph resolution root let root: DependencyResolutionNode if constraints.count == 1, let constraint = constraints.first, constraint.package.kind.isRoot { // root level package, use it as our resolution root root = .root(package: constraint.package) } else { // more complex setup requires a synthesized root root = .root(package: .root( identity: .plain("<synthesized-root>"), path: .root )) } do { // strips state return .success(try self.solve(root: root, constraints: constraints).bindings) } catch { // If version solving failing, build the user-facing diagnostic. if let pubGrubError = error as? PubgrubError, let rootCause = pubGrubError.rootCause, let incompatibilities = pubGrubError.incompatibilities { do { var builder = DiagnosticReportBuilder( root: root, incompatibilities: incompatibilities, provider: self.provider ) let diagnostic = try builder.makeErrorReport(for: rootCause) return.failure(PubgrubError.unresolvable(diagnostic)) } catch { // failed to construct the report, will report the original error return .failure(error) } } return .failure(error) } } /// Find a set of dependencies that fit the given constraints. If dependency /// resolution is unable to provide a result, an error is thrown. /// - Warning: It is expected that the root package reference has been set before this is called. internal func solve(root: DependencyResolutionNode, constraints: [Constraint]) throws -> (bindings: [DependencyResolver.Binding], state: State) { // first process inputs let inputs = try self.processInputs(root: root, with: constraints) // Prefetch the containers if prefetching is enabled. if self.prefetchBasedOnResolvedFile { // We avoid prefetching packages that are overridden since // otherwise we'll end up creating a repository container // for them. let pins = self.pinsMap.values .map { $0.packageRef } .filter { !inputs.overriddenPackages.keys.contains($0) } self.provider.prefetch(containers: pins) } let state = State(root: root, overriddenPackages: inputs.overriddenPackages) // Decide root at v1. state.decide(state.root, at: "1.0.0") // Add the root incompatibility. state.addIncompatibility(Incompatibility(terms: [Term(not: root, .exact("1.0.0"))], cause: .root), at: .topLevel) // Add inputs root incompatibilities. for incompatibility in inputs.rootIncompatibilities { state.addIncompatibility(incompatibility, at: .topLevel) } try self.run(state: state) let decisions = state.solution.assignments.filter { $0.isDecision } var flattenedAssignments: [PackageReference: (binding: BoundVersion, products: ProductFilter)] = [:] for assignment in decisions { if assignment.term.node == state.root { continue } let boundVersion: BoundVersion switch assignment.term.requirement { case .exact(let version): boundVersion = .version(version) case .range, .any, .empty, .ranges: throw InternalError("unexpected requirement value for assignment \(assignment.term)") } let products = assignment.term.node.productFilter // TODO: replace with async/await when available let container = try temp_await { provider.getContainer(for: assignment.term.node.package, completion: $0) } let updatePackage = try container.underlying.loadPackageReference(at: boundVersion) if var existing = flattenedAssignments[updatePackage] { guard existing.binding == boundVersion else { throw InternalError("Two products in one package resolved to different versions: \(existing.products)@\(existing.binding) vs \(products)@\(boundVersion)") } existing.products.formUnion(products) flattenedAssignments[updatePackage] = existing } else { flattenedAssignments[updatePackage] = (binding: boundVersion, products: products) } } var finalAssignments: [DependencyResolver.Binding] = flattenedAssignments.keys.sorted(by: { $0.deprecatedName < $1.deprecatedName }).map { package in let details = flattenedAssignments[package]! return (package: package, binding: details.binding, products: details.products) } // Add overridden packages to the result. for (package, override) in state.overriddenPackages { // TODO: replace with async/await when available let container = try temp_await { provider.getContainer(for: package, completion: $0) } let updatePackage = try container.underlying.loadPackageReference(at: override.version) finalAssignments.append((updatePackage, override.version, override.products)) } self.delegate?.solved(result: finalAssignments) return (finalAssignments, state) } private func processInputs( root: DependencyResolutionNode, with constraints: [Constraint] ) throws -> ( overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)], rootIncompatibilities: [Incompatibility] ) { // The list of constraints that we'll be working with. We start with the input constraints // and process them in two phases. The first phase finds all unversioned constraints and // the second phase discovers all branch-based constraints. var constraints = OrderedCollections.OrderedSet(constraints) // The list of packages that are overridden in the graph. A local package reference will // always override any other kind of package reference and branch-based reference will override // version-based reference. var overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)] = [:] // The list of version-based references reachable via local and branch-based references. // These are added as top-level incompatibilities since they always need to be satisfied. // Some of these might be overridden as we discover local and branch-based references. var versionBasedDependencies = OrderedCollections.OrderedDictionary<DependencyResolutionNode, [VersionBasedConstraint]>() // Process unversioned constraints in first phase. We go through all of the unversioned packages // and collect them and their dependencies. This gives us the complete list of unversioned // packages in the graph since unversioned packages can only be referred by other // unversioned packages. while let constraint = constraints.first(where: { $0.requirement == .unversioned }) { constraints.remove(constraint) // Mark the package as overridden. if var existing = overriddenPackages[constraint.package] { guard existing.version == .unversioned else { throw InternalError("Overridden package is not unversioned: \(constraint.package)@\(existing.version)") } existing.products.formUnion(constraint.products) overriddenPackages[constraint.package] = existing } else { overriddenPackages[constraint.package] = (version: .unversioned, products: constraint.products) } for node in constraint.nodes() { // Process dependencies of this package. // // We collect all version-based dependencies in a separate structure so they can // be process at the end. This allows us to override them when there is a non-version // based (unversioned/branch-based) constraint present in the graph. // TODO: replace with async/await when available let container = try temp_await { provider.getContainer(for: node.package, completion: $0) } for dependency in try container.underlying.getUnversionedDependencies(productFilter: node.productFilter) { if let versionedBasedConstraints = VersionBasedConstraint.constraints(dependency) { for constraint in versionedBasedConstraints { versionBasedDependencies[node, default: []].append(constraint) } } else if !overriddenPackages.keys.contains(dependency.package) { // Add the constraint if its not already present. This will ensure we don't // end up looping infinitely due to a cycle (which are diagnosed separately). constraints.append(dependency) } } } } // Process revision-based constraints in the second phase. Here we do the similar processing // as the first phase but we also ignore the constraints that are overridden due to // presence of unversioned constraints. while let constraint = constraints.first(where: { $0.requirement.isRevision }) { guard case .revision(let revision) = constraint.requirement else { throw InternalError("Expected revision requirement") } constraints.remove(constraint) let package = constraint.package // Check if there is an existing value for this package in the overridden packages. switch overriddenPackages[package]?.version { case .excluded?, .version?: // These values are not possible. throw InternalError("Unexpected value for overridden package \(package) in \(overriddenPackages)") case .unversioned?: // This package is overridden by an unversioned package so we can ignore this constraint. continue case .revision(let existingRevision, let branch)?: // If this branch-based package was encountered before, ensure the references match. if (branch ?? existingRevision) != revision { throw PubgrubError.unresolvable("\(package.identity) is required using two different revision-based requirements (\(existingRevision) and \(revision)), which is not supported") } else { // Otherwise, continue since we've already processed this constraint. Any cycles will be diagnosed separately. continue } case nil: break } // Process dependencies of this package, similar to the first phase but branch-based dependencies // are not allowed to contain local/unversioned packages. // TODO: replace with async/await when avail let container = try temp_await { provider.getContainer(for: package, completion: $0) } // If there is a pin for this revision-based dependency, get // the dependencies at the pinned revision instead of using // latest commit on that branch. Note that if this revision-based dependency is // already a commit, then its pin entry doesn't matter in practice. let revisionForDependencies: String if case .branch(revision, let pinRevision) = pinsMap[package.identity]?.state { revisionForDependencies = pinRevision // Mark the package as overridden with the pinned revision and record the branch as well. overriddenPackages[package] = (version: .revision(revisionForDependencies, branch: revision), products: constraint.products) } else { revisionForDependencies = revision // Mark the package as overridden. overriddenPackages[package] = (version: .revision(revision), products: constraint.products) } for node in constraint.nodes() { var unprocessedDependencies = try container.underlying.getDependencies( at: revisionForDependencies, productFilter: constraint.products ) if let sharedRevision = node.revisionLock(revision: revision) { unprocessedDependencies.append(sharedRevision) } for dependency in unprocessedDependencies { switch dependency.requirement { case .versionSet(let req): for node in dependency.nodes() { let versionedBasedConstraint = VersionBasedConstraint(node: node, req: req) versionBasedDependencies[.root(package: constraint.package), default: []].append(versionedBasedConstraint) } case .revision: constraints.append(dependency) case .unversioned: throw DependencyResolverError.revisionDependencyContainsLocalPackage( dependency: package.identity.description, localPackage: dependency.package.identity.description ) } } } } // At this point, we should be left with only version-based requirements in our constraints // list. Add them to our version-based dependency list. for constraint in constraints { switch constraint.requirement { case .versionSet(let req): for node in constraint.nodes() { let versionedBasedConstraint = VersionBasedConstraint(node: node, req: req) versionBasedDependencies[root, default: []].append(versionedBasedConstraint) } case .revision, .unversioned: throw InternalError("Unexpected revision/unversioned requirement in the constraints list: \(constraints)") } } // Finally, compute the root incompatibilities (which will be all version-based). // note versionBasedDependencies may point to the root package dependencies, or the dependencies of root's non-versioned dependencies var rootIncompatibilities: [Incompatibility] = [] for (node, constraints) in versionBasedDependencies { for constraint in constraints { if overriddenPackages.keys.contains(constraint.node.package) { continue } let incompat = try Incompatibility( Term(root, .exact("1.0.0")), Term(not: constraint.node, constraint.requirement), root: root, cause: .dependency(node: node) ) rootIncompatibilities.append(incompat) } } return (overriddenPackages, rootIncompatibilities) } /// Perform unit propagation, resolving conflicts if necessary and making /// decisions if nothing else is left to be done. /// After this method returns `solution` is either populated with a list of /// final version assignments or an error is thrown. private func run(state: State) throws { var next: DependencyResolutionNode? = state.root while let nxt = next { try self.propagate(state: state, node: nxt) // initiate prefetch of known packages that will be used to make the decision on the next step self.provider.prefetch(containers: state.solution.undecided.map { $0.node.package }) // If decision making determines that no more decisions are to be // made, it returns nil to signal that version solving is done. // TODO: replace with async/await when available next = try temp_await { self.makeDecision(state: state, completion: $0) } } } /// Perform unit propagation to derive new assignments based on the current /// partial solution. /// If a conflict is found, the conflicting incompatibility is returned to /// resolve the conflict on. internal func propagate(state: State, node: DependencyResolutionNode) throws { var changed: OrderedCollections.OrderedSet<DependencyResolutionNode> = [node] while !changed.isEmpty { let package = changed.removeFirst() loop: for incompatibility in state.positiveIncompatibilities(for: package)?.reversed() ?? [] { let result = self.propagate(state: state, incompatibility: incompatibility) switch result { case .conflict: let rootCause = try self.resolve(state: state, conflict: incompatibility) let rootCauseResult = self.propagate(state: state, incompatibility: rootCause) guard case .almostSatisfied(let pkg) = rootCauseResult else { throw InternalError(""" Expected root cause \(rootCause) to almost satisfy the \ current partial solution: \(state.solution.assignments.map { " * \($0.description)" }.joined(separator: "\n"))\n """) } changed.removeAll(keepingCapacity: false) changed.append(pkg) break loop case .almostSatisfied(let package): changed.append(package) case .none: break } } } } private func propagate(state: State, incompatibility: Incompatibility) -> PropagationResult { var unsatisfied: Term? for term in incompatibility.terms { let relation = state.solution.relation(with: term) if relation == .disjoint { return .none } else if relation == .overlap { if unsatisfied != nil { return .none } unsatisfied = term } } // We have a conflict if all the terms of the incompatibility were satisfied. guard let unsatisfiedTerm = unsatisfied else { return .conflict } self.delegate?.derived(term: unsatisfiedTerm.inverse) state.derive(unsatisfiedTerm.inverse, cause: incompatibility) return .almostSatisfied(node: unsatisfiedTerm.node) } // Based on: // https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution // https://github.com/dart-lang/pub/blob/master/lib/src/solver/version_solver.dart#L201 internal func resolve(state: State, conflict: Incompatibility) throws -> Incompatibility { self.delegate?.conflict(conflict: conflict) var incompatibility = conflict var createdIncompatibility = false // rdar://93335995 // hard protection from infinite loops let maxIterations = 1000 var iterations: Int = 0 while !isCompleteFailure(incompatibility, root: state.root) { var mostRecentTerm: Term? var mostRecentSatisfier: Assignment? var difference: Term? var previousSatisfierLevel = 0 for term in incompatibility.terms { let satisfier = try state.solution.satisfier(for: term) if let _mostRecentSatisfier = mostRecentSatisfier { let mostRecentSatisfierIdx = state.solution.assignments.firstIndex(of: _mostRecentSatisfier)! let satisfierIdx = state.solution.assignments.firstIndex(of: satisfier)! if mostRecentSatisfierIdx < satisfierIdx { previousSatisfierLevel = max(previousSatisfierLevel, _mostRecentSatisfier.decisionLevel) mostRecentTerm = term mostRecentSatisfier = satisfier difference = nil } else { previousSatisfierLevel = max(previousSatisfierLevel, satisfier.decisionLevel) } } else { mostRecentTerm = term mostRecentSatisfier = satisfier } if mostRecentTerm == term { difference = mostRecentSatisfier?.term.difference(with: term) if let difference = difference { previousSatisfierLevel = max(previousSatisfierLevel, try state.solution.satisfier(for: difference.inverse).decisionLevel) } } } guard let _mostRecentSatisfier = mostRecentSatisfier else { throw InternalError("mostRecentSatisfier not set") } if previousSatisfierLevel < _mostRecentSatisfier.decisionLevel || _mostRecentSatisfier.cause == nil { state.backtrack(toDecisionLevel: previousSatisfierLevel) if createdIncompatibility { state.addIncompatibility(incompatibility, at: .conflictResolution) } return incompatibility } let priorCause = _mostRecentSatisfier.cause! var newTerms = incompatibility.terms.filter { $0 != mostRecentTerm } newTerms += priorCause.terms.filter { $0.node != _mostRecentSatisfier.term.node } if let _difference = difference { // rdar://93335995 // do not add the exact inverse of a requirement as it can lead to endless loops if _difference.inverse != mostRecentTerm { newTerms.append(_difference.inverse) } } incompatibility = try Incompatibility( OrderedCollections.OrderedSet(newTerms), root: state.root, cause: .conflict(cause: .init(conflict: incompatibility, other: priorCause)) ) createdIncompatibility = true if let term = mostRecentTerm { if let diff = difference { self.delegate?.partiallySatisfied(term: term, by: _mostRecentSatisfier, incompatibility: incompatibility, difference: diff) } else { self.delegate?.satisfied(term: term, by: _mostRecentSatisfier, incompatibility: incompatibility) } } // rdar://93335995 // hard protection from infinite loops iterations = iterations + 1 if iterations >= maxIterations { break } } self.delegate?.failedToResolve(incompatibility: incompatibility) throw PubgrubError._unresolvable(incompatibility, state.incompatibilities) } /// Does a given incompatibility specify that version solving has entirely /// failed, meaning this incompatibility is either empty or only for the root /// package. private func isCompleteFailure(_ incompatibility: Incompatibility, root: DependencyResolutionNode) -> Bool { return incompatibility.terms.isEmpty || (incompatibility.terms.count == 1 && incompatibility.terms.first?.node == root) } private func computeCounts(for terms: [Term], completion: @escaping (Result<[Term: Int], Error>) -> Void) { if terms.isEmpty { return completion(.success([:])) } let sync = DispatchGroup() let results = ThreadSafeKeyValueStore<Term, Result<Int, Error>>() terms.forEach { term in sync.enter() provider.getContainer(for: term.node.package) { result in defer { sync.leave() } results[term] = result.flatMap { container in Result(catching: { try container.versionCount(term.requirement) }) } } } sync.notify(queue: .sharedConcurrent) { do { completion(.success(try results.mapValues { try $0.get() })) } catch { completion(.failure(error)) } } } internal func makeDecision(state: State, completion: @escaping (Result<DependencyResolutionNode?, Error>) -> Void) { // If there are no more undecided terms, version solving is complete. let undecided = state.solution.undecided guard !undecided.isEmpty else { return completion(.success(nil)) } // Prefer packages with least number of versions that fit the current requirements so we // get conflicts (if any) sooner. self.computeCounts(for: undecided) { result in do { let start = DispatchTime.now() let counts = try result.get() // forced unwraps safe since we are testing for count and errors above let pkgTerm = undecided.min { counts[$0]! < counts[$1]! }! self.delegate?.willResolve(term: pkgTerm) // at this point the container is cached let container = try self.provider.getCachedContainer(for: pkgTerm.node.package) // Get the best available version for this package. guard let version = try container.getBestAvailableVersion(for: pkgTerm) else { state.addIncompatibility(try Incompatibility(pkgTerm, root: state.root, cause: .noAvailableVersion), at: .decisionMaking) return completion(.success(pkgTerm.node)) } // Add all of this version's dependencies as incompatibilities. let depIncompatibilities = try container.incompatibilites( at: version, node: pkgTerm.node, overriddenPackages: state.overriddenPackages, root: state.root ) var haveConflict = false for incompatibility in depIncompatibilities { // Add the incompatibility to our partial solution. state.addIncompatibility(incompatibility, at: .decisionMaking) // Check if this incompatibility will satisfy the solution. haveConflict = haveConflict || incompatibility.terms.allSatisfy { // We only need to check if the terms other than this package // are satisfied because we _know_ that the terms matching // this package will be satisfied if we make this version // as a decision. $0.node == pkgTerm.node || state.solution.satisfies($0) } } // Decide this version if there was no conflict with its dependencies. if !haveConflict { self.delegate?.didResolve(term: pkgTerm, version: version, duration: start.distance(to: .now())) state.decide(pkgTerm.node, at: version) } completion(.success(pkgTerm.node)) } catch { completion(.failure(error)) } } } } private struct DiagnosticReportBuilder { let rootNode: DependencyResolutionNode let incompatibilities: [DependencyResolutionNode: [Incompatibility]] private var lines: [(number: Int, message: String)] = [] private var derivations: [Incompatibility: Int] = [:] private var lineNumbers: [Incompatibility: Int] = [:] private let provider: ContainerProvider init(root: DependencyResolutionNode, incompatibilities: [DependencyResolutionNode: [Incompatibility]], provider: ContainerProvider) { self.rootNode = root self.incompatibilities = incompatibilities self.provider = provider } mutating func makeErrorReport(for rootCause: Incompatibility) throws -> String { /// Populate `derivations`. func countDerivations(_ i: Incompatibility) { self.derivations[i, default: 0] += 1 if case .conflict(let cause) = i.cause { countDerivations(cause.conflict) countDerivations(cause.other) } } countDerivations(rootCause) if rootCause.cause.isConflict { try self.visit(rootCause) } else { assertionFailure("Unimplemented") self.record( rootCause, message: try description(for: rootCause), isNumbered: false ) } let stream = BufferedOutputByteStream() let padding = lineNumbers.isEmpty ? 0 : "\(Array(lineNumbers.values).last!) ".count for (idx, line) in lines.enumerated() { stream <<< Format.asRepeating(string: " ", count: padding) if line.number != -1 { stream <<< Format.asRepeating(string: " ", count: padding) stream <<< " (\(line.number)) " } stream <<< line.message.prefix(1).capitalized stream <<< line.message.dropFirst() if lines.count - 1 != idx { stream <<< "\n" } } return stream.bytes.description } private mutating func visit( _ incompatibility: Incompatibility, isConclusion: Bool = false ) throws { let isNumbered = isConclusion || derivations[incompatibility]! > 1 let conjunction = isConclusion || incompatibility.cause == .root ? "As a result, " : "" let incompatibilityDesc = try description(for: incompatibility) guard case .conflict(let cause) = incompatibility.cause else { assertionFailure("\(incompatibility)") return } if cause.conflict.cause.isConflict && cause.other.cause.isConflict { let conflictLine = lineNumbers[cause.conflict] let otherLine = lineNumbers[cause.other] if let conflictLine = conflictLine, let otherLine = otherLine { self.record( incompatibility, message: "\(incompatibilityDesc) because \(try description(for: cause.conflict)) (\(conflictLine)) and \(try description(for: cause.other)) (\(otherLine).", isNumbered: isNumbered ) } else if conflictLine != nil || otherLine != nil { let withLine: Incompatibility let withoutLine: Incompatibility let line: Int if let conflictLine = conflictLine { withLine = cause.conflict withoutLine = cause.other line = conflictLine } else { withLine = cause.other withoutLine = cause.conflict line = otherLine! } try self.visit(withoutLine) self.record( incompatibility, message: "\(conjunction)\(incompatibilityDesc) because \(try description(for: withLine)) \(line).", isNumbered: isNumbered ) } else { let singleLineConflict = cause.conflict.cause.isSingleLine let singleLineOther = cause.other.cause.isSingleLine if singleLineOther || singleLineConflict { let first = singleLineOther ? cause.conflict : cause.other let second = singleLineOther ? cause.other : cause.conflict try self.visit(first) try self.visit(second) self.record( incompatibility, message: "\(incompatibilityDesc).", isNumbered: isNumbered ) } else { try self.visit(cause.conflict, isConclusion: true) try self.visit(cause.other) self.record( incompatibility, message: "\(conjunction)\(incompatibilityDesc) because \(try description(for: cause.conflict)) (\(lineNumbers[cause.conflict]!)).", isNumbered: isNumbered ) } } } else if cause.conflict.cause.isConflict || cause.other.cause.isConflict { let derived = cause.conflict.cause.isConflict ? cause.conflict : cause.other let ext = cause.conflict.cause.isConflict ? cause.other : cause.conflict let derivedLine = lineNumbers[derived] if let derivedLine = derivedLine { self.record( incompatibility, message: "\(incompatibilityDesc) because \(try description(for: ext)) and \(try description(for: derived)) (\(derivedLine)).", isNumbered: isNumbered ) } else if isCollapsible(derived) { guard case .conflict(let derivedCause) = derived.cause else { assertionFailure("unreachable") return } let collapsedDerived = derivedCause.conflict.cause.isConflict ? derivedCause.conflict : derivedCause.other let collapsedExt = derivedCause.conflict.cause.isConflict ? derivedCause.other : derivedCause.conflict try self.visit(collapsedDerived) self.record( incompatibility, message: "\(conjunction)\(incompatibilityDesc) because \(try description(for: collapsedExt)) and \(try description(for: ext)).", isNumbered: isNumbered ) } else { try self.visit(derived) self.record( incompatibility, message: "\(conjunction)\(incompatibilityDesc) because \(try description(for: ext)).", isNumbered: isNumbered ) } } else { self.record( incompatibility, message: "\(incompatibilityDesc) because \(try description(for: cause.conflict)) and \(try description(for: cause.other)).", isNumbered: isNumbered ) } } private func description(for incompatibility: Incompatibility) throws -> String { switch incompatibility.cause { case .dependency(let causeNode): assert(incompatibility.terms.count == 2) let depender = incompatibility.terms.first! let dependee = incompatibility.terms.last! assert(depender.isPositive) assert(!dependee.isPositive) let dependerDesc: String // when depender is the root node, the causeNode may be different as it may represent root's indirect dependencies (e.g. dependencies of root's unversioned dependencies) if depender.node == self.rootNode, causeNode != self.rootNode { dependerDesc = causeNode.nameForDiagnostics } else { dependerDesc = try description(for: depender, normalizeRange: true) } let dependeeDesc = try description(for: dependee) return "\(dependerDesc) depends on \(dependeeDesc)" case .noAvailableVersion: assert(incompatibility.terms.count == 1) let term = incompatibility.terms.first! assert(term.isPositive) return "no versions of \(term.node.nameForDiagnostics) match the requirement \(term.requirement)" case .root: // FIXME: This will never happen I think. assert(incompatibility.terms.count == 1) let term = incompatibility.terms.first! assert(term.isPositive) return "\(term.node.nameForDiagnostics) is \(term.requirement)" case .conflict where incompatibility.terms.count == 1 && incompatibility.terms.first?.node == self.rootNode: return "dependencies could not be resolved" case .conflict: break case .versionBasedDependencyContainsUnversionedDependency(let versionedDependency, let unversionedDependency): return "package '\(versionedDependency.identity)' is required using a stable-version but '\(versionedDependency.identity)' depends on an unstable-version package '\(unversionedDependency.identity)'" case .incompatibleToolsVersion(let version): let term = incompatibility.terms.first! return "\(try description(for: term, normalizeRange: true)) contains incompatible tools version (\(version))" } let terms = incompatibility.terms if terms.count == 1 { let term = terms.first! let prefix = try hasEffectivelyAnyRequirement(term) ? term.node.nameForDiagnostics : description(for: term, normalizeRange: true) return "\(prefix) " + (term.isPositive ? "cannot be used" : "is required") } else if terms.count == 2 { let term1 = terms.first! let term2 = terms.last! if term1.isPositive == term2.isPositive { if term1.isPositive { return "\(term1.node.nameForDiagnostics) is incompatible with \(term2.node.nameForDiagnostics)" } else { return "either \(term1.node.nameForDiagnostics) or \(term2)" } } } let positive = try terms.filter { $0.isPositive }.map { try description(for: $0) } let negative = try terms.filter { !$0.isPositive }.map { try description(for: $0) } if !positive.isEmpty, !negative.isEmpty { if positive.count == 1 { let positiveTerm = terms.first { $0.isPositive }! return "\(try description(for: positiveTerm, normalizeRange: true)) practically depends on \(negative.joined(separator: " or "))" } else { return "if \(positive.joined(separator: " and ")) then \(negative.joined(separator: " or "))" } } else if !positive.isEmpty { return "one of \(positive.joined(separator: " or ")) must be true" } else { return "one of \(negative.joined(separator: " or ")) must be true" } } /// Returns true if the requirement on this term is effectively "any" because of either the actual /// `any` requirement or because the version range is large enough to fit all current available versions. private func hasEffectivelyAnyRequirement(_ term: Term) throws -> Bool { switch term.requirement { case .any: return true case .empty, .exact, .ranges: return false case .range(let range): // container expected to be cached at this point guard let container = try? provider.getCachedContainer(for: term.node.package) else { return false } let bounds = try container.computeBounds(for: range) return !bounds.includesLowerBound && !bounds.includesUpperBound } } private func isCollapsible(_ incompatibility: Incompatibility) -> Bool { if derivations[incompatibility]! > 1 { return false } guard case .conflict(let cause) = incompatibility.cause else { assertionFailure("unreachable") return false } if cause.conflict.cause.isConflict, cause.other.cause.isConflict { return false } if !cause.conflict.cause.isConflict, !cause.other.cause.isConflict { return false } let complex = cause.conflict.cause.isConflict ? cause.conflict : cause.other return !lineNumbers.keys.contains(complex) } private func description(for term: Term, normalizeRange: Bool = false) throws -> String { let name = term.node.nameForDiagnostics switch term.requirement { case .any: return name case .empty: return "no version of \(name)" case .exact(let version): // For the root package, don't output the useless version 1.0.0. if term.node == rootNode { return "root" } return "\(name) \(version)" case .range(let range): // container expected to be cached at this point guard normalizeRange, let container = try? provider.getCachedContainer(for: term.node.package) else { return "\(name) \(range.description)" } switch try container.computeBounds(for: range) { case (true, true): return "\(name) \(range.description)" case (false, false): return name case (true, false): return "\(name) >= \(range.lowerBound)" case (false, true): return "\(name) < \(range.upperBound)" } case .ranges(let ranges): let ranges = "{" + ranges.map { if $0.lowerBound == $0.upperBound { return $0.lowerBound.description } return $0.lowerBound.description + "..<" + $0.upperBound.description }.joined(separator: ", ") + "}" return "\(name) \(ranges)" } } /// Write a given output message to a stream. The message should describe /// the incompatibility and how it as derived. If `isNumbered` is true, a /// line number will be assigned to this incompatibility so that it can be /// referred to again. private mutating func record( _ incompatibility: Incompatibility, message: String, isNumbered: Bool ) { var number = -1 if isNumbered { number = lineNumbers.count + 1 self.lineNumbers[incompatibility] = number } let line = (number: number, message: message) if isNumbered { self.lines.append(line) } else { self.lines.insert(line, at: 0) } } } // MARK: - Container Management /// A container for an individual package. This enhances PackageContainer to add PubGrub specific /// logic which is mostly related to computing incompatibilities at a particular version. internal final class PubGrubPackageContainer { /// The underlying package container. let underlying: PackageContainer /// Reference to the pins map. private let pinsMap: PinsStore.PinsMap init(underlying: PackageContainer, pinsMap: PinsStore.PinsMap) { self.underlying = underlying self.pinsMap = pinsMap } var package: PackageReference { self.underlying.package } /// Returns the pinned version for this package, if any. var pinnedVersion: Version? { switch self.pinsMap[self.underlying.package.identity]?.state { case .version(let version, _): return version default: return .none } } /// Returns the numbers of versions that are satisfied by the given version requirement. func versionCount(_ requirement: VersionSetSpecifier) throws -> Int { if let pinnedVersion = self.pinnedVersion, requirement.contains(pinnedVersion) { return 1 } return try self.underlying.versionsDescending().filter(requirement.contains).count } /// Computes the bounds of the given range against the versions available in the package. /// /// `includesLowerBound` is `false` if range's lower bound is less than or equal to the lowest available version. /// Similarly, `includesUpperBound` is `false` if range's upper bound is greater than or equal to the highest available version. func computeBounds(for range: Range<Version>) throws -> (includesLowerBound: Bool, includesUpperBound: Bool) { var includeLowerBound = true var includeUpperBound = true let versions = try self.underlying.versionsDescending() if let last = versions.last, range.lowerBound < last { includeLowerBound = false } if let first = versions.first, range.upperBound > first { includeUpperBound = false } return (includeLowerBound, includeUpperBound) } /// Returns the best available version for a given term. func getBestAvailableVersion(for term: Term) throws -> Version? { assert(term.isPositive, "Expected term to be positive") let versionSet = term.requirement // Restrict the selection to the pinned version if is allowed by the current requirements. if let pinnedVersion = self.pinnedVersion { if versionSet.contains(pinnedVersion) { // Make sure the pinned version is still available let version = try self.underlying.versionsDescending().first { pinnedVersion == $0 } if version != nil { return version } } } // Return the highest version that is allowed by the input requirement. return try self.underlying.versionsDescending().first { versionSet.contains($0) } } /// Compute the bounds of incompatible tools version starting from the given version. private func computeIncompatibleToolsVersionBounds(fromVersion: Version) throws -> VersionSetSpecifier { assert(!self.underlying.isToolsVersionCompatible(at: fromVersion)) let versions: [Version] = try self.underlying.versionsAscending() // This is guaranteed to be present. let idx = versions.firstIndex(of: fromVersion)! var lowerBound = fromVersion var upperBound = fromVersion for version in versions.dropFirst(idx + 1) { let isToolsVersionCompatible = self.underlying.isToolsVersionCompatible(at: version) if isToolsVersionCompatible { break } upperBound = version } for version in versions.dropLast(versions.count - idx).reversed() { let isToolsVersionCompatible = self.underlying.isToolsVersionCompatible(at: version) if isToolsVersionCompatible { break } lowerBound = version } // If lower and upper bounds didn't change then this is the sole incompatible version. if lowerBound == upperBound { return .exact(lowerBound) } // If lower bound is the first version then we can use 0 as the sentinel. This // will end up producing a better diagnostic since we can omit the lower bound. if lowerBound == versions.first { lowerBound = "0.0.0" } if upperBound == versions.last { // If upper bound is the last version then we can use the next major version as the sentinel. // This will end up producing a better diagnostic since we can omit the upper bound. upperBound = Version(upperBound.major + 1, 0, 0) } else { // Use the next patch since the upper bound needs to be inclusive here. upperBound = upperBound.nextPatch() } return .range(lowerBound ..< upperBound.nextPatch()) } /// Returns the incompatibilities of a package at the given version. func incompatibilites( at version: Version, node: DependencyResolutionNode, overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)], root: DependencyResolutionNode ) throws -> [Incompatibility] { // FIXME: It would be nice to compute bounds for this as well. if !self.underlying.isToolsVersionCompatible(at: version) { let requirement = try self.computeIncompatibleToolsVersionBounds(fromVersion: version) let toolsVersion = try self.underlying.toolsVersion(for: version) return [try Incompatibility(Term(node, requirement), root: root, cause: .incompatibleToolsVersion(toolsVersion))] } var unprocessedDependencies = try self.underlying.getDependencies(at: version, productFilter: node.productFilter) if let sharedVersion = node.versionLock(version: version) { unprocessedDependencies.append(sharedVersion) } var constraints: [PackageContainerConstraint] = [] for dep in unprocessedDependencies { // Version-based packages are not allowed to contain unversioned dependencies. guard case .versionSet = dep.requirement else { let cause: Incompatibility.Cause = .versionBasedDependencyContainsUnversionedDependency( versionedDependency: package, unversionedDependency: dep.package ) return [try Incompatibility(Term(node, .exact(version)), root: root, cause: cause)] } // Skip if this package is overridden. if overriddenPackages.keys.contains(dep.package) { continue } for node in dep.nodes() { constraints.append( PackageContainerConstraint( package: node.package, requirement: dep.requirement, products: node.productFilter ) ) } } return try constraints.flatMap { constraint -> [Incompatibility] in // We only have version-based requirements at this point. guard case .versionSet(let constraintRequirement) = constraint.requirement else { throw InternalError("Unexpected unversioned requirement: \(constraint)") } return try constraint.nodes().compactMap { constraintNode in // cycle guard node != constraintNode else { return nil } var terms: OrderedCollections.OrderedSet<Term> = [] // the package version requirement terms.append(Term(node, .exact(version))) // the dependency's version requirement terms.append(Term(not: constraintNode, constraintRequirement)) return try Incompatibility(terms, root: root, cause: .dependency(node: node)) } } } } /// An utility class around PackageContainerProvider that allows "prefetching" the containers /// in parallel. The basic idea is to kick off container fetching before starting the resolution /// by using the list of URLs from the Package.resolved file. private final class ContainerProvider { /// The actual package container provider. private let underlying: PackageContainerProvider /// Whether to perform update (git fetch) on existing cloned repositories or not. private let skipUpdate: Bool /// Reference to the pins store. private let pinsMap: PinsStore.PinsMap /// Observability scope to emit diagnostics with private let observabilityScope: ObservabilityScope //// Store cached containers private var containersCache = ThreadSafeKeyValueStore<PackageReference, PubGrubPackageContainer>() //// Store prefetches synchronization private var prefetches = ThreadSafeKeyValueStore<PackageReference, DispatchGroup>() init( provider underlying: PackageContainerProvider, skipUpdate: Bool, pinsMap: PinsStore.PinsMap, observabilityScope: ObservabilityScope ) { self.underlying = underlying self.skipUpdate = skipUpdate self.pinsMap = pinsMap self.observabilityScope = observabilityScope } /// Get a cached container for the given identifier, asserting / throwing if not found. func getCachedContainer(for package: PackageReference) throws -> PubGrubPackageContainer { guard let container = self.containersCache[package] else { throw InternalError("container for \(package.identity) expected to be cached") } return container } /// Get the container for the given identifier, loading it if necessary. func getContainer(for package: PackageReference, completion: @escaping (Result<PubGrubPackageContainer, Error>) -> Void) { // Return the cached container, if available. if let container = self.containersCache[package], package.equalsIncludingLocation(container.package) { return completion(.success(container)) } if let prefetchSync = self.prefetches[package] { // If this container is already being prefetched, wait for that to complete prefetchSync.notify(queue: .sharedConcurrent) { if let container = self.containersCache[package], package.equalsIncludingLocation(container.package) { // should be in the cache once prefetch completed return completion(.success(container)) } else { // if prefetch failed, remove from list of prefetches and try again self.prefetches[package] = nil return self.getContainer(for: package, completion: completion) } } } else { // Otherwise, fetch the container from the provider self.underlying.getContainer( for: package, skipUpdate: self.skipUpdate, observabilityScope: self.observabilityScope, on: .sharedConcurrent ) { result in let result = result.tryMap { container -> PubGrubPackageContainer in let pubGrubContainer = PubGrubPackageContainer(underlying: container, pinsMap: self.pinsMap) // only cache positive results self.containersCache[package] = pubGrubContainer return pubGrubContainer } completion(result) } } } /// Starts prefetching the given containers. func prefetch(containers identifiers: [PackageReference]) { // Process each container. for identifier in identifiers { var needsFetching = false self.prefetches.memoize(identifier) { let group = DispatchGroup() group.enter() needsFetching = true return group } if needsFetching { self.underlying.getContainer( for: identifier, skipUpdate: self.skipUpdate, observabilityScope: self.observabilityScope, on: .sharedConcurrent ) { result in defer { self.prefetches[identifier]?.leave() } // only cache positive results if case .success(let container) = result { self.containersCache[identifier] = PubGrubPackageContainer(underlying: container, pinsMap: self.pinsMap) } } } } } } internal enum LogLocation: String { case topLevel = "top level" case unitPropagation = "unit propagation" case decisionMaking = "decision making" case conflictResolution = "conflict resolution" } extension PubgrubDependencyResolver { public enum PubgrubError: Swift.Error, CustomStringConvertible { case _unresolvable(Incompatibility, [DependencyResolutionNode: [Incompatibility]]) case unresolvable(String) public var description: String { switch self { case ._unresolvable(let rootCause, _): return rootCause.description case .unresolvable(let error): return error } } var rootCause: Incompatibility? { switch self { case ._unresolvable(let rootCause, _): return rootCause case .unresolvable: return nil } } var incompatibilities: [DependencyResolutionNode: [Incompatibility]]? { switch self { case ._unresolvable(_, let incompatibilities): return incompatibilities case .unresolvable: return nil } } } } extension PubgrubDependencyResolver { private struct VersionBasedConstraint { let node: DependencyResolutionNode let requirement: VersionSetSpecifier init(node: DependencyResolutionNode, req: VersionSetSpecifier) { self.node = node self.requirement = req } internal static func constraints(_ constraint: Constraint) -> [VersionBasedConstraint]? { switch constraint.requirement { case .versionSet(let req): return constraint.nodes().map { VersionBasedConstraint(node: $0, req: req) } case .revision: return nil case .unversioned: return nil } } } } private enum PropagationResult { case conflict case almostSatisfied(node: DependencyResolutionNode) case none } private extension PackageRequirement { var isRevision: Bool { switch self { case .versionSet, .unversioned: return false case .revision: return true } } } private extension DependencyResolutionNode { var nameForDiagnostics: String { return "'\(self.package.identity)'" } }
apache-2.0
e9988cbcc06ea290f1d88e3819835c34
43.247408
210
0.6006
5.3453
false
false
false
false
kickstarter/ios-oss
KsApi/models/templates/CommentsEnvelopeTemplates.swift
1
1233
import Prelude extension CommentsEnvelope { internal static let singleCommentTemplate = CommentsEnvelope( comments: [Comment.template], cursor: nil, hasNextPage: false, slug: "slug", totalCount: 1 ) internal static let multipleCommentTemplate = CommentsEnvelope( comments: [Comment.template, Comment.superbackerTemplate], cursor: nil, hasNextPage: false, slug: "slug", totalCount: 2 ) internal static let failedRemovedSuccessfulCommentsTemplate = CommentsEnvelope( comments: [ Comment.failedTemplate, Comment.deletedTemplate, Comment.superbackerTemplate, Comment.backerTemplate ], cursor: nil, hasNextPage: false, slug: "slug", totalCount: 4 ) internal static let emptyCommentsTemplate = CommentsEnvelope( comments: [], cursor: nil, hasNextPage: false, slug: "slug", totalCount: 0 ) internal static let successFailedRetryingRetrySuccessCommentsTemplate = CommentsEnvelope( comments: [ .failedTemplate |> \.status .~ .success, .failedTemplate, .retryingTemplate, .retrySuccessTemplate ], cursor: nil, hasNextPage: false, slug: "slug", totalCount: 4 ) }
apache-2.0
b4b69f9ac43891c75f914fff45bdbc18
22.264151
91
0.680454
4.549815
false
false
false
false
dbgrandi/EulerKit
autoRegister.swift
1
2105
// // main.swift // euler // // Created by David Grandinetti on 8/27/14. // Copyright (c) 2014 David Grandinetti. All rights reserved. // import Foundation @objc class EulerProblemDict { @objc class var sharedInstance : Dictionary<Int,String> { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : Dictionary<Int,String>? = nil } dispatch_once(&Static.onceToken) { println("EulerProblemDict: init static dictionary") Static.instance = Dictionary<Int,String>() } return Static.instance! } class func load() { println("EulerProblemDict: +load()") EulerProblemDict.sharedInstance } } @objc class EulerProblem { class func load() { let clazz = NSStringFromClass(self).componentsSeparatedByString(".").last! println("EulerProblem: +load() for class = \(clazz)") if let problemNumber:String = clazz.componentsSeparatedByString("Problem").last { if let num = problemNumber.toInt() { var dict = EulerProblemDict.sharedInstance dict[num] = clazz println("problem[\(num)] = \(clazz)") } } } class func run() { println("OVERRIDE ME") } class func allProblems() -> Dictionary<Int,String> { return EulerProblemDict.sharedInstance } } class Problem1: EulerProblem { override class func load() { let clazz = NSStringFromClass(self).componentsSeparatedByString(".").last! println("EulerProblem: +load() for class = \(clazz)") if let problemNumber:String = clazz.componentsSeparatedByString("Problem").last { if let num = problemNumber.toInt() { var dict = EulerProblemDict.sharedInstance dict[num] = clazz println("problem[\(num)] = \(clazz)") } } } override class func run() { println("Problem1: RUNNING") } } class Problem2: EulerProblem { override class func load() { super.load() } override class func run() { println("Problem2: RUNNING") } } println("Main: running") var dict = EulerProblemDict.sharedInstance Problem2.run() println("Main: \(dict.count)")
mit
523619b07c683af529b9b458fe833f1f
23.476744
85
0.657482
4.087379
false
false
false
false
Alterplay/APKenBurnsView
Pod/Classes/Private/FaceRecognition/FacesDrawer.swift
1
2584
// // Created by Nickolay Sheika on 6/11/16. // import Foundation import UIKit protocol FacesDrawerProtocol { func drawFacesInView(view: UIView, image: UIImage) func cleanUpForView(view: UIView) } class FacesDrawer: FacesDrawerProtocol { // MARK: - Public Variables var faceColor: UIColor = UIColor.red var faceAlpha: CGFloat = 0.2 // MARK: - Private Variables private var facesViews = [Int: [UIView]]() // MARK: - Public func drawFacesInView(view: UIView, image: UIImage) { cleanUpForView(view: view) DispatchQueue.global(qos: .default).async { let allFacesRects = image.allFacesRects() DispatchQueue.main.async { guard allFacesRects.count > 0 else { return } self.facesViews[view.hashValue] = [] let viewPortSize = view.bounds let imageCenter = CGPoint(x: viewPortSize.size.width / 2, y: viewPortSize.size.height / 2) let imageFrame = CGRect(center: imageCenter, size: image.size) for faceRect in allFacesRects { let faceRectConverted = self.convertFaceRect(faceRect: faceRect, inImageCoordinates: imageFrame.origin) let faceView = self.buildFaceViewWithFrame(frame: faceRectConverted) self.facesViews[view.hashValue]!.append(faceView) view.addSubview(faceView) } } } } func cleanUpForView(view: UIView) { guard let facesForView = facesViews[view.hashValue] else { return } for faceView in facesForView { faceView.removeFromSuperview() } facesViews[view.hashValue] = nil } // MARK: - Private private func convertFaceRect(faceRect: CGRect, inImageCoordinates imageOrigin: CGPoint) -> CGRect { let faceRectConvertedX = imageOrigin.x + faceRect.origin.x let faceRectConvertedY = imageOrigin.y + faceRect.origin.y let faceRectConverted = CGRect(x: faceRectConvertedX, y: faceRectConvertedY, width: faceRect.size.width, height: faceRect.size.height) return faceRectConverted.integral } private func buildFaceViewWithFrame(frame: CGRect) -> UIView { let faceView = UIView(frame: frame) faceView.translatesAutoresizingMaskIntoConstraints = false faceView.backgroundColor = faceColor faceView.alpha = faceAlpha return faceView } }
mit
affa1f5cfa9ad07fbf4280cc1a932550
28.363636
142
0.618034
4.70674
false
false
false
false
Quick/Spry
Source/Spry/Spry.swift
1
647
// // EqualTests.swift // Spry // // Created by Shaps Benkau on 22/02/2017. // // import Foundation public func expect<T>(_ expression: (@autoclosure @escaping () throws -> T?)) -> Expectation<T> { return Expectation(expression: Expression(expression: expression)) } #if os(iOS) import UIKit public typealias Color = UIColor #else import Cocoa public typealias Color = NSColor #endif extension Color { public var expectationResult: Bool { return self == .green ? true : false } } extension Bool { public var expectationResult: Color { return self ? .green : .red } } public typealias ExpectationResult = Color
apache-2.0
0078cc0e9c80acfaed964f6353f076a4
19.870968
97
0.689335
3.874251
false
false
false
false
johnno1962d/swift
benchmark/single-source/StaticArray.swift
3
3186
//===--- StaticArray.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // We use this test to benchmark the compile time and analyze the code // generation of struct initializers. //===----------------------------------------------------------------------===// import TestsUtils protocol StaticArrayProtocol { associatedtype ElemTy init(_ defaultValue : ElemTy) func get(_ idx : Int) -> ElemTy mutating func set(_ idx : Int,_ val : ElemTy) func count() -> Int } struct A0<ElemTy> : StaticArrayProtocol { init(_ defaultValue : ElemTy) { x = defaultValue } var x : ElemTy func get(_ idx : Int) -> ElemTy { if idx == 0 { return x } else { fatalError("oob"); } } mutating func set(_ idx : Int,_ val : ElemTy) { if idx == 0 { x = val }} func count() -> Int { return 1} } struct A2X<T : StaticArrayProtocol> : StaticArrayProtocol { init(_ defaultValue : T.ElemTy) { lower = T(defaultValue); upper = T(defaultValue) } var lower : T var upper : T func get(_ idx: Int) -> T.ElemTy { let size = lower.count(); if idx < size { return lower.get(idx) } else { return upper.get(idx - size) }} mutating func set(_ idx: Int,_ val : T.ElemTy) {let size = lower.count(); if idx < size { return lower.set(idx, val) } else { return upper.set(idx - size, val) }} func count() -> Int { return upper.count() + lower.count() } } struct StaticArray<T : StaticArrayProtocol> : StaticArrayProtocol, MutableCollection { init(_ defaultValue : T.ElemTy) { values = T(defaultValue) } var values : T func get(_ idx: Int) -> T.ElemTy { return values.get(idx) } mutating func set(_ idx: Int,_ val : T.ElemTy) { return values.set(idx, val) } func count() -> Int { return values.count() } typealias Index = Int let startIndex: Int = 0 var endIndex: Int { return count()} subscript(idx: Int) -> T.ElemTy { get { return get(idx) } set(val) { set(idx, val) } } typealias Iterator = IndexingIterator<StaticArray> } typealias SA2Int = StaticArray<A0<Int>> typealias SA4Int = StaticArray<A2X<A0<Int>>> typealias SA8Int = StaticArray<A2X<A2X<A0<Int>>>> typealias SA16Int = StaticArray<A2X<A2X<A2X<A0<Int>>>>> typealias SA32Int = StaticArray<A2X<A2X<A2X<A2X<A0<Int>>>>>> typealias SA64Int = StaticArray<A2X<A2X<A2X<A2X<A2X<A0<Int>>>>>>> typealias SA128Int = StaticArray<A2X<A2X<A2X<A2X<A2X<A2X<A0<Int>>>>>>>> // Make sure the optimizer does not optimize the compute away. @inline(never) public func sink(_ value: Int) { if False() { print(value) }} @inline(never) public func run_StaticArray(_ N: Int) { for _ in 1...N { var staticArray = SA128Int(0) for i in 0..<staticArray.count() { staticArray[i] = i ^ 123 } staticArray.sort() sink(staticArray[0]) } }
apache-2.0
f0669a10c275f438fd0a433a55bf7b6a
34.797753
164
0.6199
3.436893
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/ColumnarCollectionViewLayout.swift
1
14055
public protocol ColumnarCollectionViewLayoutDelegate { func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate func collectionView(_ collectionView: UICollectionView, estimatedHeightForFooterInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate func collectionView(_ collectionView: UICollectionView, shouldShowFooterForSection section: Int) -> Bool func metrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics } public class ColumnarCollectionViewLayout: UICollectionViewLayout { var info: ColumnarCollectionViewLayoutInfo? { didSet { oldInfo = oldValue } } var oldInfo: ColumnarCollectionViewLayoutInfo? var metrics: ColumnarCollectionViewLayoutMetrics? var isLayoutValid: Bool = false let defaultColumnWidth: CGFloat = 315 let maxColumnWidth: CGFloat = 740 public var slideInNewContentFromTheTop: Bool = false public var animateItems: Bool = false override public class var layoutAttributesClass: Swift.AnyClass { return ColumnarCollectionViewLayoutAttributes.self } override public class var invalidationContextClass: Swift.AnyClass { return ColumnarCollectionViewLayoutInvalidationContext.self } private var delegate: ColumnarCollectionViewLayoutDelegate? { return collectionView?.delegate as? ColumnarCollectionViewLayoutDelegate } override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let sections = info?.sections else { return [] } var attributes: [UICollectionViewLayoutAttributes] = [] for section in sections { guard rect.intersects(section.frame) else { continue } for item in section.headers { guard rect.intersects(item.frame) else { continue } attributes.append(item) } for item in section.items { guard rect.intersects(item.frame) else { continue } attributes.append(item) } for item in section.footers { guard rect.intersects(item.frame) else { continue } attributes.append(item) } } return attributes } override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return info?.layoutAttributesForItem(at: indexPath) } public override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return nil } public override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return info?.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath) } public var itemLayoutMargins: UIEdgeInsets { guard let metrics = metrics else { return .zero } return metrics.itemLayoutMargins } override public var collectionViewContentSize: CGSize { guard let info = info else { return .zero } return info.contentSize } public func layoutHeight(forWidth width: CGFloat) -> CGFloat { guard let collectionView = collectionView, let delegate = delegate, width >= 1 else { return 0 } let oldMetrics = metrics let newInfo = ColumnarCollectionViewLayoutInfo() let newMetrics = delegate.metrics(with: CGSize(width: width, height: 100), readableWidth: width, layoutMargins: .zero) metrics = newMetrics // needs to be set so that layout margins can be queried. probably not the best solution. newInfo.layout(with: newMetrics, delegate: delegate, collectionView: collectionView, invalidationContext: nil) metrics = oldMetrics return newInfo.contentSize.height } override public func prepare() { defer { super.prepare() } guard let collectionView = collectionView else { return } let size = collectionView.bounds.size guard size.width > 0 && size.height > 0 else { return } let readableWidth: CGFloat = collectionView.readableContentGuide.layoutFrame.size.width if let metrics = metrics, !metrics.readableWidth.isEqual(to: readableWidth) { isLayoutValid = false } guard let delegate = delegate, !isLayoutValid else { return } let delegateMetrics = delegate.metrics(with: size, readableWidth: readableWidth, layoutMargins: collectionView.layoutMargins) metrics = delegateMetrics let newInfo = ColumnarCollectionViewLayoutInfo() newInfo.layout(with: delegateMetrics, delegate: delegate, collectionView: collectionView, invalidationContext: nil) info = newInfo isLayoutValid = true } // MARK: - Invalidation override public func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { defer { super.invalidateLayout(with: context) } guard let context = context as? ColumnarCollectionViewLayoutInvalidationContext else { return } guard context.invalidateEverything || context.invalidateDataSourceCounts || context.boundsDidChange else { return } isLayoutValid = false } override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { guard let metrics = metrics else { return true } return !newBounds.size.width.isEqual(to: metrics.boundsSize.width) } override public func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext { let superContext = super.invalidationContext(forBoundsChange: newBounds) let context = superContext as? ColumnarCollectionViewLayoutInvalidationContext ?? ColumnarCollectionViewLayoutInvalidationContext() context.boundsDidChange = true return context } override public func shouldInvalidateLayout(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> Bool { return !preferredAttributes.frame.equalTo(originalAttributes.frame) } override public func invalidationContext(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext { let superContext = super.invalidationContext(forPreferredLayoutAttributes: preferredAttributes, withOriginalAttributes: originalAttributes) let context = superContext as? ColumnarCollectionViewLayoutInvalidationContext ?? ColumnarCollectionViewLayoutInvalidationContext() context.preferredLayoutAttributes = preferredAttributes context.originalLayoutAttributes = originalAttributes if let delegate = delegate, let metrics = metrics, let info = info, let collectionView = collectionView { info.update(with: metrics, invalidationContext: context, delegate: delegate, collectionView: collectionView) } return context } // MARK: - Animation var maxNewSection: Int = -1 var newSectionDeltaY: CGFloat = 0 var appearingIndexPaths: Set<IndexPath> = [] var disappearingIndexPaths: Set<IndexPath> = [] override public func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) { super.prepare(forCollectionViewUpdates: updateItems) guard animateItems, let info = info else { appearingIndexPaths.removeAll(keepingCapacity: true) disappearingIndexPaths.removeAll(keepingCapacity: true) maxNewSection = -1 newSectionDeltaY = 0 return } if slideInNewContentFromTheTop { var maxSection = -1 for updateItem in updateItems { guard let after = updateItem.indexPathAfterUpdate, after.item == NSNotFound, updateItem.indexPathBeforeUpdate == nil else { continue } let section: Int = after.section guard section == maxSection + 1 else { continue } maxSection = section } guard maxSection > -1 && maxSection < info.sections.count else { maxNewSection = -1 return } maxNewSection = maxSection let sectionFrame = info.sections[maxSection].frame newSectionDeltaY = 0 - sectionFrame.maxY appearingIndexPaths.removeAll(keepingCapacity: true) disappearingIndexPaths.removeAll(keepingCapacity: true) } else { appearingIndexPaths.removeAll(keepingCapacity: true) disappearingIndexPaths.removeAll(keepingCapacity: true) newSectionDeltaY = 0 maxNewSection = -1 for updateItem in updateItems { if let after = updateItem.indexPathAfterUpdate, updateItem.indexPathBeforeUpdate == nil { appearingIndexPaths.insert(after) } else if let before = updateItem.indexPathBeforeUpdate, updateItem.indexPathAfterUpdate == nil { disappearingIndexPaths.insert(before) } } } } private func adjustAttributesIfNecessary(_ attributes: UICollectionViewLayoutAttributes, forItemOrElementAppearingAtIndexPath indexPath: IndexPath) { guard indexPath.section <= maxNewSection else { guard animateItems, appearingIndexPaths.contains(indexPath) else { return } attributes.zIndex = -1 attributes.alpha = 0 return } attributes.frame.origin.y += newSectionDeltaY attributes.alpha = 1 } public override func initialLayoutAttributesForAppearingSupplementaryElement(ofKind elementKind: String, at elementIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let attributes = super.initialLayoutAttributesForAppearingSupplementaryElement(ofKind: elementKind, at: elementIndexPath) else { return nil } adjustAttributesIfNecessary(attributes, forItemOrElementAppearingAtIndexPath: elementIndexPath) return attributes } public override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath) else { return nil } adjustAttributesIfNecessary(attributes, forItemOrElementAppearingAtIndexPath: itemIndexPath) return attributes } public override func initialLayoutAttributesForAppearingDecorationElement(ofKind elementKind: String, at decorationIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return super.initialLayoutAttributesForAppearingDecorationElement(ofKind: elementKind, at: decorationIndexPath) } public override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let attributes = super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath) else { return nil } guard animateItems, disappearingIndexPaths.contains(itemIndexPath) else { return attributes } attributes.zIndex = -1 attributes.alpha = 0 return attributes } // MARK: Scroll View public var currentSection: Int? public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { var superTarget = super.targetContentOffset(forProposedContentOffset: proposedContentOffset) if let currentSection = currentSection, let oldInfo = oldInfo, let info = info, oldInfo.sections.indices.contains(currentSection), info.sections.indices.contains(currentSection) { let oldY = oldInfo.sections[currentSection].frame.origin.y let newY = info.sections[currentSection].frame.origin.y let deltaY = newY - oldY superTarget.y += deltaY } return superTarget } } extension ColumnarCollectionViewLayout: NSCopying { public func copy(with zone: NSZone? = nil) -> Any { let newLayout = ColumnarCollectionViewLayout() newLayout.info = info newLayout.oldInfo = oldInfo newLayout.metrics = metrics newLayout.isLayoutValid = isLayoutValid newLayout.slideInNewContentFromTheTop = slideInNewContentFromTheTop newLayout.animateItems = animateItems newLayout.maxNewSection = maxNewSection newLayout.newSectionDeltaY = newSectionDeltaY newLayout.appearingIndexPaths = appearingIndexPaths newLayout.disappearingIndexPaths = disappearingIndexPaths return newLayout } }
mit
05d2e97134ea453c1ed9ef37f9802275
43.198113
252
0.680612
6.299866
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/SideScrollingCollectionViewCell.swift
1
13738
import UIKit internal struct CellArticle { let articleURL: URL? let title: String? let titleHTML: String? let description: String? let imageURL: URL? } public protocol SideScrollingCollectionViewCellDelegate: AnyObject { func sideScrollingCollectionViewCell(_ sideScrollingCollectionViewCell: SideScrollingCollectionViewCell, didSelectArticleWithURL articleURL: URL, at indexPath: IndexPath) } public protocol NestedCollectionViewContextMenuDelegate: AnyObject { func contextMenu(with contentGroup: WMFContentGroup?, for articleURL: URL?, at itemIndex: Int) -> UIContextMenuConfiguration? func willCommitPreview(with animator: UIContextMenuInteractionCommitAnimating) } public protocol SubCellProtocol { func deselectSelectedSubItems(animated: Bool) } open class SideScrollingCollectionViewCell: CollectionViewCell, SubCellProtocol { static let articleCellIdentifier = "ArticleRightAlignedImageCollectionViewCell" var theme: Theme = Theme.standard public weak var selectionDelegate: SideScrollingCollectionViewCellDelegate? public let imageView = UIImageView() public let titleLabel = UILabel() public let subTitleLabel = UILabel() public let descriptionLabel = UILabel() internal var flowLayout: UICollectionViewFlowLayout? { return collectionView.collectionViewLayout as? UICollectionViewFlowLayout } public let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) internal let prototypeCell = ArticleRightAlignedImageCollectionViewCell() open var semanticContentAttributeOverride: UISemanticContentAttribute = .unspecified { didSet { titleLabel.semanticContentAttribute = semanticContentAttributeOverride subTitleLabel.semanticContentAttribute = semanticContentAttributeOverride descriptionLabel.semanticContentAttribute = semanticContentAttributeOverride collectionView.semanticContentAttribute = semanticContentAttributeOverride } } public weak var contextMenuShowingDelegate: NestedCollectionViewContextMenuDelegate? internal var articles: [CellArticle] = [] override open func setup() { titleLabel.isOpaque = true subTitleLabel.isOpaque = true descriptionLabel.isOpaque = true imageView.isOpaque = true contentView.addSubview(titleLabel) contentView.addSubview(subTitleLabel) contentView.addSubview(descriptionLabel) contentView.addSubview(imageView) contentView.addSubview(collectionView) contentView.addSubview(prototypeCell) wmf_configureSubviewsForDynamicType() // Setup the prototype cell with placeholder content so we can get an accurate height calculation for the collection view that accounts for dynamic type changes prototypeCell.configure(with: CellArticle(articleURL: nil, title: "Lorem", titleHTML: "Lorem", description: "Ipsum", imageURL: nil), semanticContentAttribute: .forceLeftToRight, theme: self.theme, layoutOnly: true) prototypeCell.isHidden = true imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true titleLabel.numberOfLines = 1 subTitleLabel.numberOfLines = 1 descriptionLabel.numberOfLines = 0 flowLayout?.scrollDirection = .horizontal collectionView.register(ArticleRightAlignedImageCollectionViewCell.self, forCellWithReuseIdentifier: SideScrollingCollectionViewCell.articleCellIdentifier) collectionView.dataSource = self collectionView.delegate = self collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.alwaysBounceHorizontal = true super.setup() } override open func reset() { super.reset() imageView.wmf_reset() } public var isImageViewHidden = false { didSet { imageView.isHidden = isImageViewHidden setNeedsLayout() } } public var imageViewHeight: CGFloat = 130 { didSet { setNeedsLayout() } } public let spacing: CGFloat = 6 override open func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize { let layoutMargins = calculatedLayoutMargins var origin = CGPoint(x: layoutMargins.left, y: layoutMargins.top) let widthToFit = size.width - layoutMargins.left - layoutMargins.right if !isImageViewHidden { if apply { let imageViewWidth = size.width - widthToFit > 50 ? widthToFit : size.width imageView.frame = CGRect(x: round(0.5 * (size.width - imageViewWidth)), y: 0, width: imageViewWidth, height: imageViewHeight) } origin.y += imageViewHeight } if titleLabel.wmf_hasAnyText { origin.y += spacing origin.y += titleLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: round(0.4 * spacing), apply: apply) } if subTitleLabel.wmf_hasAnyText { origin.y += 0 origin.y += subTitleLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: spacing, apply: apply) } origin.y += spacing origin.y += descriptionLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: spacing, apply: apply) let collectionViewSpacing: CGFloat = 10 var height = prototypeCell.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: 2*collectionViewSpacing, apply: false) if articles.isEmpty { height = 0 } if apply { flowLayout?.itemSize = CGSize(width: 250, height: height - 2*collectionViewSpacing) flowLayout?.minimumInteritemSpacing = collectionViewSpacing flowLayout?.minimumLineSpacing = 15 flowLayout?.sectionInset = UIEdgeInsets(top: collectionViewSpacing, left: collectionViewSpacing, bottom: collectionViewSpacing, right: collectionViewSpacing) collectionView.frame = CGRect(x: 0, y: origin.y, width: size.width, height: height) if semanticContentAttributeOverride == .forceRightToLeft { collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: layoutMargins.right - collectionViewSpacing) } else { collectionView.contentInset = UIEdgeInsets(top: 0, left: layoutMargins.left - collectionViewSpacing, bottom: 0, right: 0) } collectionView.reloadData() collectionView.layoutIfNeeded() deselectSelectedSubItems(animated: false) } origin.y += height origin.y += layoutMargins.bottom return CGSize(width: size.width, height: origin.y) } public func resetContentOffset() { // Without a layout pass, RTL languages on LTR chrome have an incorrect initial inset. layoutIfNeeded() let x: CGFloat = semanticContentAttributeOverride == .forceRightToLeft ? collectionView.contentSize.width - collectionView.bounds.size.width + collectionView.contentInset.right : -collectionView.contentInset.left collectionView.contentOffset = CGPoint(x: x, y: 0) } public func deselectSelectedSubItems(animated: Bool) { guard let selectedIndexPaths = collectionView.indexPathsForSelectedItems else { return } for indexPath in selectedIndexPaths { collectionView.deselectItem(at: indexPath, animated: animated) } } override open func updateBackgroundColorOfLabels() { super.updateBackgroundColorOfLabels() titleLabel.backgroundColor = labelBackgroundColor subTitleLabel.backgroundColor = labelBackgroundColor descriptionLabel.backgroundColor = labelBackgroundColor } } extension SideScrollingCollectionViewCell: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let selectedArticle = articles[indexPath.item] guard let articleURL = selectedArticle.articleURL else { return } selectionDelegate?.sideScrollingCollectionViewCell(self, didSelectArticleWithURL: articleURL, at: indexPath) } // ContextMenu public func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard let articleURL = articles[safeIndex: indexPath.item]?.articleURL else { return nil } return contextMenuShowingDelegate?.contextMenu(with: nil, for: articleURL, at: indexPath.item) } public func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) { contextMenuShowingDelegate?.willCommitPreview(with: animator) } } extension SideScrollingCollectionViewCell: UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return articles.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SideScrollingCollectionViewCell.articleCellIdentifier, for: indexPath) guard let articleCell = cell as? ArticleRightAlignedImageCollectionViewCell else { return cell } let articleForCell = articles[indexPath.item] articleCell.configure(with: articleForCell, semanticContentAttribute: semanticContentAttributeOverride, theme: self.theme, layoutOnly: false) return articleCell } } fileprivate extension ArticleRightAlignedImageCollectionViewCell { func configure(with cellArticle: CellArticle, semanticContentAttribute: UISemanticContentAttribute, theme: Theme, layoutOnly: Bool) { apply(theme: theme) backgroundColor = .clear setBackgroundColors(theme.colors.subCellBackground, selected: theme.colors.midBackground) backgroundView?.layer.cornerRadius = 3 backgroundView?.layer.masksToBounds = true selectedBackgroundView?.layer.cornerRadius = 3 selectedBackgroundView?.layer.masksToBounds = true layer.shadowOffset = CGSize(width: 0, height: 1) layer.shadowOpacity = 1.0 layer.shadowRadius = 3 layer.shadowColor = theme.colors.shadow.cgColor layer.masksToBounds = false titleLabel.backgroundColor = backgroundView?.backgroundColor descriptionLabel.backgroundColor = backgroundView?.backgroundColor titleTextStyle = .subheadline descriptionTextStyle = .footnote imageViewDimension = 40 layoutMargins = UIEdgeInsets(top: 9, left: 10, bottom: 9, right: 10) isImageViewHidden = layoutOnly || cellArticle.imageURL == nil titleHTML = cellArticle.titleHTML ?? cellArticle.title descriptionLabel.text = cellArticle.description articleSemanticContentAttribute = semanticContentAttribute if let imageURL = cellArticle.imageURL { isImageViewHidden = false if !layoutOnly { imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: { (error) in }, success: { }) } } else { isImageViewHidden = true } updateFonts(with: traitCollection) setNeedsLayout() } } extension SideScrollingCollectionViewCell { public func subItemIndex(at point: CGPoint) -> Int { // NSNotFound for not found let collectionViewFrame = collectionView.frame guard collectionViewFrame.contains(point) else { return NSNotFound } let pointInCollectionViewCoordinates = convert(point, to: collectionView) guard let indexPath = collectionView.indexPathForItem(at: pointInCollectionViewCoordinates) else { return NSNotFound } return indexPath.item } public func viewForSubItem(at index: Int) -> UIView? { guard index != NSNotFound, index >= 0, index < collectionView.numberOfItems(inSection: 0) else { return nil } guard let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) else { return nil } return cell } } extension SideScrollingCollectionViewCell: Themeable { open func apply(theme: Theme) { self.theme = theme imageView.alpha = theme.imageOpacity setBackgroundColors(theme.colors.paperBackground, selected: theme.colors.midBackground) titleLabel.textColor = theme.colors.primaryText subTitleLabel.textColor = theme.colors.secondaryText descriptionLabel.textColor = theme.colors.primaryText collectionView.backgroundColor = theme.colors.paperBackground descriptionLabel.textColor = theme.colors.primaryText updateSelectedOrHighlighted() collectionView.reloadData() imageView.accessibilityIgnoresInvertColors = true } }
mit
6556a56d27711d0abd3a49f96c730f65
43.603896
222
0.706799
6.057319
false
false
false
false
dekatotoro/PullToRefreshSwift
Example/PullToRefreshSwift/AppDelegate.swift
1
5704
// // AppDelegate.swift // test11 // // Created by Yuji Hato on 4/20/15. // Copyright (c) 2015 Yuji Hato. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } 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 inactive state; here you can undo many of the changes made on entering the background. } 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. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "dekatotoro.test11" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "test11", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("test11.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { coordinator = nil // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { if moc.hasChanges { do { try moc.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error)") abort() } } } } }
mit
421b27217eda4badefba5e35560762bc
52.811321
290
0.69723
5.874356
false
false
false
false
SwiftBond/Bond
Playground-iOS.playground/Pages/UICollectionView+ObservableArray2D.xcplaygroundpage/Contents.swift
2
4011
//: [Previous](@previous) import Foundation import PlaygroundSupport import UIKit import Bond import ReactiveKit class Cell: UICollectionViewCell { let titleLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) titleLabel.textAlignment = .center addSubview(titleLabel) contentView.backgroundColor = .white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() titleLabel.frame = bounds } } class SectionHeader: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .red } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 8 layout.minimumInteritemSpacing = 8 layout.sectionInset.top = 20 layout.sectionInset.bottom = 20 let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.frame.size = CGSize(width: 300, height: 600) collectionView.register(SectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header") // Note: Open the assistant editor to see the table view PlaygroundPage.current.liveView = collectionView PlaygroundPage.current.needsIndefiniteExecution = true // Using custom binder to provide table view header titles class CustomBinder<Changeset: SectionedDataSourceChangeset>: CollectionViewBinderDataSource<Changeset>, UICollectionViewDelegateFlowLayout where Changeset.Collection == Array2D<String, Int> { override var collectionView: UICollectionView? { didSet { collectionView?.delegate = self } } // Due to a bug in Swift related to generic subclases, we have to specify ObjC delegate method name // if it's different than Swift name (https://bugs.swift.org/browse/SR-2817). @objc (collectionView:viewForSupplementaryElementOfKind:atIndexPath:) func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! SectionHeader return headerView default: fatalError("Not implemented") } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: 200, height: 20) } } // Array2D is generic over section metadata `Section` and item value `Item`. // Section metadata is the data associated with the section, like section header titles. // You can specialise `Section` to `Void` if there is no section metadata. // Item values are values displayed by the table view cells. let initialData = Array2D<String, Int>(sectionsWithItems: [ ("A", [1, 2]), ("B", [10, 20]) ]) let data = MutableObservableArray2D(initialData) data.bind(to: collectionView, cellType: Cell.self, using: CustomBinder()) { (cell, item) in cell.titleLabel.text = "\(item)" } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { data.appendItem(3, toSectionAt: 0) } DispatchQueue.main.asyncAfter(deadline: .now() + 2) { data.batchUpdate { (data) in data.appendItem(4, toSectionAt: 0) data.insert(section: "Aa", at: 1) data.appendItem(100, toSectionAt: 1) data.insert(item: 50, at: IndexPath(item: 0, section: 1)) } } DispatchQueue.main.asyncAfter(deadline: .now() + 3) { data.moveItem(from: IndexPath(item: 0, section: 1), to: IndexPath(item: 0, section: 0)) } //: [Next](@next)
mit
b534b5efc77bf18443e33bab0b9085fe
33.282051
191
0.716779
4.636994
false
false
false
false
playbasis/native-sdk-ios
PlaybasisSDK/Classes/PBModel/PBBadge.swift
1
1256
// // PBBadge.swift // Playbook // // Created by Nuttapol Thitaweera on 6/17/2559 BE. // Copyright © 2559 smartsoftasia. All rights reserved. // import UIKit import ObjectMapper public class PBBadge: PBModel { public var imageURL:String! = "" public var name:String! = "" public var desc:String! = "" public var badgeId:String! = "" public var hint:String! = "" public var sponsor:Bool! = false public var amount:Int! = 0 public override init() { super.init() } required public init?(_ map: Map) { super.init(map) } public override func mapping(map: Map) { name <- map["name"] desc <- map["description"] badgeId <- map["badge_id"] imageURL <- map["image"] sponsor <- map["sponsor"] hint <- map["hint"] amount <- map["amount"] } class func pbBadgesFromDicArray(badgeArray:[AnyObject]) -> [PBBadge] { return Mapper<PBBadge>().mapArray(badgeArray) ?? [] } class func pbBadgeFromApiResponse(apiResponse:PBApiResponse) -> [PBBadge] { var badges:[PBBadge] = [] badges = Mapper<PBBadge>().mapArray(apiResponse.parsedJson!)! return badges } }
mit
664dd87db4b9edbfe41ac31fc53970e7
22.679245
79
0.581673
3.921875
false
false
false
false
Constructor-io/constructorio-client-swift
UserApplication/Common/BadgeView.swift
1
1332
// // BadgeView.swift // UserApplication // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import UIKit class BadgeView: UIView { private var label: UILabel init(){ self.label = UILabel(frame: .zero) super.init(frame: .zero) self.backgroundColor = UIColor.red self.clipsToBounds = true self.label.backgroundColor = .clear self.label.textAlignment = .center self.label.translatesAutoresizingMaskIntoConstraints = false self.label.textColor = UIColor.white self.label.adjustsFontSizeToFitWidth = true self.label.baselineAdjustment = .alignCenters self.label.font = UIFont.systemFont(ofSize: 10) self.addSubview(label) self.label.pinToSuperviewTop(2) self.label.pinToSuperviewBottom(2) self.label.pinToSuperviewLeft(2) self.label.pinToSuperviewRight(2) } func setValue(text: String){ self.label.text = text self.label.layoutIfNeeded() self.label.setNeedsDisplay() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.size.height/2 } }
mit
80b43be79f4dec8f06d807ece40b2eb4
24.596154
68
0.652141
4.436667
false
false
false
false
jfrowies/iEMI
iEMI/NetworkActivityViewController.swift
1
3322
// // NetworkActivityViewController.swift // iEMI // // Created by Fer Rowies on 9/17/15. // Copyright © 2015 Rowies. All rights reserved. // import UIKit class NetworkActivityViewController: UIViewController { // MARK: - Private properties private lazy var loadingView : LoadingView = { return LoadingView(frame: UIScreen.mainScreen().bounds) }() //MARK: - Public properties // MARK: - View controller life cycle override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Loading view private let kShowAnimationDuration = 0.2 private func prepareForShowNetworkActivityView() { loadingView.removeFromSuperview() loadingView.alpha = 1.0 } private func showNetworkActivityView(animated: Bool) { if !animated { self.view.addSubview(self.loadingView) } else { loadingView.alpha = 0.0 self.view.addSubview(self.loadingView) UIView.animateWithDuration(kShowAnimationDuration, animations: { () -> Void in self.loadingView.alpha = 1.0 }) } } func showLoadingView(message: String?, animated: Bool) { self.prepareForShowNetworkActivityView() self.loadingView.feedbackLabel.text = message self.loadingView.feedbackLabel.textColor = UIColor.grayLabelDefaultColor() self.loadingView.loadingSpinner.hidden = false self.loadingView.loadingSpinner.startAnimating() self.showNetworkActivityView(animated) } func showSuccessView(message: String?, animated: Bool) { self.prepareForShowNetworkActivityView() self.loadingView.feedbackLabel.text = message self.loadingView.feedbackLabel.textColor = UIColor.grayLabelDefaultColor() self.loadingView.loadingSpinner.hidden = true self.loadingView.loadingSpinner.stopAnimating() self.showNetworkActivityView(animated) } func showErrorView(errorMessage: String?, animated: Bool) { self.prepareForShowNetworkActivityView() self.loadingView.feedbackLabel.text = errorMessage self.loadingView.feedbackLabel.textColor = UIColor.redErrorColor() self.loadingView.loadingSpinner.hidden = true self.loadingView.loadingSpinner.stopAnimating() self.showNetworkActivityView(animated) } private let kHideAnimationDuration = 0.2 func hideLoadingView(animated animated: Bool) { if !animated { loadingView.removeFromSuperview() } else { UIView.animateWithDuration(kHideAnimationDuration, animations: { () -> Void in self.loadingView.alpha = 0.0 }, completion: { [unowned self] (success) -> Void in self.loadingView.removeFromSuperview() self.loadingView.alpha = 1.0 }) } } }
apache-2.0
d7be5855cec407b5763e5359fc90b1e1
26.446281
90
0.595905
5.572148
false
false
false
false
acsalu/Keymochi
Keyboard/KeyboardKeyBackground.swift
2
10616
// // KeyboardKeyBackground.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/19/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import UIKit // This class does not actually draw its contents; rather, it generates bezier curves for others to use. // (You can still move it around, resize it, and add subviews to it. It just won't display the curve assigned to it.) class KeyboardKeyBackground: UIView, Connectable { var fillPath: UIBezierPath? var underPath: UIBezierPath? var edgePaths: [UIBezierPath]? // do not set this manually var cornerRadius: CGFloat var underOffset: CGFloat var startingPoints: [CGPoint] var segmentPoints: [(CGPoint, CGPoint)] var arcCenters: [CGPoint] var arcStartingAngles: [CGFloat] var dirty: Bool var attached: Direction? { didSet { self.dirty = true self.setNeedsLayout() } } var hideDirectionIsOpposite: Bool { didSet { self.dirty = true self.setNeedsLayout() } } init(cornerRadius: CGFloat, underOffset: CGFloat) { attached = nil hideDirectionIsOpposite = false dirty = false startingPoints = [] segmentPoints = [] arcCenters = [] arcStartingAngles = [] startingPoints.reserveCapacity(4) segmentPoints.reserveCapacity(4) arcCenters.reserveCapacity(4) arcStartingAngles.reserveCapacity(4) for _ in 0..<4 { startingPoints.append(CGPoint.zero) segmentPoints.append((CGPoint.zero, CGPoint.zero)) arcCenters.append(CGPoint.zero) arcStartingAngles.append(0) } self.cornerRadius = cornerRadius self.underOffset = underOffset super.init(frame: CGRect.zero) self.isUserInteractionEnabled = false } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } var oldBounds: CGRect? override func layoutSubviews() { if !self.dirty { if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && self.bounds.equalTo(oldBounds!) { return } } oldBounds = self.bounds super.layoutSubviews() self.generatePointsForDrawing(self.bounds) self.dirty = false } let floatPi = CGFloat(M_PI) let floatPiDiv2 = CGFloat(M_PI/2.0) let floatPiDivNeg2 = -CGFloat(M_PI/2.0) func generatePointsForDrawing(_ bounds: CGRect) { let segmentWidth = bounds.width let segmentHeight = bounds.height - CGFloat(underOffset) // base, untranslated corner points self.startingPoints[0] = CGPoint(x: 0, y: segmentHeight) self.startingPoints[1] = CGPoint(x: 0, y: 0) self.startingPoints[2] = CGPoint(x: segmentWidth, y: 0) self.startingPoints[3] = CGPoint(x: segmentWidth, y: segmentHeight) self.arcStartingAngles[0] = floatPiDiv2 self.arcStartingAngles[2] = floatPiDivNeg2 self.arcStartingAngles[1] = floatPi self.arcStartingAngles[3] = 0 //// actual coordinates for each edge, including translation //self.segmentPoints.removeAll(keepCapacity: true) // //// actual coordinates for arc centers for each corner //self.arcCenters.removeAll(keepCapacity: true) // //self.arcStartingAngles.removeAll(keepCapacity: true) for i in 0 ..< self.startingPoints.count { let currentPoint = self.startingPoints[i] let nextPoint = self.startingPoints[(i + 1) % self.startingPoints.count] var floatXCorner: CGFloat = 0 var floatYCorner: CGFloat = 0 if (i == 1) { floatXCorner = cornerRadius } else if (i == 3) { floatXCorner = -cornerRadius } if (i == 0) { floatYCorner = -cornerRadius } else if (i == 2) { floatYCorner = cornerRadius } let p0 = CGPoint( x: currentPoint.x + (floatXCorner), y: currentPoint.y + underOffset + (floatYCorner)) let p1 = CGPoint( x: nextPoint.x - (floatXCorner), y: nextPoint.y + underOffset - (floatYCorner)) self.segmentPoints[i] = (p0, p1) let c = CGPoint( x: p0.x - (floatYCorner), y: p0.y + (floatXCorner)) self.arcCenters[i] = c } // order of edge drawing: left edge, down edge, right edge, up edge // We need to have separate paths for all the edges so we can toggle them as needed. // Unfortunately, it doesn't seem possible to assemble the connected fill path // by simply using CGPathAddPath, since it closes all the subpaths, so we have to // duplicate the code a little bit. let fillPath = UIBezierPath() var edgePaths: [UIBezierPath] = [] var prevPoint: CGPoint? for i in 0..<4 { var edgePath: UIBezierPath? let segmentPoint = self.segmentPoints[i] if self.attached != nil && (self.hideDirectionIsOpposite ? self.attached!.rawValue != i : self.attached!.rawValue == i) { // do nothing // TODO: quick hack if !self.hideDirectionIsOpposite { continue } } else { edgePath = UIBezierPath() // TODO: figure out if this is ncessary if prevPoint == nil { prevPoint = segmentPoint.0 fillPath.move(to: prevPoint!) } fillPath.addLine(to: segmentPoint.0) fillPath.addLine(to: segmentPoint.1) edgePath!.move(to: segmentPoint.0) edgePath!.addLine(to: segmentPoint.1) prevPoint = segmentPoint.1 } let shouldDrawArcInOppositeMode = (self.attached != nil ? (self.attached!.rawValue == i) || (self.attached!.rawValue == ((i + 1) % 4)) : false) if (self.attached != nil && (self.hideDirectionIsOpposite ? !shouldDrawArcInOppositeMode : self.attached!.rawValue == ((i + 1) % 4))) { // do nothing } else { edgePath = (edgePath == nil ? UIBezierPath() : edgePath) if prevPoint == nil { prevPoint = segmentPoint.1 fillPath.move(to: prevPoint!) } let startAngle = self.arcStartingAngles[(i + 1) % 4] let endAngle = startAngle + floatPiDiv2 let arcCenter = self.arcCenters[(i + 1) % 4] fillPath.addLine(to: prevPoint!) fillPath.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) edgePath!.move(to: prevPoint!) edgePath!.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) prevPoint = self.segmentPoints[(i + 1) % 4].0 } edgePath?.apply(CGAffineTransform(translationX: 0, y: -self.underOffset)) if edgePath != nil { edgePaths.append(edgePath!) } } fillPath.close() fillPath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset)) let underPath = { () -> UIBezierPath in let underPath = UIBezierPath() underPath.move(to: self.segmentPoints[2].1) var startAngle = self.arcStartingAngles[3] var endAngle = startAngle + CGFloat(M_PI/2.0) underPath.addArc(withCenter: self.arcCenters[3], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLine(to: self.segmentPoints[3].1) startAngle = self.arcStartingAngles[0] endAngle = startAngle + CGFloat(M_PI/2.0) underPath.addArc(withCenter: self.arcCenters[0], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLine(to: CGPoint(x: self.segmentPoints[0].0.x, y: self.segmentPoints[0].0.y - self.underOffset)) startAngle = self.arcStartingAngles[1] endAngle = startAngle - CGFloat(M_PI/2.0) underPath.addArc(withCenter: CGPoint(x: self.arcCenters[0].x, y: self.arcCenters[0].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.addLine(to: CGPoint(x: self.segmentPoints[2].1.x - self.cornerRadius, y: self.segmentPoints[2].1.y + self.cornerRadius - self.underOffset)) startAngle = self.arcStartingAngles[0] endAngle = startAngle - CGFloat(M_PI/2.0) underPath.addArc(withCenter: CGPoint(x: self.arcCenters[3].x, y: self.arcCenters[3].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.close() return underPath }() self.fillPath = fillPath self.edgePaths = edgePaths self.underPath = underPath } func attachmentPoints(_ direction: Direction) -> (CGPoint, CGPoint) { let returnValue = ( self.segmentPoints[direction.clockwise().rawValue].0, self.segmentPoints[direction.counterclockwise().rawValue].1) return returnValue } func attachmentDirection() -> Direction? { return self.attached } func attach(_ direction: Direction?) { self.attached = direction } }
bsd-3-clause
48d74c94377d8075055c1e08e98ee247
36.249123
216
0.554917
5.033665
false
false
false
false
einsteinx2/iSub
Classes/UI/Specific/VisualizerViewController.swift
1
1420
// // VisualizerViewController.swift // iSub Beta // // Created by Benjamin Baron on 7/1/17. // Copyright © 2017 Ben Baron. All rights reserved. // import UIKit class VisualizerViewController: UIViewController, UIGestureRecognizerDelegate { fileprivate let visualizerView = VisualizerView() fileprivate let tapRecognizer = UITapGestureRecognizer() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .lightGray self.view.addSubview(visualizerView) visualizerView.snp.makeConstraints { make in make.width.equalToSuperview() make.height.equalTo(self.view.snp.width) make.top.equalToSuperview().offset(20) make.left.equalToSuperview() } tapRecognizer.addTarget(self, action: #selector(handleTap(sender:))) visualizerView.addGestureRecognizer(tapRecognizer) } @objc fileprivate func handleTap(sender: UITapGestureRecognizer) { let reverse = sender.numberOfTouches > 1 toggleVisualizer(reverse: reverse) } fileprivate func toggleVisualizer(reverse: Bool) { let type = visualizerView.visualizerType visualizerView.visualizerType = reverse ? type.previous : type.next } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
gpl-3.0
cc5c6e45896a5161126ef312592e2604
31.25
89
0.680056
5.049822
false
false
false
false
SerhatSurguvec/IOSTest
example/FruitsTableViewController.swift
1
2289
// // FruitsTableViewController.swift // example // // Created by Serhat Sürgüveç on 2.11.2015. // Copyright © 2015 Serhat Sürgüveç. All rights reserved. // import UIKit class FruitsTableViewController: UITableViewController { var data = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry", "Clementine", "Coconut", "Cranberry", "Fig", "Grape", "Grapefruit", "Kiwi fruit", "Lemon", "Lime", "Lychee", "Mandarine", "Mango", "Melon", "Nectarine", "Olive", "Orange", "Papaya", "Peach", "Pear", "Pineapple", "Raspberry", "Strawberry"] override func viewDidLoad() { super.viewDidLoad() self.tableView.editing = true self.navigationItem.rightBarButtonItem = self.editButtonItem() } // MARK: - UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FruitCell", forIndexPath: indexPath) cell.textLabel?.text = data[indexPath.row] return cell } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .None } override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let movedObject = self.data[sourceIndexPath.row] data.removeAtIndex(sourceIndexPath.row) data.insert(movedObject, atIndex: destinationIndexPath.row) NSLog("%@", "\(sourceIndexPath.row) => \(destinationIndexPath.row) \(data)") // To check for correctness enable: self.tableView.reloadData() } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { let rowData = data[indexPath.row] return rowData.hasPrefix("A") } }
apache-2.0
86abe0f2691aabf89c478938f6e16f9e
37.677966
149
0.68142
4.764092
false
false
false
false
litoarias/SwiftTemplate
TemplateSwift3/Entities/NetworkModels/PostDemoModel.swift
1
1432
// // PostDemoModel.swift // // Create by Hipolito Arias on 2/8/2017 // Copyright © 2017. All rights reserved. // Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation import ObjectMapper class PostDemoModel : NSObject, NSCoding, Mappable{ var body : String? var id : Int? var title : String? var userId : Int? class func newInstance(map: Map) -> Mappable?{ return PostDemoModel() } required init?(map: Map){} private override init(){} func mapping(map: Map) { body <- map["body"] id <- map["id"] title <- map["title"] userId <- map["userId"] } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { body = aDecoder.decodeObject(forKey: "body") as? String id = aDecoder.decodeObject(forKey: "id") as? Int title = aDecoder.decodeObject(forKey: "title") as? String userId = aDecoder.decodeObject(forKey: "userId") as? Int } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encode(with aCoder: NSCoder) { if body != nil{ aCoder.encode(body, forKey: "body") } if id != nil{ aCoder.encode(id, forKey: "id") } if title != nil{ aCoder.encode(title, forKey: "title") } if userId != nil{ aCoder.encode(userId, forKey: "userId") } } }
mit
261bfd5ed76cd70efc78cdab976ab5d1
19.442857
81
0.634521
3.415274
false
false
false
false
ykpaco/LayoutComposer
Example/LayoutComposer/NestExampleViewController.swift
1
6823
// // VBoxExampleViewController.swift // LayoutComposer // // Created by Yusuke Kawakami on 2015/08/22. // Copyright (c) 2015年 CocoaPods. All rights reserved. // import UIKit import LayoutComposer enum NestExampleType: Int { case example1 } class NestExampleViewController: ExampleViewController { let exampleType: NestExampleType init(exampleType: NestExampleType, headerTitle: String) { self.exampleType = exampleType super.init(headerTitle: headerTitle) } required init(coder aDecoder: NSCoder) { fatalError("not supported") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func loadView() { super.loadView() switch exampleType { case .example1: layoutExample1() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func layoutExample1() { let profileContainer = UIView() profileContainer.backgroundColor = UIColor.white profileContainer.layer.cornerRadius = 5 let icon = UIImageView(image: UIImage(named: "avatar.jpeg")) icon.layer.cornerRadius = 2 let changeProfileBtn = UIButton(type: .system) changeProfileBtn.setTitle("Update Profile", for: UIControlState()) changeProfileBtn.layer.borderWidth = 1 changeProfileBtn.layer.borderColor = UIColor.lightGray.cgColor changeProfileBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12) changeProfileBtn.setTitleColor(UIColor.lightGray, for: UIControlState()) changeProfileBtn.layer.cornerRadius = 2 let nameLabel = UILabel() nameLabel.textColor = UIColor.black nameLabel.font = UIFont.systemFont(ofSize: 16) nameLabel.text = "YKPaco" let userIDLabel = UILabel() userIDLabel.textColor = UIColor.gray userIDLabel.font = UIFont.systemFont(ofSize: 10) userIDLabel.text = "@ykpaco" let messageLabel = UILabel() messageLabel.numberOfLines = 0 messageLabel.textColor = UIColor.black messageLabel.font = UIFont.systemFont(ofSize: 12) messageLabel.text = "Each layout pattern is able to contain other layout patterns as children and you can form camplicated layouts.\n" + "Auto Layout code written by LayoutComposer expresses the view hierarchy." + "It makes Auto Layout code very simple and intuitive" let followLabel = UILabel() followLabel.font = UIFont.systemFont(ofSize: 12) followLabel.text = "150 follows" followLabel.textColor = UIColor.darkGray let followerLabel = UILabel() followerLabel.font = UIFont.systemFont(ofSize: 12) followerLabel.text = "130 followers" followerLabel.textColor = UIColor.darkGray contentView.applyLayout(VBox(), items: [ $(profileContainer, margins: (10, 10, 10, 10), layout: VBox(pack: .fit, defaultMargins: (0, 10, 0, 10)), items: [ $(nil, height: 50, marginTop: 10, layout: Relative(), items: [ $(icon, width: 50, height: 50, halign: .left), $(changeProfileBtn, width: 100, height: 20, halign: .right, valign: .top) ]), $(nameLabel, marginTop: 5), $(userIDLabel, marginTop: 5), $(messageLabel, marginTop: 5), $(nil, height: 30, layout: HBox(), items: [ $(followLabel), $(followerLabel, marginLeft: 10) ]) ]) ]) } /* private func layoutExample1() { let messageContainer = UIView() messageContainer.backgroundColor = UIColor.whiteColor() let icon = UIImageView(image: UIImage(named: "avatar.jpeg")) icon.layer.cornerRadius = 2 let changeProfileBtn = UIButton.buttonWithType(.Custom) as! UIButton changeProfileBtn.layer.borderColor = UIColor.grayColor().CGColor changeProfileBtn.setTitle("Update Profile", forState: .Normal) let messageHeader = UIView() let nameLabel = UILabel() nameLabel.textColor = UIColor.blackColor() nameLabel.font = UIFont.systemFontOfSize(16) nameLabel.text = "YKPaco" let userIDLabel = UILabel() userIDLabel.textColor = UIColor.grayColor() userIDLabel.font = UIFont.systemFontOfSize(10) userIDLabel.text = "@ykpaco" let dateLabel = UILabel() dateLabel.textColor = UIColor.grayColor() dateLabel.font = UIFont.systemFontOfSize(10) dateLabel.text = "2015/07/20" let messageLabel = UILabel() messageLabel.numberOfLines = 0 messageLabel.textColor = UIColor.blackColor() messageLabel.font = UIFont.systemFontOfSize(12) messageLabel.text = "Each layout pattern is able to contain other layout patterns as children and you can form camplicated layouts.\n" + "Auto Layout code written by LayoutComposer expresses the view hierarchy." + "It makes Auto Layout code very simple and intuitive" contentView.applyLayout(Fit(), items: [ $(messageContainer, margins: (10, 10, 10, 10), layout: VBox(align: .Start), items: [ $(icon, width: 50, height: 50, marginLeft: 10, marginTop: 10), $(nil, flex: 1, margins: (10, 10, 0, 10), layout: VBox(pack: .Fit), items: [ $(messageHeader, height: 16, layout: HBox(), items: [ $(nameLabel), $(userIDLabel, marginLeft: 10) ]), $(messageLabel, marginTop: 10) ]) ]) ]) /* contentView.applyLayout(Fit(), items: [ $(messageContainer, margins: (10, 10, 10, 10), layout: HBox(align: .Start), items: [ $(icon, width: 50, height: 50, marginLeft: 10, marginTop: 10), $(nil, flex: 1, margins: (10, 10, 0, 10), layout: VBox(pack: .Fit), items: [ $(messageHeader, height: 16, layout: HBox(), items: [ $(nameLabel), $(userIDLabel, marginLeft: 10) ]), $(messageLabel, marginTop: 10) ]) ]) ]) */ // add date label to right bottom of message header. messageHeader.applyLayout(Relative(), item: $(dateLabel, halign: .Right, valign: .Center)) } */ }
mit
a878a003328ec41fffeb5a5796e2d56a
37.536723
144
0.591555
4.917808
false
false
false
false
aliceatlas/daybreak
Classes/SBFindbar.swift
1
10888
/* SBFindbar.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import BLKGUI @objc protocol SBFindbarTarget { func searchFor(_: String, direction forward: Bool, caseSensitive: Bool, wrap: Bool, continuous: Bool) -> Bool } class SBFindbar: SBView, NSTextFieldDelegate, NSControlTextEditingDelegate { var searchedString: String? override var frame: NSRect { didSet { contentView.frame = contentRect } } internal lazy var contentView: NSView = { return NSView(frame: self.contentRect) }() private lazy var closeButton: SBButton = { let r = self.closeRect let closeButton = SBButton(frame: r) closeButton.autoresizingMask = .ViewMaxXMargin closeButton.image = SBIconImage(SBCloseIconImage(), .Exclusive, r.size) closeButton.target = self closeButton.action = #selector(executeClose) return closeButton }() internal lazy var searchField: SBFindSearchField = { let string: String? = NSPasteboard(name: NSFindPboard).stringForType(NSStringPboardType) let searchField = SBFindSearchField(frame: self.searchRect) searchField.autoresizingMask = .ViewWidthSizable searchField.delegate = self searchField.target = self searchField.action = #selector(search(_:)) searchField.nextAction = #selector(searchForward(_:)) searchField.previousAction = #selector(searchBackward(_:)) searchField.cell!.sendsWholeSearchString = true searchField.cell!.sendsSearchStringImmediately = false string !! { searchField.stringValue = $0 } return searchField }() internal lazy var backwardButton: SBButton? = { let r = self.backwardRect let backwardButton = SBButton(frame: r) backwardButton.autoresizingMask = .ViewMinXMargin backwardButton.image = SBFindBackwardIconImage(r.size, true) backwardButton.disableImage = SBFindBackwardIconImage(r.size, false) backwardButton.target = self backwardButton.action = #selector(searchBackward(_:)) return backwardButton }() internal lazy var forwardButton: SBButton? = { let r = self.forwardRect let forwardButton = SBButton(frame: r) forwardButton.autoresizingMask = .ViewMinXMargin forwardButton.image = SBFindForwardIconImage(r.size, true) forwardButton.disableImage = SBFindForwardIconImage(r.size, false) forwardButton.target = self forwardButton.action = #selector(searchForward(_:)) forwardButton.keyEquivalent = "g" return forwardButton }() internal lazy var caseSensitiveCheck: BLKGUI.Button? = { let caseFlag = NSUserDefaults.standardUserDefaults().boolForKey(kSBFindCaseFlag) let caseSensitiveCheck = BLKGUI.Button(frame: self.caseSensitiveRect) caseSensitiveCheck.autoresizingMask = .ViewMinXMargin caseSensitiveCheck.buttonType = .SwitchButton caseSensitiveCheck.font = .systemFontOfSize(10.0) caseSensitiveCheck.title = NSLocalizedString("Ignore Case", comment: "") caseSensitiveCheck.state = caseFlag ? NSOnState : NSOffState caseSensitiveCheck.target = self caseSensitiveCheck.action = #selector(checkCaseSensitive(_:)) return caseSensitiveCheck }() internal lazy var wrapCheck: BLKGUI.Button? = { let wrapFlag = NSUserDefaults.standardUserDefaults().boolForKey(kSBFindWrapFlag) let wrapCheck = BLKGUI.Button(frame: self.wrapRect) wrapCheck.autoresizingMask = .ViewMinXMargin wrapCheck.buttonType = .SwitchButton wrapCheck.font = .systemFontOfSize(10.0) wrapCheck.title = NSLocalizedString("Wrap Around", comment: "") wrapCheck.state = wrapFlag ? NSOnState : NSOffState wrapCheck.target = self wrapCheck.action = #selector(checkWrap(_:)) return wrapCheck }() override init(frame: NSRect) { super.init(frame: frame) addSubview(contentView) contentView.addSubviews(searchField, closeButton) backwardButton !! contentView.addSubview forwardButton !! contentView.addSubview caseSensitiveCheck !! contentView.addSubview wrapCheck !! contentView.addSubview } required init(coder: NSCoder) { fatalError("NSCoding not supported") } class var minimumWidth: CGFloat { return 750 } class var availableWidth: CGFloat { return 300 } // MARK: Rects var contentRect: NSRect { var r = bounds r.size.width.constrain(min: self.dynamicType.minimumWidth) return r } var closeRect: NSRect { return NSMakeRect(0, 0, bounds.size.height, bounds.size.height) } var searchRect: NSRect { var r = NSZeroRect let marginNextToCase: CGFloat = 150.0; r.size.width = caseSensitiveRect.origin.x - closeRect.maxX - marginNextToCase - 24.0 * 2 r.size.height = 19.0 r.origin.x = closeRect.maxX r.origin.y = (bounds.size.height - r.size.height) / 2 return r } var backwardRect: NSRect { var r = NSZeroRect r.size.width = 24.0 r.size.height = 18.0 r.origin.y = (bounds.size.height - r.size.height) / 2 r.origin.x = searchRect.maxX return r } var forwardRect: NSRect { var r = NSZeroRect r.size.width = 24.0 r.size.height = 18.0 r.origin.y = (bounds.size.height - r.size.height) / 2 r.origin.x = backwardRect.maxX return r } var caseSensitiveRect: NSRect { var r = NSZeroRect r.size.width = 150.0 r.size.height = bounds.size.height r.origin.x = wrapRect.origin.x - r.size.width return r } var wrapRect: NSRect { var r = NSZeroRect r.size.width = 150.0 r.size.height = bounds.size.height r.origin.x = contentRect.size.width - r.size.width return r } // MARK: Delegate override func controlTextDidChange(notification: NSNotification) { if !searchField.stringValue.isEmpty { searchContinuous(nil) } } func control(control: NSControl, textView: NSTextView, doCommandBySelector command: Selector) -> Bool { if control === searchField && command == #selector(cancelOperation(_:)) && searchField.stringValue.isEmpty { executeClose() return true } return false } // MARK: Actions func selectText(sender: AnyObject?) { searchField.selectText(nil) } func searchContinuous(sender: AnyObject?) { executeSearch(true, continuous: true) } func search(sender: AnyObject?) { if !searchField.stringValue.isEmpty { executeSearch(true, continuous: false) executeClose() } } func searchBackward(sender: AnyObject?) { executeSearch(false, continuous: false) } func searchForward(sender: AnyObject?) { executeSearch(true, continuous: false) } func checkCaseSensitive(sender: AnyObject?) { let caseFlag = caseSensitiveCheck!.state == NSOnState NSUserDefaults.standardUserDefaults().setBool(caseFlag, forKey: kSBFindCaseFlag) } func checkWrap(sender: AnyObject?) { let wrapFlag = wrapCheck!.state == NSOnState NSUserDefaults.standardUserDefaults().setBool(wrapFlag, forKey: kSBFindWrapFlag) } func executeClose() { if target?.respondsToSelector(doneSelector) ?? false { NSApp.sendAction(doneSelector, to: target, from: self) } } func executeSearch(forward: Bool, continuous: Bool) -> Bool { var r = false let string = searchField.stringValue let pasteboard = NSPasteboard(name: NSFindPboard) pasteboard.declareTypes([NSStringPboardType], owner: self) pasteboard.setString(string, forType: NSStringPboardType) if let target = target as? SBFindbarTarget { let caseFlag = caseSensitiveCheck!.state == NSOnState let wrap = wrapCheck!.state == NSOnState r = target.searchFor(string, direction: forward, caseSensitive: caseFlag, wrap: wrap, continuous: continuous) } searchedString = string return r } // MARK: Drawing override func drawRect(rect: NSRect) { let lh: CGFloat = 1.0 // Background let gradient = NSGradient(startingColor: .blackColor(), endingColor: .init(deviceWhite: 0.50, alpha: 1.0))! gradient.drawInRect(bounds, angle: 90) // Lines NSColor.blackColor().set() NSRectFill(NSMakeRect(bounds.origin.x, bounds.maxY - lh, bounds.size.width, lh)) NSRectFill(NSMakeRect(bounds.origin.x, bounds.origin.y, bounds.size.width, lh)) } } class SBFindSearchField: NSSearchField { var nextAction: Selector = nil var previousAction: Selector = nil func performFindNext(sender: AnyObject?) { if target?.respondsToSelector(nextAction) ?? false { NSApp.sendAction(nextAction, to: target, from: self) } } func performFindPrevious(sender: AnyObject?) { if target?.respondsToSelector(previousAction) ?? false { NSApp.sendAction(previousAction, to: target, from: self) } } }
bsd-2-clause
0fa41985e87635af5816a5be57abf4ef
35.056291
121
0.658339
4.719549
false
false
false
false
ntwf/TheTaleClient
TheTale/Stores/AccountShow/Clan.swift
1
538
// // Clan.swift // TheTaleClient // // Created by Mikhail Vospennikov on 04/09/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import Foundation struct Clan { var id: Int var abbr: Int var name: String } extension Clan { init?(jsonObject: JSON) { guard let id = jsonObject["id"] as? Int, let abbr = jsonObject["abbr"] as? Int, let name = jsonObject["name"] as? String else { return nil } self.id = id self.abbr = abbr self.name = name } }
mit
bc3228d6480044303da6f13c164ebd20
17.517241
62
0.599628
3.487013
false
false
false
false
denrase/TimeTracking-iOS
TimeTracking WatchKit Extension/TodayController.swift
1
3737
// // TodayController.swift // TimeTracking // // Created by Denis Andrasec on 01.05.15. // Copyright (c) 2015 Bytepoets. All rights reserved. // import WatchKit import Foundation import TimeTrackingKit class TodayController: WKInterfaceController { @IBOutlet weak var disabledTimerLabel: WKInterfaceLabel! @IBOutlet weak var workedInterfaceTimer: WKInterfaceTimer! @IBOutlet weak var pausedTimeLabel: WKInterfaceLabel! @IBOutlet weak var startStopButton: WKInterfaceButton! var todaysWorkDay: WorkDay? override func willActivate() { super.willActivate() updateInterface() fetchStatus() } @IBAction func pressedStartStop() { if let today = todaysWorkDay { if (today.timeStatus() == WorkDay.Status.Running) { sendStop() } else { sendStart() } } } @IBAction func refresh() { fetchStatus() } func updateInterface() { if let today = self.todaysWorkDay { self.workedInterfaceTimer.setHidden(false) self.disabledTimerLabel.setHidden(true) self.startStopButton.setEnabled(true) if (today.timeStatus() == WorkDay.Status.Running) { self.startStopButton.setBackgroundColor(TimeTrackingColors.red()) self.startStopButton.setTitle("STOP") self.workedInterfaceTimer.start() } else { self.startStopButton.setBackgroundColor(TimeTrackingColors.green()) self.startStopButton.setTitle("START") self.workedInterfaceTimer.stop() } self.workedInterfaceTimer.setDate(today.todaysStartDate()) let pausedHours = String(format: "%02d", today.pausedHoursAndMinutesToday().0) let pausedMinutes = String(format: "%02d", today.pausedHoursAndMinutesToday().1) self.pausedTimeLabel.setText("\(pausedHours):\(pausedMinutes)") } else { self.workedInterfaceTimer.setHidden(true) self.disabledTimerLabel.setHidden(false) self.startStopButton.setBackgroundColor(UIColor.lightGrayColor()) self.startStopButton.setTitle("START") self.startStopButton.setEnabled(false) self.workedInterfaceTimer.setDate(NSDate()) self.workedInterfaceTimer.stop() self.pausedTimeLabel.setText("--") } } func fetchStatus() { APIClient.sharedInstance.status { (workDay, error) -> Void in if (error == nil && workDay != nil) { self.todaysWorkDay = workDay; } else { print("Error retrieving status"); } self.updateInterface() } } func sendStart() { startStopButton.setEnabled(false) APIClient.sharedInstance.start { (workDay, error) -> Void in if (error == nil && workDay != nil) { self.todaysWorkDay = workDay; } else { print("Error starting timetracking"); } self.updateInterface() } } func sendStop() { startStopButton.setEnabled(false) APIClient.sharedInstance.stop { (workDay, error) -> Void in if (error == nil && workDay != nil) { self.todaysWorkDay = workDay; } else { print("Error stopping timetracking"); } self.updateInterface() } } }
mit
d150a4ef1c047cb07a5ce1447ad30621
29.884298
92
0.559005
5.197497
false
false
false
false
terietor/GTForms
Source/FormSection.swift
1
5868
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class FormSection { weak var tableViewType: TableViewType? /** The rows of the section */ public private(set) var rows: [FormRow] = [FormRow]() /** The title of the section */ public var title: String? public init() {} /** Adds a new row to the section from a FormViewable - parameter form: the form from which the new row will be created */ @discardableResult public func addRow(_ form: FormableType) -> FormRow { let row = FormRow(form: form) self.rows.append(row) return row } /** Appends a new row in the section - parameter form: The form that will be appended to the tableView - parameter animation: The UITableViewRowAnimation which will be used */ @discardableResult public func appendRow(_ form: FormableType, animation: UITableViewRowAnimation) -> FormRow { let row = addRow(form) guard let tableViewType = self.tableViewType, let tableView = tableViewType.tableView else { return row } tableView.beginUpdates() defer { tableView.endUpdates() } guard let section = tableViewType.formSections.index(where: { $0 === self }) else { return row } let indexPath = IndexPath( row: formItemsForSection().count - 1, section: section ) tableView.insertRows(at: [indexPath], with: animation) return row } /** Removes a new row from the section - parameter form: The form that will be removed from the tableView - parameter animation: The UITableViewRowAnimation which will be used */ public func removeRow(_ form: FormableType, animation: UITableViewRowAnimation) { guard let tableViewType = self.tableViewType, let tableView = tableViewType.tableView else { return } tableView.beginUpdates() defer { tableView.endUpdates() } guard let section = tableViewType.formSections.index(where: { $0 === self }) else { return } var rowsToDelete = [Int]() for (index, item) in formItemsForSection().enumerated() { if let f = item as? FormRow , f.form === form { rowsToDelete.append(index) } else if let baseSelectionItem = item as? BaseSelectionFormItem, let selectionForm = form as? BaseSelectionForm , baseSelectionItem.selectionForm === selectionForm { rowsToDelete.append(index) } } if rowsToDelete.isEmpty { return } var isSafeToDeleteRow = false for (index, it) in self.rows.enumerated() { if it.form === form { self.rows.remove(at: index) isSafeToDeleteRow = true break } } if !isSafeToDeleteRow { return } var indexPaths = [IndexPath]() rowsToDelete.forEach() { indexPaths.append(IndexPath( row: $0, section: section ) ) } tableView.deleteRows(at: indexPaths, with: animation) } /** Returns all the items in the section. It doesn't return the same number of items as the rows variable - returns: All the items of the section */ func formItemsForSection() -> [AnyObject] { var formRows = [AnyObject]() for row in self.rows { formRows.append(row) if let selectionForm = row.form as? BaseSelectionForm, let showItems = selectionForm.showItems , showItems { selectionForm.items.forEach() { formRows.append($0) } } else if let selectionForm = row.form as? BaseSelectionForm , selectionForm.shouldAlwaysShowAllItems { selectionForm.items.forEach() { formRows.append($0) } } if let datePickerForm = row.form as? FormDatePickerType, let shouldExpand = datePickerForm.shouldExpand , shouldExpand { formRows.append(datePickerForm.datePicker) } } return formRows } }
mit
39c650f24da04f0b3acf6b547fd7de52
29.404145
96
0.575494
5.071737
false
false
false
false
artursDerkintis/YouTube
YouTube/ChannelsViewController.swift
1
2208
// // ChannelsViewController.swift // YouTube // // Created by Arturs Derkintis on 1/30/16. // Copyright © 2016 Starfly. All rights reserved. // import UIKit class ChannelsViewController: UINavigationController { var channelViewControllers = [ChannelViewController]() override func viewDidLoad() { super.viewDidLoad() navigationBarHidden = true // Do any additional setup after loading the view. } func addChannelController(channel : Channel){ let channelVC = ChannelViewController() channelVC.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext channelVC.modalTransitionStyle = .CrossDissolve let last = channelViewControllers.last ?? self last.presentViewController(channelVC, animated: true, completion: nil) if let lasty = last as? ChannelViewController{ UIView.animateWithDuration(0.3, animations: { () -> Void in lasty.collectionView.alpha = 0.0 lasty.collectionView.transform = CGAffineTransformMakeScale(0.7, 0.7) }) } self.channelViewControllers.append(channelVC) channelVC.pageToken = nil channelVC.loadVideosForChannel(channel.channelDetails!.id!) channelVC.loading = true channelVC.collectionView.scrollsToTop = true } func removeCurrentChannelController(){ if let lastVC = channelViewControllers.last{ channelViewControllers.removeLast() lastVC.dismissViewControllerAnimated(true, completion: nil) if let last = channelViewControllers.last{ UIView.animateWithDuration(0.3, animations: { () -> Void in last.collectionView.alpha = 1.0 last.collectionView.transform = CGAffineTransformIdentity }) } } } func removeAll(){ for vc in channelViewControllers{ vc.dismissViewControllerAnimated(true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5df670f6c8be1eeb8014f91beeb64af3
32.953846
86
0.647938
5.462871
false
false
false
false
StephenMIMI/U17Comics
U17Comics/U17Comics/classes/Public/MainTabBarController.swift
1
4691
// // MainTabBarController.swift // U17Comics // // Created by qianfeng on 16/10/21. // Copyright © 2016年 zhb. All rights reserved. // import UIKit import SnapKit class MainTabBarController: UITabBarController { private var bgView: UIView? override func viewDidLoad() { super.viewDidLoad() createViewControllers() } func createViewControllers() { let nameArray = ["HomePageViewController","SearchViewController"] let imageArray = ["tabbar_comic","tabbar_Special"] let titleArray = ["首页","分类"] // let nameArray = ["HomePageViewController","SearchViewController","BookShelfViewController","ProfileViewController"] // let imageArray = ["tabbar_comic","tabbar_Special","tabbar_collection","tabbar_mine"] // let titleArray = ["首页","分类","书架","我的"] var ctrlArray = Array<UINavigationController>() for i in 0..<nameArray.count { let name = "U17Comics."+nameArray[i] let ctrl = NSClassFromString(name) as! UIViewController.Type let vc = ctrl.init() let navCtrl = UINavigationController(rootViewController: vc) ctrlArray.append(navCtrl) } viewControllers = ctrlArray //隐藏系统的tabbar tabBar.hidden = true createMyTabBar(imageArray,titles: titleArray) } func createMyTabBar(imageNames: Array<String>, titles: Array<String>) { bgView = UIView.createView() bgView?.backgroundColor = UIColor.whiteColor() view.addSubview(bgView!) bgView?.snp_makeConstraints(closure: { [weak self](make) in make.left.right.bottom.equalTo(self!.view) make.height.equalTo(49) }) let width = screenWidth/CGFloat(imageNames.count) for i in 0..<imageNames.count { //首先创建2个按钮添加视图 let btnView = UIView.createView() bgView?.addSubview(btnView) btnView.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(bgView!) make.width.equalTo(width) make.left.equalTo(width*CGFloat(i)) }) //循环创建按钮 let imageName = imageNames[i]+"_normal" let selectName = imageNames[i]+"_selected" let btn = UIButton.createBtn(nil, normalImage: imageName, highlightImage: nil, selectImage: selectName, target: self, action: #selector(btnClick(_:))) btn.tag = 100+i btn.adjustsImageWhenHighlighted = false//禁用高亮 bgView?.addSubview(btn) btn.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(btnView) make.centerX.equalTo(btnView) make.width.equalTo(80) }) let titleLabel = UILabel.createLabel(titles[i], textAlignment: .Center, font: UIFont.systemFontOfSize(10)) titleLabel.textColor = UIColor.lightGrayColor() titleLabel.backgroundColor = UIColor.whiteColor() titleLabel.tag = 400 btn.addSubview(titleLabel) titleLabel.snp_makeConstraints(closure: { (make) in make.left.right.bottom.equalTo(btn) make.height.equalTo(12) }) //默认选中第一个按钮 if i == 0 { btn.selected = true titleLabel.textColor = UIColor.redColor() } } } func showTabBar() { UIView.animateWithDuration(0.25) { [weak self] in self!.bgView?.hidden = false } } func hideTabBar() { UIView.animateWithDuration(0.25) { [weak self] in self!.bgView?.hidden = true } } func btnClick(curBtn: UIButton) { let index = curBtn.tag-100 //1.1 获取取消选中之前的按钮 let lastBtn = bgView?.viewWithTag(100+selectedIndex) as! UIButton lastBtn.selected = false lastBtn.userInteractionEnabled = true let lastLabel = lastBtn.viewWithTag(400) as! UILabel lastLabel.textColor = UIColor.lightGrayColor() //1.2选中当前按钮 curBtn.selected = true selectedIndex = index curBtn.userInteractionEnabled = false let curLabel = curBtn.viewWithTag(400) as! UILabel curLabel.textColor = UIColor.redColor() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
e742a9077dda00c30dddd010dc8e9576
33.80916
162
0.591228
4.820296
false
false
false
false
panther99/Projects
swift/projects.swift
1
1982
// // projects.swift // Projects // // Created by panther99 on 8/13/17. // Copyright © 2017 panther99. All rights reserved. // import Foundation func fib(n: Int) -> Int { switch n { case 0: return 0 case 1: return 1 default: return fib(n: n-1) + fib(n: n-2) } } func fact(n: Int) -> Int { return (n <= 1) ? 1 : n * fact(n: n-1) } func primeFactors(n: Int) -> [Int] { var primeFactors: [Int] = [Int]() var x: Int = n var d: Int = 2 while (d * d <= n) { while (x % d == 0) { primeFactors.append(d) x = x / d } d += 1 } if (x > 1) { primeFactors.append(x) } return primeFactors } func reverse(string: String) -> String { let strlen: Int = string.characters.count var reversedString: String = "" for i in stride(from: strlen, to: 0, by: -1) { reversedString += String(string[string.index(string.startIndex, offsetBy: i-1)]) } return reversedString } func isPalindrome(string: String) -> Bool { return string == reverse(string: string) } func fizzbuzz(limit: Int) { for i in 0..<limit { if (i % 3 == 0 && i % 5 == 0) { print("FizzBuzz") } else if (i % 3 == 0) { print("Fizz") } else if (i % 5 == 0) { print("Buzz") } else { print(i) } } } func wordsCount(string: String) -> Int { return string.components(separatedBy: [" ", ".", "!", "?", "-"]).filter {$0 != ""}.count } func vowelsCount(string: String) -> Int { let lower: String = string.lowercased() var counter: Int = 0 for i in 0..<string.characters.count { switch(String(lower[lower.index(lower.startIndex, offsetBy: i)])) { case "a", "e", "i", "o", "u": counter += 1 default: continue } } return counter }
mit
fdd9aba5f347b3a266c4bcbe75bce719
20.311828
92
0.491671
3.45122
false
false
false
false
longjianjiang/BlogDemo
CAGradientLayerDemo/CAGradientLayerDemo/GradientAnimationViewController.swift
1
3434
// // GradientAnimationViewController.swift // CAGradientLayerDemo // // Created by longjianjiang on 2017/10/7. // Copyright © 2017年 Jiang. All rights reserved. // import UIKit class LockEffectLabel: UIView { var gradientLayer: CAGradientLayer = { let layer = CAGradientLayer() layer.startPoint = CGPoint(x: 0, y: 0.5) layer.endPoint = CGPoint(x: 1, y: 0.5) layer.colors = [ UIColor.black.cgColor, UIColor.white.cgColor, UIColor.black.cgColor] let locations: [NSNumber] = [ 0.25, 0.5, 0.75] layer.locations = locations layer.backgroundColor = UIColor.red.cgColor return layer }() let textAttributes: [NSAttributedStringKey: AnyObject] = { let style = NSMutableParagraphStyle() style.alignment = .center return [ NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue): UIFont( name: "HelveticaNeue-Thin", size: 28.0)!, NSAttributedStringKey(rawValue: NSAttributedStringKey.paragraphStyle.rawValue): style ] }() var text: String! override func layoutSubviews() { gradientLayer.frame = CGRect(x: -bounds.width, y: bounds.origin.y, width: 3 * bounds.width, height: bounds.height) setNeedsDisplay() let image = UIGraphicsImageRenderer(size: bounds.size) .image { _ in text.draw(in: bounds, withAttributes: textAttributes) } let maskLayer = CALayer() maskLayer.backgroundColor = UIColor.clear.cgColor maskLayer.frame = bounds.offsetBy(dx: bounds.width, dy: 0) maskLayer.contents = image.cgImage gradientLayer.mask = maskLayer } override func didMoveToWindow() { super.didMoveToWindow() layer.addSublayer(gradientLayer) let gradientAnimation = CABasicAnimation(keyPath: "locations") gradientAnimation.fromValue = [0.0, 0.0, 0.25] gradientAnimation.toValue = [0.75, 1.0, 1.0] gradientAnimation.duration = 3.0 gradientAnimation.repeatCount = Float.infinity gradientLayer.add(gradientAnimation, forKey: nil) } } class GradientAnimationViewController: UIViewController { var slideLockView = LockEffectLabel() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.gray slideLockView.text = "滑动来解锁" slideLockView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(slideLockView) slideLockView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 70).isActive = true slideLockView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -70).isActive = true slideLockView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100).isActive = true slideLockView.heightAnchor.constraint(equalToConstant: 44).isActive = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
ccec3810016a69be2b2f7130be9c1c13
31.273585
108
0.608009
5.159879
false
false
false
false
dreamsxin/swift
stdlib/public/core/ErrorType.swift
3
5802
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // TODO: API review /// A type representing an error value that can be thrown. /// /// Any type that declares conformance to `ErrorProtocol` can be used to /// represent an error in Swift's error handling system. Because /// `ErrorProtocol` has no requirements of its own, you can declare /// conformance on any custom type you create. /// /// Using Enumerations as Errors /// ============================ /// /// Swift's enumerations are well suited to represent simple errors. Create an /// enumeration that conforms to `ErrorProtocol` with a case for each possible /// error. If there are additional details about the error that could be /// helpful for recovery, use associated values to include that information. /// /// The following example shows an `IntParsingError` enumeration that captures /// two different kinds of errors that can occur when parsing an integer from /// a string: overflow, where the value represented by the string is too large /// for the integer data type, and invalid input, where nonnumeric characters /// are found within the input. /// /// enum IntParsingError: ErrorProtocol { /// case overflow /// case invalidInput(String) /// } /// /// The `invalidInput` case includes the invalid character as an associated /// value. /// /// The next code sample shows a possible extension to the `Int` type that /// parses the integer value of a `String` instance, throwing an error when /// there is a problem during parsing. /// /// extension Int { /// init(validating input: String) throws { /// // ... /// if !_isValid(s) { /// throw IntParsingError.invalidInput(s) /// } /// // ... /// } /// } /// /// When calling the new `Int` initializer within a `do` statement, you can use /// pattern matching to match specific cases of your custom error type and /// access their associated values, as in the example below. /// /// do { /// let price = try Int(validating: "$100") /// } catch IntParsingError.invalidInput(let invalid) { /// print("Invalid character: '\(invalid)'") /// } catch IntParsingError.overflow { /// print("Overflow error") /// } catch { /// print("Other error") /// } /// // Prints "Invalid character: '$'" /// /// Including More Data in Errors /// ============================= /// /// Sometimes you may want different error states to include the same common /// data, such as the position in a file or some of your application's state. /// When you do, use a structure to represent errors. The following example /// uses a structure to represent an error when parsing an XML document, /// including the line and column numbers where the error occurred: /// /// struct XMLParsingError: ErrorProtocol { /// enum ErrorKind { /// case invalidCharacter /// case mismatchedTag /// case internalError /// } /// /// let line: Int /// let column: Int /// let kind: ErrorKind /// } /// /// func parse(_ source: String) throws -> XMLDoc { /// // ... /// throw XMLParsingError(line: 19, column: 5, kind: .mismatchedTag) /// // ... /// } /// /// Once again, use pattern matching to conditionally catch errors. Here's how /// you can catch any `XMLParsingError` errors thrown by the `parse(_:)` /// function: /// /// do { /// let xmlDoc = try parse(myXMLData) /// } catch let e as XMLParsingError { /// print("Parsing error: \(e.kind) [\(e.line):\(e.column)]") /// } catch { /// print("Other error: \(error)") /// } /// // Prints "Parsing error: mismatchedTag [19:5]" public protocol ErrorProtocol { var _domain: String { get } var _code: Int { get } } extension ErrorProtocol { public var _domain: String { return String(reflecting: self.dynamicType) } } #if _runtime(_ObjC) // Helper functions for the C++ runtime to have easy access to domain and // code as Objective-C values. @_silgen_name("swift_stdlib_getErrorDomainNSString") public func _stdlib_getErrorDomainNSString<T : ErrorProtocol>(_ x: UnsafePointer<T>) -> AnyObject { return x.pointee._domain._bridgeToObjectiveCImpl() } @_silgen_name("swift_stdlib_getErrorCode") public func _stdlib_getErrorCode<T : ErrorProtocol>(_ x: UnsafePointer<T>) -> Int { return x.pointee._code } // Known function for the compiler to use to coerce `ErrorProtocol` instances // to `NSError`. @_silgen_name("swift_bridgeErrorProtocolToNSError") public func _bridgeErrorProtocolToNSError(_ error: ErrorProtocol) -> AnyObject #endif /// Invoked by the compiler when the subexpression of a `try!` expression /// throws an error. @_silgen_name("swift_unexpectedError") public func _unexpectedError(_ error: ErrorProtocol) { preconditionFailure("'try!' expression unexpectedly raised an error: \(String(reflecting: error))") } /// Invoked by the compiler when code at top level throws an uncaught error. @_silgen_name("swift_errorInMain") public func _errorInMain(_ error: ErrorProtocol) { fatalError("Error raised at top level: \(String(reflecting: error))") } @available(*, unavailable, renamed: "ErrorProtocol") public typealias ErrorType = ErrorProtocol
apache-2.0
5423aa9d7f6eb87538c6b2c50b786f98
36.192308
101
0.639779
4.392127
false
false
false
false