repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
bryant81pts/PhotoBrowser
refs/heads/master
PhotoBrowser/PhotoBrowser/Classes/Home/HomeCollectionViewLayout.swift
mit
1
// // HomeCollectionViewLayout.swift // PhotoBrowser // // Created by Mac on 16/4/28. // Copyright © 2016年 dalpha. All rights reserved. // import UIKit class HomeCollectionViewLayout: UICollectionViewFlowLayout { /** Tells the layout object to update the current layout. Layout updates occur the first time the collection view presents its content and whenever the layout is invalidated explicitly or implicitly because of a change to the view. During each layout update, the collection view calls this method first to give your layout object a chance to prepare for the upcoming layout operation. The default implementation of this method does nothing. Subclasses can override it and use it to set up data structures or perform any initial computations needed to perform the layout later. */ override func prepareLayout() { //item之间的间距 let margin : CGFloat = 10 //列数 let colums : CGFloat = 3 //计算item的宽度 let itemWidth : CGFloat = (UIScreen.mainScreen().bounds.width - (colums + 1) * margin) / colums minimumLineSpacing = margin minimumInteritemSpacing = margin itemSize = CGSize(width: itemWidth, height: itemWidth) //假如scroll view嵌套了navigation controller 那么为了不让scroll view的内容被 navigation bar挡住 所以系统会将scroll view的内边距增加64,但如果自己设置scroll view的contentInset,系统就不会帮增加内边距,需要自己设置 collectionView?.contentInset = UIEdgeInsets(top: margin + 64, left: margin, bottom: margin, right: margin) } }
9ab15f89062abacdfbe72c4c83856311
39.333333
331
0.701208
false
false
false
false
loretoparisi/swift-promise-example
refs/heads/master
CrossTest/CrossTest/Promise+Foundation.swift
mit
1
// // Promise.swift // CrossTest // // Created by Loreto Parisi on 16/12/15. // Copyright © 2015 Musixmatch. All rights reserved. // import Foundation class Deferred: Promise { var promise:Promise override convenience init() { self.init(promise: Promise()) } private init(promise: Promise) { self.promise = promise } func resolve(value: AnyObject?) { promise.doResolve(value) } func reject(error: AnyObject?) { promise.doReject(error) } override func then(then: thenClosure) -> Promise { return promise.then(then) } override func catch_(catch_: catchClosure) -> Promise { return promise.catch_(catch_) } override func finally(finally: finallyClosure) -> Promise { return promise.finally(finally) } } class Promise { enum Status: String { case PENDING = "Pending" case RESOLVED = "Resolved" case REJECTED = "Rejected" } typealias thenClosure = (AnyObject?) -> (AnyObject?) typealias thenClosureNoReturn = (AnyObject?) -> () typealias catchClosure = (AnyObject?) -> () typealias finallyClosure = () -> () typealias promiseClosure = ( (AnyObject?) -> (), (AnyObject?) -> () ) -> () var thens = Array<thenClosure>() var cat: catchClosure? var fin: finallyClosure? var value: AnyObject? var _status: Status = .PENDING private var statusObserver: ( (Promise) -> () )? var status: Status { get { return _status } set(status) { _status = status statusObserver?(self) } } private init() { } func then(then: thenClosureNoReturn) -> Promise { self.then { (value) -> (AnyObject?) in then(value) return nil } return self } func then(then: thenClosure) -> Promise { self.sync { () in if (self.status == .PENDING) { self.thens.append(then) } else if (self.status == .RESOLVED) { then(self.value) } } return self } func catch_(catch_: catchClosure) -> Promise { if (self.cat != nil) { return self } self.sync { () in if (self.status == .PENDING) { self.cat = catch_ } else if (self.status == .REJECTED) { catch_(self.value) } } return self } func finally(finally: finallyClosure) -> Promise { if (self.fin != nil) { return self } self.sync { () in if (self.status == .PENDING) { self.fin = finally } else { finally() } } return self } /*func sync(closure: () -> ()) { let lockQueue = dispatch_queue_create("com.rokkincat.promises.LockQueue", nil) dispatch_sync(lockQueue, closure) }*/ func sync<T>(lock: AnyObject, @noescape closure: () -> T) -> T { objc_sync_enter(lock) defer { objc_sync_exit(lock) } return closure() } private func doResolve(value: AnyObject?, shouldRunFinally: Bool = true) { self.sync { () in if (self.status != .PENDING) { return } self.value = value var chain: Promise? var paramValue: AnyObject? = self.value for (_, then) in self.thens.enumerate() { // If a chain is hit, add the then if (chain != nil) { chain?.then(then); return } let ret: AnyObject? = then(paramValue) if let retPromise = ret as? Promise { // Set chained promised chain = retPromise // // Transfer catch and finally to chained promise if (self.cat != nil) { chain?.catch_(self.cat!); self.cat = nil } if (self.fin != nil) { chain?.finally(self.fin!); self.fin = nil } } else if let retAny: AnyObject = ret { paramValue = retAny } } // Run the finally if (shouldRunFinally) { if (chain == nil) { self.doFinally(.RESOLVED) } } } } private func doReject(error: AnyObject?, shouldRunFinally: Bool = true) { self.sync { () in if (self.status != .PENDING) { return } self.value = error self.cat?(self.value) if (shouldRunFinally) { self.doFinally(.REJECTED) } } } private func doFinally(status: Status) { if (self.status != .PENDING) { return } self.status = status self.fin?() } } extension Promise { convenience init(promiseClosure: ( resolve: (AnyObject?) -> (), reject: (AnyObject?) -> () ) -> ()) { self.init() let deferred = Deferred(promise: self) promiseClosure( resolve: deferred.resolve, reject: deferred.reject ) } } extension Promise { class func all(promises: Array<Promise>) -> Promise { return All(promises: promises) } private class All: Promise { var promises = Array<Promise>() var promiseCount: Int = 0 var numberOfResolveds: Int = 0 var numberOfRejecteds: Int = 0 var total: Int { get { return numberOfResolveds + numberOfRejecteds } } private var statusToChangeTo: Status = .PENDING private func observe(promise: Promise) { self.sync { () in switch promise.status { case .RESOLVED: self.numberOfResolveds++ case .REJECTED: self.numberOfRejecteds++ if (self.statusToChangeTo == .PENDING) { self.statusToChangeTo = .REJECTED self.doReject(promise.value, shouldRunFinally: false) } default: 0 // noop } if (self.total >= self.promiseCount) { if (self.statusToChangeTo == .PENDING) { self.statusToChangeTo = .RESOLVED // Need to filter out nil values before mapping values to array let filteredNils = self.promises.filter( { (p) -> (Bool) in return (p.value != nil) } ) let values = filteredNils.map( { (p) -> (AnyObject) in print(p.value); return p.value! } ) self.doResolve(values, shouldRunFinally: false) } self.doFinally(self.statusToChangeTo) } } } init(promises: Array<Promise>) { super.init() self.promiseCount = promises.count for promise in promises { let p = (promise as? Deferred == nil) ? promise : (promise as! Deferred).promise self.promises.append(p) p.statusObserver = observe } } } }
44889a3010b18c49aef442a6096e53f3
26.588028
114
0.465348
false
false
false
false
JerrySir/YCOA
refs/heads/master
YCOA/Main/DetailPage/View/DetailPageTableVC_ReplyTableViewCell.swift
mit
1
// // DetailPageTableVC_ReplyTableViewCell.swift // YCOA // // Created by Jerry on 2017/2/1. // Copyright © 2017年 com.baochunsteel. All rights reserved. // // 回复Cell import UIKit class DetailPageTableVC_ReplyTableViewCell: UITableViewCell { open var infoStringTextView: UITextView! private var submitButton: UIButton! private var selectActionOptionButton: UIButton! open func configure(selectedOptionString: String, didSelectTap: @escaping (_ sender: UIButton)-> Swift.Void, didSubmitTap: @escaping (_ sender: UIButton,_ infoString: String)-> Swift.Void) { self.selectActionOptionButton.setTitle(selectedOptionString, for: .normal) self.selectActionOptionButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (sender) in didSelectTap((sender as! UIButton)) } self.submitButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (sender) in didSubmitTap((sender as! UIButton), self.infoStringTextView.text) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.contentView.backgroundColor = UIColor.groupTableViewBackground let titleLabel = UILabel() titleLabel.text = "任务回复" titleLabel.textColor = UIColor.darkText titleLabel.font = UIFont.systemFont(ofSize: 22) self.contentView.addSubview(titleLabel) let bgView = UIView() bgView.backgroundColor = UIColor.white self.contentView.addSubview(bgView) let selectActionOptionLabel = UILabel() selectActionOptionLabel.text = "*处理动作:" selectActionOptionLabel.font = UIFont.systemFont(ofSize: 17) selectActionOptionLabel.textColor = UIColor.lightGray bgView.addSubview(selectActionOptionLabel) self.selectActionOptionButton = UIButton(type: .system) self.selectActionOptionButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) self.selectActionOptionButton.setTitle("请选择", for: .normal) self.selectActionOptionButton.backgroundColor = UIColor.white self.selectActionOptionButton.setTitleColor(UIColor.darkText, for: .normal) self.selectActionOptionButton.titleLabel?.textAlignment = .left self.selectActionOptionButton.layer.masksToBounds = true self.selectActionOptionButton.layer.borderColor = UIColor.lightGray.cgColor self.selectActionOptionButton.layer.borderWidth = 1 self.selectActionOptionButton.layer.cornerRadius = 0.1 bgView.addSubview(self.selectActionOptionButton) let infoStringLabel = UILabel() infoStringLabel.text = "说明:" infoStringLabel.font = UIFont.systemFont(ofSize: 17) infoStringLabel.textColor = UIColor.lightGray bgView.addSubview(infoStringLabel) self.infoStringTextView = UITextView() self.infoStringTextView.font = UIFont.systemFont(ofSize: 16) self.infoStringTextView.layer.masksToBounds = true self.infoStringTextView.layer.borderColor = UIColor.lightGray.cgColor self.infoStringTextView.layer.borderWidth = 1 self.infoStringTextView.layer.cornerRadius = 0.1 bgView.addSubview(self.infoStringTextView) self.submitButton = UIButton(type: .system) self.submitButton.setTitle("提交处理", for: .normal) self.submitButton.backgroundColor = UIColor.init(colorLiteralRed: 30/255.0, green: 160/255.0, blue: 80/255.0, alpha: 1) self.submitButton.setTitleColor(UIColor.white, for: .normal) bgView.addSubview(self.submitButton) //AutoLayout titleLabel.snp.makeConstraints { (make) in make.left.top.equalTo(8) } bgView.snp.makeConstraints { (make) in make.left.equalTo(8) make.top.equalTo(titleLabel.snp.bottom).offset(8) make.right.bottom.equalTo(-8) make.bottom.equalTo(-8) } selectActionOptionLabel.snp.makeConstraints { (make) in make.left.equalTo(8) make.centerY.equalTo(self.selectActionOptionButton.snp.centerY) make.width.lessThanOrEqualTo(self.selectActionOptionButton.snp.width) } self.selectActionOptionButton.snp.makeConstraints { (make) in make.left.equalTo(selectActionOptionLabel.snp.right).offset(8) make.top.equalTo(8) make.right.equalTo(-8) make.height.equalTo(44) } infoStringLabel.snp.makeConstraints { (make) in make.left.equalTo(8) make.centerY.equalTo(infoStringTextView.snp.centerY) } self.infoStringTextView.snp.makeConstraints { (make) in make.left.equalTo(infoStringLabel.snp.right).offset(8) make.top.equalTo(self.selectActionOptionButton.snp.bottom).offset(8) make.right.equalTo(-8) make.height.equalTo(55) } self.submitButton.snp.makeConstraints { (make) in make.left.equalTo(8) make.top.equalTo(infoStringTextView.snp.bottom).offset(8) make.right.bottom.equalTo(-8) make.height.equalTo(50) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
a763df07377298fa81742ac017a814e3
40.104895
192
0.666553
false
false
false
false
DanielOYC/Tools
refs/heads/master
YCEmoticonKeyboard/YCEmoticonKeyboard/YCEmoticonView/YCEmoticonView.swift
mit
1
// // YCEmoticonView.swift // YCEmoticonKeyboard // // Created by daniel on 2017/8/20. // Copyright © 2017年 daniel. All rights reserved. // import UIKit import SnapKit fileprivate let kEmoticonCollectionViewCellId = "kEmoticonCollectionViewCellId" class YCEmoticonView: UIView { fileprivate let kEmoticonToolBarH: CGFloat = 45.0 // 表情键盘底部工具条高度 fileprivate let kEmoticonContentViewH: CGFloat = 226.0 // 表情键盘内容高度 fileprivate lazy var packages: [YCEmoticons] = { // 表情包数据源 return YCEmoticonsViewModel().packages! }() // fileprivate var clickEmoticonCallBack: (YCEmoticon) -> () weak var targetTextView: UITextView? // init(clickEmoticon: @escaping (YCEmoticon) -> ()) { // // clickEmoticonCallBack = clickEmoticon // // let tempFrame = CGRect(x: 0, y: 0, width: 0, height: kEmoticonToolBarH + kEmoticonContentViewH) // super.init(frame: tempFrame) // // setupUI() // // //准备历史表情数据 // prepareHistoryEmoticons() // // } init(targetView: UITextView) { targetTextView = targetView // targetTextView?.font = UIFont.systemFont(ofSize: 34) let tempFrame = CGRect(x: 0, y: 0, width: 0, height: kEmoticonToolBarH + kEmoticonContentViewH) super.init(frame: tempFrame) setupUI() //准备历史表情数据 prepareHistoryEmoticons() } //准备历史表情数据 fileprivate func prepareHistoryEmoticons() { let historyEmoticons = YCEmoticons(dic: ["emoticons" : ["" : ""]]) packages.insert(historyEmoticons, at: 0) } @objc fileprivate func toolBarItemClick(item: UIBarButtonItem) { let index = item.tag - 1000 emoticonContentView.scrollToItem(at: NSIndexPath(item: 0, section: index) as IndexPath, at: .left, animated: true) } // 底部工具条 fileprivate lazy var toolBar: UIToolbar = UIToolbar() // 表情内容视图 fileprivate lazy var emoticonContentViewLayout: UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout() let width = UIScreen.main.bounds.width / 7 layout.itemSize = CGSize(width: width, height: width) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = UICollectionViewScrollDirection.horizontal return layout }() fileprivate lazy var emoticonContentView: UICollectionView = { let contentView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.emoticonContentViewLayout) return contentView }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置界面 extension YCEmoticonView { fileprivate func setupUI() { addSubview(toolBar) addSubview(emoticonContentView) emoticonContentView.backgroundColor = UIColor.white toolBar.snp.makeConstraints { (make) in make.bottom.equalToSuperview() make.left.equalToSuperview() make.right.equalToSuperview() make.height.equalTo(kEmoticonToolBarH) } emoticonContentView.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview() make.right.equalToSuperview() make.bottom.equalTo(toolBar.snp.top) } // 设置工具条内容 setupToolBar() // 设置表情内容视图 setupEmoticonContentView() } // 设置工具条内容 fileprivate func setupToolBar() { var items = [UIBarButtonItem]() let historyItem = UIBarButtonItem.init(title: "历史", style: .plain, target: self, action: #selector(YCEmoticonView.toolBarItemClick(item:))) historyItem.tag = 1000 historyItem.tintColor = UIColor.darkGray items.append(historyItem) var index = 1 for emoticons in packages { items.append(UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)) let item = UIBarButtonItem.init(title: emoticons.group_name_cn, style: .plain, target: self, action: #selector(YCEmoticonView.toolBarItemClick(item:))) item.tag = 1000 + index item.tintColor = UIColor.darkGray items.append(item) index += 1 } toolBar.items = items } // 设置表情内容视图 fileprivate func setupEmoticonContentView() { let margin = (kEmoticonContentViewH - (UIScreen.main.bounds.width / 7 * 3)) / 2 emoticonContentView.contentInset = UIEdgeInsetsMake(margin, 0, margin, 0) emoticonContentView.register(YCEmoticonViewCell.self, forCellWithReuseIdentifier: kEmoticonCollectionViewCellId) emoticonContentView.isPagingEnabled = true emoticonContentView.bounces = false emoticonContentView.dataSource = self emoticonContentView.delegate = self } } // MARK: - UICollectionView DataSource extension YCEmoticonView: UICollectionViewDataSource,UICollectionViewDelegate { func numberOfSections(in collectionView: UICollectionView) -> Int { return packages.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return packages[section].emoticons.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kEmoticonCollectionViewCellId, for: indexPath) as! YCEmoticonViewCell cell.emoticon = packages[indexPath.section].emoticons[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let emoticon = packages[indexPath.section].emoticons[indexPath.row] if emoticon.isDelete { targetTextView?.deleteBackward() return } if emoticon.code != nil { targetTextView?.replace(targetTextView!.selectedTextRange!, withText: emoticon.code!.emoji) return } if emoticon.pngPath != nil { let attachment = NSTextAttachment() attachment.image = UIImage(named: emoticon.pngPath!) let lineHeight = (targetTextView!.font?.lineHeight)! + 1.8 attachment.bounds = CGRect.init(x: 0, y: -4, width: lineHeight, height: lineHeight) let imageAttributeString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) imageAttributeString.addAttributes([NSFontAttributeName : targetTextView!.font!], range: NSRange.init(location: 0, length: 1)) let attributeString = NSMutableAttributedString(attributedString: targetTextView!.attributedText) attributeString.replaceCharacters(in: targetTextView!.selectedRange, with: imageAttributeString) // 4. 替换属性文本 // 1) 记录住`光标`位置 let range = targetTextView!.selectedRange targetTextView!.attributedText = attributeString // 3) 恢复光标 targetTextView!.selectedRange = NSRange(location: range.location + 1, length: 0) return } } } /// 表情Cell fileprivate class YCEmoticonViewCell: UICollectionViewCell { var emoticon: YCEmoticon? { didSet { contentBtn.setTitle("", for: .normal) contentBtn.setImage(UIImage.init(named: ""), for: .normal) if emoticon!.isEmpty { contentBtn.setImage(UIImage.init(named: ""), for: .normal) return } if emoticon!.isDelete { contentBtn.setImage(UIImage.init(named: "compose_emotion_delete"), for: .normal) return } if emoticon!.pngPath != nil { contentBtn.setImage(UIImage.init(named: emoticon!.pngPath!), for: .normal) return } if emoticon!.emoji != nil { contentBtn.setTitle(emoticon?.emoji, for: .normal) } } } fileprivate lazy var contentBtn: UIButton = { let btn = UIButton() btn.titleLabel?.font = UIFont.systemFont(ofSize: 32) btn.isUserInteractionEnabled = false return btn }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(contentBtn) contentBtn.snp.makeConstraints { (make) in make.edges.equalToSuperview().offset(5) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
189c89039729a2de98b21bd432e86ff0
32.148014
163
0.612176
false
false
false
false
remirobert/ImageDownloader
refs/heads/master
source/ImageDownloader.swift
mit
1
// // Cache.swift // Cache // // Created by Remi Robert on 12/10/14. // Copyright (c) 2014 remirobert. All rights reserved. // import UIKit extension String { var md5: String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(Int(CC_MD5_DIGEST_LENGTH)) var hash = NSMutableString() CC_MD5(str!, CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)), result) for i in 0..<Int(CC_MD5_DIGEST_LENGTH) { hash.appendFormat("%02x", result[i]) } result.destroy() return String(format: hash) } } class ImageDownloader :NSObject, NSURLConnectionDelegate, NSURLConnectionDataDelegate { private var dataImage: NSMutableData? = NSMutableData() private var blockCompletion: ((imageDownloaded: UIImage?) -> ())? private var pathImage: String? private var sizeImage: CGSize? func connection(connection: NSURLConnection, didFailWithError error: NSError) { blockCompletion?(imageDownloaded: nil) } func connection(connection: NSURLConnection, didReceiveData data: NSData) { self.dataImage?.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection) { var imageDownloaded = UIImage(data: UIImageJPEGRepresentation(UIImage(data: self.dataImage!), 0)) if let compressSizeImage = self.sizeImage { self.resizeImage(&imageDownloaded!, sizeImage: compressSizeImage) } NSFileManager.defaultManager().createFileAtPath(self.pathImage!, contents: self.dataImage, attributes: nil) self.blockCompletion?(imageDownloaded: imageDownloaded) } private func resizeImage(inout imageDownloaded: UIImage, sizeImage: CGSize) { if imageDownloaded.size.width == sizeImage.width && imageDownloaded.size.height == sizeImage.height { return Void() } UIGraphicsBeginImageContextWithOptions(self.sizeImage!, false, 0.0) imageDownloaded.drawInRect(CGRectMake(0, 0, sizeImage.width, sizeImage.height)) imageDownloaded = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } private func createRequest(urlImage: String) { let request: NSURLRequest = NSURLRequest(URL: NSURL(string: urlImage)!) let connection = NSURLConnection(request: request, delegate: self, startImmediately: true) } private class func runDownloadImage(#urlImage: String, sizeImage: CGSize?, completionBlock: ((image:UIImage?) -> ())) { let pathCacheDirectory = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [AnyObject])[0] as String let pathPhoto = pathCacheDirectory.stringByAppendingPathComponent(urlImage.md5) if NSFileManager.defaultManager().fileExistsAtPath(pathPhoto) == true { completionBlock(image: UIImage(data: NSFileManager.defaultManager().contentsAtPath(pathPhoto)!)) return Void() } let dImage = ImageDownloader() dImage.sizeImage = sizeImage dImage.pathImage = pathPhoto dImage.blockCompletion = completionBlock dImage.createRequest(urlImage) } class func downloadImage(#urlImage: String, completionBlock: ((imageDownloaded:UIImage?) -> ())) { runDownloadImage(urlImage: urlImage, sizeImage: nil, completionBlock: completionBlock) } class func downloadImageWithSize(#urlImage: String, sizeImage:CGSize, completionBlock: ((imageDownloaded:UIImage?) -> ())) { runDownloadImage(urlImage: urlImage, sizeImage: sizeImage, completionBlock: completionBlock) } } extension UIImageView { func downloadImage(urlImage: String) { ImageDownloader.downloadImage(urlImage: urlImage) { (imageDownloaded) -> () in self.image = imageDownloaded } } func downloadImageWithSize(urlImage: String) { ImageDownloader.downloadImageWithSize(urlImage: urlImage, sizeImage:self.frame.size) { (imageDownloaded) -> () in self.image = imageDownloaded } } }
ea58cfe8ba0adefe157b9acd9011419f
37.238938
128
0.677389
false
false
false
false
JulianGindi/Critiq
refs/heads/master
Critiq/AppDelegate.swift
mit
1
// // AppDelegate.swift // Critiq // // Created by Thomas Degry and Julian Gindi on 3/3/15. // Copyright (c) 2015 Thomas Degry and Julian Gindi. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, APIHelperDelegate, NSUserNotificationCenterDelegate { var menuBarController : MenuBarController? var apiHelper:APIHelper? func applicationDidFinishLaunching(aNotification: NSNotification) { self.apiHelper = APIHelper() self.apiHelper?.delegate = self; menuBarController = MenuBarController.init() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func uploadClipboard() { let content = getMostRecentClipboardContents() if content != "" { self.apiHelper?.makeRequest(content) } } func didReceiveUrl(url: String) { // We will copy url to clipboard let clipboard = NSPasteboard.generalPasteboard() let outputArray = [url] clipboard.clearContents() clipboard.writeObjects(outputArray) // Send out notification to change icon again NSNotificationCenter.defaultCenter().postNotificationName("DID_UPLOAD", object: nil) // Now display a notification displayNotification() } func getMostRecentClipboardContents() -> String { let clipboard = NSPasteboard.generalPasteboard() let contents = clipboard.stringForType(NSPasteboardTypeString) if let actualContent = contents { return actualContent } return "" } func displayNotification() { let notification = NSUserNotification() notification.title = "Critiq Upload" notification.informativeText = "The URL of your snippet has been copied to your clipboard" notification.hasActionButton = true var center:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() center.delegate = self center.scheduleNotification(notification) } func notify (center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification){ center.delegate = self println("clicked") //this does not print } }
b0b0d5cd11edc1cc7f63a91de8c68b4e
31.351351
109
0.671261
false
false
false
false
billhsu0913/VideBounceButtonView
refs/heads/master
VideBounceButtonView/VideBounceButtonView.swift
mit
1
// // VideBounceButtonView.swift // VideBounceButtonViewExample // // Created by Oreki Houtarou on 11/29/14. // Copyright (c) 2014 Videgame. All rights reserved. // import UIKit class VideBounceButtonView: UIView { var exclusiveButtons: [UIButton]? var currentSelectedButton: UIButton? override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { let hitTestView = super.hitTest(point, withEvent: event) if (hitTestView is UIButton) && (exclusiveButtons == nil || !contains(exclusiveButtons!, hitTestView as UIButton)) { return self } return hitTestView } // MARK: Touch-Event Handling Methods override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch if touch.view != self { super.touchesBegan(touches, withEvent: event) return } let button = buttonForTouch(touch) if button != nil { currentSelectedButton = button bounceInButton(button!) } else { currentSelectedButton = nil } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch if touch.view != self { super.touchesMoved(touches, withEvent: event) return } let button = buttonForTouch(touch) if button != nil && button != currentSelectedButton { if currentSelectedButton != nil { bounceOutButton(currentSelectedButton!) } currentSelectedButton = button bounceInButton(button!) return } if button == nil && currentSelectedButton != nil { bounceOutButton(currentSelectedButton!) currentSelectedButton = nil } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch if touch.view != self { super.touchesEnded(touches, withEvent: event) return } let button = buttonForTouch(touch) if button != nil { bounceOutButton(button!) button!.sendActionsForControlEvents(.TouchUpInside) } else { startBlackAtPoint(touch.locationInView(self)) } if currentSelectedButton != nil { bounceOutButton(currentSelectedButton!) currentSelectedButton = nil } } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { startBlackAtPoint((touches.anyObject() as UITouch).locationInView(self)) if currentSelectedButton != nil { bounceOutButton(currentSelectedButton!) currentSelectedButton = nil } } // MARK: Private Methods private func buttonForTouch(touch: UITouch) -> UIButton? { let location = touch.locationInView(self) for subView in self.subviews.reverse() { if let button = subView as? UIButton { if (exclusiveButtons == nil || !contains(exclusiveButtons!, button)) && button.frame.contains(location) { return button; } } } return nil } private func bounceInButton(button: UIButton) { if button.transform.a < CGAffineTransformIdentity.a && button.transform.d < CGAffineTransformIdentity.d { return } UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in button.transform = CGAffineTransformMakeScale(0.85, 0.85) }) { (finished) -> Void in if finished { UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in button.transform = CGAffineTransformMakeScale(0.90, 0.90) }, completion: nil) } } } private func bounceOutButton(button: UIButton) { if button.transform.a >= CGAffineTransformIdentity.a && button.transform.d >= CGAffineTransformIdentity.d { return } UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in button.transform = CGAffineTransformMakeScale(1.10, 1.10) }) { (finished) -> Void in if finished { UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in button.transform = CGAffineTransformIdentity }, completion: nil) } } } private func startBlackAtPoint(point: CGPoint) { let sideLength: CGFloat = 10 let snapView = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: sideLength, height: sideLength))) snapView.center = point snapView.layer.cornerRadius = sideLength / 2.0 snapView.backgroundColor = UIColor.blackColor() self.insertSubview(snapView, atIndex: 0) let maxScale = max(self.frame.width / snapView.frame.width * 2.0, self.frame.height / snapView.frame.height * 2.0) UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in snapView.transform = CGAffineTransformMakeScale(maxScale, maxScale) }) { (finished) -> Void in if finished { self.backgroundColor = UIColor.blackColor() snapView.removeFromSuperview() } } } }
0bae3715cce2b47ee61a9f23c51140a4
37.94
134
0.594932
false
false
false
false
urklc/UKHorizontalPicturePicky
refs/heads/master
UKPickyDemo/ViewController.swift
mit
1
// // ViewController.swift // UKPickyDemo // // Created by ugur on 27/02/15. // Copyright (c) 2015 urklc. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UKHorizontalPicturePicky! let imagesData = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"] override func viewDidLoad() { super.viewDidLoad() collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "myCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imagesData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as UICollectionViewCell if let imgView = cell.contentView.viewWithTag(hppImageViewTag) as? UIImageView { imgView.image = UIImage(named: imagesData[indexPath.row]) } else { let img = UIImageView(frame: CGRect(x: 6, y: 6, width: 128, height: 128)) img.tag = hppImageViewTag img.image = UIImage(named: imagesData[indexPath.row]) cell.contentView.addSubview(img) } return cell } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let imgView = cell.contentView.viewWithTag(hppImageViewTag) { if let imgView = imgView as? UIImageView { imgView.image = nil } } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let collectionSelectorViewController = CollectionSelectorViewController() collectionSelectorViewController.imagename = imagesData[indexPath.row] collectionSelectorViewController.modalPresentationStyle = .popover collectionSelectorViewController.preferredContentSize = CGSize(width: 400, height: 400) collectionSelectorViewController.delegate = self let popoverViewController = collectionSelectorViewController.popoverPresentationController popoverViewController?.permittedArrowDirections = UIPopoverArrowDirection.down popoverViewController?.passthroughViews = [collectionView] popoverViewController?.sourceView = collectionView.cellForItem(at: indexPath)?.contentView.viewWithTag(hppImageViewTag) popoverViewController?.sourceRect = CGRect(x: 50, y: 0, width: 1, height: 1) present(collectionSelectorViewController, animated: true, completion: nil) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { dismiss(animated: false, completion: nil) } } extension ViewController: ImagePanGestureHandler { func handlePan(_ recognizer: UIPanGestureRecognizer) { let imageView = recognizer.view as? UIImageView switch (recognizer.state) { case UIGestureRecognizerState.began: dismiss(animated: false, completion: nil); let rect = imageView?.frame let frame = imageView?.convert(rect!, to: self.view) imageView?.frame = frame! // To prevent flashing when started mobving the UIImageView object let fakeCopy = UIImageView(frame: rect!) fakeCopy.image = imageView?.image imageView?.superview?.addSubview(fakeCopy) // Move the actual UIImageView to self imageView?.tag = kFakeCopyImageViewTag self.view.addSubview(imageView!) UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions(), animations: { self.view.viewWithTag(kFakeCopyImageViewTag)?.transform = CGAffineTransform(scaleX: 0.4, y: 0.4) return }, completion: { finished in }) break; case UIGestureRecognizerState.cancelled, UIGestureRecognizerState.failed, UIGestureRecognizerState.ended: self.view.viewWithTag(kFakeCopyImageViewTag)?.tag = 0 break; default: break; } imageView?.center = recognizer.location(in: imageView?.superview); } }
bb0ce54171f510706f855920a1f8073e
39.661157
145
0.654268
false
false
false
false
TerryCK/GogoroBatteryMap
refs/heads/master
GogoroMap/NetworkActivityIndicatorManager.swift
mit
1
// // NetworkActivityIndicatorManager.swift // SwiftyStoreKit // // Created by Andrea Bizzotto on 28/09/2015. // // 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 final class NetworkActivityIndicatorManager: NSObject { private override init() { super.init() } static let shared = NetworkActivityIndicatorManager() private var loadingCount = 0 func networkOperationStarted() { #if os(iOS) if loadingCount == 0 { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = true } } loadingCount += 1 #endif } func networkOperationFinished() { #if os(iOS) if loadingCount > 0 { loadingCount -= 1 } if loadingCount == 0 { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } #endif } }
dcacc3eb1cfaf9bf3d188248fca2f79b
32.984127
83
0.641289
false
false
false
false
nyalix/shiro-obi-app
refs/heads/master
Todoapp3/TodoItemViewController.swift
mit
1
// // TodoItemViewController.swift // Todoapp // // Created by Katsuya yamamoto on 2015/12/13. // Copyright (c) 2015年 nyalix. All rights reserved. // import UIKit class TodoItemViewController: UIViewController, UITextViewDelegate{ var task: Todo? = nil @IBOutlet weak var todoField: UITextView! // textViewの底辺のy座標用 @IBOutlet weak var bottomField: NSLayoutConstraint! @IBAction func cancel(sender: UIBarButtonItem) { navigationController!.popViewControllerAnimated(true) } @IBAction func save(sender: UIBarButtonItem) { if task != nil { editTask() } else { createTask() } navigationController!.popViewControllerAnimated(true) } func createTask() { let newTask: Todo = Todo.MR_createEntity() as Todo newTask.item = todoField.text //let newDeta = NSDate() let dateFormatter = NSDateFormatter() // フォーマットの取得 dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") // JPロケール dateFormatter.dateFormat = "yyyy/MM/dd HH:mm" // フォーマットの指定 newTask.date = dateFormatter.stringFromDate(NSDate()) // 現在日時 newTask.managedObjectContext!.MR_saveToPersistentStoreAndWait() } func editTask() { task?.item = todoField.text task?.managedObjectContext!.MR_saveToPersistentStoreAndWait() } override func viewDidLoad() { super.viewDidLoad() // デバイスごとのスクリーン幅を取得 let width = UIScreen.mainScreen().bounds.width // ボタンビュー作成 let myKeyboard = UIView(frame: CGRectMake(0, 0, width, 40)) myKeyboard.backgroundColor = UIColor(red:0.93,green:0.93,blue:0.93,alpha:1.0) // Doneボタン作成 let myButton = UIButton(frame: CGRectMake(width - 60, 5, 60, 30)) myButton.backgroundColor = UIColor(red:0.93,green:0.93,blue:0.93,alpha:1.0) myButton.setTitle("Done", forState: .Normal) myButton.setTitleColor(UIColor(red:0.1,green:0.5,blue:1.0,alpha:1.0), forState: .Normal) myButton.layer.cornerRadius = 3 myButton.addTarget(self, action: "onMyButton", forControlEvents: UIControlEvents.TouchUpInside) // ボタンをビューに追加 myKeyboard.addSubview(myButton) // ビューをフィールドに設定 todoField.inputAccessoryView = myKeyboard todoField.delegate = self if let taskTodo = task { todoField.text = taskTodo.item } // Do any additional setup after loading the view. } func onMyButton () { if task != nil { editTask() } else { createTask() } self.view.endEditing(true ) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillChangeFrame(notification: NSNotification) { if let userInfo = notification.userInfo { let keyBoardValue : NSValue = userInfo[UIKeyboardFrameEndUserInfoKey]! as! NSValue let keyBoardFrame : CGRect = keyBoardValue.CGRectValue() let duration : NSTimeInterval = userInfo[UIKeyboardAnimationDurationUserInfoKey]! as! NSTimeInterval //let bottom = self.bottomField self.bottomField.constant = 40 - keyBoardFrame.size.height UIView.animateWithDuration(duration, animations: { () -> Void in self.view.layoutIfNeeded() }) } } func keyboardWillHide(notification: NSNotification) { if let userInfo = notification.userInfo { let duration : NSTimeInterval = userInfo[UIKeyboardAnimationDurationUserInfoKey]! as! NSTimeInterval self.bottomField.constant = 0 UIView.animateWithDuration(duration, animations: { () -> Void in self.view.layoutIfNeeded() }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
c21b1e03580cecc407cee0766633e869
34.454545
112
0.627022
false
false
false
false
midoks/Swift-Learning
refs/heads/master
GitHubStar/GitHubStar/GitHubStar/Controllers/common/issues/GsUserCommentCell.swift
apache-2.0
1
// // GsUserCommentCell.swift // GitHubStar // // Created by midoks on 16/4/24. // Copyright © 2016年 midoks. All rights reserved. // import UIKit //用户提交Cell class GsUserCommentCell: UITableViewCell { //头像视图 var userIcon = UIImageView() //项目名 var userName = UILabel() //项目创建时间 var userCommentTime = UILabel() //项目介绍 var userCommentContent = UILabel() let repoH:CGFloat = 40 override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.initView() } //初始化视图 func initView(){ let w = self.getWinWidth() //提交人头像 userIcon.image = UIImage(named: "avatar_default") userIcon.layer.cornerRadius = 15 userIcon.frame = CGRect(x:5, y: 5, width:30, height:30) userIcon.clipsToBounds = true userIcon.backgroundColor = UIColor.white contentView.addSubview(userIcon) //提交用户名 userName = UILabel(frame: CGRect(x: 40, y: 5, width: w-40-140, height: 18)) userName.font = UIFont.systemFont(ofSize: 16) userName.text = "项目名" userName.textColor = UIColor(red: 64/255, green: 120/255, blue: 192/255, alpha: 1) userName.font = UIFont.boldSystemFont(ofSize: 16) contentView.addSubview(userName) //提交时间 userCommentTime = UILabel(frame: CGRect(x: 40, y: 23, width: 140, height: 17)) userCommentTime.font = UIFont.systemFont(ofSize: 12) userCommentTime.text = "create at:2008-12-12" contentView.addSubview(userCommentTime) //userCommentTime.backgroundColor = UIColor.blueColor() // //提交内容 userCommentContent.frame = CGRect(x: 40, y: repoH, width: w - 50, height:0) userCommentContent.font = UIFont.systemFont(ofSize: 14) userCommentContent.text = "" userCommentContent.numberOfLines = 0 userCommentContent.lineBreakMode = .byWordWrapping contentView.addSubview(userCommentContent) //userCommentContent.backgroundColor = UIColor.blueColor() } func getCommentSize(text:String) -> CGSize{ userCommentContent.text = text userCommentContent.frame.size.width = self.getWinWidth() - 50 let size = self.getLabelSize(label: userCommentContent) return size } override func layoutSubviews() { super.layoutSubviews() if userCommentContent.text != "" { let size = self.getCommentSize(text: userCommentContent.text!) userCommentContent.frame.size.height = size.height } } }
a8e27e56fadc1063fb2da01a1bf31842
29.959184
90
0.625247
false
false
false
false
cdmx/MiniMancera
refs/heads/master
miniMancera/View/Option/ReformaCrossing/Scene/VOptionReformaCrossingScene.swift
mit
1
import SpriteKit class VOptionReformaCrossingScene:ViewGameScene<MOptionReformaCrossing> { required init(controller:ControllerGame<MOptionReformaCrossing>) { super.init(controller:controller) physicsWorld.gravity = CGVector.zero factoryNodes() } required init?(coder:NSCoder) { return nil } //MARK: private private func factoryNodes() { let model:MOptionReformaCrossing = controller.model let background:VOptionReformaCrossingBackground = VOptionReformaCrossingBackground( controller:controller) let player:VOptionReformaCrossingPlayer = VOptionReformaCrossingPlayer( controller:controller) model.player.view = player let hud:VOptionReformaCrossingHud = VOptionReformaCrossingHud( controller:controller) model.hud.view = hud let menu:ViewGameNodeMenu<MOptionReformaCrossing> = ViewGameNodeMenu<MOptionReformaCrossing>( controller:controller, texture:model.textures.menu) model.viewMenu = menu let title:VOptionReformaCrossingTitle = VOptionReformaCrossingTitle() model.title.view = title let stop:VOptionReformaCrossingStop = VOptionReformaCrossingStop( controller:controller) model.stop.view = stop addChild(background) addChild(player) addChild(hud) addChild(menu) addChild(stop) addChild(title) } //MARK: public func showCoin(coin:MOptionReformaCrossingCoinItem) { let soundCoin:SKAction = controller.model.sounds.soundCoin controller.playSound(actionSound:soundCoin) let view:VOptionReformaCrossingCoin = VOptionReformaCrossingCoin( controller:controller, positionY:coin.positionY) coin.view = view addChild(view) } }
f3163c4c4bfe7cc53f04e72c0eef97d0
28.367647
101
0.645468
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/PanelUtils.swift
gpl-2.0
1
// // InputFinderPanelUtils.swift // Telegram-Mac // // Created by keepcoder on 24/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import Foundation import Postbox import TelegramCore let mediaExts:[String] = ["png","jpg","jpeg","tiff", "heic","mp4","mov","avi", "gif", "m4v"] let photoExts:[String] = ["png","jpg","jpeg","tiff", "heic"] let videoExts:[String] = ["mp4","mov","avi", "m4v"] let audioExts:[String] = ["mp3","wav", "m4a", "ogg"] func filePanel(with exts:[String]? = nil, allowMultiple:Bool = true, canChooseDirectories: Bool = false, for window:Window, completion:@escaping ([String]?)->Void) { delay(0.01, closure: { var result:[String] = [] let panel:NSOpenPanel = NSOpenPanel() panel.canChooseFiles = true panel.canChooseDirectories = canChooseDirectories panel.canCreateDirectories = true panel.allowedFileTypes = exts panel.allowsMultipleSelection = allowMultiple panel.beginSheetModal(for: window) { (response) in if response.rawValue == NSFileHandlingPanelOKButton { for url in panel.urls { let path:String = url.path if let exts = exts { let ext:String = path.nsstring.pathExtension.lowercased() if exts.contains(ext) || (canChooseDirectories && path.isDirectory) { result.append(path) } } else { result.append(path) } } completion(result) } else { completion(nil) } } }) } func selectFolder(for window:Window, completion:@escaping (String)->Void) { delay(0.01, closure: { var result:[String] = [] let panel:NSOpenPanel = NSOpenPanel() panel.canChooseFiles = false panel.canChooseDirectories = true panel.canCreateDirectories = true panel.allowsMultipleSelection = false panel.beginSheetModal(for: window) { (response) in if response.rawValue == NSFileHandlingPanelOKButton { for url in panel.urls { let path:String = url.path result.append(path) } if let first = result.first { completion(first) } } } }) } func savePanel(file:String, ext:String, for window:Window, defaultName: String? = nil, completion:((String?)->Void)? = nil) { delay(0.01, closure: { let savePanel:NSSavePanel = NSSavePanel() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH.mm.ss" savePanel.nameFieldStringValue = defaultName ?? "\(dateFormatter.string(from: Date())).\(ext)" let wLevel = window.level // if wLevel == .screenSaver { window.level = .normal //} savePanel.begin { (result) in if result == NSApplication.ModalResponse.OK, let saveUrl = savePanel.url { try? FileManager.default.removeItem(atPath: saveUrl.path) try? FileManager.default.copyItem(atPath: file, toPath: saveUrl.path) completion?(saveUrl.path) #if !SHARE delay(0.3, closure: { appDelegate?.showSavedPathSuccess(saveUrl.path) }) #endif } else { completion?(nil) } window.level = wLevel } }) } func savePanel(file:String, named:String, for window:Window) { delay(0.01, closure: { let savePanel:NSSavePanel = NSSavePanel() let dateFormatter = DateFormatter() savePanel.nameFieldStringValue = named savePanel.beginSheetModal(for: window, completionHandler: {(result) in if result == NSApplication.ModalResponse.OK, let saveUrl = savePanel.url { try? FileManager.default.copyItem(atPath: file, toPath: saveUrl.path) } }) }) } func alert(for window:Window, header:String = appName, info:String?, runModal: Bool = false, completion: (()->Void)? = nil, appearance: NSAppearance? = nil) { delay(0.01, closure: { let alert:NSAlert = NSAlert() alert.window.appearance = appearance ?? theme.appearance alert.alertStyle = .informational alert.messageText = header alert.informativeText = info ?? "" alert.addButton(withTitle: strings().alertOK) if runModal { alert.runModal() } else { alert.beginSheetModal(for: window, completionHandler: { (_) in completion?() }) } }) } func notSupported() { alert(for: mainWindow, header: "Not Supported", info: "This feature is not available in this app yet. Sorry! Keep calm and use the stable version.") } enum ConfirmResult { case thrid case basic } func confirm(for window:Window, header: String? = nil, information:String?, okTitle:String? = nil, cancelTitle:String = strings().alertCancel, thridTitle:String? = nil, fourTitle: String? = nil, successHandler:@escaping (ConfirmResult)->Void, cancelHandler: (()->Void)? = nil, appearance: NSAppearance? = nil) { delay(0.01, closure: { let alert:NSAlert = NSAlert() alert.window.appearance = appearance ?? theme.appearance alert.alertStyle = .informational alert.messageText = header ?? appName alert.informativeText = information ?? "" alert.addButton(withTitle: okTitle ?? strings().alertOK) if !cancelTitle.isEmpty { alert.addButton(withTitle: cancelTitle) alert.buttons.last?.keyEquivalent = "\u{1b}" } if let thridTitle = thridTitle { alert.addButton(withTitle: thridTitle) } if let fourTitle = fourTitle { alert.addButton(withTitle: fourTitle) } alert.beginSheetModal(for: window, completionHandler: { response in Queue.mainQueue().justDispatch { if response.rawValue == 1000 { successHandler(.basic) } else if response.rawValue == 1002 { successHandler(.thrid) } else if response.rawValue == 1001, cancelTitle == "" { successHandler(.thrid) } else if response.rawValue == 1001 { cancelHandler?() } } }) }) } func modernConfirm(for window:Window, account: Account? = nil, peerId: PeerId? = nil, header: String = appName, information:String? = nil, okTitle:String = strings().alertOK, cancelTitle:String = strings().alertCancel, thridTitle:String? = nil, thridAutoOn: Bool = true, successHandler:@escaping(ConfirmResult)->Void, appearance: NSAppearance? = nil) { delay(0.01, closure: { let alert:NSAlert = NSAlert() alert.window.appearance = appearance ?? theme.appearance alert.alertStyle = .informational alert.messageText = header alert.informativeText = information ?? "" alert.addButton(withTitle: okTitle) alert.addButton(withTitle: cancelTitle) if let thridTitle = thridTitle { alert.showsSuppressionButton = true alert.suppressionButton?.title = thridTitle alert.suppressionButton?.state = thridAutoOn ? .on : .off // alert.addButton(withTitle: thridTitle) } var shown: Bool = false let readyToShow:() -> Void = { if !shown { shown = true alert.beginSheetModal(for: window, completionHandler: { [weak alert] response in if let alert = alert { if alert.showsSuppressionButton, let button = alert.suppressionButton, response.rawValue != 1001 { switch button.state { case .off: successHandler(.basic) case .on: successHandler(.thrid) default: break } } else { if response.rawValue == 1000 { successHandler(.basic) } else if response.rawValue == 1002 { successHandler(.thrid) } } } }) } } readyToShow() }) } func modernConfirmSignal(for window:Window, account: Account?, peerId: PeerId?, header: String = appName, information:String? = nil, okTitle:String = strings().alertOK, cancelTitle:String = strings().alertCancel, thridTitle: String? = nil, thridAutoOn: Bool = true) -> Signal<ConfirmResult, NoError> { let value:ValuePromise<ConfirmResult> = ValuePromise(ignoreRepeated: true) delay(0.01, closure: { modernConfirm(for: window, account: account, peerId: peerId, header: header, information: information, okTitle: okTitle, cancelTitle: cancelTitle, thridTitle: thridTitle, thridAutoOn: thridAutoOn, successHandler: { response in value.set(response) }) }) return value.get() |> take(1) } func confirmSignal(for window:Window, header: String? = nil, information:String?, okTitle:String? = nil, cancelTitle:String? = nil, appearance: NSAppearance? = nil) -> Signal<Bool, NoError> { let value:ValuePromise<Bool> = ValuePromise(ignoreRepeated: true) delay(0.01, closure: { let alert:NSAlert = NSAlert() alert.alertStyle = .informational alert.messageText = header ?? appName alert.window.appearance = appearance ?? theme.appearance alert.informativeText = information ?? "" alert.addButton(withTitle: okTitle ?? strings().alertOK) alert.addButton(withTitle: cancelTitle ?? strings().alertCancel) alert.beginSheetModal(for: window, completionHandler: { response in value.set(response.rawValue == 1000) }) }) return value.get() |> take(1) }
d2f566b2b2b6399c64ffc032bc906cfb
36.413428
352
0.564413
false
false
false
false
qutheory/vapor
refs/heads/master
Sources/Development/routes.swift
mit
1
import Vapor import _Vapor3 struct Creds: Content { var email: String var password: String } public func routes(_ app: Application) throws { app.on(.GET, "ping") { req -> StaticString in return "123" as StaticString } // ( echo -e 'POST /slow-stream HTTP/1.1\r\nContent-Length: 1000000000\r\n\r\n'; dd if=/dev/zero; ) | nc localhost 8080 app.on(.POST, "slow-stream", body: .stream) { req -> EventLoopFuture<String> in let done = req.eventLoop.makePromise(of: String.self) var total = 0 req.body.drain { result in let promise = req.eventLoop.makePromise(of: Void.self) switch result { case .buffer(let buffer): req.eventLoop.scheduleTask(in: .milliseconds(1000)) { total += buffer.readableBytes promise.succeed(()) } case .error(let error): done.fail(error) case .end: promise.succeed(()) done.succeed(total.description) } // manually return pre-completed future // this should balloon in memory // return req.eventLoop.makeSucceededFuture(()) // return real future that indicates bytes were handled // this should use very little memory return promise.futureResult } return done.futureResult } app.post("login") { req -> String in let creds = try req.content.decode(Creds.self) return "\(creds)" } app.on(.POST, "large-file", body: .collect(maxSize: 1_000_000_000)) { req -> String in return req.body.data?.readableBytes.description ?? "none" } app.get("json") { req -> [String: String] in return ["foo": "bar"] }.description("returns some test json") app.webSocket("ws") { req, ws in ws.onText { ws, text in ws.send(text.reversed()) if text == "close" { ws.close(promise: nil) } } let ip = req.remoteAddress?.description ?? "<no ip>" ws.send("Hello 👋 \(ip)") } app.on(.POST, "file", body: .stream) { req -> EventLoopFuture<String> in let promise = req.eventLoop.makePromise(of: String.self) req.body.drain { result in switch result { case .buffer(let buffer): debugPrint(buffer) case .error(let error): promise.fail(error) case .end: promise.succeed("Done") } return req.eventLoop.makeSucceededFuture(()) } return promise.futureResult } app.get("shutdown") { req -> HTTPStatus in guard let running = req.application.running else { throw Abort(.internalServerError) } running.stop() return .ok } let cache = MemoryCache() app.get("cache", "get", ":key") { req -> String in guard let key = req.parameters.get("key") else { throw Abort(.internalServerError) } return "\(key) = \(cache.get(key) ?? "nil")" } app.get("cache", "set", ":key", ":value") { req -> String in guard let key = req.parameters.get("key") else { throw Abort(.internalServerError) } guard let value = req.parameters.get("value") else { throw Abort(.internalServerError) } cache.set(key, to: value) return "\(key) = \(value)" } app.get("hello", ":name") { req in return req.parameters.get("name") ?? "<nil>" } app.get("search") { req in return req.query["q"] ?? "none" } let sessions = app.grouped("sessions") .grouped(app.sessions.middleware) sessions.get("set", ":value") { req -> HTTPStatus in req.session.data["name"] = req.parameters.get("value") return .ok } sessions.get("get") { req -> String in req.session.data["name"] ?? "n/a" } sessions.get("del") { req -> String in req.session.destroy() return "done" } app.get("client") { req in return req.client.get("http://httpbin.org/status/201").map { $0.description } } app.get("client-json") { req -> EventLoopFuture<String> in struct HTTPBinResponse: Decodable { struct Slideshow: Decodable { var title: String } var slideshow: Slideshow } return req.client.get("http://httpbin.org/json") .flatMapThrowing { try $0.content.decode(HTTPBinResponse.self) } .map { $0.slideshow.title } } let users = app.grouped("users") users.get { req in return "users" } users.get(":userID") { req in return req.parameters.get("userID") ?? "no id" } app.directory.viewsDirectory = "/Users/tanner/Desktop" app.get("view") { req in req.view.render("hello.txt", ["name": "world"]) } app.get("error") { req -> String in throw TestError() } app.get("secret") { (req) -> EventLoopFuture<String> in return Environment .secret(key: "PASSWORD_SECRET", fileIO: req.application.fileio, on: req.eventLoop) .unwrap(or: Abort(.badRequest)) } app.on(.POST, "max-256", body: .collect(maxSize: 256)) { req -> HTTPStatus in print("in route") return .ok } app.on(.POST, "upload", body: .stream) { req -> EventLoopFuture<HTTPStatus> in enum BodyStreamWritingToDiskError: Error { case streamFailure(Error) case fileHandleClosedFailure(Error) case multipleFailures([BodyStreamWritingToDiskError]) } return req.application.fileio.openFile( path: "/Users/tanner/Desktop/foo.txt", mode: .write, flags: .allowFileCreation(), eventLoop: req.eventLoop ).flatMap { fileHandle in let promise = req.eventLoop.makePromise(of: HTTPStatus.self) req.body.drain { part in switch part { case .buffer(let buffer): return req.application.fileio.write( fileHandle: fileHandle, buffer: buffer, eventLoop: req.eventLoop ) case .error(let drainError): do { try fileHandle.close() promise.fail(BodyStreamWritingToDiskError.streamFailure(drainError)) } catch { promise.fail(BodyStreamWritingToDiskError.multipleFailures([ .fileHandleClosedFailure(error), .streamFailure(drainError) ])) } return req.eventLoop.makeSucceededFuture(()) case .end: do { try fileHandle.close() promise.succeed(.ok) } catch { promise.fail(BodyStreamWritingToDiskError.fileHandleClosedFailure(error)) } return req.eventLoop.makeSucceededFuture(()) } } return promise.futureResult } } } struct TestError: AbortError, DebuggableError { var status: HTTPResponseStatus { .internalServerError } var reason: String { "This is a test." } var source: ErrorSource? var stackTrace: StackTrace? init( file: String = #file, function: String = #function, line: UInt = #line, column: UInt = #column, range: Range<UInt>? = nil, stackTrace: StackTrace? = .capture(skip: 1) ) { self.source = .init( file: file, function: function, line: line, column: column, range: range ) self.stackTrace = stackTrace } }
07cd3f6c22e671fb614ec3e164ef9332
30.638132
123
0.525889
false
false
false
false
ziaukhan/Swift-Big-Nerd-Ranch-Guide
refs/heads/master
chapter 5/Chap5/Chap5/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // Chap5 // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) //Create CGRects for frames var screenRect = self.window!.bounds var bigRect = screenRect bigRect.size.width *= 2.0 //bigRect.size.height *= 2.0 //Create a screen-sized scroll view and add it to the window var scrollView = UIScrollView(frame: screenRect) scrollView.pagingEnabled = true self.window!.addSubview(scrollView) /*//Create a super sized hypnosisView and add it to the scroll View var hypnosisView = BNRHypnosisView(frame: bigRect) scrollView.addSubview(hypnosisView)*/ //Create a screen-sized hypnosis view and add it to the scroll view var hypnosisView = BNRHypnosisView(frame: screenRect) scrollView.addSubview(hypnosisView) //Add a second sized hypnosis view just off screen to the right screenRect.origin.x += screenRect.size.width var anotherView = BNRHypnosisView(frame: screenRect) scrollView.addSubview(anotherView) //Tell the scroll view how big its content area is scrollView.contentSize = bigRect.size self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() 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:. } }
f5954a6cf86074134814a52b8dddae48
43.776316
285
0.704085
false
false
false
false
udark/underdark-cocoa
refs/heads/master
UDApp/UDApp/LogViewController.swift
apache-2.0
1
// // LogViewController.swift // UDApp // // Created by Virl on 23/03/16. // Copyright © 2016 Underdark. All rights reserved. // import UIKit class LogViewController: UIViewController, FormLoggerDelegate { @IBOutlet weak var textView: UITextView! fileprivate let formatter = DateFormatter() override func viewDidLoad() { super.viewDidLoad() formatter.dateStyle = .none formatter.timeStyle = .medium AppModel.shared.formLogger.updateDelegate(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } @IBAction func clearLog(_ sender: AnyObject) { textView.text = "" } func scrollToBottom() { let range = NSMakeRange(textView.text.characters.count - 1, 1); textView.scrollRangeToVisible(range); } // MARK: - UDLoggerDelegate func logMessage(_ message: String) { textView.text = textView.text + message + "\n"// + "\n" } }
c95122fb2fa4db96fa837ddad39a7da7
19.156863
68
0.68677
false
false
false
false
LOTUM/ModularAnimation
refs/heads/master
ModularAnimation/AnimationModule.swift
apache-2.0
1
/* Copyright (c) 2017 LOTUM GmbH Licensed under Apache License v2.0 See https://github.com/LOTUM/ModularAnimation/blob/master/LICENSE for license information */ import Foundation import UIKit public protocol AnimationModule { typealias Block = () -> Void var duration: TimeInterval { get } func animationBlock(completion: Block?) -> Block? func play(completion: Block?) } extension AnimationModule { public func play(completion: Block? = nil) { let animation = animationBlock(completion: completion) animation?() } } public struct BasicAnimationModule: AnimationModule { public let duration: TimeInterval public let delay: TimeInterval public let options: UIViewAnimationOptions public let animations: Block public init(duration: TimeInterval, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], animations: @escaping Block) { self.duration = duration self.animations = animations self.delay = delay self.options = options } public func animationBlock(completion: Block? = nil) -> Block? { return { _ in let completionWrapper: (Bool) -> Void = { _ in completion?() } UIView.animate( withDuration: self.duration, delay: self.delay, options: self.options, animations: self.animations, completion: completionWrapper ) } } } public struct SpringAnimationModule: AnimationModule { public let duration: TimeInterval public let delay: TimeInterval public let dampingRatio: CGFloat public let velocity: CGFloat public let options: UIViewAnimationOptions public let animations: Block public init(duration: TimeInterval, delay: TimeInterval = 0, dampingRatio: CGFloat = 0.8, velocity: CGFloat = 4, options: UIViewAnimationOptions = [], animations: @escaping Block) { self.duration = duration self.delay = delay self.dampingRatio = dampingRatio self.velocity = velocity self.options = options self.animations = animations } public func animationBlock(completion: Block? = nil) -> Block? { return { _ in let completionWrapper: (Bool) -> Void = { _ in completion?() } UIView.animate( withDuration: self.duration, delay: self.delay, usingSpringWithDamping: self.dampingRatio, initialSpringVelocity: self.velocity, options: self.options, animations: self.animations, completion: completionWrapper ) } } } public class SerialAnimation: AnimationModule { private var animationModules: [AnimationModule] public init() { animationModules = [] } public convenience init(_ modules: AnimationModule...) { self.init() animationModules.append(contentsOf: modules) } public func append(_ animationModule: AnimationModule) { animationModules.append(animationModule) } public var duration: TimeInterval { let durationSum = animationModules.reduce(0, {$0 + $1.duration}) return durationSum } public func animationBlock(completion: Block? = nil) -> Block? { var animations: [Block?] = [completion] for (index, animationModule) in animationModules.reversed().enumerated() { let completion = animations[index] let animation = animationModule.animationBlock(completion: completion) animations.append(animation) } return animations.last! } } public class ParallelAnimation: AnimationModule { private var animationModules: [AnimationModule] public init() { animationModules = [] } public convenience init(_ modules: AnimationModule...) { self.init() animationModules.append(contentsOf: modules) } public func add(_ animationModule: AnimationModule) { animationModules.append(animationModule) } public var duration: TimeInterval { let longestDuration = animationModules.reduce(0, {max($0, $1.duration)}) return longestDuration } public func animationBlock(completion: Block? = nil) -> Block? { if animationModules.isEmpty { return completion } // return a function which plays all animations at once and passes the completion to longest return { _ in let longestDuration = self.duration var completionUsed = false // in case of multiple animations with same duration for animationModule in self.animationModules { if !completionUsed && animationModule.duration == longestDuration { animationModule.play(completion: completion) completionUsed = true } else { animationModule.play() } } } } }
c9fad77e706bd437c14c9efc5a67abf2
31.207547
185
0.621754
false
false
false
false
ibm-wearables-sdk-for-mobile/ibm-wearables-swift-sdk
refs/heads/master
IBMMobileEdge/IBMMobileEdge/Classification.swift
epl-1.0
2
// // Classification.swift // IBMMobileEdge // // Created by Cirill Aizenberg on 1/4/16. // Copyright © 2016 IBM. All rights reserved. // import Foundation public class Classification : BaseInterpretation{ let jsEngine = JSEngine.instance var accelerometerDataArrays = [[Double]]() var gyroscopeDataArrays = [[Double]]() var timer: NSTimer! let accelerometerListenerName = "accelerometerListener" let gyroscopeListenerName = "gyroscopeListener" public init(){ super.init(interpretationName: "Classification") jsEngine.loadJS("commonClassifier") } public func loadGesturesByNames(gesturesFileNames:[String]){ for name in gesturesFileNames { jsEngine.loadJS(name) } } public func loadGesturesByFilePath(gesturesFilePaths:[String]){ for filePath in gesturesFilePaths { jsEngine.loadJSFromPath(filePath) } } public func setSensitivity(payload:Dictionary<String,Double>){ if payload.count > 0 { print("set sensitivity payload = \(payload)") jsEngine.executeMethod("setGesturesSensitivity", payload: payload) } } override public func registerForEvents(sensors: Sensors) { sensors.accelerometer.registerListener(accelerometerDataChanged,withName: accelerometerListenerName) sensors.gyroscope.registerListener(gyroscopeDataChanged, withName: gyroscopeListenerName) } override public func unregisterEvents(sensors: Sensors){ sensors.accelerometer.unregisterListener(accelerometerListenerName) sensors.gyroscope.unregisterListener(gyroscopeListenerName) } func accelerometerDataChanged(data:AccelerometerData) { accelerometerDataArrays.append([data.x,data.y,data.z]) executeCalassification() } func gyroscopeDataChanged(data:GyroscopeData){ gyroscopeDataArrays.append([data.x,data.y,data.z]) executeCalassification() } func executeCalassification(){ if (accelerometerDataArrays.count > 2 && gyroscopeDataArrays.count > 2){ //make correction to data syncronization makeDataSyncronizationFix() //build the payload using the first 3 values var payload = Dictionary<String,AnyObject>() payload["accelerometer"] = [accelerometerDataArrays[0],accelerometerDataArrays[1],accelerometerDataArrays[2]] payload["gyroscope"] = [gyroscopeDataArrays[0],gyroscopeDataArrays[1],gyroscopeDataArrays[2]] //execute the js engine let result = jsEngine.executeMethod("detectGesture", payload: payload).toDictionary() //remove the first 3 value from the buffer accelerometerDataArrays.removeFirst(3) gyroscopeDataArrays.removeFirst(3) if result["detected"] as! Bool == true{ notifyResult(result["additionalInfo"]) } else if let scores = result["additionalInfo"]{ nofifyStatusUpdate(scores) } /* if let resultFromJs = result{ print("Result from Calassification \(NSDate())") print(resultFromJs) } */ } } func makeDataSyncronizationFix(){ let accelerometerLength = accelerometerDataArrays.count let gyroscopeLenght = gyroscopeDataArrays.count if (accelerometerLength > gyroscopeLenght){ accelerometerDataArrays.removeFirst(accelerometerLength - gyroscopeLenght) print("Info: Data correction fix, dropped first \(accelerometerLength - gyroscopeLenght) reads of accelerometer") } else if (gyroscopeLenght > accelerometerLength){ gyroscopeDataArrays.removeFirst(gyroscopeLenght - accelerometerLength) print("Info: Data correction fix, dropped first \(gyroscopeLenght - accelerometerLength) reads of gyroscope") } } }
1f7a50092521dd9f5ab926b5cf33969e
33.801653
125
0.634054
false
false
false
false
DimensionSrl/Acapulco
refs/heads/master
AcapulcoSample/MainViewController.swift
bsd-3-clause
1
// // ViewController.swift // AcapulcoSample // // Created by Nicolo' on 25/02/15. // Copyright (c) 2015 Dimension s.r.l. All rights reserved. // import UIKit public class MainViewController: UIViewController { public override func viewDidLoad() { super.viewDidLoad() // Load the webview content let URL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("README", ofType: "html")!) let request = NSURLRequest(URL: URL) if let webView = view as? UIWebView { webView.loadRequest(request) } // Renew registrations to NSNotificationCenter NSNotificationCenter.defaultCenter().removeObserver(self) NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleApplicationDidEnterBackgroundNotification:", name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleApplicationDidBecomeActiveNotification:", name: UIApplicationWillEnterForegroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name: NotificationFactory.Names.PushReceivedNotificationName, object: nil) } override public func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Check if we have already registered on Acapulco. If not, // start the registration flow if !(Acapulco.sharedInstance.isRegistered()) { print("Acapulco is not registered, yet") performSegueWithIdentifier("registration", sender: self) } else { print("Acapulco is already registered") } } public func handleApplicationDidEnterBackgroundNotification(notification: NSNotification) { // Stop accepting local notification while in background NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFactory.Names.PushReceivedNotificationName, object: nil) } public func handleApplicationDidBecomeActiveNotification(notification: NSNotification) { // Resume handling local notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name: NotificationFactory.Names.PushReceivedNotificationName, object: nil) } public func handleNotification(notification: NSNotification) { if let userInfo = notification.object as? [NSObject : AnyObject] { if let navController = self.presentedViewController as? UINavigationController, let contentViewController = navController.viewControllers[0] as? ContentViewController { contentViewController.userInfo = userInfo } else { performSegueWithIdentifier("showContent", sender: userInfo) // We use the sender to pass the notification content } } } override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let navController = segue.destinationViewController as? UINavigationController, let contentViewController = navController.viewControllers[0] as? ContentViewController { if let userInfo = sender as? [NSObject : AnyObject] { contentViewController.userInfo = userInfo } } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
f97f12a73441470f3dda52da1cd4a810
40.37931
188
0.677778
false
false
false
false
cmoulton/grokRouter
refs/heads/master
grokRouter/ViewController.swift
mit
1
// // ViewController.swift // grokRouter // // Created by Christina Moulton on 2015-10-19. // Copyright © 2015 Teak Mobile Inc. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class ViewController: UIViewController { func getFirstPost() { // Get first post let request = Alamofire.request(PostRouter.Get(1)) .responseJSON { response in guard response.result.error == nil else { // got an error in getting the data, need to handle it print("error calling GET on /posts/1") print(response.result.error!) return } if let value: AnyObject = response.result.value { // handle the results as JSON, without a bunch of nested if loops let post = JSON(value) // now we have the results, let's just print them though a tableview would definitely be better UI: print("The post is: " + post.description) if let title = post["title"].string { // to access a field: print("The title is: " + title) } else { print("error parsing /posts/1") } } } debugPrint(request) } func createPost() { let newPost = ["title": "Frist Psot", "body": "I iz fisrt", "userId": 1] Alamofire.request(PostRouter.Create(newPost)) .responseJSON { response in guard response.result.error == nil else { // got an error in getting the data, need to handle it print("error calling GET on /posts/1") print(response.result.error!) return } if let value: AnyObject = response.result.value { // handle the results as JSON, without a bunch of nested if loops let post = JSON(value) print("The post is: " + post.description) } } } func deleteFirstPost() { Alamofire.request(PostRouter.Delete(1)) .responseJSON { response in if let error = response.result.error { // got an error while deleting, need to handle it print("error calling DELETE on /posts/1") print(error) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. getFirstPost() //createPost() //deleteFirstPost() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
b38a505f1cfd92b64ec351e1a7be5465
27.772727
109
0.596761
false
false
false
false
iluuu1994/Conway-s-Game-of-Life
refs/heads/master
Conway's Game of Life/Conway's Game of Life/TwoWayBinding.swift
bsd-2-clause
1
// // TwoWayBinding.swift // Conway's Game of Life // // Created by Ilija Tovilo on 26/08/14. // Copyright (c) 2014 Ilija Tovilo. 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 public class TwoWayBinding: NSObject { public let leadingElement: NSObject public let leadingKeyPath: String public let followingElement: NSObject public let followingKeyPath: String public init(leadingElement: NSObject, leadingKeyPath: String, followingElement: NSObject, followingKeyPath: String) { self.leadingElement = leadingElement self.leadingKeyPath = leadingKeyPath self.followingElement = followingElement self.followingKeyPath = followingKeyPath super.init() bind() } deinit { unbind() } public func bind() { leadingElement.addObserver( self, forKeyPath: leadingKeyPath, options: NSKeyValueObservingOptions.New, context: nil ) followingElement.addObserver( self, forKeyPath: followingKeyPath, options: NSKeyValueObservingOptions.New, context: nil ) } public func unbind() { leadingElement.removeObserver(self, forKeyPath: leadingKeyPath) followingElement.removeObserver(self, forKeyPath: followingKeyPath) } override public func observeValueForKeyPath( keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) { let (from, fromKP, to, toKP) = object === leadingElement ? (leadingElement, leadingKeyPath, followingElement, followingKeyPath) : (followingElement, followingKeyPath, leadingElement, leadingKeyPath) let oldValue = to.valueForKeyPath(toKP) as NSNumber let newValue = from.valueForKeyPath(fromKP) as NSNumber if oldValue !== newValue { to.setValue(newValue, forKeyPath: toKP) } } }
0768b03a3c5699f6bbf30341bab34ccf
35.390805
121
0.674984
false
false
false
false
juliangrosshauser/PercentAge
refs/heads/master
PercentAge/Classes/View Controllers/BirthdayViewController.swift
mit
1
// // BirthdayViewController.swift // PercentAge // // Created by Julian Grosshauser on 14/03/15. // Copyright (c) 2015 Julian Grosshauser. All rights reserved. // import UIKit import PercentAgeKit class BirthdayViewController: UIViewController { //MARK: Properties private let viewModel = BirthdayViewModel() private var longPressTimer: NSTimer? //MARK: Initialization init() { super.init(nibName: nil, bundle: nil) viewModel.addObserver(self, forKeyPath: "day", options: .New, context: &BirthdayViewModel.observeContext) viewModel.addObserver(self, forKeyPath: "month", options: .New, context: &BirthdayViewModel.observeContext) viewModel.addObserver(self, forKeyPath: "year", options: .New, context: &BirthdayViewModel.observeContext) modalTransitionStyle = .CrossDissolve } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: Deinitialization deinit { viewModel.removeObserver(self, forKeyPath: "day", context: &BirthdayViewModel.observeContext) viewModel.removeObserver(self, forKeyPath: "month", context: &BirthdayViewModel.observeContext) viewModel.removeObserver(self, forKeyPath: "year", context: &BirthdayViewModel.observeContext) } //MARK: Key-Value Observing override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if (context == &BirthdayViewModel.observeContext) { if let newValue = change[NSKeyValueChangeNewKey] as? Int { let birthdayView = view as! BirthdayView switch keyPath { case "day": birthdayView.dayValueLabel.text = String(newValue) case "month": birthdayView.monthValueLabel.text = String(newValue) case "year": birthdayView.yearValueLabel.text = String(newValue) default: super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } //MARK: UIViewController override func loadView() { view = BirthdayView() } override func viewDidLoad() { super.viewDidLoad() let birthdayView = view as! BirthdayView birthdayView.dayValueLabel.text = String(viewModel.day) birthdayView.monthValueLabel.text = String(viewModel.month) birthdayView.yearValueLabel.text = String(viewModel.year) birthdayView.incrementDayButton.addTarget(self, action: "incrementDayButtonDown:", forControlEvents: .TouchDown) birthdayView.incrementDayButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside) birthdayView.decrementDayButton.addTarget(self, action: "decrementDayButtonDown:", forControlEvents: .TouchDown) birthdayView.decrementDayButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside) birthdayView.incrementMonthButton.addTarget(self, action: "incrementMonthButtonDown:", forControlEvents: .TouchDown) birthdayView.incrementMonthButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside) birthdayView.decrementMonthButton.addTarget(self, action: "decrementMonthButtonDown:", forControlEvents: .TouchDown) birthdayView.decrementMonthButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside) birthdayView.incrementYearButton.addTarget(self, action: "incrementYearButtonDown:", forControlEvents: .TouchDown) birthdayView.incrementYearButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside) birthdayView.decrementYearButton.addTarget(self, action: "decrementYearButtonDown:", forControlEvents: .TouchDown) birthdayView.decrementYearButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside) birthdayView.saveButton.addTarget(self, action: "saveBirthday:", forControlEvents: .TouchUpInside) let longPressIncrementDay = UILongPressGestureRecognizer(target: self, action: "longPressIncrementDay:") longPressIncrementDay.minimumPressDuration = 0.3 birthdayView.incrementDayButton.addGestureRecognizer(longPressIncrementDay) let longPressIncrementMonth = UILongPressGestureRecognizer(target: self, action: "longPressIncrementMonth:") longPressIncrementMonth.minimumPressDuration = 0.3 birthdayView.incrementMonthButton.addGestureRecognizer(longPressIncrementMonth) let longPressIncrementYear = UILongPressGestureRecognizer(target: self, action: "longPressIncrementYear:") longPressIncrementYear.minimumPressDuration = 0.3 birthdayView.incrementYearButton.addGestureRecognizer(longPressIncrementYear) let longPressDecrementDay = UILongPressGestureRecognizer(target: self, action: "longPressDecrementDay:") longPressDecrementDay.minimumPressDuration = 0.3 birthdayView.decrementDayButton.addGestureRecognizer(longPressDecrementDay) let longPressDecrementMonth = UILongPressGestureRecognizer(target: self, action: "longPressDecrementMonth:") longPressDecrementMonth.minimumPressDuration = 0.3 birthdayView.decrementMonthButton.addGestureRecognizer(longPressDecrementMonth) let longPressDecrementYear = UILongPressGestureRecognizer(target: self, action: "longPressDecrementYear:") longPressDecrementYear.minimumPressDuration = 0.3 birthdayView.decrementYearButton.addGestureRecognizer(longPressDecrementYear) } //MARK: Button Actions @objc private func incrementDayButtonDown(sender: UIButton) { tranformButton(sender) viewModel.incrementDay() } @objc private func decrementDayButtonDown(sender: UIButton) { tranformButton(sender) viewModel.decrementDay() } @objc private func incrementMonthButtonDown(sender: UIButton) { tranformButton(sender) viewModel.incrementMonth() } @objc private func decrementMonthButtonDown(sender: UIButton) { tranformButton(sender) viewModel.decrementMonth() } @objc private func incrementYearButtonDown(sender: UIButton) { tranformButton(sender) viewModel.incrementYear() } @objc private func decrementYearButtonDown(sender: UIButton) { tranformButton(sender) viewModel.decrementYear() } @objc private func saveBirthday(sender: AnyObject) { let userDefaults = NSUserDefaults(suiteName: "group.com.juliangrosshauser.PercentAge")! viewModel.saveBirthdayIntoUserDefaults(userDefaults) presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } //MARK: Gesture Recognizer Actions @objc private func longPressIncrementDay(longPressGestureRecognizer: UILongPressGestureRecognizer) { if (longPressGestureRecognizer.state == .Began) { longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "incrementDay", userInfo: nil, repeats: true) } if (longPressGestureRecognizer.state == .Ended) { longPressTimer?.invalidate() let birthdayView = view as! BirthdayView resetButtonTransform(birthdayView.incrementDayButton) } } @objc private func longPressIncrementMonth(longPressGestureRecognizer: UILongPressGestureRecognizer) { if (longPressGestureRecognizer.state == .Began) { longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "incrementMonth", userInfo: nil, repeats: true) } if (longPressGestureRecognizer.state == .Ended) { longPressTimer?.invalidate() let birthdayView = view as! BirthdayView resetButtonTransform(birthdayView.incrementMonthButton) } } @objc private func longPressIncrementYear(longPressGestureRecognizer: UILongPressGestureRecognizer) { if (longPressGestureRecognizer.state == .Began) { longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "incrementYear", userInfo: nil, repeats: true) } if (longPressGestureRecognizer.state == .Ended) { longPressTimer?.invalidate() let birthdayView = view as! BirthdayView resetButtonTransform(birthdayView.incrementYearButton) } } @objc private func longPressDecrementDay(longPressGestureRecognizer: UILongPressGestureRecognizer) { if (longPressGestureRecognizer.state == .Began) { longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "decrementDay", userInfo: nil, repeats: true) } if (longPressGestureRecognizer.state == .Ended) { longPressTimer?.invalidate() let birthdayView = view as! BirthdayView resetButtonTransform(birthdayView.decrementDayButton) } } @objc private func longPressDecrementMonth(longPressGestureRecognizer: UILongPressGestureRecognizer) { if (longPressGestureRecognizer.state == .Began) { longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "decrementMonth", userInfo: nil, repeats: true) } if (longPressGestureRecognizer.state == .Ended) { longPressTimer?.invalidate() let birthdayView = view as! BirthdayView resetButtonTransform(birthdayView.decrementMonthButton) } } @objc private func longPressDecrementYear(longPressGestureRecognizer: UILongPressGestureRecognizer) { if (longPressGestureRecognizer.state == .Began) { longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "decrementYear", userInfo: nil, repeats: true) } if (longPressGestureRecognizer.state == .Ended) { longPressTimer?.invalidate() let birthdayView = view as! BirthdayView resetButtonTransform(birthdayView.decrementYearButton) } } //MARK: Button Transform private func tranformButton(button: UIButton) { UIView.animateWithDuration(0.1, animations: { button.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1.0) }) } @objc private func resetButtonTransform(button: UIButton) { UIView.animateWithDuration(0.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .CurveEaseInOut, animations: { button.layer.transform = CATransform3DIdentity }, completion: nil) } }
8b1a675b0e5ddc0975f369922ec49928
39.512635
156
0.704331
false
false
false
false
CodaFi/swift
refs/heads/main
test/Serialization/search-paths-relative.swift
apache-2.0
33
// RUN: %empty-directory(%t) // RUN: %empty-directory(%t/secret) // RUN: %target-swift-frontend -emit-module -o %t/secret %S/Inputs/struct_with_operators.swift // RUN: %empty-directory(%t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule) // RUN: %target-swift-frontend -emit-module -o %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/%target-swiftmodule-name %S/Inputs/alias.swift -module-name has_alias // RUN: cd %t/secret && %target-swiftc_driver -emit-module -o %t/has_xref.swiftmodule -I . -F ../Frameworks -parse-as-library %S/Inputs/has_xref.swift %S/../Inputs/empty.swift -Xfrontend -serialize-debugging-options -Xcc -ivfsoverlay -Xcc %S/../Inputs/unextended-module-overlay.yaml -Xcc -DDUMMY // RUN: %target-swift-frontend %s -typecheck -I %t // Check the actual serialized search paths. // RUN: llvm-bcanalyzer -dump %t/has_xref.swiftmodule > %t/has_xref.swiftmodule.txt // RUN: %FileCheck %s < %t/has_xref.swiftmodule.txt // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/has_xref.swiftmodule.txt import has_xref numeric(42) // CHECK-LABEL: <OPTIONS_BLOCK // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-working-directory' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '{{.+}}{{/|\\}}secret' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-DDUMMY' // CHECK: </OPTIONS_BLOCK> // CHECK-LABEL: <INPUT_BLOCK // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1 op1=0/> blob data = '{{.+}}{{/|\\}}secret{{/|\\}}../Frameworks' // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0 op1=0/> blob data = '{{.+}}{{/|\\}}secret{{/|\\}}.' // CHECK: </INPUT_BLOCK> // NEGATIVE-NOT: '.' // NEGATIVE-NOT: '../Frameworks' // This should be filtered out. // NEGATIVE-NOT: -ivfsoverlay{{.*}}unextended-module-overlay.yaml
c71f2add337641cb06b021b6cbdc091d
51.969697
295
0.671053
false
false
false
false
KellenYangs/KLSwiftTest_05_05
refs/heads/master
CoreGraphicsTest/CoreGraphicsTest/Flo/CounterView.swift
mit
1
// // CounterView.swift // CoreGraphicsTest // // Created by bcmac3 on 16/5/26. // Copyright © 2016年 KellenYangs. All rights reserved. // import UIKit let NoOfGlasses = 8 let π: CGFloat = CGFloat(M_PI) @IBDesignable class CounterView: UIView { /// 当前计数 @IBInspectable var counter: Int = 5 { didSet { if counter <= NoOfGlasses && counter >= 0 { setNeedsDisplay() } } } @IBInspectable var outlineColor: UIColor = UIColor.blueColor() @IBInspectable var counterColor: UIColor = UIColor.orangeColor() override func drawRect(rect: CGRect) { // 1. 外轮廓 let center: CGPoint = CGPoint(x: bounds.width / 2, y: bounds.height / 2) let radius: CGFloat = max(bounds.width, bounds.height) / 2 let arcWidth: CGFloat = radius * 2 / 3 let startAngle: CGFloat = 3 * π / 4 let endAngle: CGFloat = π / 4 let path = UIBezierPath(arcCenter: center, radius: radius - arcWidth / 2, startAngle: startAngle, endAngle: endAngle, clockwise: true) path.lineWidth = arcWidth counterColor.setStroke() path.stroke() // 2. 当前计数轮廓 let angleDifference: CGFloat = 2 * π - startAngle + endAngle let arcLengthPerGlass = angleDifference / CGFloat(NoOfGlasses) let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle let outlinePath = UIBezierPath(arcCenter: center, radius: radius - 2.5, startAngle: startAngle, endAngle:outlineEndAngle, clockwise: true) outlinePath.addArcWithCenter(center, radius: radius - arcWidth + 2.5, startAngle: outlineEndAngle, endAngle: startAngle, clockwise: false) outlinePath.closePath() outlineColor.setStroke() outlinePath.lineWidth = 5.0 outlinePath.stroke() // 3.小指标 let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context) outlineColor.setFill() let markerWidth: CGFloat = 5.0 let markerSize: CGFloat = 10.0 let markerPath = UIBezierPath(rect: CGRect(x: -markerWidth/2, y: 0, width: markerWidth, height: markerSize)) // 移动 CGContextTranslateCTM(context, rect.width/2, rect.height/2) for i in 1...NoOfGlasses { CGContextSaveGState(context) let angle = arcLengthPerGlass * CGFloat(i) + startAngle - π/2 CGContextRotateCTM(context, angle) CGContextTranslateCTM(context, 0, rect.height/2 - markerSize) markerPath.fill() CGContextRestoreGState(context) } CGContextRestoreGState(context) } }
2a6c6e5c88f285414fe50be2fd7b9747
31.593023
146
0.601498
false
false
false
false
fjtrujy/FTMTableSectionModules
refs/heads/master
Tests/ModuleServicesTests/TableSectionModuleTest.swift
mit
1
// // TableSectionModuleTest.swift // ModuleServices // // Created by Francisco Trujillo on 16/05/2016. // Copyright © 2016 FJTRUJY. All rights reserved. // import UIKit import XCTest import ModuleServices class TableSectionModuleTest: XCTestCase { } // MARK: - Fetching functions extension TableSectionModuleTest { func testStartFetchDefault() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) XCTAssert(!module.isFetching, "The module shouldnt be fecthing by default") } func testStartFetchTrue() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) module.startFetch() XCTAssert(module.isFetching, "The module should be fecthing") } func testStartFetch() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) XCTAssert(!module.isFetching, "The module shouldn't be fecthing") module.startFetch() XCTAssert(module.isFetching, "The module should be fecthing") } func testStopFetchDefault() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) XCTAssert(!module.isFetching, "The module shouldnt be fecthing by default") } func testStopFetchTrue() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) module.startFetch() module.stopFetch() XCTAssert(!module.isFetching, "The module shouldnt be fecthing") } func testStopFetchFalse() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) module.startFetch() XCTAssert(module.isFetching, "The module should be fecthing") } func testStopFetch() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) module.startFetch() XCTAssert(module.isFetching, "The module should be fecthing") module.stopFetch() XCTAssert(!module.isFetching, "The module should be fecthing") } func testFetchCicle() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) XCTAssert(!module.isFetching, "The module shouldnt be fecthing by default") module.startFetch() XCTAssert(module.isFetching, "The module should be fecthing") module.stopFetch() XCTAssert(!module.isFetching, "The module should be fecthing") } } //MARK: - isPresented Functions extension TableSectionModuleTest { func testDefaultPresentedValue() { let tableView : UITableView = UITableView() let module : TableSectionModule = TableSectionModule(tableView: tableView) XCTAssert(!module.isPresented, "The module shouldnt be presented by default") } } //MARK: - Registers Functions extension TableSectionModuleTest { func testRegisterNotNilHeader() { let tableView : UITableView = UITableView() let module : TestModule1 = TestModule1(tableView: tableView) let header : UITableViewHeaderFooterView = module.tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: TestExample1HeaderFooterView.self))! XCTAssertNotNil(header, "The TestExample1HeaderFooterView should be dequeued") } func testRegisterNotNilCells() { let tableView : UITableView = UITableView() let module : TestModule1 = TestModule1(tableView: tableView) let cell : UITableViewCell = module.tableView.dequeueReusableCell(withIdentifier: String(describing: TestExample1TableViewCell.self))! XCTAssertNotNil(cell, "The TestExample1TableViewCell should be dequeued") } func testRegisterFullModule() { let tableView : UITableView = UITableView() let module : TestModule3 = TestModule3(tableView: tableView) var header : UITableViewHeaderFooterView var cell : UITableViewCell header = module.tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: TestExample1HeaderFooterView.self))! XCTAssertNotNil(header, "The TestExample1HeaderFooterView should be dequeued") header = module.tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: TestExample2HeaderFooterView.self))! XCTAssertNotNil(header, "The TestExample2HeaderFooterView should be dequeued") cell = module.tableView.dequeueReusableCell(withIdentifier: String(describing: TestExample1TableViewCell.self))! XCTAssertNotNil(cell, "The TestExample1TableViewCell should be dequeued") cell = module.tableView.dequeueReusableCell(withIdentifier: String(describing: TestExample2TableViewCell.self))! XCTAssertNotNil(cell, "The TestExample2TableViewCell should be dequeued") } }
efa46381701018aa9738e950cfa020c1
35.744966
171
0.680548
false
true
false
false
sirhans/ListeningTest
refs/heads/master
HelloWorld/ViewController.swift
unlicense
1
// // ViewController.swift // ListeningTest // // Created by hans anderson on 12/4/15. // Anyone may use this file without restrictions // import AudioKit import UIKit class ViewController: UIViewController { var oscillator1 = AKOscillator() var oscillator2 = AKOscillator() var mixer = AKMixer() var file: AKAudioFile! var playerA: AKAudioPlayer! var playerB: AKAudioPlayer! var playerReference: AKAudioPlayer! var audioFolderURL: URL! var folderList: [String]! var totalQuestions = 0 var currentQuestion = 1 var correctAnswers = [answerChoice]() var userAnswers = [answerChoice]() var activeQuestions = [Bool]() var orangeColour = UIColor(hue: 38.0/360.0, saturation: 1.0, brightness: 1.0, alpha: 1.0) var blueColour = UIColor(hue: 196.0/360.0, saturation: 1.0, brightness: 1.0, alpha: 1.0) @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var resultsView: UITextView! @IBOutlet weak var questionNumberLabel: UILabel! @IBOutlet weak var BButton: UIButton! @IBOutlet weak var AButton: UIButton! @IBOutlet weak var questionDataLabel: UILabel! @IBOutlet weak var copyButton: UIButton! enum answerChoice { case A, B, unknown } func segmentedControlIndex(ac: answerChoice) -> Int { switch ac { case .A: return 0 case .unknown: return 1 case .B: return 2 } } func indexToAnswerChoice(idx: Int) -> answerChoice { switch idx { case 0: return answerChoice.A case 1: return answerChoice.unknown case 2: return answerChoice.B default: return answerChoice.unknown } } // hide status bar override var prefersStatusBarHidden: Bool { return true } func sortFunc(num1: String, num2: String) -> Bool { return num1 < num2 } func randomiseCorrectAnswers() { correctAnswers.removeAll() for _ in 1...totalQuestions { // set correct answers randomly let randomAnswer = 2*Int(arc4random_uniform(2)); correctAnswers.append(indexToAnswerChoice(idx: randomAnswer)); // initialise all user answers to unknown userAnswers.append(answerChoice.unknown); activeQuestions.append(true); } } func updateResults(copy: Bool = false) { var results = ""; for i in 1...totalQuestions{ // generate a right or wrong string var correctQ = String(userAnswers[i-1]==correctAnswers[i-1]) // don't show anyresult if the user didn't answer the question if (userAnswers[i-1] == answerChoice.unknown){ correctQ = " "; } // append the result of question i results.append(String(i) + ": " + correctQ + "\n") } // update the results text view resultsView.text = results // copy to pasteboard if(copy){ UIPasteboard.general.setValue(results, forPasteboardType: "public.plain-text"); } } func updateQuestion(){ // update the label text at the top of the screen updateQuestionLabel() // load the answer previously given by the user into the // segmented control loadAnswer() // update results page to show how the user scored updateResults() // if at the end of the test, // show the results if(currentQuestion > totalQuestions){ // otherwise load the audio } else { AudioKit.stop() let questionFolderURL = URL(fileURLWithPath: folderList[currentQuestion-1], relativeTo: audioFolderURL) let referenceAudioURL = URL(fileURLWithPath: "reference.wav", relativeTo: questionFolderURL) let whiteAudioURL = URL(fileURLWithPath: "white.wav", relativeTo: questionFolderURL) let filteredAudioURL = URL(fileURLWithPath: "filtered.wav", relativeTo: questionFolderURL) questionDataLabel.text = questionFolderURL.relativeString do { // load the reference audio file let referenceAudioFile = try AKAudioFile(forReading: referenceAudioURL) playerReference = try AKAudioPlayer(file: referenceAudioFile) let audioFileA: AKAudioFile! let audioFileB: AKAudioFile! // switch the order of samples A and B according to the random // selection determined at the start of the test if (correctAnswers[currentQuestion-1] == answerChoice.A) { audioFileB = try AKAudioFile(forReading: whiteAudioURL) audioFileA = try AKAudioFile(forReading: filteredAudioURL) } else { audioFileA = try AKAudioFile(forReading: whiteAudioURL) audioFileB = try AKAudioFile(forReading: filteredAudioURL) } // load the A and B audio files playerA = try AKAudioPlayer(file: audioFileA) playerB = try AKAudioPlayer(file: audioFileB) } catch let error { print("Error: \(error.localizedDescription)") } mixer = AKMixer(playerA, playerB, playerReference) AudioKit.output = mixer AudioKit.start() } } override func viewDidLoad() { let font = UIFont.systemFont(ofSize: 20) segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],for: .normal) // set the colour for buttons in disabled state //backButton.setTitleColor(UIColor.darkGray, for: .disabled) //nextButton.setTitleColor(UIColor.darkGray, for: .disabled) // hide the question data label questionDataLabel.alpha = 0.0; // get the list of subfolders in the audio folder // audioFolderURL = URL(fileURLWithPath: "audio", relativeTo: Bundle.main.bundleURL) audioFolderURL = URL(fileURLWithPath: "audio", relativeTo: Bundle.main.bundleURL) do { folderList = try FileManager.default.contentsOfDirectory(atPath: audioFolderURL.path) as [String] folderList = folderList.sorted { $0.localizedStandardCompare($1) == ComparisonResult.orderedAscending } print (folderList); } catch let error { print("Error loading audio files: \(error.localizedDescription)") } // each folder is one question; update the question label // to show the correct number of questions totalQuestions = folderList.count updateQuestionLabel() // randomly generate correct answers randomiseCorrectAnswers() // start the test updateQuestion() super.viewDidLoad() } @IBAction func playReferenceSound(_ sender: Any) { if !playerReference.isPlaying { playerReference.start() } } @IBAction func stopReferenceSound(_ sender: Any) { if playerReference.isPlaying { playerReference.stop() } } @IBAction func playSoundA(_ sender: UIButton) { if !playerA.isPlaying { //sender.setTitle("Stop", for: .normal) playerA.start() } } @IBAction func stopSoundA(_ sender: UIButton) { if playerA.isPlaying { //sender.setTitle("Play", for: .normal) playerA.stop() } } @IBAction func playSoundB(_ sender: UIButton) { if !playerB.isPlaying { //sender.setTitle("Stop", for: .normal) playerB.start() } } @IBAction func stopSoundB(_ sender: UIButton) { if playerB.isPlaying { //sender.setTitle("Play", for: .normal) playerB.stop() } } func updateQuestionLabel(){ questionNumberLabel.text = String(currentQuestion) + " / " + String(totalQuestions) // show results at the end if(currentQuestion == totalQuestions + 1){ questionNumberLabel.text = "results"; } } func recordAnswer() { if (currentQuestion <= totalQuestions){ userAnswers[currentQuestion - 1] = indexToAnswerChoice(idx: segmentedControl.selectedSegmentIndex) } } func loadAnswer() { // load the answer unless we are on the results page if (currentQuestion <= totalQuestions){ // load the answer to the segmented control segmentedControl.selectedSegmentIndex = segmentedControlIndex(ac: userAnswers[currentQuestion - 1]) // don't allow the user to change the // answer for questions after viewing // the correct answer segmentedControl.isEnabled = activeQuestions[currentQuestion - 1] } } func advanceQuestion(amount: Int){ // record the answer to the current question recordAnswer() // increment the question number currentQuestion += amount // wrap back to the beginning when we reach the end if(currentQuestion > totalQuestions + 1){ currentQuestion = 1 } // show results when we reach the end resultsView.isHidden = !(currentQuestion == totalQuestions+1) copyButton.isHidden = resultsView.isHidden updateQuestion() } @IBAction func nextButtonTouched(_ sender: Any) { advanceQuestion(amount:1); } @IBAction func fastNextTouched(_ sender: Any) { advanceQuestion(amount:10); } @IBAction func doubleFastNextTouched(_ sender: Any) { advanceQuestion(amount:100); } func toPreviousQuestion(amount: Int){ // record the answer to the current question recordAnswer() // decrement the question number currentQuestion -= amount // wrap to the end if we are at the beginning if (currentQuestion < 1){ currentQuestion = totalQuestions + 1 } // hide results when we are not yet at the end resultsView.isHidden = !(currentQuestion == totalQuestions+1) copyButton.isHidden = resultsView.isHidden updateQuestion() } @IBAction func backButtonTouched(_ sender: Any) { toPreviousQuestion(amount:1) } @IBAction func fastBackTouched(_ sender: Any) { toPreviousQuestion(amount:10) } @IBAction func doubleFastBackTouched(_ sender: Any) { toPreviousQuestion(amount:100) } @IBAction func showAnswer(_ sender: Any) { if correctAnswers[currentQuestion-1] == answerChoice.A { AButton.backgroundColor = orangeColour } else { BButton.backgroundColor = orangeColour } questionDataLabel.alpha = 1.0 // set the current question inactive // now that the user has seen the answer activeQuestions[currentQuestion-1] = false; // disable the control so that the user // can not change the answer segmentedControl.isEnabled = false; } @IBAction func hideAnswer(_ sender: Any) { AButton.backgroundColor = blueColour BButton.backgroundColor = blueColour questionDataLabel.alpha = 0.0 } @IBAction func copyResults(_ sender: Any) { updateResults(copy: true); } }
4b9f2fe24f37a7bcc1e6cc0f1fda51c9
27.377574
115
0.56689
false
false
false
false
lixiangzhou/ZZKG
refs/heads/master
ZZKG/ZZKG/Classes/Lib/ZZLib/ZZExtension/ZZUIExtension/UIColor+ZZExtension.swift
mit
1
// // UIColor+ZZExtension.swift // ZZLib // // Created by lixiangzhou on 17/3/12. // Copyright © 2017年 lixiangzhou. All rights reserved. // import UIKit public extension UIColor { /// 快速创建颜色 /// /// - parameter red: 红 /// - parameter green: 绿 /// - parameter blue: 蓝 /// - parameter alpha: 透明度 convenience init(red: Int, green: Int, blue: Int, alphaValue: CGFloat = 1.0) { self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alphaValue) } /// 16进制rgb颜色值生成对应UIColor /// /// - parameter stringHexValue: 16进制颜色值, 可包含前缀0x,#,颜色值可以是 RGB RGBA RRGGBB RRGGBBAA convenience init?(stringHexValue: String) { var hexValue = stringHexValue.zz_trim.uppercased() if hexValue.hasPrefix("#") { hexValue = hexValue.substring(from: hexValue.index(hexValue.startIndex, offsetBy: 1)) } else if hexValue.hasPrefix("0X") { hexValue = hexValue.substring(from: hexValue.index(hexValue.startIndex, offsetBy: 2)) } let len = hexValue.characters.count // RGB RGBA RRGGBB RRGGBBAA if len != 3 && len != 4 && len != 6 && len != 8 { return nil } var resultHexValue: UInt32 = 0 guard Scanner(string: hexValue).scanHexInt32(&resultHexValue) else { return nil } var divisor: CGFloat = 255 var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if len == 3 { divisor = 15 r = CGFloat((resultHexValue & 0xF00) >> 8) / divisor g = CGFloat((resultHexValue & 0x0F0) >> 4) / divisor b = CGFloat( resultHexValue & 0x00F) / divisor a = 1 } else if len == 4 { divisor = 15 r = CGFloat((resultHexValue & 0xF000) >> 12) / divisor g = CGFloat((resultHexValue & 0x0F00) >> 8) / divisor b = CGFloat((resultHexValue & 0x00F0) >> 4) / divisor a = CGFloat(resultHexValue & 0x000F) / divisor } else if len == 6 { r = CGFloat((resultHexValue & 0xFF0000) >> 16) / divisor g = CGFloat((resultHexValue & 0x00FF00) >> 8) / divisor b = CGFloat(resultHexValue & 0x0000FF) / divisor a = 1 } else if len == 8 { r = CGFloat((resultHexValue & 0xFF000000) >> 24) / divisor g = CGFloat((resultHexValue & 0x00FF0000) >> 16) / divisor b = CGFloat((resultHexValue & 0x0000FF00) >> 8) / divisor a = CGFloat(resultHexValue & 0x000000FF) / divisor } self.init(red: r, green: g, blue: b, alpha: a) } /// 随机色 static var zz_random: UIColor { let red = arc4random() % 256 let green = arc4random() % 256 let blue = arc4random() % 256 return UIColor(red: Int(red), green: Int(green), blue: Int(blue)) } /// 返回颜色的rgba值 var rgbaValue: String? { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if getRed(&r, green: &g, blue: &b, alpha: &a) { let red = Int(r * 255) let green = Int(g * 255) let blue = Int(b * 255) let alpha = Int(a * 255) /* 进制转换 String(value: T, radix: Int) value的radix表现形式 Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制 */ let value = (red << 24) + (green << 16) + (blue << 8) + alpha return String(value, radix: 16) } return nil } var rgbValue: String? { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 if getRed(&r, green: &g, blue: &b, alpha: nil) { let red = Int(r * 255) let green = Int(g * 255) let blue = Int(b * 255) /* 进制转换 String(value: T, radix: Int) value的radix表现形式 Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制 */ let value = (red << 16) + (green << 8) + blue return String(value, radix: 16) } return nil } /// 返回颜色的rgba值 var rgbaHexStringValue: (red: String, green: String, blue: String, alpha: String)? { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if getRed(&r, green: &g, blue: &b, alpha: &a) { let red = String(Int(r * 255), radix: 16) let green = String(Int(g * 255), radix: 16) let blue = String(Int(b * 255), radix: 16) let alpha = String(Int(a * 255), radix: 16) return (red: red, green: green, blue: blue, alpha: alpha) } return nil } /// 返回颜色的rgba值,0-255 var rgbaIntValue: (red: Int, green: Int, blue: Int, alpha: Int)? { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if getRed(&r, green: &g, blue: &b, alpha: &a) { let red = Int(r * 255) let green = Int(g * 255) let blue = Int(b * 255) let alpha = Int(a * 255) return (red: red, green: green, blue: blue, alpha: alpha) } return nil } }
09e086ffbae6721e7f0cbeece453c5ae
31.602339
123
0.498475
false
false
false
false
illescasDaniel/Questions
refs/heads/master
Questions/Models/Question.swift
mit
1
// // QuestionType.swift // Questions // // Created by Daniel Illescas Romero on 24/05/2018. // Copyright © 2018 Daniel Illescas Romero. All rights reserved. // import Foundation class Question: Codable, CustomStringConvertible { let question: String let answers: [String] var correctAnswers: Set<UInt8>! = [] let correct: UInt8? let imageURL: String? init(question: String, answers: [String], correct: Set<UInt8>, singleCorrect: UInt8? = nil, imageURL: String? = nil) { self.question = question.trimmingCharacters(in: .whitespacesAndNewlines) self.answers = answers.map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) }) self.correctAnswers = correct self.correct = singleCorrect self.imageURL = imageURL?.trimmingCharacters(in: .whitespacesAndNewlines) } } extension Question: Equatable { static func ==(lhs: Question, rhs: Question) -> Bool { return lhs.question == rhs.question && lhs.answers == rhs.answers && lhs.correctAnswers == rhs.correctAnswers } } extension Question: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(self.question.hash) } }
344ed7553de3d84f9e9e86375077a2c5
28.236842
119
0.730873
false
false
false
false
KogiMobileSAS/KeyboardResize
refs/heads/master
Example/TableViewController.swift
mit
1
// // TableViewController.swift // Example // // Created by Juan Alberto Uribe on 6/16/16. // Copyright © 2016 Kogi Mobile. All rights reserved. // import UIKit class TableViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() configureTable() kr_resizeViewWhenKeyboardAppears = true } private func configureTable() { tableView.dataSource = self let footerFrame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 50) let footerLabel = UILabel(frame: footerFrame) footerLabel.text = "FOOTER" tableView.tableFooterView = footerLabel } } extension TableViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 15 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) return cell } }
8dd989dd7d0326b18e2a831a59746655
26.431818
109
0.63546
false
false
false
false
EugeneVegner/sws-copyleaks-sdk-test
refs/heads/master
PlagiarismChecker/Classes/CopyleaksToken.swift
mit
1
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) * * 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 private let copyleaksToken = "copyleaksToken" class CopyleaksToken: NSObject, NSCoding { var accessToken: String? var issued: String? var expires: String? private let copyleaksTokenKey = "copyleaksTokenKey" private let copyleaksTokenIssued = "copyleaksTokenIssued" private let copyleaksTokenExpired = "copyleaksTokenExpired" init(response: CopyleaksResponse<AnyObject, NSError>) { if let accessTokenVal = response.result.value?["access_token"] as? String, let issuedVal = response.result.value?[".issued"] as? String, let expiresVal = response.result.value?[".expires"] as? String { accessToken = accessTokenVal issued = issuedVal expires = expiresVal } } required init(coder aDecoder: NSCoder) { accessToken = aDecoder.decodeObjectForKey(copyleaksTokenKey) as? String issued = aDecoder.decodeObjectForKey(copyleaksTokenIssued) as? String expires = aDecoder.decodeObjectForKey(copyleaksTokenExpired) as? String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(accessToken, forKey: copyleaksTokenKey) aCoder.encodeObject(issued, forKey: copyleaksTokenIssued) aCoder.encodeObject(expires, forKey: copyleaksTokenExpired) } func save() { let data = NSKeyedArchiver.archivedDataWithRootObject(self) let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(data, forKey:copyleaksToken ) } func isValid() -> Bool { guard let accessTokenVal = accessToken, issuedVal = issued, expiresVal = expires else { return false } let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = CopyleaksConst.dateTimeFormat dateFormatter.timeZone = NSTimeZone(name: "UTC") let issuedDate = dateFormatter.dateFromString(issuedVal) let expiresDate = dateFormatter.dateFromString(expiresVal) return true } func generateAccessToken() -> String { if self.isValid() { return "Bearer " + accessToken! } else { return "" } } class func hasAccessToken() -> Bool { guard let _ = getAccessToken() else { return false } return true } class func getAccessToken() -> CopyleaksToken? { if let data = NSUserDefaults.standardUserDefaults().objectForKey(copyleaksToken) as? NSData { return (NSKeyedUnarchiver.unarchiveObjectWithData(data) as? CopyleaksToken)! } return nil } class func clear() { NSUserDefaults.standardUserDefaults().removeObjectForKey(copyleaksToken) } }
d741a0a9b515ab9c308665b84932f6df
33.86087
101
0.676727
false
false
false
false
mkrisztian95/iOS
refs/heads/master
Tardis/ScheduleItem.swift
apache-2.0
1
// // ScheduleItem.swift // Tardis // // Created by Molnar Kristian on 7/25/16. // Copyright © 2016 Molnar Kristian. All rights reserved. // import UIKit import Firebase @IBDesignable class ScheduleItem: UIView { @IBOutlet weak var eventTitle: UILabel! @IBOutlet weak var locationLabel: UILabel! var view: UIView! let storage = FIRStorage.storage() var tapped = false func xibSetup() { view = loadViewFromNib() // use bounds not frame or it'll be offset view.frame = bounds // Make the view stretch with containing view view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] // Adding custom subview on top of our view (over any custom drawing > see note below) addSubview(view) } func loadViewFromNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "ScheduleItem", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView view.layer.cornerRadius = 5.0 return view } override init(frame: CGRect) { // 1. setup any properties here // 2. call super.init(frame:) super.init(frame: frame) // 3. Setup view from .xib file xibSetup() } func setUp(time:String, title:String, location:String) { self.eventTitle.text = title self.locationLabel.text = "Location: \(location)" self.eventTitle.adjustsFontSizeToFitWidth = true } required init?(coder aDecoder: NSCoder) { // 1. setup any properties here // 2. call super.init(coder:) super.init(coder: aDecoder) // 3. Setup view from .xib file xibSetup() } }
283daca4540eb159241b72b9f9def824
24.455882
97
0.65338
false
false
false
false
SmallPlanetSwift/PlanetSwift
refs/heads/master
Sources/PlanetSwift/PlanetCollectionViewController.swift
mit
1
// // PlanetCollectionViewController.swift // Planned // // Created by Quinn McHenry on 12/2/15. // Copyright (c) 2015 Small Planet Digital. All rights reserved. // // swiftlint:disable line_length // swiftlint:disable force_cast import UIKit public protocol PlanetCollectionViewTemplate { var reuseId: String { get } var size: TemplateSize { get } func decorate(_ cell: UICollectionViewCell) } public typealias TemplateSize = (width: TemplateConstraint, height: TemplateConstraint) public enum TemplateConstraint { case unconstrained case full case half case fixed(points: Float) } public func == (lhs: TemplateConstraint, rhs: TemplateConstraint) -> Bool { switch (lhs, rhs) { case (.unconstrained, .unconstrained): return true case (.full, .full): return true case (.half, .half): return true case (.fixed(let aaa), .fixed(let bbb)) where aaa == bbb: return true default: return false } } public func != (lhs: TemplateConstraint, rhs: TemplateConstraint) -> Bool { return !(lhs == rhs) } public func == (lhs: TemplateSize, rhs: TemplateSize) -> Bool { return lhs.width == rhs.width && lhs.height == rhs.height } public func != (lhs: TemplateSize, rhs: TemplateSize) -> Bool { return !(lhs == rhs) } public protocol PlanetCollectionViewCell: class { var bundlePath: String { get } var xmlView: View? { get set } func loadView() } public extension PlanetCollectionViewCell where Self: UICollectionViewCell { func loadView() { guard xmlView == nil else { return } xmlView = PlanetUI.readFromFile(String(bundlePath: bundlePath)) as? View guard let xmlView = xmlView else { // failed to create xml view from bundlePath \(bundlePath) return } contentView.addSubview(xmlView.view) xmlView.visit { $0.gaxbDidPrepare() } let mirror = Mirror(reflecting: self) for case let (label?, _) in mirror.children { if let element = xmlView.elementForId(label) as? View { setValue(element.view, forKey: label) } } addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .width)) addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .height)) addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .left)) addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .top)) xmlView.view.translatesAutoresizingMaskIntoConstraints = false contentView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .width)) addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .height)) addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .left)) addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .top)) } } public extension PlanetCollectionViewCell where Self: UICollectionReusableView { func loadView() { guard xmlView == nil else { return } xmlView = PlanetUI.readFromFile(String(bundlePath: bundlePath)) as? View guard let xmlView = xmlView else { // failed to create xml view from bundlePath \(bundlePath) return } addSubview(xmlView.view) xmlView.visit { $0.gaxbDidPrepare() } let mirror = Mirror(reflecting: self) for case let (label?, _) in mirror.children { if let element = xmlView.elementForId(label) as? View { setValue(element.view, forKey: label) } } addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .width)) addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .height)) addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .left)) addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .top)) xmlView.view.translatesAutoresizingMaskIntoConstraints = false } } open class PlanetCollectionViewController: PlanetViewController, UICollectionViewDelegateFlowLayout { @IBOutlet open var collectionView: UICollectionView! open var cellReferences = [String: PlanetCollectionViewCell]() open var cellMapping: [String: PlanetCollectionViewCell.Type] { return [:] } open var cellSizes: [[CGSize]] = [] open var objects: [[PlanetCollectionViewTemplate]] = [] { didSet { cellSizes.removeAll(keepingCapacity: false) for subarray in objects { cellSizes.append([CGSize](repeating: CGSize.zero, count: subarray.count)) } } } override open func viewDidLoad() { super.viewDidLoad() configureCollectionView() collectionView.contentOffset = CGPoint.zero } open func configureCollectionView() { for (cellId, cellClass) in cellMapping { collectionView?.register(cellClass, forCellWithReuseIdentifier: cellId) } if collectionView?.collectionViewLayout == nil { collectionView?.setCollectionViewLayout(UICollectionViewFlowLayout(), animated: false) } } // MARK: - Collection View Cell Handling open func configure(_ cell: PlanetCollectionViewCell?, atIndexPath indexPath: IndexPath) { guard cell?.xmlView == nil else { return } // only configure each cell once cell?.loadView() guard let xmlView = cell?.xmlView, let template = cellObject(indexPath as IndexPath), let cell = cell as? UICollectionViewCell else { return } switch template.size.width { case .unconstrained: break case .full: let insets = collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: indexPath.section) let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: collectionView.frame.size.width - insets.left - insets.right) xmlView.view.addConstraint(constraint) case .half: let insets = collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: indexPath.section) let constant = (collectionView.frame.size.width - insets.left - insets.right - max(insets.right, insets.left)) / 2 let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: floor(constant)) xmlView.view.addConstraint(constraint) case .fixed(let points): let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: CGFloat(points)) xmlView.view.addConstraint(constraint) } switch template.size.height { case .unconstrained: break case .full: let insets = collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: indexPath.section) let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: collectionView.frame.size.height - insets.top - insets.bottom) xmlView.view.addConstraint(constraint) case .half: break case .fixed(let points): let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: CGFloat(points)) xmlView.view.addConstraint(constraint) } cell.contentView.translatesAutoresizingMaskIntoConstraints = false } open func cellMapping(_ reuseId: String) -> PlanetCollectionViewCell.Type? { return cellMapping[reuseId] } open func reuseIdentifier(_ indexPath: IndexPath) -> String { return cellObject(indexPath)?.reuseId ?? "invalidReuseId" } open func cellObject(_ indexPath: IndexPath) -> PlanetCollectionViewTemplate? { guard objects.count > indexPath.section && objects[indexPath.section].count > indexPath.row else { return nil } return objects[indexPath.section][indexPath.row] } // MARK: - UICollectionViewDelegateFlowLayout open func cellSize(_ indexPath: IndexPath) -> CGSize? { guard cellSizes.count > indexPath.section && cellSizes[indexPath.section].count > indexPath.row else { return nil } return cellSizes[indexPath.section][indexPath.row] } open func setCellSize(_ size: CGSize, forIndexPath indexPath: IndexPath) { guard cellSizes.count > indexPath.section && cellSizes[indexPath.section].count > indexPath.row else { return } cellSizes[indexPath.section][indexPath.row] = size } open func cellHeight(_ indexPath: IndexPath) -> CGFloat? { return (cellSize(indexPath) ?? CGSize.zero).height } open func setCellHeight(_ height: CGFloat, forIndexPath indexPath: IndexPath) { if let size = cellSize(indexPath) { setCellSize(CGSize(width: size.width, height: height), forIndexPath: indexPath) } } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var size = cellSize(indexPath) ?? CGSize.zero if let template = cellObject(indexPath), size == CGSize.zero { let reuseId = reuseIdentifier(indexPath) var cellReference: PlanetCollectionViewCell? = cellReferences[reuseId] if cellReference == nil { if let cellReferenceType = cellMapping(reuseId) as? UICollectionViewCell.Type { cellReference = cellReferenceType.init() as? PlanetCollectionViewCell } if cellReference == nil { assertionFailure("Could not create cell from reuseId \"\(reuseId)\"") return CGSize.zero } configure(cellReference!, atIndexPath: indexPath) cellReferences[reuseId] = cellReference } configure(cellReference!, atIndexPath: indexPath) template.decorate(cellReference as! UICollectionViewCell) let xmlView = cellReference?.xmlView size = xmlView?.view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? CGSize.zero setCellSize(size, forIndexPath: indexPath) } return size } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: section == 0 ? 64 : 0, left: 0, bottom: 0, right: 0) } public init(frame: CGRect) { super.init(nibName: nil, bundle: nil) let cvv = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: UICollectionViewFlowLayout()) cvv.delegate = self cvv.dataSource = self self.collectionView = cvv self.view = cvv self.configureCollectionView() } public init() { super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } extension PlanetCollectionViewController: UICollectionViewDataSource { open func numberOfSections(in collectionView: UICollectionView) -> Int { return objects.count } open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return objects[section].count } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier(indexPath), for: indexPath) configure(cell as? PlanetCollectionViewCell, atIndexPath: indexPath) cellObject(indexPath)?.decorate(cell) return cell } open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "", for: indexPath) return cell } } extension PlanetCollectionViewController: UICollectionViewDelegate { open func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { collectionView.cellForItem(at: indexPath)?.isHighlighted = true } open func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) { collectionView.cellForItem(at: indexPath)?.isHighlighted = false } open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } }
3e84610252127bda814e1154d8961d55
41.913183
229
0.68455
false
false
false
false
duliodenis/cs193p-Spring-2016
refs/heads/master
democode/Smashtag-L11/Smashtag/TweetTableViewController.swift
mit
1
// // TweetTableViewController.swift // Smashtag // // Created by CS193p Instructor. // Copyright © 2016 Stanford University. All rights reserved. // import UIKit import Twitter import CoreData class TweetTableViewController: UITableViewController, UITextFieldDelegate { // MARK: Model // if this is nil, then we simply don't update the database // having this default to the AppDelegate's context is a little bit of "demo cheat" // probably it would be better to subclass TweetTableViewController // and set this var in that subclass and then use that subclass in our storyboard // (the only purpose of that subclass would be to pick what database we're using) var managedObjectContext: NSManagedObjectContext? = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext var tweets = [Array<Twitter.Tweet>]() { didSet { tableView.reloadData() } } var searchText: String? { didSet { tweets.removeAll() lastTwitterRequest = nil searchForTweets() title = searchText } } // MARK: Fetching Tweets private var twitterRequest: Twitter.Request? { if lastTwitterRequest == nil { if let query = searchText where !query.isEmpty { return Twitter.Request(search: query + " -filter:retweets", count: 100) } } return lastTwitterRequest?.requestForNewer } private var lastTwitterRequest: Twitter.Request? private func searchForTweets() { if let request = twitterRequest { lastTwitterRequest = request request.fetchTweets { [weak weakSelf = self] newTweets in dispatch_async(dispatch_get_main_queue()) { if request == weakSelf?.lastTwitterRequest { if !newTweets.isEmpty { weakSelf?.tweets.insert(newTweets, atIndex: 0) weakSelf?.updateDatabase(newTweets) } } weakSelf?.refreshControl?.endRefreshing() } } } else { self.refreshControl?.endRefreshing() } } // add the Twitter.Tweets to our database private func updateDatabase(newTweets: [Twitter.Tweet]) { managedObjectContext?.performBlock { for twitterInfo in newTweets { // the _ = just lets readers of our code know // that we are intentionally ignoring the return value _ = Tweet.tweetWithTwitterInfo(twitterInfo, inManagedObjectContext: self.managedObjectContext!) } // there is a method in AppDelegate // which will save the context as well // but we're just showing how to save and catch any error here do { try self.managedObjectContext?.save() } catch let error { print("Core Data Error: \(error)") } } printDatabaseStatistics() // note that even though we do this print() // AFTER printDatabaseStatistics() is called // it will print BEFORE because printDatabaseStatistics() // returns immediately after putting a closure on the context's queue // (that closure then runs sometime later, after this print()) print("done printing database statistics") } // print out how many Tweets and TwitterUsers are in the database // uses two different ways of counting them // the second way (countForFetchRequest) is much more efficient // (since it does the count in the database itself) private func printDatabaseStatistics() { managedObjectContext?.performBlock { if let results = try? self.managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName: "TwitterUser")) { print("\(results.count) TwitterUsers") } // a more efficient way to count objects ... let tweetCount = self.managedObjectContext!.countForFetchRequest(NSFetchRequest(entityName: "Tweet"), error: nil) print("\(tweetCount) Tweets") } } // prepare for the segue that happens // when the user hits the Tweeters bar button item override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "TweetersMentioningSearchTerm" { if let tweetersTVC = segue.destinationViewController as? TweetersTableViewController { tweetersTVC.mention = searchText tweetersTVC.managedObjectContext = managedObjectContext } } } @IBAction func refresh(sender: UIRefreshControl) { searchForTweets() } // MARK: UITableViewDataSource override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "\(tweets.count - section)" } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return tweets.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets[section].count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TweetCellIdentifier, forIndexPath: indexPath) let tweet = tweets[indexPath.section][indexPath.row] if let tweetCell = cell as? TweetTableViewCell { tweetCell.tweet = tweet } return cell } // MARK: Constants private struct Storyboard { static let TweetCellIdentifier = "Tweet" } // MARK: Outlets @IBOutlet weak var searchTextField: UITextField! { didSet { searchTextField.delegate = self searchTextField.text = searchText } } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() searchText = textField.text return true } // MARK: View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
fb8a2a5ffc063b378d0d7ac82d692aa3
34.147208
125
0.628827
false
false
false
false
rudkx/swift
refs/heads/main
test/Generics/protocol_typealias_same_type_requirement.swift
apache-2.0
1
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=verify 2>&1 | %FileCheck %s protocol P1 { associatedtype A } protocol P2 { associatedtype B } // CHECK-LABEL: protocol_typealias_same_type_requirement.(file).P3@ // CHECK-LABEL: Requirement signature: <Self where Self : P1, Self : P2, Self.[P1]A == Self.[P2]B> protocol P3 : P1, P2 { typealias A = B } // CHECK-LABEL: protocol_typealias_same_type_requirement.(file).P4@ // CHECK-LABEL: Requirement signature: <Self where Self : P1, Self : P2, Self.[P2]B == Int> protocol P4 : P1, P2 { typealias B = Int } // CHECK-LABEL: protocol_typealias_same_type_requirement.(file).P5@ // CHECK-LABEL: Requirement signature: <Self> protocol P5 { associatedtype A associatedtype B } extension P5 where A == Int { typealias B = Int } protocol P6 { typealias A = Array<Int> } protocol P7 { associatedtype X typealias A = Array<X> } // CHECK-LABEL: protocol_typealias_same_type_requirement.(file).P8@ // CHECK-LABEL: Requirement signature: <Self where Self : P6, Self : P7, Self.[P7]X == Int> protocol P8 : P6, P7 {} func testP8<T : P8>(_: T, x: T.X) -> Int { return x }
075e8fbcef3eb465eee9758e858facde
24.446809
139
0.687291
false
false
false
false
bartekchlebek/SwiftHelpers
refs/heads/master
Example/Tests/DiffTests.swift
mit
1
import XCTest import Nimble import SwiftHelpers struct DiffedItem { var ID: String var property: String } struct EquatableDiffedItem: Equatable { var ID: String var property: String } struct IdentifiableDiffedItem: Identifiable { var ID: String var property: String } struct FastIdentifiableDiffedItem: FastIdentifiable { var ID: String var property: String } struct IdentifiableEquatableDiffedItem: Identifiable, Equatable { var ID: String var property: String } struct FastIdentifiableEquatableDiffedItem: FastIdentifiable, Equatable { var ID: String var property: String } func ==(lhs: EquatableDiffedItem, rhs: EquatableDiffedItem) -> Bool { return (lhs.ID == rhs.ID) && (lhs.property == rhs.property) } func ==(lhs: IdentifiableEquatableDiffedItem, rhs: IdentifiableEquatableDiffedItem) -> Bool { return (lhs.ID == rhs.ID) && (lhs.property == rhs.property) } func ==(lhs: FastIdentifiableEquatableDiffedItem, rhs: FastIdentifiableEquatableDiffedItem) -> Bool { return (lhs.ID == rhs.ID) && (lhs.property == rhs.property) } struct TestScenario<T> { var oldItems: [T] var newItems: [T] var added: [T] var removed: [T] var updatedFrom: [T] var updatedTo: [T] var addedIndexes: [Int] var removedIndexes: [Int] var updatedIndexes: [Int] var movedFromIndexes: [Int] var movedToIndexes: [Int] init(oldItems: [T], newItems: [T], added: [T], removed: [T], updatedFrom: [T], updatedTo: [T], addedIndexes: [Int], removedIndexes: [Int], updatedIndexes: [Int], movedFromIndexes: [Int], movedToIndexes: [Int]) { self.oldItems = oldItems self.newItems = newItems self.added = added self.removed = removed self.updatedFrom = updatedFrom self.updatedTo = updatedTo self.addedIndexes = addedIndexes self.removedIndexes = removedIndexes self.updatedIndexes = updatedIndexes self.movedFromIndexes = movedFromIndexes self.movedToIndexes = movedToIndexes } init<U>(fromScenario scenario: TestScenario<U>, conversionBlock: (U) -> T) { self.oldItems = scenario.oldItems.map(conversionBlock) self.newItems = scenario.newItems.map(conversionBlock) self.added = scenario.added.map(conversionBlock) self.removed = scenario.removed.map(conversionBlock) self.updatedFrom = scenario.updatedFrom.map(conversionBlock) self.updatedTo = scenario.updatedTo.map(conversionBlock) self.addedIndexes = scenario.addedIndexes self.removedIndexes = scenario.removedIndexes self.updatedIndexes = scenario.updatedIndexes self.movedFromIndexes = scenario.movedFromIndexes self.movedToIndexes = scenario.movedToIndexes } } let testScenarioSource = TestScenario( oldItems: [ (ID: "1", property: "a"), // stays (ID: "2", property: "b"), // stays (ID: "3", property: "c"), // is removed (ID: "4", property: "d"), // is removed (ID: "5", property: "e"), // is updated (ID: "6", property: "f"), // is updated (ID: "7", property: "g"), // is moved (ID: "8", property: "h"), // is moved // (ID: "9", property: "i"), // is added // (ID: "10", property: "j"), // is added ], newItems: [ (ID: "1", property: "a"), // stays (ID: "2", property: "b"), // stays // (ID: "3", property: "c"), // is removed // (ID: "4", property: "d"), // is removed (ID: "5", property: "E"), // is updated (ID: "6", property: "F"), // is updated (ID: "8", property: "h"), // is moved (ID: "7", property: "g"), // is moved (ID: "9", property: "i"), // is added (ID: "10", property: "j"), // is added ], added: [ (ID: "9", property: "i"), (ID: "10", property: "j"), ], removed: [ (ID: "3", property: "c"), (ID: "4", property: "d"), ], updatedFrom: [ (ID: "5", property: "e"), (ID: "6", property: "f"), ], updatedTo: [ (ID: "5", property: "E"), (ID: "6", property: "F"), ], addedIndexes: [6, 7], removedIndexes: [2, 3], updatedIndexes: [4, 5], movedFromIndexes: [6, 7], movedToIndexes: [5, 4] ) let testScenario = TestScenario(fromScenario: testScenarioSource) { DiffedItem(ID: $0.ID, property: $0.property) } let equatableTestScenario = TestScenario(fromScenario: testScenarioSource) { EquatableDiffedItem(ID: $0.ID, property: $0.property) } let identifiableTestScenario = TestScenario(fromScenario: testScenarioSource) { IdentifiableDiffedItem(ID: $0.ID, property: $0.property) } let fastIdentifiableTestScenario = TestScenario(fromScenario: testScenarioSource) { FastIdentifiableDiffedItem(ID: $0.ID, property: $0.property) } let identifiableEquatableTestScenario = TestScenario(fromScenario: testScenarioSource) { IdentifiableEquatableDiffedItem(ID: $0.ID, property: $0.property) } let fastIdentifiableEquatableTestScenario = TestScenario(fromScenario: testScenarioSource) { FastIdentifiableEquatableDiffedItem(ID: $0.ID, property: $0.property) } final class DiffTests: XCTestCase { func performTestWithContext<T>(_ context: DiffContext<T>, testScenario: TestScenario<T>, elementComparison: @escaping (T, T) -> Bool) { let diff = Diff(context) print(diff.added) print(testScenario.added) expect(diff.added.elementsEqual(testScenario.added, by: elementComparison)).to(beTrue()) expect(diff.added.elementsEqual(testScenario.added, by: elementComparison)) == true expect(diff.removed.elementsEqual(testScenario.removed, by: elementComparison)) == true expect(diff.updated.map{ $0.from }.elementsEqual(testScenario.updatedFrom, by: elementComparison)) == true expect(diff.updated.map{ $0.to }.elementsEqual(testScenario.updatedTo, by: elementComparison)) == true let indexDiff = IndexDiff(context) expect(indexDiff.addedIndexes) == testScenario.addedIndexes expect(indexDiff.removedIndexes) == testScenario.removedIndexes expect(indexDiff.updatedIndexes) == testScenario.updatedIndexes expect(indexDiff.movedIndexes.map({ $0.from })) == testScenario.movedFromIndexes expect(indexDiff.movedIndexes.map({ $0.to })) == testScenario.movedToIndexes } func performTestWithContext<T: Equatable>(_ context: DiffContext<T>, testScenario: TestScenario<T>) { self.performTestWithContext(context, testScenario: testScenario, elementComparison: ==) } func testDiffWithVerboseDiffContext() { let context = DiffContext<DiffedItem>( oldItems: testScenario.oldItems, newItems: testScenario.newItems, oldItemsContainItem: { item in testScenario.oldItems.contains { $0.ID == item.ID} }, newItemsContainItem: { item in testScenario.newItems.contains { $0.ID == item.ID} }, oldItemWithSameIDAsItem: { item in testScenario.oldItems.index { $0.ID == item.ID }.map { testScenario.oldItems[$0] } }, newItemWithSameIDAsItem: { item in testScenario.newItems.index { $0.ID == item.ID }.map { testScenario.newItems[$0] } }, isSameInstanceComparator: { $0.ID == $1.ID }, isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) } ) self.performTestWithContext(context, testScenario: testScenario) { ($0.ID == $1.ID) && ($0.property == $1.property) } } func testDiffWithConciseDiffContext1() { let context = DiffContext<DiffedItem>( oldItems: testScenario.oldItems, newItems: testScenario.newItems, isSameInstanceComparator: { $0.ID == $1.ID }, isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) } ) self.performTestWithContext(context, testScenario: testScenario) { ($0.ID == $1.ID) && ($0.property == $1.property) } } func testDiffWithConciseDiffContext2() { let context = DiffContext<DiffedItem>( oldItems: testScenario.oldItems, newItems: testScenario.newItems, itemsContainItem: { (items, item) -> Bool in return items.contains { $0.ID == item.ID } }, indexOfItemInItems: { (item, items) -> Int? in return items.index { $0.ID == item.ID } }, isSameInstanceComparator: { $0.ID == $1.ID }, isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) } ) self.performTestWithContext(context, testScenario: testScenario) { ($0.ID == $1.ID) && ($0.property == $1.property) } } func testDiffWithConciseDiffContext3() { let context = DiffContext<DiffedItem>( oldItems: testScenario.oldItems, newItems: testScenario.newItems, instanceIdentifierGetter: { $0.ID }, isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) } ) self.performTestWithContext(context, testScenario: testScenario) { ($0.ID == $1.ID) && ($0.property == $1.property) } } func testDiffWithDiffContextOfEquatableType() { let context = DiffContext<EquatableDiffedItem>( oldItems: equatableTestScenario.oldItems, newItems: equatableTestScenario.newItems, isSameInstanceComparator: { $0.ID == $1.ID } ) self.performTestWithContext(context, testScenario: equatableTestScenario) } func testDiffWithDiffContextOfIdentifiableType() { let context = DiffContext<IdentifiableDiffedItem>( oldItems: identifiableTestScenario.oldItems, newItems: identifiableTestScenario.newItems, isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) } ) self.performTestWithContext(context, testScenario: identifiableTestScenario) { ($0.ID == $1.ID) && ($0.property == $1.property) } } func testDiffWithDiffContextOfIdentifiableAndEquatableType() { let context = DiffContext<IdentifiableEquatableDiffedItem>( oldItems: identifiableEquatableTestScenario.oldItems, newItems: identifiableEquatableTestScenario.newItems ) self.performTestWithContext(context, testScenario: identifiableEquatableTestScenario) } func testDiffWithDiffContextOfFastIdentifiableType() { let context = DiffContext<FastIdentifiableDiffedItem>( oldItems: fastIdentifiableTestScenario.oldItems, newItems: fastIdentifiableTestScenario.newItems, isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) } ) self.performTestWithContext(context, testScenario: fastIdentifiableTestScenario) { ($0.ID == $1.ID) && ($0.property == $1.property) } } func testDiffWithDiffContextOfFastIdentifiableAndEquatableType() { let context = DiffContext<FastIdentifiableEquatableDiffedItem>( oldItems: fastIdentifiableEquatableTestScenario.oldItems, newItems: fastIdentifiableEquatableTestScenario.newItems ) self.performTestWithContext(context, testScenario: fastIdentifiableEquatableTestScenario) } func testIndexDiffWithOneInsertion() { let a = [ "1", "2", "3", "4", ] let b = [ "1", "NEW", "2", "3", "4", ] let context = DiffContext(oldItems: a, newItems: b) let indexDiff = IndexDiff(context) expect(indexDiff.addedIndexes) == [1] expect(indexDiff.removedIndexes) == [] expect(indexDiff.updatedIndexes) == [] expect(indexDiff.movedIndexes.count) == 0 } } extension String: FastIdentifiable { public var ID: String { return self } }
2a987d7a38dcec251b14081f96ce70d1
32.103976
108
0.700693
false
true
false
false
qhf012607/HFToolHandle
refs/heads/master
DemoClass/RxSwiftProject/Pods/Moya/Sources/RxMoya/MoyaProvider+Rx.swift
mit
2
import Foundation import RxSwift #if !COCOAPODS import Moya #endif extension MoyaProvider: ReactiveCompatible {} public extension Reactive where Base: MoyaProviderType { /// Designated request-making method. /// /// - Parameters: /// - token: Entity, which provides specifications necessary for a `MoyaProvider`. /// - callbackQueue: Callback queue. If nil - queue from provider initializer will be used. /// - Returns: Single response object. public func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Single<Response> { return Single.create { [weak base] single in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in switch result { case let .success(response): single(.success(response)) case let .failure(error): single(.error(error)) } } return Disposables.create { cancellableToken?.cancel() } } } /// Designated request-making method with progress. public func requestWithProgress(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Observable<ProgressResponse> { let progressBlock: (AnyObserver) -> (ProgressResponse) -> Void = { observer in return { progress in observer.onNext(progress) } } let response: Observable<ProgressResponse> = Observable.create { [weak base] observer in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: progressBlock(observer)) { result in switch result { case .success: observer.onCompleted() case let .failure(error): observer.onError(error) } } return Disposables.create { cancellableToken?.cancel() } } // Accumulate all progress and combine them when the result comes return response.scan(ProgressResponse()) { last, progress in let progressObject = progress.progressObject ?? last.progressObject let response = progress.response ?? last.response return ProgressResponse(progress: progressObject, response: response) } } }
b81301a1a7f37852416aa660b9fb0e98
36.828125
132
0.599339
false
false
false
false
prey/prey-ios-client
refs/heads/master
Prey/Classes/AlertVC.swift
gpl-3.0
1
// // AlertVC.swift // Prey // // Created by Javier Cala Uribe on 29/06/16. // Copyright © 2016 Prey, Inc. All rights reserved. // import UIKit class AlertVC: UIViewController { // MARK: Properties @IBOutlet var messageLbl : UILabel! @IBOutlet var subtitleLbl : UILabel! var messageToShow = "" // MARK: Init override func viewDidLoad() { super.viewDidLoad() // View title for GAnalytics // self.screenName = "Alert" // Set message messageLbl.text = messageToShow } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool){ // Hide navigationBar when appear this ViewController self.navigationController?.isNavigationBarHidden = true super.viewWillAppear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // Hide navigationBar when appear this ViewController self.navigationController?.isNavigationBarHidden = false } }
9961cfbeecce2d12bef9dd336b07330b
23.215686
64
0.616194
false
false
false
false
simorgh3196/GitHubSearchApp
refs/heads/master
Carthage/Checkouts/Himotoki/Sources/DecodeError.swift
mit
1
// // DecodeError.swift // Himotoki // // Created by Syo Ikeda on 8/29/15. // Copyright © 2015 Syo Ikeda. All rights reserved. // public enum DecodeError: ErrorType { case MissingKeyPath(KeyPath) case TypeMismatch(expected: String, actual: String, keyPath: KeyPath) case Custom(String) } extension DecodeError: CustomStringConvertible { public var description: String { switch self { case let .MissingKeyPath(keyPath): return "MissingKeyPath(\(keyPath))" case let .TypeMismatch(expected, actual, keyPath): return "TypeMismatch(expected: \(expected), actual: \(actual), keyPath: \(keyPath.description))" case let .Custom(message): return "Custom(\(message))" } } } extension DecodeError: Hashable { public var hashValue: Int { switch self { case let .MissingKeyPath(keyPath): return keyPath.hashValue case let .TypeMismatch(expected, actual, keyPath): return expected.hashValue ^ actual.hashValue ^ keyPath.hashValue case let .Custom(message): return message.hashValue } } } public func == (lhs: DecodeError, rhs: DecodeError) -> Bool { switch (lhs, rhs) { case let (.MissingKeyPath(l), .MissingKeyPath(r)): return l == r case let (.TypeMismatch(la, lb, lc), .TypeMismatch(ra, rb, rc)): return la == ra && lb == rb && lc == rc case let (.Custom(l), .Custom(r)): return l == r default: return false } } public func missingKeyPath(keyPath: KeyPath) -> DecodeError { return DecodeError.MissingKeyPath(keyPath) } public func typeMismatch<T>(expected: String, actual: T, keyPath: KeyPath = KeyPath.empty) -> DecodeError { return DecodeError.TypeMismatch(expected: expected, actual: String(actual), keyPath: keyPath) } public func customError(message: String) -> DecodeError { return DecodeError.Custom(message) }
6107f3d8134aea0c18cf70f380e12442
26.788732
108
0.643183
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/SettingsPrivacy/Views/Cells/SettingsPrivacyDeleteAccountCell.swift
apache-2.0
1
import KsApi import Library import Prelude import ReactiveExtensions import ReactiveSwift import UIKit internal protocol SettingsPrivacyDeleteAccountCellDelegate: AnyObject { func settingsPrivacyDeleteAccountCellTapped(_ cell: SettingsPrivacyDeleteAccountCell, with url: URL) } internal final class SettingsPrivacyDeleteAccountCell: UITableViewCell, ValueCell { fileprivate let viewModel: SettingsDeleteAccountCellViewModelType = SettingsDeleteAccountCellViewModel() internal weak var delegate: SettingsPrivacyDeleteAccountCellDelegate? @IBOutlet fileprivate var deleteAccountButton: UIButton! @IBOutlet fileprivate var deleteAccountLabel: UILabel! @IBOutlet fileprivate var separatorView: [UIView]! internal override func awakeFromNib() { super.awakeFromNib() _ = self |> \.accessibilityElements .~ [self.deleteAccountButton].compact() _ = self.deleteAccountButton |> \.accessibilityLabel %~ { _ in Strings.Delete_my_Kickstarter_Account() } self.deleteAccountButton.addTarget(self, action: #selector(self.deleteAccountTapped), for: .touchUpInside) } internal func configureWith(value user: User) { self.viewModel.inputs.configureWith(user: user) } internal override func bindStyles() { super.bindStyles() _ = self |> baseTableViewCellStyle() |> UITableViewCell.lens.contentView.layoutMargins %~~ { _, cell in cell.traitCollection.isRegularRegular ? .init(topBottom: Styles.grid(2), leftRight: Styles.grid(20)) : .init(topBottom: Styles.grid(1), leftRight: Styles.grid(2)) } _ = self.separatorView ||> settingsSeparatorStyle _ = self.deleteAccountLabel |> UILabel.lens.textColor .~ .ksr_alert |> UILabel.lens.font .~ .ksr_body() |> UILabel.lens.numberOfLines .~ 2 |> UILabel.lens.text %~ { _ in Strings.Delete_my_Kickstarter_Account() } } internal override func bindViewModel() { super.bindViewModel() self.viewModel.outputs.notifyDeleteAccountTapped .observeForUI() .observeValues { [weak self] url in guard let _self = self else { return } self?.delegate?.settingsPrivacyDeleteAccountCellTapped(_self, with: url) } } @objc fileprivate func deleteAccountTapped() { self.viewModel.inputs.deleteAccountTapped() } }
e8fd8d2c1fc9a38fa03e3f9d5b98a6c7
31.830986
110
0.723724
false
false
false
false
parthdubal/MyNewyorkTimes
refs/heads/master
MyNewyorkTimes/Modules/NewsDetails/View/NewsDetailController.swift
mit
1
// // NewsDetailController.swift // MyNewyorkTimes // // Created by Parth Dubal on 7/10/17. // Copyright © 2017 Parth Dubal. All rights reserved. // import UIKit import WebKit import SVProgressHUD class NewsDetailController: BaseViewController , NewsDetailViewInterface, UICollectionViewDelegate, UICollectionViewDataSource, WKNavigationDelegate { @IBOutlet weak var collectionView: UICollectionView! weak var newsDetailPresenter : NewsDetailsModuleInterface! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // showing selected news detail information in view let selectedIndexPath = IndexPath(item: newsDetailPresenter.currentNewsIndex, section: 0) self.collectionView.scrollToItem(at: selectedIndexPath, at: .left, animated: true) } func setupView() { self.title = "News Details" self.setCellSize() self.collectionView.isPagingEnabled = true self.updateNewsDetailsViewInterface() self.setNavigationIndicatorItem() } func setCellSize() { // Update cell size according to device screen size. var size = self.navigationController!.navigationBar.frame.size let statusBarHeight = UIApplication.shared.statusBarFrame.size.height size.height += statusBarHeight // updateing item size according to self.view size if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.itemSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height-size.height) } } // MARK:- View Interface implementation func updateNewsDetailsViewInterface() { collectionView.reloadData() } func requestErrorOccured(errorMessage:String) { SVProgressHUD.dismissHUD(error: errorMessage) } //MARK:- Collection View datasource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return newsDetailPresenter.newsInfoList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NewsDetailsCell.cellIdentifer, for: indexPath) as! NewsDetailsCell let newsInfo = newsDetailPresenter.newsInfoList[indexPath.item] cell.loadUrl(stringUrl: newsInfo.webUrl) cell.wkwebView.navigationDelegate = self return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let newsDetailCell = cell as? NewsDetailsCell { newsDetailCell.wkwebView.tag = indexPath.row + 1 activityIndicator?.tag = indexPath.row + 1 if newsDetailCell.wkwebView.isLoading { activityIndicator?.startAnimating() } } if indexPath.item >= newsDetailPresenter.newsInfoList.count - 3 && newsDetailPresenter.canLoadMore { newsDetailPresenter.requestMoreNewsInfoList() } } // MARK: - WKWebView Navigation delegates func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if webView.tag == activityIndicator?.tag { activityIndicator?.startAnimating() } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if webView.tag == activityIndicator?.tag { activityIndicator?.stopAnimating() } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
6199b471deca727ef38f063842b98c9c
31.669065
150
0.659546
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/ExplainedActionView/ExplainedActionViewModel.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxCocoa import RxSwift public struct DescriptionTitle { public var title: String public var titleColor: UIColor public var titleFontSize: CGFloat public init(title: String, titleColor: UIColor, titleFontSize: CGFloat) { self.title = title self.titleColor = titleColor self.titleFontSize = titleFontSize } } public struct ExplainedActionViewModel { // MARK: - Types private typealias AccessibilityId = Accessibility.Identifier.ExplainedActionView // MARK: - Setup let thumbBadgeImageViewModel: BadgeImageViewModel let titleLabelContent: LabelContent let descriptionLabelContents: [LabelContent] let badgeViewModel: BadgeViewModel? // MARK: - Accessors public var tap: Signal<Void> { tapRelay.asSignal() } let tapRelay = PublishRelay<Void>() // MARK: - Setup public init( thumbImage: String, title: String, descriptions: [DescriptionTitle], badgeTitle: String?, uniqueAccessibilityIdentifier: String, thumbRenderDefault: Bool = false ) { if thumbRenderDefault { thumbBadgeImageViewModel = .default( image: .local(name: thumbImage, bundle: .platformUIKit), backgroundColor: .clear, cornerRadius: .none, accessibilityIdSuffix: uniqueAccessibilityIdentifier ) } else { thumbBadgeImageViewModel = .primary( image: .local(name: thumbImage, bundle: .platformUIKit), cornerRadius: .round, accessibilityIdSuffix: uniqueAccessibilityIdentifier ) thumbBadgeImageViewModel.marginOffsetRelay.accept(6) } titleLabelContent = .init( text: title, font: .main(.semibold, 16), color: .titleText, accessibility: .id(uniqueAccessibilityIdentifier + AccessibilityId.titleLabel) ) descriptionLabelContents = descriptions .enumerated() .map { payload in .init( text: payload.element.title, font: .main(.medium, 14), color: payload.element.titleColor, accessibility: .id( uniqueAccessibilityIdentifier + AccessibilityId.descriptionLabel + ".\(payload.offset)" ) ) } if let badgeTitle = badgeTitle { badgeViewModel = .affirmative( with: badgeTitle, accessibilityId: uniqueAccessibilityIdentifier + AccessibilityId.badgeView ) } else { // hide badge badgeViewModel = nil } } } extension ExplainedActionViewModel: Equatable { public static func == (lhs: ExplainedActionViewModel, rhs: ExplainedActionViewModel) -> Bool { lhs.badgeViewModel == rhs.badgeViewModel && lhs.titleLabelContent == rhs.titleLabelContent && lhs.thumbBadgeImageViewModel == rhs.thumbBadgeImageViewModel && lhs.descriptionLabelContents == rhs.descriptionLabelContents } }
20f4c8ee4a8b9587ac6ea3aa19529a29
31.019608
111
0.609308
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Aztec/Processors/VideoUploadProcessor.swift
gpl-2.0
2
import Foundation import Aztec import WordPressEditor class VideoUploadProcessor: Processor { let mediaUploadID: String let remoteURLString: String let videoPressID: String? init(mediaUploadID: String, remoteURLString: String, videoPressID: String?) { self.mediaUploadID = mediaUploadID self.remoteURLString = remoteURLString self.videoPressID = videoPressID } lazy var videoPostMediaUploadProcessor = ShortcodeProcessor(tag: "video", replacer: { (shortcode) in guard let uploadValue = shortcode.attributes[MediaAttachment.uploadKey]?.value, case let .string(uploadID) = uploadValue, self.mediaUploadID == uploadID else { return nil } var html = "" if let videoPressGUID = self.videoPressID { html = "[wpvideo " html += videoPressGUID html += " ]" } else { html = "[video " var updatedAttributes = shortcode.attributes updatedAttributes.set(.string(self.remoteURLString), forKey: "src") //remove the uploadKey updatedAttributes.remove(key: MediaAttachment.uploadKey) let attributeSerializer = ShortcodeAttributeSerializer() html += attributeSerializer.serialize(updatedAttributes) html += "]" } return html }) func process(_ text: String) -> String { return videoPostMediaUploadProcessor.process(text) } }
77780e9eca8c88e272ae17ff056bf405
31.042553
104
0.634794
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
refs/heads/master
the-blue-alliance-ios/Operations/App Setup/AppSetupOperation.swift
mit
1
import CoreData import Foundation import Search import TBAKit import TBAOperation import UIKit class AppSetupOperation: TBAOperation { var destroyPersistentStoreOperation: DestroyPersistentStoreOperation var persistentContainerOperation: PersistentContainerOperation let appSetupOperationQueue = OperationQueue() init(indexDelegate: TBACoreDataCoreSpotlightDelegate, persistentContainer: NSPersistentContainer, tbaKit: TBAKit, userDefaults: UserDefaults) { self.destroyPersistentStoreOperation = DestroyPersistentStoreOperation(persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) self.persistentContainerOperation = PersistentContainerOperation(indexDelegate: indexDelegate, persistentContainer: persistentContainer) self.persistentContainerOperation.addDependency(self.destroyPersistentStoreOperation) super.init() } override func execute() { let blockOperation = BlockOperation { [unowned self] in self.completionError = [self.destroyPersistentStoreOperation, self.persistentContainerOperation].compactMap({ $0.completionError }).first self.finish() } let dependentOperations = [destroyPersistentStoreOperation, persistentContainerOperation] for op in dependentOperations { blockOperation.addDependency(op) } appSetupOperationQueue.addOperations(dependentOperations + [blockOperation], waitUntilFinished: false) } }
bf60b595ad8f269aa7d70606ed2147e2
39.675676
164
0.780066
false
false
false
false
apple/swift
refs/heads/main
test/SILOptimizer/assemblyvision_remark/basic.swift
apache-2.0
2
// RUN: %target-swiftc_driver -O -Rpass-missed=sil-assembly-vision-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xfrontend -enable-copy-propagation -emit-sil %s -o /dev/null -Xfrontend -verify -Xfrontend -enable-lexical-borrow-scopes=false // REQUIRES: optimized_stdlib,swift_stdlib_no_asserts // REQUIRES: swift_in_compiler public class Klass { var next: Klass? = nil } // TODO: Change global related code to be implicit/autogenerated (as // appropriate) so we don't emit this remark. public var global = Klass() // expected-remark {{heap allocated ref of type 'Klass'}} @inline(never) public func getGlobal() -> Klass { return global // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-5:12 {{of 'global'}} // expected-remark @-2:12 {{begin exclusive access to value of type 'Klass'}} // expected-note @-7:12 {{of 'global'}} // expected-remark @-4:12 {{end exclusive access to value of type 'Klass'}} // expected-note @-9:12 {{of 'global'}} } // Make sure that the retain msg is at the beginning of the print and the // releases are the end of the print. // // The heap allocated ref is for the temporary array and the release that is // unannotated is for that array as well. We make sure that the heap allocated // ref is on the argument that necessitated its creation. public func useGlobal() { let x = getGlobal() print(x) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:12 {{release of type}} } public enum TrivialState { case first case second case third } struct StructWithOwner { var owner = Klass() var state = TrivialState.first } func printStructWithOwner(x : StructWithOwner) { print(x) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1 {{retain of type 'Klass'}} // expected-note @-3:27 {{of 'x.owner'}} // expected-remark @-3:12 {{release of type}} } func printStructWithOwnerOwner(x : StructWithOwner) { print(x.owner) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1 {{retain of type 'Klass'}} // expected-note @-3:32 {{of 'x.owner'}} // expected-remark @-3:18 {{release of type}} } func returnStructWithOwnerOwner(x: StructWithOwner) -> Klass { return x.owner // expected-remark {{retain of type 'Klass'}} // expected-note @-2:33 {{of 'x.owner'}} } func callingAnInitializerStructWithOwner(x: Klass) -> StructWithOwner { return StructWithOwner(owner: x) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:42 {{of 'x'}} } struct KlassPair { var lhs: Klass var rhs: Klass } func printKlassPair(x : KlassPair) { // We pattern match columns to ensure we get retain on the p and release on // the end ')' print(x) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-5:21 {{of 'x.lhs'}} // expected-remark @-3:5 {{retain of type 'Klass'}} // expected-note @-7:21 {{of 'x.rhs'}} // expected-remark @-5:12 {{release of type}} } func printKlassPairLHS(x : KlassPair) { // We print the remarks at the 'p' and at the ending ')'. print(x.lhs) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-4:24 {{of 'x.lhs'}} // expected-remark @-3:16 {{release of type}} } // We put the retain on the return here since it is part of the result // convention. func returnKlassPairLHS(x: KlassPair) -> Klass { return x.lhs // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-2:25 {{of 'x.lhs'}} } func callingAnInitializerKlassPair(x: Klass, y: Klass) -> KlassPair { return KlassPair(lhs: x, rhs: y) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:36 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-4:46 {{of 'y'}} } func printKlassTuplePair(x : (Klass, Klass)) { // We pattern match columns to ensure we get retain on the p and release on // the end ')' print(x) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-5:26 {{of 'x'}} // expected-remark @-3:5 {{retain of type 'Klass'}} // expected-note @-7:26 {{of 'x'}} // expected-remark @-5:12 {{release of type}} } func printKlassTupleLHS(x : (Klass, Klass)) { // We print the remarks at the 'p' and at the ending ')'. print(x.0) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-4:25 {{of 'x'}} // Release on Array<Any> for print. // expected-remark @-4:14 {{release of type}} } func returnKlassTupleLHS(x: (Klass, Klass)) -> Klass { return x.0 // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-2:26 {{of 'x'}} } func callingAnInitializerKlassTuplePair(x: Klass, y: Klass) -> (Klass, Klass) { return (x, y) // expected-remark {{retain of type 'Klass'}} // expected-note @-2:41 {{of 'x'}} // expected-remark @-2:5 {{retain of type 'Klass'}} // expected-note @-4:51 {{of 'y'}} } public class SubKlass : Klass { @inline(never) final func doSomething() {} } func lookThroughCast(x: SubKlass) -> Klass { return x as Klass // expected-remark {{retain of type 'Klass'}} // expected-note @-2:22 {{of 'x.upcast<$Klass>'}} } func lookThroughRefCast(x: Klass) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'SubKlass'}} } func lookThroughEnum(x: Klass?) -> Klass { return x! // expected-remark {{retain of type 'Klass'}} // expected-note @-2:22 {{of 'x.some'}} } func castAsQuestion(x: Klass) -> SubKlass? { x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2:21 {{of 'x'}} } func castAsQuestionDiamond(x: Klass) -> SubKlass? { guard let y = x as? SubKlass else { return nil } y.doSomething() return y // expected-remark {{retain of type 'Klass'}} // expected-note @-7:28 {{of 'x'}} } func castAsQuestionDiamondGEP(x: KlassPair) -> SubKlass? { guard let y = x.lhs as? SubKlass else { return nil } y.doSomething() // We eliminate the rhs retain/release. return y // expected-remark {{retain of type 'Klass'}} // expected-note @-8:31 {{of 'x.lhs'}} } // We don't handle this test case as well. func castAsQuestionDiamondGEP2(x: KlassPair) { switch (x.lhs as? SubKlass, x.rhs as? SubKlass) { // expected-remark @:39 {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.lhs'}} // expected-remark @-2:19 {{retain of type 'Klass'}} // expected-note @-4 {{of 'x.rhs'}} case let (.some(x1), .some(x2)): print(x1, x2) // expected-remark @:15 {{heap allocated ref of type}} // expected-remark @-1 {{release of type}} case let (.some(x1), nil): print(x1) // expected-remark @:15 {{heap allocated ref of type}} // expected-remark @-1 {{release of type}} case let (nil, .some(x2)): print(x2) // expected-remark @:15 {{heap allocated ref of type}} // expected-remark @-1 {{release of type}} case (nil, nil): break } } func inoutKlassPairArgument(x: inout KlassPair) -> Klass { return x.lhs // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.lhs'}} } func inoutKlassTuplePairArgument(x: inout (Klass, Klass)) -> Klass { return x.0 // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.0'}} } func inoutKlassOptionalArgument(x: inout Klass?) -> Klass { return x! // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } func inoutKlassBangCastArgument(x: inout Klass) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x'}} } func inoutKlassQuestionCastArgument(x: inout Klass) -> SubKlass? { return x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x'}} } func inoutKlassBangCastArgument2(x: inout Klass?) -> SubKlass { return x as! SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } func inoutKlassQuestionCastArgument2(x: inout Klass?) -> SubKlass? { return x as? SubKlass // expected-remark {{retain of type 'Klass'}} // expected-note @-2 {{of 'x.some'}} } // We should have 1x rr remark here on calleeX for storing it into the array to // print. Release is from the array. We don't pattern match it due to the actual // underlying Array type name changing under the hood in between platforms. @inline(__always) func alwaysInlineCallee(_ calleeX: Klass) { print(calleeX) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-3:27 {{of 'calleeX'}} // expected-remark @-3:18 {{release of type}} } // We should have 3x rr remarks here on callerX and none on calleeX. All of the // releases are for the temporary array that we pass into print. // // TODO: Should we print out as notes the whole inlined call stack? func alwaysInlineCaller(_ callerX: Klass) { alwaysInlineCallee(callerX) // expected-remark @:5 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-3:27 {{of 'callerX'}} // expected-remark @-3:31 {{release of type}} print(callerX) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-7:27 {{of 'callerX'}} // expected-remark @-3:18 {{release of type}} alwaysInlineCallee(callerX) // expected-remark @:5 {{heap allocated ref of type}} // expected-remark @-1:5 {{retain of type 'Klass'}} // expected-note @-11:27 {{of 'callerX'}} // expected-remark @-3:31 {{release of type}} } func allocateValue() { // Remark should be on Klass and note should be on k. let k = Klass() // expected-remark @:13 {{heap allocated ref of type 'Klass'}} // expected-note @-1:9 {{of 'k'}} print(k) // expected-remark @:11 {{heap allocated ref of type}} // expected-remark @-1:12 {{release of type}} } @inline(never) func simpleInOutUser<T>(_ x: inout T) { } func simpleInOut() -> Klass { let x = Klass() // expected-remark @:13 {{heap allocated ref of type 'Klass'}} // expected-note @-1:9 {{of 'x'}} simpleInOutUser(&x.next) // expected-remark @:5 {{begin exclusive access to value of type 'Optional<Klass>'}} // expected-note @-3:9 {{of 'x.next'}} // expected-remark @-2:28 {{end exclusive access to value of type 'Optional<Klass>'}} // expected-note @-5:9 {{of 'x.next'}} return x }
31ca17d3e45c3302fe2650d5b2cf2a48
41.017241
252
0.568322
false
false
false
false
safx/TypetalkApp
refs/heads/master
TypetalkApp/DataSources/TopicsDataSource.swift
mit
1
// // TopicsDataSource.swift // TypetalkApp // // Created by Safx Developer on 2014/11/09. // Copyright (c) 2014年 Safx Developers. All rights reserved. // import TypetalkKit import RxSwift import ObservableArray class TopicsDataSource { typealias OArray = ObservableArray<TopicWithUserInfo> typealias Event = Observable<OArray.EventType> var topics = OArray() let disposeBag = DisposeBag() func fetch(observe: Bool = false) -> Event { let s = TypetalkAPI.rx_sendRequest(GetTopics()) s.subscribe( onNext: { res in self.topics.appendContentsOf(res.topics) }, onError: { err in print("\(err)") }, onCompleted:{ () in if (observe) { self.startObserving() } } ) .addDisposableTo(disposeBag) return topics.rx_events() } private func startObserving() { TypetalkAPI.rx_streamimg .subscribeNext { event in switch event { case .CreateTopic(let res): self.insertTopic(res) case .DeleteTopic(let res): self.deleteTopic(res) case .UpdateTopic(let res): self.updateTopic(res) case .JoinTopics(let res): self.insertTopics(res.topics) case .LeaveTopics(let res): self.deleteTopics(res.topics) case .FavoriteTopic(let res): self.updateTopic(res) case .UnfavoriteTopic(let res): self.updateTopic(res) case .PostMessage(let res): self.updateTopic(res.topic!, post: res.post!, advance: +1) case .DeleteMessage(let res): self.updateTopic(res.topic!, post: res.post!, advance: -1) case .SaveBookmark(let res): self.updateTopic(res.unread) default: () } } .addDisposableTo(disposeBag) } private func insertTopic(topic: TopicWithUserInfo) { topics.insert(topic, atIndex: 0) } private func insertTopics(topics: [TopicWithUserInfo]) { topics.forEach { self.insertTopic($0) } } private func find(topicId: TopicID, closure: (TopicWithUserInfo, Int) -> ()) { for i in 0..<topics.count { if topics[i].topic.id == topicId { closure(topics[i], i) return } } } private func updateTopic(topic: Topic) { find(topic.id) { oldValue, i in self.topics[i] = TopicWithUserInfo(topic: topic, favorite: oldValue.favorite, unread: oldValue.unread) } } private func updateTopic(topicWithUserInfo: TopicWithUserInfo) { find(topicWithUserInfo.topic.id) { oldValue, i in self.topics[i] = topicWithUserInfo } } private func updateTopic(unread: Unread) { find(unread.topicId) { oldValue, i in self.topics[i] = TopicWithUserInfo(topic: oldValue.topic, favorite: oldValue.favorite, unread: unread) } } private func updateTopic(topic: Topic, post: Post, advance: Int) { find(topic.id) { oldValue, i in let c = (oldValue.unread?.count ?? 0) + advance let unread = Unread(topicId: topic.id, postId: post.id, count: max(c, 0)) self.topics[i] = TopicWithUserInfo(topic: topic, favorite: oldValue.favorite, unread: unread) } } private func deleteTopic(topic: Topic) { find(topic.id) { oldValue, i in self.topics.removeAtIndex(i) () } } private func deleteTopics(topics: [Topic]) { topics.forEach { self.deleteTopic($0) } } // MARK: Acting to REST client func createTopic(topicName: String) -> Observable<CreateTopic.Response> { let teamId: TeamID? = nil let inviteMembers = [String]() let inviteMessage = "" return TypetalkAPI.rx_sendRequest(CreateTopic(name: topicName, teamId: teamId, inviteMembers: inviteMembers, inviteMessage: inviteMessage)) } func deleteTopic(topicId: TopicID) -> Observable<DeleteTopic.Response> { return TypetalkAPI.rx_sendRequest(DeleteTopic(topicId: topicId)) } func favoriteTopic(topicId: TopicID) -> Observable<FavoriteTopic.Response> { return TypetalkAPI.rx_sendRequest(FavoriteTopic(topicId: topicId)) } func unfavoriteTopic(topicId: TopicID) -> Observable<UnfavoriteTopic.Response> { return TypetalkAPI.rx_sendRequest(UnfavoriteTopic(topicId: topicId)) } }
953c8974d3314a66161ae94e53278f9d
32.674074
147
0.606247
false
false
false
false
wess/reddift
refs/heads/master
reddift/Model/Message.swift
mit
1
// // Message.swift // reddift // // Created by generator.rb via from https://github.com/reddit/reddit/wiki/JSON // Created at 2015-04-15 11:23:32 +0900 // import Foundation /** Message object. */ public struct Message : Thing { /// identifier of Thing like 15bfi0. public var id:String /// name of Thing, that is fullname, like t3_15bfi0. public var name:String /// type of Thing, like t3. public static var kind = "t4" /** the message itself example: Hello! [Hola!](http.... */ public let body:String /** example: false */ public let wasComment:Bool /** example: */ public let firstMessage:String /** either null or the first message's fullname example: */ public let firstMessageName:String /** example: 1427126074 */ public let created:Int /** example: sonson_twit */ public let dest:String /** example: reddit */ public let author:String /** example: 1427122474 */ public let createdUtc:Int /** the message itself with HTML formatting example: &lt;!-- SC_OFF --&gt;&l.... */ public let bodyHtml:String /** null if not a comment. example: */ public let subreddit:String /** null if no parent is attached example: */ public let parentId:String /** if the message is a comment, then the permalink to the comment with ?context=3 appended to the end, otherwise an empty string example: */ public let context:String /** Again, an empty string if there are no replies. example: */ public let replies:String /** unread? not sure example: false */ public let new:Bool /** example: admin */ public let distinguished:String /** subject of message example: Hello, /u/sonson_twit! Welcome to reddit! */ public let subject:String public init(id:String) { self.id = id self.name = "\(Message.kind)_\(self.id)" body = "" wasComment = false firstMessage = "" firstMessageName = "" created = 0 dest = "" author = "" createdUtc = 0 bodyHtml = "" subreddit = "" parentId = "" context = "" replies = "" new = false distinguished = "" subject = "" } /** Parse t4 object. :param: data Dictionary, must be generated parsing "t4". :returns: Message object as Thing. */ public init(data:JSONDictionary) { id = data["id"] as? String ?? "" body = data["body"] as? String ?? "" wasComment = data["was_comment"] as? Bool ?? false firstMessage = data["first_message"] as? String ?? "" name = data["name"] as? String ?? "" firstMessageName = data["first_message_name"] as? String ?? "" created = data["created"] as? Int ?? 0 dest = data["dest"] as? String ?? "" author = data["author"] as? String ?? "" createdUtc = data["created_utc"] as? Int ?? 0 bodyHtml = data["body_html"] as? String ?? "" subreddit = data["subreddit"] as? String ?? "" parentId = data["parent_id"] as? String ?? "" context = data["context"] as? String ?? "" replies = data["replies"] as? String ?? "" new = data["new"] as? Bool ?? false distinguished = data["distinguished"] as? String ?? "" subject = data["subject"] as? String ?? "" } }
dfe6368760836ad95bd9ce49857cc2f4
22.581699
129
0.5449
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/Blueprints-master/Tests/Shared/BlueprintLayoutAnimatorTests.swift
mit
1
import XCTest import Blueprints class BlueprintLayoutAnimatorTests: XCTestCase { class MockCollectionViewUpdateItem: CollectionViewUpdateItem { var beforeIndexPath: IndexPath? var afterIndexPath: IndexPath? var action: CollectionViewUpdateAction = .none init(action: CollectionViewUpdateAction? = nil, beforeIndexPath: IndexPath? = nil, afterIndexPath: IndexPath? = nil) { self.beforeIndexPath = beforeIndexPath self.afterIndexPath = afterIndexPath super.init() switch (beforeIndexPath != nil, afterIndexPath != nil) { case (true, true): self.action = .move case (false, true): self.action = .insert case (true, false): self.action = .delete default: self.action = .none } if let action = action { self.action = action } } override var indexPathBeforeUpdate: IndexPath? { return beforeIndexPath } override var indexPathAfterUpdate: IndexPath? { return afterIndexPath } override var updateAction: UICollectionViewUpdateItem.Action { return action } } let dataSource = MockDataSource(numberOfItems: 15) func testDefaultAnimatorFadeInsertion() { let (animator, collectionView, layout) = Helper.createAnimator(dataSource: dataSource) let indexPath = IndexPath(item: 0, section: 0) let insertion = MockCollectionViewUpdateItem(afterIndexPath: indexPath) animator.prepare(forCollectionViewUpdates: [insertion]) XCTAssertTrue(animator.indexPathsToAnimate.contains(indexPath)) let attributes = LayoutAttributes() attributes.size = .init(width: 100, height: 100) XCTAssertEqual(attributes.alpha, 1.0) animator.animation = .fade _ = animator.initialLayoutAttributesForAppearingItem(at: indexPath, with: attributes) XCTAssertEqual(attributes.alpha, 0.0) } func testDefaultAnimatorFadeDeletion() { let (animator, collectionView, layout) = Helper.createAnimator(dataSource: dataSource) let indexPath = IndexPath(item: 0, section: 0) let deletion = MockCollectionViewUpdateItem(beforeIndexPath: indexPath) animator.prepare(forCollectionViewUpdates: [deletion]) XCTAssertTrue(animator.indexPathsToAnimate.contains(indexPath)) let attributes = LayoutAttributes() attributes.size = .init(width: 100, height: 100) XCTAssertEqual(attributes.alpha, 1.0) animator.animation = .fade _ = animator.finalLayoutAttributesForDisappearingItem(at: indexPath, with: attributes) XCTAssertEqual(attributes.alpha, 0.0) } func testDefaultAnimatorFadeMultipleAttributes() { let (animator, collectionView, layout) = Helper.createAnimator(dataSource: dataSource) let beforeIndexPath = IndexPath(item: 0, section: 0) let afterIndexPath = IndexPath(item: 1, section: 0) let move = MockCollectionViewUpdateItem( beforeIndexPath: beforeIndexPath, afterIndexPath: afterIndexPath ) animator.prepare(forCollectionViewUpdates: [move]) XCTAssertTrue(animator.indexPathsToMove.contains(beforeIndexPath)) let attributes = LayoutAttributes() attributes.size = .init(width: 100, height: 100) attributes.alpha = 0.0 animator.animation = .fade _ = animator.initialLayoutAttributesForAppearingItem(at: beforeIndexPath, with: attributes) XCTAssertEqual(attributes.alpha, 1.0) } }
3ea2ef4a1db9bf22b33b48121767aeb0
35.053763
122
0.731882
false
true
false
false
chrislavender/Thumbafon
refs/heads/master
Thumbafon/Extensions/ModelAdditions/Scale+Create.swift
cc0-1.0
1
// // ScaleCreation.swift // Thumbafon // // Created by Chris Lavender on 9/15/15. // Copyright (c) 2015 Gnarly Dog Music. All rights reserved. // import Foundation import CoreData extension Scale { // MARK: CoreData static func baseNoteNumbers() -> [Int] { // let tempIntervals = [2, 2, 3, 2, 2] let tempIntervals = [2, 2, 3, 2] var noteNumbers = [0] var prevNote = noteNumbers[0] for index in 0...tempIntervals.count - 1 { let interval = tempIntervals[index] let nextNote = prevNote + interval noteNumbers.append(nextNote) prevNote = nextNote } return noteNumbers } static func scale(name:String, context: NSManagedObjectContext) -> Scale? { var match: (Scale)? = nil do { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Scale") fetchRequest.predicate = NSPredicate(format: "name == \(name)") if let fetchResults = try context.fetch(fetchRequest) as? [Scale] { match = fetchResults.first } } catch { print(error) } return match } }
0d0226c9716b60fe9ecc0f280259677b
24.078431
88
0.542611
false
false
false
false
grantjbutler/Artikolo
refs/heads/master
Carthage/Checkouts/Dip/Tests/DipTests/Utils.swift
mit
2
// // Dip // // Copyright (c) 2015 Olivier Halligon <[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 XCTest #if os(Linux) typealias NSObject = AnyObject #endif func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T) { AssertThrows(file, line: line, expression: expression, "") } func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, _ message: String) { AssertThrows(expression: expression, checkError: { _ in true }, message) } func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, checkError: (Error) -> Bool) { AssertThrows(file, line: line, expression: expression, checkError: checkError, "") } func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, checkError: (Error) -> Bool, _ message: String) { do { let _ = try expression() XCTFail(message, file: file, line: line) } catch { XCTAssertTrue(checkError(error), "Thrown unexpected error: \(error)", file: file, line: line) } } func AssertNoThrow<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T) { AssertNoThrow(file, line: line, expression: expression, "") } func AssertNoThrow<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, _ message: String) { do { let _ = try expression() } catch { XCTFail(message, file: file, line: line) } } #if os(Linux) import Glibc typealias TMain = @convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? private func startThread(_ block: @escaping TMain) -> pthread_t { var pid: pthread_t = 0 pthread_create(&pid, nil, block, nil) return pid } func dispatch_async(block: @escaping TMain) -> pthread_t { return startThread(block) } func dispatch_sync(block: @escaping TMain) -> UnsafeMutableRawPointer? { var result: UnsafeMutableRawPointer? = UnsafeMutableRawPointer.allocate(bytes: 1, alignedTo: 0) let pid = startThread(block) pthread_join(pid, &result) return result } extension pthread_spinlock_t { mutating func lock() { pthread_spin_lock(&self) } mutating func unlock() { pthread_spin_unlock(&self) } } #endif
0771d22339bdff1363d4369c544708a2
34.642105
161
0.709392
false
false
false
false
NordRosann/Analysis
refs/heads/master
Tests/Analysis/ListTests.swift
mit
1
import XCTest @testable import Analysis class ListTests: XCTestCase { func testListMap() { let list: List = [2, 3, 5, "andrey"] let changed: List = list.map { switch $0 { case .integerValue(let number): return .stringValue(String(number)) default: return $0 } } let awaited: List = ["2", "3", "5", "andrey"] XCTAssertEqual(changed, awaited) } func testUnifiedMap() { let list: List = [2, 3, 5, "andrey", 12, "peter"] let numbers: [Int] = list.map { (number: Int) -> Int in return number * 2 } XCTAssertEqual(numbers, [4, 6, 10, 24]) let strings: [String] = list.map { (string: String) -> String in return string.uppercased() } XCTAssertEqual(strings, ["ANDREY", "PETER"]) } func testAdvancedUnifiedMap() { let list: List = [2, 3, 5, "andrey", 12, "peter"] let numbers: [Int] = list.map { $0 * 2 } XCTAssertEqual(numbers, [4, 6, 10, 24]) let strings: [String] = list.map { ($0 as String).uppercased() } XCTAssertEqual(strings, ["ANDREY", "PETER"]) } func testEnumMapping() { enum Name: String, DataPointConvertible { case andrey, peter } let list: List = [2, 3, 5, "andrey", 12, "peter", "bjorn"] let names: [String] = list.map { ($0 as Name).rawValue } XCTAssertEqual(names, ["andrey", "peter"]) } func testFilter() { let list: List = [2, 3, 5, false, nil, nil, "human", 4.0] let changed: [Int] = list.filter { $0 > 2 } XCTAssertEqual(changed, [3, 5]) } func testKeying() { let year = Variable(name: "year", type: Int.self) let code = Variable(name: "code", type: String.self) let value = Variable(name: "value", type: Int.self) let schema = RowSchema(variables: year, code, value) let list: List = [2015, "UA", 4] let keyed = list.keyed(with: schema) let expected: [String: DataPoint] = ["year": 2015, "code": "UA", "value": 4] XCTAssertEqual(keyed, expected) } func testCoupling() { let year = Variable(name: "year", type: Int.self) let code = Variable(name: "code", type: String.self) let value = Variable(name: "value", type: Int.self) let schema = RowSchema(variables: year, code, value) let list: List = [2015, "UA", 4] let keyed = list.coupled(with: schema) let expected: [Variable: DataPoint] = [year: 2015, code: "UA", value: 4] XCTAssertEqual(keyed, expected) } func testUnifiedSorting() { let list: List = [2, 5, 0, 4, "key", 8, -1, "fake", false, nil, nil, 15] let unifiedSorted: [Int] = list.unified().sorted { $0 < $1 } let unifiedStrignsSorted: [String] = list.unified().sorted { $0.characters.count < $1.characters.count } let expected = [-1, 0, 2, 4, 5, 8, 15] let expectedStrings = ["key", "fake"] XCTAssertEqual(unifiedSorted, expected) XCTAssertEqual(unifiedStrignsSorted, expectedStrings) } }
00fb337c4321d998d32bc19d755709b5
36.302326
112
0.548488
false
true
false
false
voloshynslavik/MVx-Patterns-In-Swift
refs/heads/master
MVX Patterns In Swift/PatternsTableViewController.swift
mit
1
// // PatternsTableViewController.swift // MVX Patterns In Swift // // Created by Yaroslav Voloshyn on 18/07/2017. // import UIKit final class PatternsTableViewController: UITableViewController { private lazy var mvvvmcCoordinator: MVVMCCoordinator? = { guard let nc = self.navigationController else { return nil } return MVVMCCoordinator(navigationController: nc) }() override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let mvvmViewController = segue.destination as? MVVMViewController { let viewModel = ViewModel() viewModel.delegate = mvvmViewController mvvmViewController.viewModel = viewModel } else if let mvpViewController = segue.destination as? MVPViewController { let presenter = ConcretePresenter(view: mvpViewController) mvpViewController.presenter = presenter } } @IBAction func onSelectMVVMC(_ sender: UITapGestureRecognizer) { mvvvmcCoordinator?.start() } }
ff88bdf1a49277eba9880153d74fe5e6
28.638889
83
0.671978
false
false
false
false
wyp767363905/GiftSay
refs/heads/master
GiftSay/GiftSay/classes/hot/hotDetail/view/HotDetailView.swift
mit
1
// // HotDetailView.swift // GiftSay // // Created by qianfeng on 16/9/3. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class HotDetailView: UIView { private var tbView: UITableView? var itemModel: HotItemModel?{ didSet { tbView?.reloadData() } } var likeModel: HotLikeModel?{ didSet { tbView?.reloadData() } } init() { super.init(frame: CGRectZero) tbView = UITableView(frame: CGRectZero, style: .Plain) tbView?.delegate = self tbView?.dataSource = self addSubview(tbView!) tbView?.separatorStyle = .None tbView?.snp_makeConstraints(closure: { [weak self] (make) in make.edges.equalTo(self!) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension HotDetailView : UITableViewDelegate,UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { var sectionNum = 0 if itemModel?.data != nil { sectionNum += 1 } if likeModel?.data?.recommend_posts?.count > 0 { sectionNum += 1 } if likeModel?.data?.recommend_items?.count > 0 { sectionNum += 1 } return sectionNum } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rowNum = 0 if itemModel?.data != nil && likeModel?.data?.recommend_posts?.count > 0 && likeModel?.data?.recommend_items?.count > 0 { rowNum = 1 } return rowNum } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height: CGFloat = 0 if indexPath.section == 0 { let model = itemModel?.data if model != nil { height = ItemCell.heightForModel(model!) } }else if indexPath.section == 1 { let num = likeModel?.data?.recommend_posts?.count if num > 0 { height = 160 } }else if indexPath.section == 2 { let model = likeModel?.data if model != nil { height = HMyLayout.ToObtainHeight(model!) } } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() if indexPath.section == 0 { cell = ItemCell.createItemCellFor(tableView, atIndexPath: indexPath, withDataModel: (itemModel?.data)!) }else if indexPath.section == 1 { cell = ItemRecommendCell.createItemCellFor(tableView, atIndexPath: indexPath, withDataModel: (likeModel?.data)!) }else if indexPath.section == 2 { cell = ItemLikeCell.createItemCellFor(tableView, atIndexPath: indexPath, withDataModel: (likeModel?.data)!) } return cell } }
4d091d2ffde5b42cc2929903ff52659f
22
129
0.513389
false
false
false
false
AirChen/ACSwiftDemoes
refs/heads/master
Target9-backgroundLogin/ViewController.swift
mit
1
// // ViewController.swift // Target9-backgroundLogin // // Created by Air_chen on 2016/11/4. // Copyright © 2016年 Air_chen. All rights reserved. // import UIKit import AVKit import MediaPlayer class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let sourcePath = NSURL.fileURL(withPath: Bundle.main.path(forResource: "moments", ofType: "mp4")!) let mediaPlayer = AVPlayerViewController() mediaPlayer.player = AVPlayer(url: sourcePath) mediaPlayer.view.frame = self.view.bounds self.addChildViewController(mediaPlayer) self.view.insertSubview(mediaPlayer.view, at: 0) mediaPlayer.player?.volume = 1 mediaPlayer.showsPlaybackControls = false mediaPlayer.player?.play() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.playEndAction), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: mediaPlayer.player?.currentItem) } func playEndAction() { for vc in self.childViewControllers { if vc.isKind(of: AVPlayerViewController.classForCoder()){ let player = vc as! AVPlayerViewController player.player?.seek(to: kCMTimeZero) player.player?.play() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } }
298fc1018e2d219de7a6d56a17f4b080
30.910714
200
0.655288
false
false
false
false
Sage-Bionetworks/MoleMapper
refs/heads/master
MoleMapper/Charts/Classes/Renderers/CandleStickChartRenderer.swift
bsd-3-clause
1
// // CandleStickChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit @objc public protocol CandleStickChartRendererDelegate { func candleStickChartRendererCandleData(renderer: CandleStickChartRenderer) -> CandleChartData! func candleStickChartRenderer(renderer: CandleStickChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func candleStickChartDefaultRendererValueFormatter(renderer: CandleStickChartRenderer) -> NSNumberFormatter! func candleStickChartRendererChartYMax(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererChartYMin(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererChartXMax(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererChartXMin(renderer: CandleStickChartRenderer) -> Double func candleStickChartRendererMaxVisibleValueCount(renderer: CandleStickChartRenderer) -> Int } public class CandleStickChartRenderer: LineScatterCandleRadarChartRenderer { public weak var delegate: CandleStickChartRendererDelegate? public init(delegate: CandleStickChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(context context: CGContext?) { let candleData = delegate!.candleStickChartRendererCandleData(self) for set in candleData.dataSets as! [CandleChartDataSet] { if (set.isVisible) { drawDataSet(context: context, dataSet: set) } } } private var _shadowPoints = [CGPoint](count: 2, repeatedValue: CGPoint()) private var _bodyRect = CGRect() private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawDataSet(context context: CGContext?, dataSet: CandleChartDataSet) { let trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency) let phaseX = _animator.phaseX let phaseY = _animator.phaseY let bodySpace = dataSet.bodySpace var entries = dataSet.yVals as! [CandleChartDataEntry] let entryFrom = dataSet.entryForXIndex(_minX) let entryTo = dataSet.entryForXIndex(_maxX) let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.shadowWidth) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { // get the entry let e = entries[j] if (e.xIndex < _minX || e.xIndex > _maxX) { continue } // calculate the shadow _shadowPoints[0].x = CGFloat(e.xIndex) _shadowPoints[0].y = CGFloat(e.high) * phaseY _shadowPoints[1].x = CGFloat(e.xIndex) _shadowPoints[1].y = CGFloat(e.low) * phaseY trans.pointValuesToPixel(&_shadowPoints) // draw the shadow var shadowColor: UIColor! = nil if (dataSet.shadowColorSameAsCandle) { if (e.open > e.close) { shadowColor = dataSet.decreasingColor ?? dataSet.colorAt(j) } else if (e.open < e.close) { shadowColor = dataSet.increasingColor ?? dataSet.colorAt(j) } } if (shadowColor === nil) { shadowColor = dataSet.shadowColor ?? dataSet.colorAt(j); } CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeLineSegments(context, _shadowPoints, 2) // calculate the body _bodyRect.origin.x = CGFloat(e.xIndex) - 0.5 + bodySpace _bodyRect.origin.y = CGFloat(e.close) * phaseY _bodyRect.size.width = (CGFloat(e.xIndex) + 0.5 - bodySpace) - _bodyRect.origin.x _bodyRect.size.height = (CGFloat(e.open) * phaseY) - _bodyRect.origin.y trans.rectValueToPixel(&_bodyRect) // draw body differently for increasing and decreasing entry if (e.open > e.close) { let color = dataSet.decreasingColor ?? dataSet.colorAt(j) if (dataSet.isDecreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else if (e.open < e.close) { let color = dataSet.increasingColor ?? dataSet.colorAt(j) if (dataSet.isIncreasingFilled) { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, _bodyRect) } else { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextStrokeRect(context, _bodyRect) } } else { CGContextSetStrokeColorWithColor(context, shadowColor.CGColor) CGContextStrokeRect(context, _bodyRect) } } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext?) { let candleData = delegate!.candleStickChartRendererCandleData(self) if (candleData === nil) { return } let defaultValueFormatter = delegate!.candleStickChartDefaultRendererValueFormatter(self) // if values are drawn if (candleData.yValCount < Int(ceil(CGFloat(delegate!.candleStickChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX))) { var dataSets = candleData.dataSets for (var i = 0; i < dataSets.count; i++) { let dataSet = dataSets[i] if (!dataSet.isDrawValuesEnabled) { continue } let valueFont = dataSet.valueFont let valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } let trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entries = dataSet.yVals as! [CandleChartDataEntry] let entryFrom = dataSet.entryForXIndex(_minX) let entryTo = dataSet.entryForXIndex(_maxX) let minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) let maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) var positions = trans.generateTransformedValuesCandle(entries, phaseY: _animator.phaseY) let lineHeight = valueFont.lineHeight let yOffset: CGFloat = lineHeight + 5.0 for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * _animator.phaseX + CGFloat(minx))); j < count; j++) { let x = positions[j].x let y = positions[j].y if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsLeft(x) || !viewPortHandler.isInBoundsY(y)) { continue } let val = entries[j].high ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: x, y: y - yOffset), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(context context: CGContext?) { } private var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint()) public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight]) { let candleData = delegate!.candleStickChartRendererCandleData(self) if (candleData === nil) { return } for (var i = 0; i < indices.count; i++) { let xIndex = indices[i].xIndex; // get the x-position let set = candleData.getDataSetByIndex(indices[i].dataSetIndex) as! CandleChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } let e = set.entryForXIndex(xIndex) as! CandleChartDataEntry! if (e === nil || e.xIndex != xIndex) { continue } let trans = delegate!.candleStickChartRenderer(self, transformerForAxis: set.axisDependency) CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let low = CGFloat(e.low) * _animator.phaseY let high = CGFloat(e.high) * _animator.phaseY let y = (low + high) / 2.0 _highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(delegate!.candleStickChartRendererChartYMax(self))) _highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(delegate!.candleStickChartRendererChartYMin(self))) _highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMin(self)), y: y) _highlightPtsBuffer[3] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMax(self)), y: y) trans.pointValuesToPixel(&_highlightPtsBuffer) // draw the lines drawHighlightLines(context: context, points: _highlightPtsBuffer, horizontal: set.isHorizontalHighlightIndicatorEnabled, vertical: set.isVerticalHighlightIndicatorEnabled) } } }
06d2e7dd5aec91cbf30df9177f81c4cb
38.168317
246
0.562653
false
false
false
false
VladislavJevremovic/Exchange-Rates-NBS
refs/heads/master
Exchange Rates NBS/Logic/Constants.swift
mit
1
// // Constants.swift // Exchange Rates NBS // // Created by Vladislav Jevremovic on 12/6/14. // Copyright (c) 2014 Vladislav Jevremovic. All rights reserved. // import Foundation import UIKit struct Constants { struct CustomColor { static let Manatee = UIColor(red: 142.0 / 255.0, green: 142.0 / 255.0, blue: 147.0 / 255.0, alpha: 1.0) static let RadicalRed = UIColor(red: 255.0 / 255.0, green: 45.0 / 255.0, blue: 85.0 / 255.0, alpha: 1.0) static let RedOrange = UIColor(red: 255.0 / 255.0, green: 59.0 / 255.0, blue: 48.0 / 255.0, alpha: 1.0) static let Pizazz = UIColor(red: 255.0 / 255.0, green: 149.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0) static let Supernova = UIColor(red: 255.0 / 255.0, green: 204.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0) static let Emerald = UIColor(red: 76.0 / 255.0, green: 217.0 / 255.0, blue: 100.0 / 255.0, alpha: 1.0) static let Malibu = UIColor(red: 90.0 / 255.0, green: 200.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0) static let CuriousBlue = UIColor(red: 52.0 / 255.0, green: 170.0 / 255.0, blue: 220.0 / 255.0, alpha: 1.0) static let AzureRadiance = UIColor(red: 0.0 / 255.0, green: 122.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0) static let Indigo = UIColor(red: 88.0 / 255.0, green: 86.0 / 255.0, blue: 214.0 / 255.0, alpha: 1.0) static let TableBackgroundColor = UIColor(red: 176.0 / 255.0, green: 214.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0) static let TableCellColor = UIColor(red: 120.0 / 255.0, green: 185.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0) static let TableFooterColor = UIColor(red: 0.43, green: 0.45, blue: 0.45, alpha: 1.0) } }
fd51582cc960af64fbba13989ecbe2c0
54.193548
124
0.610754
false
false
false
false
matsuda/MuddlerKit
refs/heads/master
MuddlerKit/Reusable.swift
mit
1
// // Reusable.swift // MuddlerKit // // Created by Kosuke Matsuda on 2016/11/28. // Copyright © 2016年 Kosuke Matsuda. All rights reserved. // import UIKit // MARK: - Reusable public protocol Reusable { static var reusableIdentifier: String { get } } // MARK: - ReusableView public protocol ReusableView: Reusable {} extension ReusableView { public static var reusableIdentifier: String { return String(describing: self) } } // MARK: - UITableView extension UITableView { public func registerNib<T: UITableViewCell>(_ type: T.Type) where T: ReusableView { let identifier = T.reusableIdentifier let bundle = Bundle(for: T.self) let nib = UINib(nibName: identifier, bundle: bundle) register(nib, forCellReuseIdentifier: identifier) } public func registerClass<T: UITableViewCell>(_ type: T.Type) where T: ReusableView { let identifier = T.reusableIdentifier register(T.self, forCellReuseIdentifier: identifier) } public func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T where T: ReusableView { let identifier = T.reusableIdentifier guard let cell = dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else { fatalError("Could not dequeue cell: \(T.self) with identifier: \(identifier).") } return cell } public func registerNib<T: UITableViewHeaderFooterView>(_ type: T.Type) where T: ReusableView { let identifier = T.reusableIdentifier let bundle = Bundle(for: T.self) let nib = UINib(nibName: identifier, bundle: bundle) register(nib, forHeaderFooterViewReuseIdentifier: identifier) } public func registerClass<T: UITableViewHeaderFooterView>(_ type: T.Type) where T: ReusableView { let identifier = T.reusableIdentifier register(T.self, forHeaderFooterViewReuseIdentifier: identifier) } public func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(_ type: T.Type) -> T where T: ReusableView { let identifier = T.reusableIdentifier guard let view = dequeueReusableHeaderFooterView(withIdentifier: identifier) as? T else { fatalError("Could not dequeue HeaderFooterView: \(T.self) with identifier: \(identifier).") } return view } } // MARK: - UICollectionView extension UICollectionView { public func registerNib<T: UICollectionViewCell>(_ type: T.Type) where T: ReusableView { let identifier = T.reusableIdentifier let bundle = Bundle(for: T.self) let nib = UINib(nibName: identifier, bundle: bundle) register(nib, forCellWithReuseIdentifier: identifier) } public func registerClass<T: UICollectionViewCell>(_ type: T.Type) where T: ReusableView { let identifier = T.reusableIdentifier register(T.self, forCellWithReuseIdentifier: identifier) } public func dequeueReusableCell<T: UICollectionViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T where T: ReusableView { let identifier = T.reusableIdentifier guard let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? T else { fatalError("Could not dequeue cell: \(T.self) with identifier: \(identifier).") } return cell } } // MARK: - UINib extension UINib { public class func instantiate<T: ReusableView>(_ type: T.Type) -> T { let identifier = T.reusableIdentifier let bundle: Bundle? if let klass = T.self as? AnyClass { bundle = Bundle(for: klass) } else { bundle = nil } let nib = UINib(nibName: identifier, bundle: bundle) guard let view = nib.instantiate(withOwner: nil, options: nil).first as? T else { fatalError("Could not load view: \(T.self) with identifier: \(identifier).") } return view } }
99a9727f33fcde42781d27dfbbd2d8c0
33.293103
131
0.670689
false
false
false
false
Jpadilla1/react-native-ios-charts
refs/heads/master
RNiOSCharts/chartDataHelpers.swift
mit
1
// // chartDataHelpers.swift // ChartsExplorer // // Created by Jose Padilla on 3/18/16. // Copyright © 2016 Facebook. All rights reserved. // import Foundation import Charts import SwiftyJSON var maximumDecimalPlaces: Int = 0; var minimumDecimalPlaces: Int = 0; func getLineData(_ labels: [String], json: JSON!) -> LineChartData { if !json["dataSets"].exists() { return LineChartData(); } let dataSets = json["dataSets"].arrayObject; var sets: [LineChartDataSet] = []; for set in dataSets! { let tmp = JSON(set); if tmp["values"].exists() { let values = tmp["values"].arrayValue.map({$0.doubleValue}); let label = tmp["label"].exists() ? tmp["label"].stringValue : ""; var dataEntries: [ChartDataEntry] = []; for i in 0..<values.count { let dataEntry = ChartDataEntry(value: values[i], xIndex: i); dataEntries.append(dataEntry); } let dataSet = LineChartDataSet(yVals: dataEntries, label: label); if tmp["colors"].exists() { let arrColors = tmp["colors"].arrayValue.map({$0.intValue}); dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)}); } if tmp["drawCircles"].exists() { dataSet.drawCirclesEnabled = tmp["drawCircles"].boolValue; } if tmp["lineWidth"].exists() { dataSet.lineWidth = CGFloat(tmp["lineWidth"].floatValue); } if tmp["circleColors"].exists() { let arrColors = tmp["circleColors"].arrayValue.map({$0.intValue}); dataSet.circleColors = arrColors.map({return RCTConvert.uiColor($0)}); } if tmp["circleHoleColor"].exists() { dataSet.circleHoleColor = RCTConvert.uiColor(tmp["circleHoleColor"].intValue); } if tmp["circleRadius"].exists() { dataSet.circleRadius = CGFloat(tmp["circleRadius"].floatValue); } if tmp["cubicIntensity"].exists() { dataSet.cubicIntensity = CGFloat(tmp["cubicIntensity"].floatValue); } if tmp["drawCircleHole"].exists() { dataSet.drawCircleHoleEnabled = tmp["drawCircleHole"].boolValue; } if tmp["drawCubic"].exists() { dataSet.drawCubicEnabled = tmp["drawCubic"].boolValue; } if tmp["drawFilled"].exists() { dataSet.drawFilledEnabled = tmp["drawFilled"].boolValue; } if tmp["drawHorizontalHighlightIndicator"].exists() { dataSet.drawHorizontalHighlightIndicatorEnabled = tmp["drawHorizontalHighlightIndicator"].boolValue; } if tmp["drawVerticalHighlightIndicator"].exists() { dataSet.drawVerticalHighlightIndicatorEnabled = tmp["drawVerticalHighlightIndicator"].boolValue; } if tmp["drawValues"].exists() { dataSet.drawValuesEnabled = tmp["drawValues"].boolValue; } if tmp["fillAlpha"].exists() { dataSet.fillAlpha = CGFloat(tmp["fillAlpha"].floatValue); } if tmp["fillColor"].exists() { dataSet.fillColor = RCTConvert.uiColor(tmp["fillColor"].intValue); } if tmp["highlightColor"].exists() { dataSet.highlightColor = RCTConvert.uiColor(tmp["highlightColor"].intValue); } if tmp["highlightEnabled"].exists() { dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue; } if tmp["highlightLineDashLengths"].exists() { dataSet.highlightLineDashLengths = [CGFloat(tmp["highlightLineDashLengths"].floatValue)]; } if tmp["highlightLineDashPhase"].exists() { dataSet.highlightLineDashPhase = CGFloat(tmp["highlightLineDashPhase"].floatValue); } if tmp["highlightLineWidth"].exists() { dataSet.highlightLineWidth = CGFloat(tmp["highlightLineWidth"].floatValue); } if tmp["lineDashLengths"].exists() { dataSet.lineDashLengths = [CGFloat(tmp["lineDashLengths"].floatValue)]; } if tmp["lineDashPhase"].exists() { dataSet.lineDashPhase = CGFloat(tmp["lineDashPhase"].floatValue); } if tmp["lineWidth"].exists() { dataSet.lineWidth = CGFloat(tmp["lineWidth"].floatValue); } if tmp["axisDependency"].exists() { let value = tmp["axisDependency"].stringValue; if value == "left" { dataSet.axisDependency = .left; } else if value == "right" { dataSet.axisDependency = .right; } } if tmp["valueTextFontName"].exists() { dataSet.valueFont = UIFont( name: tmp["valueTextFontName"].stringValue, size: dataSet.valueFont.pointSize )!; } if tmp["valueTextFontSize"].exists() { dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue)); } if tmp["valueTextColor"].exists() { dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue); } if json["valueFormatter"].exists() { if json["valueFormatter"]["minimumDecimalPlaces"].exists() { minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue; } if json["valueFormatter"]["maximumDecimalPlaces"].exists() { maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue; } if json["valueFormatter"]["type"].exists() { switch(json["valueFormatter"]["type"]) { case "regular": dataSet.valueFormatter = NumberFormatter(); break; case "abbreviated": dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces); break; default: dataSet.valueFormatter = NumberFormatter(); } } if json["valueFormatter"]["numberStyle"].exists() { switch(json["valueFormatter"]["numberStyle"]) { case "CurrencyAccountingStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyAccounting; } break; case "CurrencyISOCodeStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyISOCode; } break; case "CurrencyPluralStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyPlural; } break; case "CurrencyStyle": dataSet.valueFormatter?.numberStyle = .currency; break; case "DecimalStyle": dataSet.valueFormatter?.numberStyle = .decimal; break; case "NoStyle": dataSet.valueFormatter?.numberStyle = .none; break; case "OrdinalStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .ordinal; } break; case "PercentStyle": dataSet.valueFormatter?.numberStyle = .percent; break; case "ScientificStyle": dataSet.valueFormatter?.numberStyle = .scientific; break; case "SpellOutStyle": dataSet.valueFormatter?.numberStyle = .spellOut; break; default: dataSet.valueFormatter?.numberStyle = .none; } } dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces; dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces; } sets.append(dataSet); } } return LineChartData(xVals: labels, dataSets: sets); } func getBarData(_ labels: [String], json: JSON!) -> BarChartData { if !json["dataSets"].exists() { return BarChartData(); } let dataSets = json["dataSets"].arrayObject; var sets: [BarChartDataSet] = []; for set in dataSets! { let tmp = JSON(set); if tmp["values"].exists() { let values = tmp["values"].arrayValue.map({$0.doubleValue}); let label = tmp["label"].exists() ? tmp["label"].stringValue : ""; var dataEntries: [BarChartDataEntry] = []; for i in 0..<values.count { let dataEntry = BarChartDataEntry(value: values[i], xIndex: i); dataEntries.append(dataEntry); } let dataSet = BarChartDataSet(yVals: dataEntries, label: label); if tmp["barShadowColor"].exists() { dataSet.barShadowColor = RCTConvert.uiColor(tmp["barShadowColor"].intValue); } if tmp["barSpace"].exists() { dataSet.barSpace = CGFloat(tmp["barSpace"].floatValue); } if tmp["highlightAlpha"].exists() { dataSet.highlightAlpha = CGFloat(tmp["highlightAlpha"].floatValue); } if tmp["highlightColor"].exists() { dataSet.highlightColor = RCTConvert.uiColor(tmp["highlightColor"].intValue); } if tmp["highlightLineDashLengths"].exists() { dataSet.highlightLineDashLengths = [CGFloat(tmp["highlightLineDashLengths"].floatValue)]; } if tmp["highlightLineDashPhase"].exists() { dataSet.highlightLineDashPhase = CGFloat(tmp["highlightLineDashPhase"].floatValue); } if tmp["highlightLineWidth"].exists() { dataSet.highlightLineWidth = CGFloat(tmp["highlightLineWidth"].floatValue); } if tmp["stackLabels"].exists() { dataSet.stackLabels = tmp["stackLabels"].arrayValue.map({$0.stringValue}); } if tmp["colors"].exists() { let arrColors = tmp["colors"].arrayValue.map({$0.intValue}); dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)}); } if tmp["drawValues"].exists() { dataSet.drawValuesEnabled = tmp["drawValues"].boolValue; } if tmp["highlightEnabled"].exists() { dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue; } if tmp["valueTextFontName"].exists() { dataSet.valueFont = UIFont( name: tmp["valueTextFontName"].stringValue, size: dataSet.valueFont.pointSize )!; } if tmp["valueTextFontSize"].exists() { dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue)) } if tmp["valueTextColor"].exists() { dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue); } if tmp["axisDependency"].exists() { let value = tmp["axisDependency"].stringValue; if value == "left" { dataSet.axisDependency = .left; } else if value == "right" { dataSet.axisDependency = .right; } } if json["valueFormatter"].exists() { if json["valueFormatter"]["minimumDecimalPlaces"].exists() { minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue; } if json["valueFormatter"]["maximumDecimalPlaces"].exists() { maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue; } if json["valueFormatter"]["type"].exists() { switch(json["valueFormatter"]["type"]) { case "regular": dataSet.valueFormatter = NumberFormatter(); break; case "abbreviated": dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces); break; default: dataSet.valueFormatter = NumberFormatter(); } } if json["valueFormatter"]["numberStyle"].exists() { switch(json["valueFormatter"]["numberStyle"]) { case "CurrencyAccountingStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyAccounting; } break; case "CurrencyISOCodeStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyISOCode; } break; case "CurrencyPluralStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyPlural; } break; case "CurrencyStyle": dataSet.valueFormatter?.numberStyle = .currency; break; case "DecimalStyle": dataSet.valueFormatter?.numberStyle = .decimal; break; case "NoStyle": dataSet.valueFormatter?.numberStyle = .none; break; case "OrdinalStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .ordinal; } break; case "PercentStyle": dataSet.valueFormatter?.numberStyle = .percent; break; case "ScientificStyle": dataSet.valueFormatter?.numberStyle = .scientific; break; case "SpellOutStyle": dataSet.valueFormatter?.numberStyle = .spellOut; break; default: dataSet.valueFormatter?.numberStyle = .none; } } dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces; dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces; } sets.append(dataSet); } } return BarChartData(xVals: labels, dataSets: sets); } func getBubbleData(_ labels: [String], json: JSON!) -> BubbleChartData { if !json["dataSets"].exists() { return BubbleChartData(); } let dataSets = json["dataSets"].arrayObject; var sets: [BubbleChartDataSet] = []; for set in dataSets! { let tmp = JSON(set); if tmp["values"].exists() { let values = tmp["values"].arrayObject!; let label = tmp["label"].exists() ? tmp["label"].stringValue : ""; var dataEntries: [BubbleChartDataEntry] = []; for i in 0..<values.count { let object = JSON(values[i]); let dataEntry = BubbleChartDataEntry( xIndex: i, value: object["value"].doubleValue, size: CGFloat(object["size"].floatValue) ); dataEntries.append(dataEntry); } let dataSet = BubbleChartDataSet(yVals: dataEntries, label: label); if tmp["colors"].exists() { let arrColors = tmp["colors"].arrayValue.map({$0.intValue}); dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)}); } if tmp["drawValues"].exists() { dataSet.drawValuesEnabled = tmp["drawValues"].boolValue; } if tmp["highlightEnabled"].exists() { dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue; } if tmp["highlightCircleWidth"].exists() { dataSet.highlightCircleWidth = CGFloat(tmp["highlightCircleWidth"].floatValue); } if tmp["valueTextFontName"].exists() { dataSet.valueFont = UIFont( name: tmp["valueTextFontName"].stringValue, size: dataSet.valueFont.pointSize )!; } if tmp["axisDependency"].exists() { let value = tmp["axisDependency"].stringValue; if value == "left" { dataSet.axisDependency = .left; } else if value == "right" { dataSet.axisDependency = .right; } } if tmp["valueTextFontSize"].exists() { dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue)) } if tmp["valueTextColor"].exists() { dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue); } if json["valueFormatter"].exists() { if json["valueFormatter"]["minimumDecimalPlaces"].exists() { minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue; } if json["valueFormatter"]["maximumDecimalPlaces"].exists() { maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue; } if json["valueFormatter"]["type"].exists() { switch(json["valueFormatter"]["type"]) { case "regular": dataSet.valueFormatter = NumberFormatter(); break; case "abbreviated": dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces); break; default: dataSet.valueFormatter = NumberFormatter(); } } if json["valueFormatter"]["numberStyle"].exists() { switch(json["valueFormatter"]["numberStyle"]) { case "CurrencyAccountingStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyAccounting; } break; case "CurrencyISOCodeStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyISOCode; } break; case "CurrencyPluralStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyPlural; } break; case "CurrencyStyle": dataSet.valueFormatter?.numberStyle = .currency; break; case "DecimalStyle": dataSet.valueFormatter?.numberStyle = .decimal; break; case "NoStyle": dataSet.valueFormatter?.numberStyle = .none; break; case "OrdinalStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .ordinal; } break; case "PercentStyle": dataSet.valueFormatter?.numberStyle = .percent; break; case "ScientificStyle": dataSet.valueFormatter?.numberStyle = .scientific; break; case "SpellOutStyle": dataSet.valueFormatter?.numberStyle = .spellOut; break; default: dataSet.valueFormatter?.numberStyle = .none; } } dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces; dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces; } sets.append(dataSet); } } return BubbleChartData(xVals: labels, dataSets: sets); } func getScatterData(_ labels: [String], json: JSON!) -> ScatterChartData { if !json["dataSets"].exists() { return ScatterChartData(); } let dataSets = json["dataSets"].arrayObject; var sets: [ScatterChartDataSet] = []; for set in dataSets! { let tmp = JSON(set); if tmp["values"].exists() { let values = tmp["values"].arrayValue.map({$0.doubleValue}); let label = tmp["label"].exists() ? tmp["label"].stringValue : ""; var dataEntries: [ChartDataEntry] = []; for i in 0..<values.count { let dataEntry = ChartDataEntry(value: values[i], xIndex: i); dataEntries.append(dataEntry); } let dataSet = ScatterChartDataSet(yVals: dataEntries, label: label); if tmp["colors"].exists() { let arrColors = tmp["colors"].arrayValue.map({$0.intValue}); dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)}); } if tmp["drawValues"].exists() { dataSet.drawValuesEnabled = tmp["drawValues"].boolValue; } if tmp["highlightEnabled"].exists() { dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue; } if tmp["scatterShapeSize"].exists() { dataSet.scatterShapeSize = CGFloat(tmp["scatterShapeSize"].floatValue); } if tmp["scatterShapeHoleRadius"].exists() { dataSet.scatterShapeHoleRadius = CGFloat(tmp["scatterShapeHoleRadius"].floatValue); } if tmp["scatterShapeHoleColor"].exists() { dataSet.scatterShapeHoleColor = RCTConvert.uiColor(tmp["scatterShapeHoleColor"].intValue); } if tmp["scatterShape"].exists() { switch(tmp["scatterShape"]) { case "Square": dataSet.scatterShape = .square; break; case "Circle": dataSet.scatterShape = .circle; break; case "Triangle": dataSet.scatterShape = .triangle; break; case "Cross": dataSet.scatterShape = .cross; break; case "X": dataSet.scatterShape = .x; break; default: dataSet.scatterShape = .square; break; } } if tmp["valueTextFontName"].exists() { dataSet.valueFont = UIFont( name: tmp["valueTextFontName"].stringValue, size: dataSet.valueFont.pointSize )!; } if tmp["valueTextFontSize"].exists() { dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue)) } if tmp["valueTextColor"].exists() { dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue); } if tmp["axisDependency"].exists() { let value = tmp["axisDependency"].stringValue; if value == "left" { dataSet.axisDependency = .left; } else if value == "right" { dataSet.axisDependency = .right; } } if json["valueFormatter"].exists() { if json["valueFormatter"]["minimumDecimalPlaces"].exists() { minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue; } if json["valueFormatter"]["maximumDecimalPlaces"].exists() { maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue; } if json["valueFormatter"]["type"].exists() { switch(json["valueFormatter"]["type"]) { case "regular": dataSet.valueFormatter = NumberFormatter(); break; case "abbreviated": dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces); break; default: dataSet.valueFormatter = NumberFormatter(); } } if json["valueFormatter"]["numberStyle"].exists() { switch(json["valueFormatter"]["numberStyle"]) { case "CurrencyAccountingStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyAccounting; } break; case "CurrencyISOCodeStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyISOCode; } break; case "CurrencyPluralStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyPlural; } break; case "CurrencyStyle": dataSet.valueFormatter?.numberStyle = .currency; break; case "DecimalStyle": dataSet.valueFormatter?.numberStyle = .decimal; break; case "NoStyle": dataSet.valueFormatter?.numberStyle = .none; break; case "OrdinalStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .ordinal; } break; case "PercentStyle": dataSet.valueFormatter?.numberStyle = .percent; break; case "ScientificStyle": dataSet.valueFormatter?.numberStyle = .scientific; break; case "SpellOutStyle": dataSet.valueFormatter?.numberStyle = .spellOut; break; default: dataSet.valueFormatter?.numberStyle = .none; } } dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces; dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces; } sets.append(dataSet); } } return ScatterChartData(xVals: labels, dataSets: sets); } func getCandleStickData(_ labels: [String], json: JSON!) -> CandleChartData { if !json["dataSets"].exists() { return CandleChartData(); } let dataSets = json["dataSets"].arrayObject; var sets: [CandleChartDataSet] = []; for set in dataSets! { let tmp = JSON(set); if tmp["values"].exists() { let values = tmp["values"].arrayObject!; let label = tmp["label"].exists() ? tmp["label"].stringValue : ""; var dataEntries: [CandleChartDataEntry] = []; for i in 0..<values.count { let object = JSON(values[i]); let dataEntry = CandleChartDataEntry( xIndex: i, shadowH: object["shadowH"].doubleValue, shadowL: object["shadowL"].doubleValue, open: object["open"].doubleValue, close: object["close"].doubleValue ); dataEntries.append(dataEntry); } let dataSet = CandleChartDataSet(yVals: dataEntries, label: label); if tmp["colors"].exists() { let arrColors = tmp["colors"].arrayValue.map({$0.intValue}); dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)}); } if tmp["drawValues"].exists() { dataSet.drawValuesEnabled = tmp["drawValues"].boolValue; } if tmp["highlightEnabled"].exists() { dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue; } if tmp["valueTextFontName"].exists() { dataSet.valueFont = UIFont( name: tmp["valueTextFontName"].stringValue, size: dataSet.valueFont.pointSize )!; } if tmp["valueTextFontSize"].exists() { dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue)) } if tmp["valueTextColor"].exists() { dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue); } if tmp["axisDependency"].exists() { let value = tmp["axisDependency"].stringValue; if value == "left" { dataSet.axisDependency = .left; } else if value == "right" { dataSet.axisDependency = .right; } } if tmp["barSpace"].exists() { dataSet.barSpace = CGFloat(tmp["barSpace"].floatValue); } if tmp["showCandleBar"].exists() { dataSet.showCandleBar = tmp["showCandleBar"].boolValue; } if tmp["shadowWidth"].exists() { dataSet.shadowWidth = CGFloat(tmp["shadowWidth"].floatValue); } if tmp["shadowColor"].exists() { dataSet.shadowColor = RCTConvert.uiColor(tmp["shadowColor"].intValue); } if tmp["shadowColorSameAsCandle"].exists() { dataSet.shadowColorSameAsCandle = tmp["shadowColorSameAsCandle"].boolValue; } if tmp["neutralColor"].exists() { dataSet.neutralColor = RCTConvert.uiColor(tmp["neutralColor"].intValue); } if tmp["increasingColor"].exists() { dataSet.increasingColor = RCTConvert.uiColor(tmp["increasingColor"].intValue); } if tmp["decreasingColor"].exists() { dataSet.decreasingColor = RCTConvert.uiColor(tmp["decreasingColor"].intValue); } if tmp["increasingFilled"].exists() { dataSet.increasingFilled = tmp["increasingFilled"].boolValue; } if tmp["decreasingFilled"].exists() { dataSet.decreasingFilled = tmp["decreasingFilled"].boolValue; } if json["valueFormatter"].exists() { if json["valueFormatter"]["minimumDecimalPlaces"].exists() { minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue; } if json["valueFormatter"]["maximumDecimalPlaces"].exists() { maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue; } if json["valueFormatter"]["type"].exists() { switch(json["valueFormatter"]["type"]) { case "regular": dataSet.valueFormatter = NumberFormatter(); break; case "abbreviated": dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces); break; default: dataSet.valueFormatter = NumberFormatter(); } } if json["valueFormatter"]["numberStyle"].exists() { switch(json["valueFormatter"]["numberStyle"]) { case "CurrencyAccountingStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyAccounting; } break; case "CurrencyISOCodeStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyISOCode; } break; case "CurrencyPluralStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .currencyPlural; } break; case "CurrencyStyle": dataSet.valueFormatter?.numberStyle = .currency; break; case "DecimalStyle": dataSet.valueFormatter?.numberStyle = .decimal; break; case "NoStyle": dataSet.valueFormatter?.numberStyle = .none; break; case "OrdinalStyle": if #available(iOS 9.0, *) { dataSet.valueFormatter?.numberStyle = .ordinal; } break; case "PercentStyle": dataSet.valueFormatter?.numberStyle = .percent; break; case "ScientificStyle": dataSet.valueFormatter?.numberStyle = .scientific; break; case "SpellOutStyle": dataSet.valueFormatter?.numberStyle = .spellOut; break; default: dataSet.valueFormatter?.numberStyle = .none; } } dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces; dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces; } sets.append(dataSet); } } return CandleChartData(xVals: labels, dataSets: sets); }
8820c74dafd19231d804cbfa8eedb6c0
39.349277
155
0.491702
false
false
false
false
abelsanchezali/ViewBuilder
refs/heads/master
ViewBuilderDemo/ViewBuilderDemo/ViewControllers/OnboardingPhoneScreenView.swift
mit
1
// // OnboardingPhoneScreenView.swift // ViewBuilderDemo // // Created by Abel Sanchez on 10/9/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit import ViewBuilder public class OnboardingPhoneScreenView: Panel { weak var messageContainer: StackPanel! weak var container: UIScrollView! init() { super.init(frame: CGRect.zero) self.loadFromDocument(Constants.bundle.path(forResource: "OnboardingPhoneScreenView", ofType: "xml")!) container = self.documentReferences!["container"] as! UIScrollView messageContainer = self.documentReferences!["messageContainer"] as! StackPanel } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension OnboardingPhoneScreenView { public func gotoIntialState() { messageContainer.subviews.forEach() { $0.isHidden = true $0.alpha = 0 } } public func playAnimation() { var index = 0 func showNextMessage() { showMesageIndex(index) { (completed) in if completed { index += 1 AnimationHelper.delayedBlock(1.0, block: { showNextMessage() }) } } } showNextMessage() } public func showMesageIndex(_ index: Int, comletion: ((Bool) -> Void)?) { if index >= messageContainer.subviews.count { comletion?(false) return } let subview = messageContainer.subviews[index] let delay = Double(subview.tag) / 1000.0 UIView.animate(withDuration: 0.75, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: [.curveEaseOut, .beginFromCurrentState], animations: { subview.isHidden = false self.layoutIfNeeded() self.container.scrollToBottom(false) }, completion: nil) subview.layer.removeAllAnimations() subview.transform = CGAffineTransform(translationX: 0, y: 50) UIView.animate(withDuration: 0.75, delay: 0.25, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.1, options: [.curveEaseOut, .beginFromCurrentState], animations: { subview.alpha = 1 subview.transform = CGAffineTransform.identity }, completion: {(completed) in if !completed { comletion?(false) } else { AnimationHelper.delayedBlock(delay, block: { comletion?(true) }) } }) } }
871104746688618bbe6ddef9245c5c87
34.712644
110
0.509173
false
false
false
false
trill-lang/LLVMSwift
refs/heads/master
Sources/LLVM/FunctionType.swift
mit
1
#if SWIFT_PACKAGE import cllvm #endif /// `FunctionType` represents a function's type signature. It consists of a /// return type and a list of formal parameter types. The return type of a /// function type is a `void` type or first class type — except for `LabelType` /// and `MetadataType`. public struct FunctionType: IRType { /// The list of argument types. public let parameterTypes: [IRType] /// The return type of this function type. public let returnType: IRType /// Returns whether this function is variadic. public let isVariadic: Bool /// Creates a function type with the given argument types and return type. /// /// - parameter argTypes: A list of the argument types of the function type. /// - parameter returnType: The return type of the function type. /// - parameter isVarArg: Indicates whether this function type is variadic. /// Defaults to `false`. /// - note: The context of this type is taken from it's `returnType` @available(*, deprecated, message: "Use the more concise initializer instead", renamed: "FunctionType.init(_:_:variadic:)") public init(argTypes: [IRType], returnType: IRType, isVarArg: Bool = false) { self.parameterTypes = argTypes self.returnType = returnType self.isVariadic = isVarArg } /// Creates a function type with the given argument types and return type. /// /// - parameter parameterTypes: A list of the argument types of the function /// type. /// - parameter returnType: The return type of the function type. /// - parameter variadic: Indicates whether this function type is variadic. /// Defaults to `false`. /// - note: The context of this type is taken from it's `returnType` public init( _ parameterTypes: [IRType], _ returnType: IRType, variadic: Bool = false ) { self.parameterTypes = parameterTypes self.returnType = returnType self.isVariadic = variadic } /// Retrieves the underlying LLVM type object. public func asLLVM() -> LLVMTypeRef { var argIRTypes = parameterTypes.map { $0.asLLVM() as Optional } return argIRTypes.withUnsafeMutableBufferPointer { buf in return LLVMFunctionType(returnType.asLLVM(), buf.baseAddress, UInt32(buf.count), isVariadic.llvm)! } } } // MARK: Legacy Accessors extension FunctionType { /// The list of argument types. @available(*, deprecated, message: "Use FunctionType.parameterTypes instead") public var argTypes: [IRType] { return self.parameterTypes } /// Returns whether this function is variadic. @available(*, deprecated, message: "Use FunctionType.isVariadic instead") public var isVarArg: Bool { return self.isVariadic } } extension FunctionType: Equatable { public static func == (lhs: FunctionType, rhs: FunctionType) -> Bool { return lhs.asLLVM() == rhs.asLLVM() } }
6258f90d686647f2f75e5519ed987377
35.5375
125
0.685255
false
false
false
false
adrfer/swift
refs/heads/master
test/SILGen/struct_resilience.swift
apache-2.0
1
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s import resilient_struct // Resilient structs are always address-only // CHECK-LABEL: sil hidden @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_ : $@convention(thin) (@out Size, @in Size, @owned @callee_owned (@out Size, @in Size) -> ()) -> () // CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@callee_owned (@out Size, @in Size) -> ()): func functionWithResilientTypes(s: Size, f: Size -> Size) -> Size { // Stored properties of resilient structs from outside our resilience // domain are accessed through accessors // CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size var s2 = s // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1wSi : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizes1wSi : $@convention(method) (Int, @inout Size) -> () // CHECK: apply [[FN]]([[RESULT]], [[OTHER_SIZE_BOX]]) s2.w = s.w // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1hSi : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) _ = s.h // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: apply %2(%0, [[SIZE_BOX]]) // CHECK: return return f(s) } // Fixed-layout structs may be trivial or loadable // CHECK-LABEL: sil hidden @_TF17struct_resilience28functionWithFixedLayoutTypesFTV16resilient_struct5Point1fFS1_S1__S1_ : $@convention(thin) (Point, @owned @callee_owned (Point) -> Point) -> Point // CHECK: bb0(%0 : $Point, %1 : $@callee_owned (Point) -> Point): func functionWithFixedLayoutTypes(p: Point, f: Point -> Point) -> Point { // Stored properties of fixed layout structs are accessed directly var p2 = p // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x // CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x // CHECK: assign [[RESULT]] to [[DEST]] : $*Int p2.x = p.x // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y _ = p.y // CHECK: [[NEW_POINT:%.*]] = apply %1(%0) // CHECK: return [[NEW_POINT]] return f(p) } // Fixed-layout struct with resilient stored properties is still address-only // CHECK-LABEL: sil hidden @_TF17struct_resilience39functionWithFixedLayoutOfResilientTypesFTV16resilient_struct9Rectangle1fFS1_S1__S1_ : $@convention(thin) (@out Rectangle, @in Rectangle, @owned @callee_owned (@out Rectangle, @in Rectangle) -> ()) -> () // CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@callee_owned (@out Rectangle, @in Rectangle) -> ()): func functionWithFixedLayoutOfResilientTypes(r: Rectangle, f: Rectangle -> Rectangle) -> Rectangle { return f(r) } // Make sure we generate getters and setters for stored properties of // resilient structs public struct MySize { // Static computed property // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg10expirationSi : $@convention(thin) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes10expirationSi : $@convention(thin) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem10expirationSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize.Type, @thick MySize.Type.Type) -> ()>) public static var expiration: Int { get { return copyright + 70 } set { copyright = newValue - 70 } } // Instance computed property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1dSi : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1dSi : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1dSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize, @thick MySize.Type) -> ()>) public var d: Int { get { return 0 } set { } } // Instance stored property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1wSi : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1wSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize, @thick MySize.Type) -> ()>) public var w: Int // Read-only instance stored property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1hSi : $@convention(method) (@in_guaranteed MySize) -> Int public let h: Int // Static stored property // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg9copyrightSi : $@convention(thin) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes9copyrightSi : $@convention(thin) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem9copyrightSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize.Type, @thick MySize.Type.Type) -> ()>) public static var copyright: Int = 0 } // CHECK-LABEL: sil @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_ : $@convention(thin) (@out MySize, @in MySize, @owned @callee_owned (@out MySize, @in MySize) -> ()) -> () public func functionWithMyResilientTypes(s: MySize, f: MySize -> MySize) -> MySize { // Stored properties of resilient structs from inside our resilience // domain are accessed directly // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize var s2 = s // CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w // CHECK: [[SRC:%.*]] = load [[SRC_ADDR]] : $*Int // CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[SIZE_BOX]] : $*MySize, #MySize.w // CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int s2.w = s.w // CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h // CHECK: [[RESULT:%.*]] = load [[RESULT_ADDR]] : $*Int _ = s.h // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize // CHECK: apply %2(%0, [[SIZE_BOX]]) // CHECK: return return f(s) }
f2ef24ede1bcd796ec9c89fd3f609430
52.338346
319
0.661545
false
false
false
false
HusamAamer/Versioner
refs/heads/master
Example/Versioner/ViewController.swift
mit
1
// // ViewController.swift // Versioner // // Created by [email protected] on 08/05/2017. // Copyright (c) 2017 [email protected]. All rights reserved. // import UIKit import Versioner class ViewController: UIViewController { @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var subtitle: UILabel! @IBOutlet weak var version_info_title: UILabel! @IBOutlet weak var details: UILabel! var ui_updated : Bool = false override func viewDidLoad() { super.viewDidLoad() // Get current version let current_version = Versioner.currentVersion // For example beauty let launchesNumber = current_version.launchNumber let formatter = NumberFormatter() formatter.numberStyle = .ordinal let styled_launchesNumber = formatter.string(from: NSNumber.init(value: launchesNumber))! let welcoming_string = "This is your \(styled_launchesNumber) visit 😃" //////////////////////////////////////////////////////////// // :: BEFORE NEXT CODE :: // You should add Versioner.initiate() to // didFinishLaunchingWithOptions in AppDelegate.swift //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // :: Usage #1 => at current version state do something cool //////////////////////////////////////////////////////////// Versioner.currentVersion.isFreshInstall { /* 🔸 App first launch ever - App was not installed before this version or - App was installed but this library was not included in previous versions */ updateUI(set: "Welcome 🙏🏻", subtitle: welcoming_string, details: current_version) }.isUpdate { (prevVersion) in /* 🔸 Update opened - (App was installed before) and (this version has a number newer than previous one and launched for the first time) */ updateUI(set: "Updated successfully ✅", subtitle: welcoming_string, version_info: "Previous version info", details: prevVersion) }.isDowngrade { (prevVersion) in // 🔸 Old version launched updateUI(set: "🙁", subtitle: "Please get me back to the newer version", version_info: "Previous version info", details: prevVersion) }.isLaunch(number: 3) { /* 🔸 Launch number X of this version (not all versions together), X = any number you want */ updateUI(set: "Third Welcome is special ❤️", subtitle: welcoming_string, details: current_version) }.isBuildUpdate { (prevVersion) in /* 🔸 New build launched with same previous version number */ updateUI(set: "Welcome tester", subtitle: "I'm the newest build", version_info: "Previous version info", details: prevVersion) }.isBuildDowngrade(handler: { (prevVersion) in /* 🔸 Old build launched with same previous version number */ updateUI(set: "YOU, Don't play with my build !!", subtitle: welcoming_string, version_info: "Previous version info", details: prevVersion) }) // If nothing of the above changed the UI if !ui_updated { updateUI(set: "Welcome back!", subtitle: welcoming_string, details: current_version) } //////////////////////////////////////////////////////////// // :: Usage #2 => Execute another specific code in future relase //////////////////////////////////////////////////////////// if Versioner.currentVersion > AppVersion("3.0") { // Do new code // ex: call new backend } else { // Do old code // ex: call old backend } //////////////////////////////////////////////////////////// // :: Usage #3 => Version number comparision operators //////////////////////////////////////////////////////////// print(Versioner.currentVersion > AppVersion("3.0.0.1")) // true or false print(AppVersion("3.0") < AppVersion("3.1")) // true print(AppVersion("3.0") == AppVersion("3.0")) // true } /// Updates Example app Labels in Main.storyboard /// private func updateUI (set title:String, subtitle:String, version_info:String = "Current version info ", details:AppVersion) { self.titleLbl.text = title self.subtitle.text = subtitle self.version_info_title.text = version_info self.details.text = "Version : \(details.number) build \(details.build)\n" self.details.text?.append("Launched \(details.launchNumber) time(s)\n") self.details.text?.append("First launch : \(details.firstLaunchDate)\n") self.details.text?.append("First installed os version : \(details.os_version)\n") ui_updated = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
ff77a2f9001aafbdebf2216bd74759cb
35.103659
132
0.479649
false
false
false
false
groschovskiy/lerigos_music
refs/heads/master
Mobile/iOS/Beta/Pods/PhoneNumberKit/PhoneNumberKit/Formatter.swift
apache-2.0
1
// // Formatter.swift // PhoneNumberKit // // Created by Roy Marmelstein on 03/11/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation class Formatter { // MARK: Formatting functions let regex = RegularExpressions.sharedInstance /** Formats phone numbers for display - Parameter phoneNumber: Phone number object. - Returns: Modified national number ready for display. */ func formatPhoneNumber(phoneNumber: PhoneNumber, formatType: PhoneNumberFormat) -> String { let metadata = Metadata.sharedInstance var formattedNationalNumber = phoneNumber.adjustedNationalNumber() if let regionMetadata = metadata.metadataPerCode[phoneNumber.countryCode] { formattedNationalNumber = formatNationalNumber(formattedNationalNumber, regionMetadata: regionMetadata, formatType: formatType) if let formattedExtension = formatExtension(phoneNumber.numberExtension, regionMetadata: regionMetadata) { formattedNationalNumber = formattedNationalNumber + formattedExtension } } return formattedNationalNumber } /** Formats extension for display - Parameter numberExtension: Number extension string. - Returns: Modified number extension with either a preferred extension prefix or the default one. */ func formatExtension(numberExtension: String?, regionMetadata: MetadataTerritory) -> String? { if let extns = numberExtension { if let preferredExtnPrefix = regionMetadata.preferredExtnPrefix { return "\(preferredExtnPrefix)\(extns)" } else { return "\(defaultExtnPrefix)\(extns)" } } return nil } /** Formats national number for display - Parameter nationalNumber: National number string. - Returns: Modified nationalNumber for display. */ func formatNationalNumber(nationalNumber: String, regionMetadata: MetadataTerritory, formatType: PhoneNumberFormat) -> String { let formats = regionMetadata.numberFormats var selectedFormat: MetadataPhoneNumberFormat? for format in formats { if let leadingDigitPattern = format.leadingDigitsPatterns?.last { if (regex.stringPositionByRegex(leadingDigitPattern, string: String(nationalNumber)) == 0) { if (regex.matchesEntirely(format.pattern, string: String(nationalNumber))) { selectedFormat = format break; } } } else { if (regex.matchesEntirely(format.pattern, string: String(nationalNumber))) { selectedFormat = format break; } } } if let formatPattern = selectedFormat { guard let numberFormatRule = (formatType == PhoneNumberFormat.International && formatPattern.intlFormat != nil) ? formatPattern.intlFormat : formatPattern.format, let pattern = formatPattern.pattern else { return nationalNumber } var formattedNationalNumber = String() var prefixFormattingRule = String() if let nationalPrefixFormattingRule = formatPattern.nationalPrefixFormattingRule, let nationalPrefix = regionMetadata.nationalPrefix { prefixFormattingRule = regex.replaceStringByRegex(npPattern, string: nationalPrefixFormattingRule, template: nationalPrefix) prefixFormattingRule = regex.replaceStringByRegex(fgPattern, string: prefixFormattingRule, template:"\\$1") } if formatType == PhoneNumberFormat.National && regex.hasValue(prefixFormattingRule){ let replacePattern = regex.replaceFirstStringByRegex(firstGroupPattern, string: numberFormatRule, templateString: prefixFormattingRule) formattedNationalNumber = self.regex.replaceStringByRegex(pattern, string: nationalNumber, template: replacePattern) } else { formattedNationalNumber = self.regex.replaceStringByRegex(pattern, string: nationalNumber, template: numberFormatRule) } return formattedNationalNumber } else { return nationalNumber } } } public extension PhoneNumber { // MARK: Formatting extenstions to PhoneNumber /** Formats a phone number to E164 format (e.g. +33689123456) - Returns: A string representing the phone number in E164 format. */ public func toE164() -> String { let formattedNumber = "+" + String(countryCode) + adjustedNationalNumber() return formattedNumber } /** Formats a phone number to International format (e.g. +33 6 89 12 34 56) - Returns: A string representing the phone number in International format. */ public func toInternational() -> String { let formatter = Formatter() let formattedNationalNumber = formatter.formatPhoneNumber(self, formatType: .International) let formattedNumber = "+" + String(countryCode) + " " + formattedNationalNumber return formattedNumber } /** Formats a phone number to local national format (e.g. 06 89 12 34 56) - Returns: A string representing the phone number in the local national format. */ public func toNational() -> String { let formatter = Formatter() let formattedNationalNumber = formatter.formatPhoneNumber(self, formatType: .National) let formattedNumber = formattedNationalNumber return formattedNumber } /** Adjust national number for display by adding leading zero if needed. Used for basic formatting functions. - Returns: A string representing the adjusted national number. */ private func adjustedNationalNumber() -> String { if self.leadingZero == true { return "0" + String(nationalNumber) } else { return String(nationalNumber) } } }
90ea556adf5711ca194f9646b28ea3cf
40.402685
217
0.653266
false
false
false
false
sseitov/v-Chess-Swift
refs/heads/master
v-Chess/Extensions/UIFontExtension.swift
gpl-3.0
1
// // UIFontExtension.swift // // Created by Сергей Сейтов on 22.05.17. // Copyright © 2017 V-Channel. All rights reserved. // import UIKit func printFontNames() { for family:String in UIFont.familyNames { print("\(family)") for names:String in UIFont.fontNames(forFamilyName: family) { print("== \(names)") } } } extension UIFont { class func mainFont(_ size:CGFloat = 17) -> UIFont { return UIFont(name: "HelveticaNeue", size: size)! } class func thinFont(_ size:CGFloat = 17) -> UIFont { return UIFont(name: "HelveticaNeue-Thin", size: size)! } class func condensedFont(_ size:CGFloat = 17) -> UIFont { return UIFont(name: "HelveticaNeue-CondensedBold", size: size)! } class func commentsFont() -> UIFont { return mainFont(15) } }
0172d151ae177a23044a24b414264804
23.111111
71
0.599078
false
false
false
false
ddstone/4ddcmj
refs/heads/master
AmateurTimeRecoder/TimingViewController.swift
gpl-3.0
1
// // TimingViewController.swift // TimeRecorder // // Created by apple on 5/19/16. // Copyright © 2016 ddstone. All rights reserved. // import UIKit class TimingViewController: UIViewController, TurnOffTiming { var isTiming = false { didSet { updateUI() } } var from: NSDate! let imageView = UIImageView() @IBOutlet weak var timingView: UIView! @IBAction func longTap(sender: UILongPressGestureRecognizer) { if sender.state == .Began { if isTiming { let title = "经过" + Utility.toCost(NSDate().timeIntervalSinceDate(from)) + ",CD好了么?" let alert = UIAlertController(title: title, message: "", preferredStyle: .ActionSheet) alert.addAction(UIAlertAction(title: "确定", style: .Default) { (action) in self.performSegueWithIdentifier(Constant.TimeToProjectSegueIdentifier, sender: nil) }) alert.addAction(UIAlertAction(title: "清零", style: .Destructive) { (action) in self.isTiming = false }) alert.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } else { from = NSDate() isTiming = !isTiming } } } // MARK: - Respond to shake gesture override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { if motion == .MotionShake { performSegueWithIdentifier(Constant.TimeToProjectSegueIdentifier, sender: event) } } // MARK: - Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() timingView.addSubview(imageView) timingView.backgroundColor = UIColor.blackColor() // restore from db if let isTiming = AppDelegate.database.read(Constant.DBIsTimingFile, key: Constant.DBIsTimingKey) as? Bool { self.isTiming = isTiming self.from = AppDelegate.database.read(Constant.DBFromFile, key: Constant.DBFromKey) as! NSDate } updateUI() // Listen to backup when into background NSNotificationCenter.defaultCenter().addObserverForName( NotificationName.DidEnterBackground, object: UIApplication.sharedApplication().delegate, queue: NSOperationQueue.mainQueue()) { (notification) in if self.isTiming { self.storeData() } else { self.delData() } } } // MARK: - Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Constant.TimeToProjectSegueIdentifier { switch sender { case nil: let ptvc = segue.destinationViewController.containerController as! ProjectsTableViewController ptvc.timeIntervals = TimeInterval(from: from, to: NSDate()) ptvc.timingVC = self case let event where event is UIEvent: break default: break } } } // MARK: - Delegate func turnOffTiming() { isTiming = !isTiming } // MARK: - Internal functions private func updateUI() { let name = isTiming ? Constant.WadeSuspend : Constant().WadeOntheGo imageView.image = UIImage(named: name)! centerForImage() } private func centerForImage() { let width = imageView.superview!.superview!.bounds.width let height = width / imageView.image!.aspecRatio let y = (imageView.superview!.superview!.bounds.height - height)/2 imageView.frame = CGRect(x: 0, y: y, width: width, height: height) } private func storeData() { AppDelegate.database.insert(Constant.DBIsTimingFile, obj: self.isTiming, key: Constant.DBIsTimingKey) AppDelegate.database.insert(Constant.DBFromFile, obj: self.from, key: Constant.DBFromKey) } private func delData() { [Constant.DBIsTimingFile, Constant.DBFromFile].forEach { AppDelegate.database.delFile($0) } } // MARK: - Constains struct Constant { static let TimeToProjectSegueIdentifier = "TimeToProjectSegueIdentifier" static let WadeSuspend = "Wade_suspend" var WadeOntheGo = "Wade_onthego" + String(arc4random()%UInt32(6)) static let DBIsTimingFile = "DB_isTiming_file" static let DBIsTimingKey = "DB isTiming Key" static let DBFromFile = "DB_from_file" static let DBFromKey = "DB from Key" } } extension UIViewController { var containerController: UIViewController { if let navi = self as? UINavigationController { return navi.visibleViewController! } else { return self } } } extension UIImage { var aspecRatio: CGFloat { return size.height != 0 ? size.width/size.height : 0 } }
653ff597a3862420587db1c3a04d192c
32.966887
116
0.601677
false
false
false
false
sssbohdan/Design-Patterns-In-Swift
refs/heads/master
source/behavioral/iterator.swift
gpl-3.0
2
/*: 🍫 Iterator ----------- The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure. ### Example: */ struct NovellasCollection<T> { let novellas: [T] } extension NovellasCollection: SequenceType { typealias Generator = AnyGenerator<T> func generate() -> AnyGenerator<T> { var i = 0 return AnyGenerator { i += 1; return i >= self.novellas.count ? nil : self.novellas[i] } } } /*: ### Usage */ let greatNovellas = NovellasCollection(novellas:["Mist"]) for novella in greatNovellas { print("I've read: \(novella)") }
a67f812a8d7a68097878606f14f6ddd4
23.25
177
0.671576
false
false
false
false
ddaguro/clintonconcord
refs/heads/master
OIMApp/TasksCell.swift
mit
1
// // TasksCell.swift // OIMApp // // Created by Linh NGUYEN on 5/28/15. // Copyright (c) 2015 Persistent Systems. All rights reserved. // import Foundation import UIKit class TasksCell : UITableViewCell { @IBOutlet var typeImageView : UIImageView! @IBOutlet var dateImageView : UIImageView! @IBOutlet var nameLabel : UILabel! @IBOutlet var postLabel : UILabel? @IBOutlet var dateLabel : UILabel! @IBOutlet var approveBtn: UIButton! @IBOutlet var declineBtn: UIButton! @IBOutlet var moreBtn: UIButton! @IBOutlet var beneficiaryLabel: UILabel! @IBOutlet var beneiciaryUserLabel: UILabel! @IBOutlet var justificationLabel: UILabel! override func awakeFromNib() { nameLabel.font = UIFont(name: MegaTheme.fontName, size: 14) nameLabel.textColor = MegaTheme.darkColor postLabel?.font = UIFont(name: MegaTheme.fontName, size: 12) postLabel?.textColor = MegaTheme.lightColor dateImageView.image = UIImage(named: "clock") dateImageView.alpha = 0.20 dateLabel.font = UIFont(name: MegaTheme.fontName, size: 10) dateLabel.textColor = MegaTheme.lightColor beneficiaryLabel.font = UIFont(name: MegaTheme.fontName, size: 12) beneficiaryLabel.textColor = MegaTheme.darkColor beneiciaryUserLabel.font = UIFont(name: MegaTheme.fontName, size: 12) beneiciaryUserLabel.textColor = MegaTheme.lightColor justificationLabel.font = UIFont(name: MegaTheme.fontName, size: 12) justificationLabel.textColor = MegaTheme.lightColor } override func layoutSubviews() { super.layoutSubviews() if postLabel != nil { let label = postLabel! label.preferredMaxLayoutWidth = CGRectGetWidth(label.frame) } } }
31a0c5f4fe4e8c831e4883f90577491e
30.163934
77
0.656842
false
false
false
false
getsocial-im/getsocial-ios-sdk
refs/heads/master
example/GetSocialDemo/Views/Communities/Groups/MyGroups/MyGroupsView.swift
apache-2.0
1
// // TopicsView.swift // GetSocialDemo // // Copyright © 2020 GetSocial BV. All rights reserved. // import UIKit import GetSocialUI class MyGroupsView { var viewController: MyGroupsViewController var showGroupMembersOfGroup: ((String, Role) -> Void)? var showPolls: ((String) -> Void)? var showAnnouncementsPolls: ((String) -> Void)? init() { self.viewController = MyGroupsViewController() self.viewController.delegate = self } } extension MyGroupsView: MyGroupTableViewControllerDelegate { func onEditGroup(_ group: Group) { let vc = CreateGroupViewController(group) self.viewController.navigationController?.pushViewController(vc, animated: true) } func onShowFeed(_ ofGroupId: String) { let query = ActivitiesQuery.inGroup(ofGroupId) let activitiesView = GetSocialUIActivityFeedView.init(for: query) activitiesView.setAvatarClickHandler { user in let mainVC = self.viewController.parent?.parent as? MainViewController mainVC?.didClick(on: user) } activitiesView.setActionHandler { action in let mainVC = self.viewController.parent?.parent as? MainViewController mainVC?.handle(action) } activitiesView.setMentionClickHandler { mention in let mainVC = self.viewController.parent?.parent as? MainViewController if mention == GetSocialUI_Shortcut_App { mainVC?.showAlert(withText: "Application mention clicked") } else { let userId = UserId.create(mention!) Communities.user(userId, success: { user in mainVC?.didClick(on: user) }, failure: { error in print("Failed to get user, error: \(error)") }) } } activitiesView.setTagClickHandler { tag in let mainVC = self.viewController.parent?.parent as? MainViewController mainVC?.showAlert(withText: "Clicked on tag [\(tag!)]") } if let mainVC = self.viewController.parent?.parent as? MainViewController { if mainVC.showCustomErrorMessages { activitiesView.setCustomErrorMessageProvider { (errorCode, errorMessage) -> String? in if errorCode == ErrorCode.ActivityRejected { return "Be careful what you say :)" } return errorMessage } } } activitiesView.setHandlerForViewOpen({ // do nothing here }, close: { self.viewController.viewDidAppear(true) }) GetSocialUI.show(activitiesView) } func onShowPolls(_ inGroup: String) { self.showPolls?(inGroup) } func onShowAnnouncementsPolls(_ inGroup: String) { self.showAnnouncementsPolls?(inGroup) } func onPostActivity(_ groupId: String) { let target = PostActivityTarget.group(groupId) let vc = UIStoryboard.viewController(forName: "PostActivity", in: .activityFeed) as! PostActivityViewController vc.postTarget = target self.viewController.navigationController?.pushViewController(vc, animated: true) } func onShowGroupMembers(_ ofGroupId: String, role: Role) { self.showGroupMembersOfGroup?(ofGroupId, role) } func onCreatePoll(_ groupId: String) { let target = PostActivityTarget.group(groupId) let vc = CreatePollView(target) self.viewController.navigationController?.pushViewController(vc, animated: true) } }
f202318afdce915f4703a0bf833535b5
33.941176
119
0.643939
false
false
false
false
wftllc/hahastream
refs/heads/master
Haha Stream/Features/Content List/ContentListViewController.swift
mit
1
import UIKit import Kingfisher import Moya private let reuseIdentifier = "ContentListViewCell" protocol ContentListView: AnyObject { var interactor: ContentListInteractor? { get } func updateView(contentList: ContentList, lastSelectedItem: ContentItem?) func showLoading(animated: Bool) func hideLoading(animated: Bool, completion: (()->Void)?) func playURL(_ url: URL) func showStreamChoiceAlert(game: Game, streams: [Stream]) var apiErrorClosure: (Any) -> Void { get } var networkFailureClosure: (MoyaError) -> Void { get } } class ContentListViewController: HahaViewController, ContentListView, DateListDelegate, NFLDateListDelegate, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var inlinePlayerContainerView: UIView! @IBOutlet weak var inlineVideoPlayerView: InlineVideoPlayerView! @IBOutlet weak var noResultsLabel: UILabel! var interactor: ContentListInteractor? { get { return self.interactorStorage } } var interactorStorage: ContentListInteractor? var contentList: ContentList? var preferredFocusIndexPath: IndexPath? override var preferredFocusEnvironments: [UIFocusEnvironment] { get { let def = super.preferredFocusEnvironments; return self.collectionView.preferredFocusEnvironments + def }} //TODO - show something when no current results override func viewDidLoad() { super.viewDidLoad() self.inlinePlayerContainerView.layer.masksToBounds = true self.inlinePlayerContainerView.layer.cornerRadius = 8.0 self.inlinePlayerContainerView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner] self.inlinePlayerContainerView.layer.shadowRadius = 12; self.inlinePlayerContainerView.layer.shadowOpacity = 0.25; self.inlinePlayerContainerView.layer.shadowOffset = CGSize(width:0, height:5); // Uncomment the following line to preserve selection between presentations self.restoresFocusAfterTransition = false self.collectionView.remembersLastFocusedIndexPath = true self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 90) // self.clearsSelectionOnViewWillAppear = false self.dateLabel.text = "" interactor?.viewDidLoad(); } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) interactor?.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated); interactor?.viewWillDisappear(animated); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func playStream(stream: Stream, game: Game) { interactor?.viewDidSelect(stream: stream, game: game) } override func showLoading(animated: Bool) { self.activityIndicator.startAnimating() UIView.animate(withDuration: animated ? 0.25 : 0) { self.noResultsLabel.alpha = 0 self.collectionView.alpha = 0 } } override func hideLoading(animated: Bool, completion: (() -> Void)?) { self.activityIndicator.stopAnimating() let duration = animated ? 0.25 : 0 UIView.animate(withDuration: duration, animations: { self.noResultsLabel.alpha = 1 self.collectionView.alpha = 1 }) { (_) in completion?() } } //MARK: - interactor callbacks func updateView(contentList: ContentList, lastSelectedItem: ContentItem?) { self.contentList = contentList self.dateLabel.text = contentList.title if let item = lastSelectedItem { self.preferredFocusIndexPath = contentList.indexPath(forItem: item) } self.collectionView.reloadData() self.noResultsLabel.isHidden = self.contentList?.sections.count != 0 } //MARK: - DateListDelegate func dateListDidSelect(date: Date) { interactor?.viewDidSelect(date: date) } //MARK: - NFLDateListDelegate func nflDateDidSelect(_ week: NFLWeek) { interactor?.viewDidSelect(nflWeek: week) } // MARK: UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return self.contentList?.sections.count ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.contentList?.items(inSection: section).count ?? 0 } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ContentListHeader.ReuseIdentifier, for: indexPath) as! ContentListHeader header.lineView.isHidden = indexPath.section == 0 return header } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ContentListViewCell; guard let item = self.contentList?.item(atIndexPath: indexPath) else { return cell } cell.update(withContentItem: item, inSection: contentList!.sections[indexPath.section]) return cell } func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? { return self.preferredFocusIndexPath } // MARK: UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let item = self.contentList?.item(atIndexPath: indexPath) else { return } interactor?.viewDidSelect(item: item) } } class ContentListHeader: UICollectionReusableView { public static let ReuseIdentifier = "ContentListHeader" @IBOutlet weak var lineView: UIView! override func awakeFromNib() { super.awakeFromNib() self.lineView.layer.shadowRadius = 12; self.lineView.layer.shadowOpacity = 0.25; self.lineView.layer.shadowOffset = CGSize(width:0, height:5); } }
bac503ad7c8f5ac5a9bcdad54d8e2736
32.162921
170
0.772827
false
false
false
false
0xced/Carthage
refs/heads/master
Source/carthage/Checkout.swift
mit
1
// // Checkout.swift // Carthage // // Created by Alan Rogers on 11/10/2014. // Copyright (c) 2014 Carthage. All rights reserved. // import CarthageKit import Commandant import Foundation import LlamaKit import ReactiveCocoa public struct CheckoutCommand: CommandType { public let verb = "checkout" public let function = "Check out the project's dependencies" public func run(mode: CommandMode) -> Result<()> { return ColdSignal.fromResult(CheckoutOptions.evaluate(mode)) .map { self.checkoutWithOptions($0) } .merge(identity) .wait() } /// Checks out dependencies with the given options. public func checkoutWithOptions(options: CheckoutOptions) -> ColdSignal<()> { return options.loadProject() .map { $0.checkoutResolvedDependencies() } .merge(identity) } } public struct CheckoutOptions: OptionsType { public let directoryPath: String public let useSSH: Bool public let useSubmodules: Bool public static func create(useSSH: Bool)(useSubmodules: Bool)(directoryPath: String) -> CheckoutOptions { return self(directoryPath: directoryPath, useSSH: useSSH, useSubmodules: useSubmodules) } public static func evaluate(m: CommandMode) -> Result<CheckoutOptions> { return create <*> m <| Option(key: "use-ssh", defaultValue: false, usage: "use SSH for downloading GitHub repositories") <*> m <| Option(key: "use-submodules", defaultValue: false, usage: "add dependencies as Git submodules") <*> m <| Option(defaultValue: NSFileManager.defaultManager().currentDirectoryPath, usage: "the directory containing the Carthage project") } /// Attempts to load the project referenced by the options, and configure it /// accordingly. public func loadProject() -> ColdSignal<Project> { if let directoryURL = NSURL.fileURLWithPath(self.directoryPath, isDirectory: true) { return ColdSignal<Project>.lazy { return .fromResult(Project.loadFromDirectory(directoryURL)) } .map { project in project.preferHTTPS = !self.useSSH project.useSubmodules = self.useSubmodules project.projectEvents.observe(ProjectEventSink()) return project } .mergeMap { (project: Project) -> ColdSignal<Project> in return project .migrateIfNecessary() .on(next: carthage.println) .then(.single(project)) } } else { return .error(CarthageError.InvalidArgument(description: "Invalid project path: \(directoryPath)").error) } } } /// Logs project events put into the sink. private struct ProjectEventSink: SinkType { mutating func put(event: ProjectEvent) { switch event { case let .Cloning(project): carthage.println("*** Cloning \(project.name)") case let .Fetching(project): carthage.println("*** Fetching \(project.name)") case let .CheckingOut(project, revision): carthage.println("*** Checking out \(project.name) at \"\(revision)\"") } } }
0cb2cc5e1953b4a5210c91ba7a1e3cf1
31.235955
141
0.721157
false
false
false
false
kaltura/playkit-ios
refs/heads/develop
Classes/Player/PlayerController.swift
agpl-3.0
1
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation class PlayerController: NSObject, Player { /************************************************************/ // MARK: - Properties /************************************************************/ var onEventBlock: ((PKEvent) -> Void)? fileprivate var currentPlayer: PlayerEngine = DefaultPlayerWrapper() { // Initialize the currentPlayer to DefaultPlayerWrapper, which does nothing except printing warnings. didSet { // When set to a real player, enable the observer. timeObserver.enabled = !(currentPlayer is DefaultPlayerWrapper) } } var playerEngineWrapper: PlayerEngineWrapper? /// Current selected media source fileprivate var selectedSource: PKMediaSource? /// Current handler for the selected source fileprivate var assetHandler: AssetHandler? /// Current media config that was set private var mediaConfig: MediaConfig? /// A semaphore to make sure prepare calling will wait till assetToPrepare it set. private let prepareSemaphore = DispatchSemaphore(value: 0) let sessionUUID = UUID() var mediaSessionUUID: UUID? // Every player that is created should own Reachability instance let reachability = PKReachability() var shouldRefresh: Bool = false /* Time Observation */ lazy var timeObserver = TimeObserver(timeProvider: self) var playheadObserverUUID: UUID? struct PausePosition { let date: Date = Date() let savedPosition: TimeInterval init(_ position: TimeInterval) { self.savedPosition = position } } var liveDVRPausedPosition: PausePosition? /************************************************************/ // MARK: - Initialization /************************************************************/ public override init() { super.init() self.currentPlayer.onEventBlock = { [weak self] event in guard let self = self else { return } PKLog.verbose("postEvent:: \(event)") self.onEventBlock?(event) } self.playheadObserverUUID = self.timeObserver.addPeriodicObserver(interval: 0.1, observeOn: DispatchQueue.global()) { [weak self] (time) in guard let self = self else { return } self.onEventBlock?(PlayerEvent.PlayheadUpdate(currentTime: time)) } self.onEventBlock = nil } deinit { if let uuid = self.playheadObserverUUID { self.timeObserver.removePeriodicObserver(uuid) } self.timeObserver.stopTimer() self.timeObserver.removePeriodicObservers() self.timeObserver.removeBoundaryObservers() } // ***************************** // // MARK: - Player // ***************************** // public var mediaEntry: PKMediaEntry? { return self.mediaConfig?.mediaEntry } let settings = PKPlayerSettings() var mediaFormat = PKMediaSource.MediaFormat.unknown public var sessionId: String { return self.sessionUUID.uuidString + ":" + (self.mediaSessionUUID?.uuidString ?? "") } func addObserver(_ observer: AnyObject, event: PKEvent.Type, block: @escaping (PKEvent) -> Void) { //Assert.shouldNeverHappen(); } func addObserver(_ observer: AnyObject, events: [PKEvent.Type], block: @escaping (PKEvent) -> Void) { //Assert.shouldNeverHappen(); } func removeObserver(_ observer: AnyObject, event: PKEvent.Type) { //Assert.shouldNeverHappen(); } func removeObserver(_ observer: AnyObject, events: [PKEvent.Type]) { //Assert.shouldNeverHappen(); } func isLive() -> Bool { let avPlayerItemAccessLogEventPlaybackTypeLive = "LIVE" if let playbackType = currentPlayer.playbackType, playbackType == avPlayerItemAccessLogEventPlaybackTypeLive { return true } if let entry = self.mediaEntry { if entry.mediaType == MediaType.live || entry.mediaType == MediaType.dvrLive { return true } } return false } public func getController(type: PKController.Type) -> PKController? { if type is PKVRController.Type && self.currentPlayer is VRPlayerEngine { return PKVRController(player: self.currentPlayer) } return nil } public func updatePluginConfig(pluginName: String, config: Any) { //Assert.shouldNeverHappen(); } func updateTextTrackStyling() { self.currentPlayer.updateTextTrackStyling(self.settings.textTrackStyling) } // ***************************** // // MARK: - BasicPlayer // ***************************** // public var duration: TimeInterval { return self.currentPlayer.duration } public var currentState: PlayerState { return self.currentPlayer.currentState } public var isPlaying: Bool { return self.currentPlayer.isPlaying } public weak var view: PlayerView? { get { return self.currentPlayer.view } set { self.currentPlayer.view = newValue } } public var currentTime: TimeInterval { get { let position = self.currentPlayer.currentPosition let duration = self.duration if position != TimeInterval.infinity && position > duration { return duration } return position } set { self.seek(to: newValue) } } public var currentProgramTime: Date? { return self.currentPlayer.currentProgramTime } public var currentAudioTrack: String? { return self.currentPlayer.currentAudioTrack } public var currentTextTrack: String? { return self.currentPlayer.currentTextTrack } public var rate: Float { get { return self.currentPlayer.rate } set { self.currentPlayer.rate = newValue } } public var volume: Float { get { return self.currentPlayer.volume } set { self.currentPlayer.volume = newValue } } public var loadedTimeRanges: [PKTimeRange]? { return self.currentPlayer.loadedTimeRanges } public var bufferedTime: TimeInterval { return self.currentPlayer.bufferedTime } private func shouldDVRLivePlayFromLiveEdge() -> Bool { if let pausedPosition = liveDVRPausedPosition, currentTime == 0 { let timePassed: TimeInterval = Date().timeIntervalSince(pausedPosition.date) let shouldPlayFromLiveEdge = timePassed > pausedPosition.savedPosition liveDVRPausedPosition = nil return shouldPlayFromLiveEdge } return false } func play() { guard let mediaEntry = self.mediaEntry else { currentPlayer.play() return } switch mediaEntry.mediaType { case .live: currentPlayer.playFromLiveEdge() case .dvrLive: if shouldDVRLivePlayFromLiveEdge() { currentPlayer.playFromLiveEdge() } else { currentPlayer.play() } default: currentPlayer.play() } } func pause() { // Save the paused position only if the player is playing, not every time the pause is called. if mediaEntry?.mediaType == .dvrLive, currentPlayer.isPlaying { liveDVRPausedPosition = PausePosition(currentTime) } self.currentPlayer.pause() } func resume() { guard let mediaEntry = self.mediaEntry else { currentPlayer.resume() return } switch mediaEntry.mediaType { case .live: currentPlayer.playFromLiveEdge() case .dvrLive: if shouldDVRLivePlayFromLiveEdge() { currentPlayer.playFromLiveEdge() } else { currentPlayer.resume() } default: currentPlayer.resume() } } func stop() { self.currentPlayer.stop() } func replay() { self.currentPlayer.replay() } func seek(to time: TimeInterval) { self.currentPlayer.currentPosition = time } func seekToLiveEdge() { self.currentPlayer.seekToLiveEdge() } public func selectTrack(trackId: String) { self.currentPlayer.selectTrack(trackId: trackId) } func destroy() { self.timeObserver.stopTimer() self.timeObserver.removePeriodicObservers() self.timeObserver.removeBoundaryObservers() self.currentPlayer.stop() self.currentPlayer.destroy() self.removeAssetRefreshObservers() } func prepare(_ mediaConfig: MediaConfig) { self.currentPlayer.prepare(mediaConfig) if let source = self.selectedSource { self.mediaFormat = source.mediaFormat } } func startBuffering() { currentPlayer.startBuffering() } // ****************************************** // // MARK: - Private Functions // ****************************************** // /// Creates the wrapper if we haven't created it yet, otherwise uses the same instance we have. /// - Returns: true if a new player was created and false if wrapper already exists. private func createPlayerWrapper(_ mediaConfig: MediaConfig) -> Bool { let isCreated: Bool if (mediaConfig.mediaEntry.vrData != nil) { if type(of: self.currentPlayer) is VRPlayerEngine.Type { // do not create new if current player is already vr player isCreated = false } else { if let vrPlayerWrapper = NSClassFromString("PlayKitVR.VRPlayerWrapper") as? VRPlayerEngine.Type { self.currentPlayer = vrPlayerWrapper.init() isCreated = true } else { PKLog.error("VRPlayerWrapper does not exist, VR library is missing, make sure to add it via Podfile.") // Create AVPlayer if self.currentPlayer is AVPlayerWrapper { // do not create new if current player is already vr player isCreated = false } else { self.currentPlayer = AVPlayerWrapper() isCreated = true } } } } else { if type(of: self.currentPlayer) is VRPlayerEngine.Type { self.currentPlayer.destroy() self.currentPlayer = AVPlayerWrapper() isCreated = true } else if self.currentPlayer is AVPlayerWrapper { // do not create new if current player is already vr player isCreated = false } else { self.currentPlayer = AVPlayerWrapper() isCreated = true } } if let currentPlayer = self.currentPlayer as? AVPlayerWrapper { currentPlayer.settings = self.settings } if let playerEW = playerEngineWrapper { playerEW.playerEngine = currentPlayer currentPlayer = playerEW } return isCreated } // ****************************************** // // MARK: - Public Functions // ****************************************** // func setMedia(from mediaConfig: MediaConfig) { self.mediaConfig = mediaConfig // create new media session uuid self.mediaSessionUUID = UUID() // get the preferred media source and post source selected event guard let (selectedSource, handler) = SourceSelector.selectSource(from: mediaConfig.mediaEntry) else { PKLog.error("No playable source found for entry") self.onEventBlock?(PlayerEvent.Error(error: PlayerError.missingMediaSource)) return } self.onEventBlock?(PlayerEvent.SourceSelected(mediaSource: selectedSource)) self.selectedSource = selectedSource self.assetHandler = handler // Update the selected source if there are external subtitles. selectedSource.externalSubtitle = mediaConfig.mediaEntry.externalSubtitles // update the media source request adapter with new media uuid if using kaltura request adapter var pms = selectedSource self.updateRequestAdapter(in: &pms) // Take saved eventBlock from DefaultPlayerWrapper // Must be called before `self.currentPlayer` reference is changed let eventBlock = self.currentPlayer.onEventBlock // Take saved view from DefaultPlayerWrapper // Must be called before `self.currentPlayer` reference is changed let playerView = self.currentPlayer.view // if create player wrapper returns yes meaning a new wrapper was created, otherwise same wrapper as last time is used. if self.createPlayerWrapper(mediaConfig) { // After Setting PlayerWrapper set saved player's params self.currentPlayer.onEventBlock = eventBlock self.currentPlayer.view = playerView } // Update the mediaConfig self.currentPlayer.mediaConfig = mediaConfig // Reset the pause position liveDVRPausedPosition = nil self.currentPlayer.loadMedia(from: self.selectedSource, handler: handler) } } /************************************************************/ // MARK: - Private /************************************************************/ fileprivate extension PlayerController { /// Updates the request adapter if one exists func updateRequestAdapter(in mediaSource: inout PKMediaSource) { // configure media sources content request adapter if request adapter exists if let adapter = self.settings.contentRequestAdapter { // update the request adapter with the updated session id adapter.updateRequestAdapter(with: self) // configure media source with the adapter mediaSource.contentRequestAdapter = adapter } // Maybe update licenseRequestAdapter and fpsLicenseRequestDelegate in params let drmAdapter = self.settings.licenseRequestAdapter drmAdapter?.updateRequestAdapter(with: self) let licenseProvider = self.settings.fairPlayLicenseProvider if let drmData = mediaSource.drmData { for d in drmData { d.requestAdapter = drmAdapter if let fps = d as? FairPlayDRMParams { fps.licenseProvider = licenseProvider } } } } } /************************************************************/ // MARK: - Reachability & Application States Handling /************************************************************/ extension PlayerController { private func shouldRefreshAsset() { guard let selectedSource = self.selectedSource, let refreshableHandler = assetHandler as? RefreshableAssetHandler else { return } refreshableHandler.shouldRefreshAsset(mediaSource: selectedSource) { [weak self] (shouldRefresh) in guard let self = self else { return } if shouldRefresh { self.shouldRefresh = true } } } private func refreshAsset() { guard let selectedSource = self.selectedSource, let refreshableHandler = assetHandler as? RefreshableAssetHandler else { return } self.currentPlayer.startPosition = self.currentPlayer.currentPosition refreshableHandler.refreshAsset(mediaSource: selectedSource) } func addAssetRefreshObservers() { self.addReachabilityObserver() self.addAppStateChangeObserver() self.shouldRefreshAsset() } func removeAssetRefreshObservers() { self.removeReachabilityObserver() self.removeAppStateChangeObserver() } // Reachability Handling private func addReachabilityObserver() -> Void { guard let reachability = self.reachability else { return } reachability.startNotifier() reachability.onUnreachable = { reachability in PKLog.warning("network unreachable") } reachability.onReachable = { [weak self] reachability in guard let self = self else { return } if self.shouldRefresh { self.handleRefreshAsset() } } } private func removeReachabilityObserver() -> Void { self.reachability?.stopNotifier() } // Application States Handling private func addAppStateChangeObserver() { NotificationCenter.default.addObserver(self, selector: #selector(PlayerController.applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } private func removeAppStateChangeObserver() { NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } @objc private func applicationDidBecomeActive() { self.handleRefreshAsset() } private func handleRefreshAsset() { self.shouldRefresh = false self.refreshAsset() } }
4fdad5044955f103e831581c77806a66
33.202206
147
0.569924
false
false
false
false
yangalex/TimeMatch
refs/heads/master
TimeMatch/TimeButton.swift
mit
2
// // TimeButton.swift // TimeMatch // // Created by Alexandre Yang on 7/15/15. // Copyright (c) 2015 Alex Yang. All rights reserved. // import UIKit class TimeButton: UIButton { // Used only if handle var matchingHandle: TimeButton? // keep spacing constant var spacing: CGFloat? enum TimeState { case Single, Handle, Path, Unselected } var timeState: TimeState = .Unselected { didSet { // fix positioning for when button was a path if oldValue == .Path { self.frame = CGRectMake(self.frame.origin.x + (spacing! - CGFloat(self.frame.size.height)), self.frame.origin.y, CGFloat(self.frame.size.height), CGFloat(self.frame.size.height)) self.layer.cornerRadius = 0.5 * self.frame.size.width } if timeState == .Single { self.layer.borderColor = blueColor.CGColor self.layer.cornerRadius = 0.5 * self.frame.size.width self.backgroundColor = blueColor self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) self.setBackgroundImage(nil, forState: .Selected) } else if timeState == .Handle { self.layer.borderColor = UIColor.clearColor().CGColor } else if timeState == .Path { let lightBlueColor = UIColor(red: 121/255, green: 219/255, blue: 243/255, alpha: 1.0) self.layer.borderColor = blueColor.CGColor self.layer.cornerRadius = 0 self.backgroundColor = blueColor self.setBackgroundImage(nil, forState: .Selected) self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) self.selected = true // change size of button self.frame = CGRectMake(self.frame.origin.x - (spacing! - CGFloat(self.frame.size.height)), self.frame.origin.y, self.frame.width + (spacing! - CGFloat(self.frame.size.height))*2, self.frame.height) } else if timeState == .Unselected { self.layer.cornerRadius = 0.5 * self.frame.size.width self.layer.borderColor = buttonColor.CGColor self.backgroundColor = UIColor.whiteColor() self.setTitleColor(buttonColor, forState: UIControlState.Normal) self.setBackgroundImage(nil, forState: .Selected) } } } // Use for paths var leftHandle: TimeButton? var rightHandle: TimeButton? /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
b640f3940bcdf34b77b68d7c50707c39
37.12
214
0.594264
false
false
false
false
artursDerkintis/Starfly
refs/heads/master
Starfly/SFHistoryController.swift
mit
1
// // SFHistoryController.swift // Starfly // // Created by Arturs Derkintis on 12/10/15. // Copyright © 2015 Starfly. All rights reserved. // import UIKit class SFHistoryController: UIViewController { var tableView : UITableView! var historyProvider : SFHistoryProvider! override func viewDidLoad() { super.viewDidLoad() historyProvider = SFHistoryProvider() tableView = UITableView(frame: .zero) historyProvider.tableView = tableView tableView.registerClass(SFHistoryCell.self, forCellReuseIdentifier: historyCell) tableView.registerClass(SFHistoryHeader.self, forHeaderFooterViewReuseIdentifier: historyHeader) tableView.backgroundColor = .clearColor() tableView.separatorColor = .clearColor() addSubviewSafe(tableView) tableView.snp_makeConstraints { (make) -> Void in make.top.equalTo(0) make.bottom.equalTo(0) make.width.equalTo(768) make.centerX.equalTo(self.view.snp_centerX) } tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0) } func load() { historyProvider.loadData() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showDeleteActions(){ let actionController = UIAlertController(title: "What to delete?", message: nil, preferredStyle: UIAlertControllerStyle.Alert) let actionHour = UIAlertAction(title: "Last Hour", style: UIAlertActionStyle.Default) { (k) -> Void in self.historyProvider.deleteLastHour() } let actionToday = UIAlertAction(title: "Today", style: UIAlertActionStyle.Default) { (k) -> Void in self.historyProvider.deleteToday() } let actionThisWeek = UIAlertAction(title: "This Week", style: UIAlertActionStyle.Default) { (k) -> Void in self.historyProvider.deleteThisWeek() } let actionAll = UIAlertAction(title: "Delete All", style: UIAlertActionStyle.Default) { (k) -> Void in self.historyProvider.deleteAll() } let actionDeep = UIAlertAction(title: "Delete Deeply", style: UIAlertActionStyle.Default) { (k) -> Void in self.historyProvider.deleteAllAndDeep() } let actionCancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (k) -> Void in } for action in [actionHour, actionToday, actionThisWeek, actionAll, actionDeep, actionCancel]{ actionController.addAction(action) } presentViewController(actionController, animated: true, completion: nil) } }
68387aa0df1000144856e70066da42ff
34.410256
134
0.681028
false
false
false
false
atrick/swift
refs/heads/main
test/StringProcessing/Parse/regex_parse_error.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking // REQUIRES: swift_in_compiler _ = /(/ // expected-error@:7 {{expected ')'}} _ = #/(/# // expected-error@:8 {{expected ')'}} // FIXME: Should be 'group openings' _ = /)/ // expected-error@:6 {{closing ')' does not balance any groups openings}} _ = #/)/# // expected-error@:7 {{closing ')' does not balance any groups openings}} _ = #/\\/''/ // expected-error@:5 {{unterminated regex literal}} _ = #/\| // expected-error@:5 {{unterminated regex literal}} _ = #// // expected-error@:5 {{unterminated regex literal}} _ = #/xy // expected-error@:5 {{unterminated regex literal}} _ = #/(?/# // expected-error@:7 {{expected group specifier}} _ = #/(?'/# // expected-error@:10 {{expected group name}} _ = #/(?'abc/# // expected-error@:13 {{expected '''}} _ = #/(?'abc /# // expected-error@:13 {{expected '''}} do { _ = #/(?'a // expected-error@-1:7 {{unterminated regex literal}} // expected-error@-2:13 {{cannot parse regular expression: expected '''}} } _ = #/\(?'abc/# do { _ = /\ / // expected-error@-2:7 {{unterminated regex literal}} // expected-error@-3:9 {{expected escape sequence}} } // expected-error@:1 {{expected expression after operator}} do { _ = #/\ /# // expected-error@-2:7 {{unterminated regex literal}} // expected-error@-3:10 {{expected escape sequence}} // expected-error@-3:3 {{unterminated regex literal}} // expected-warning@-4:3 {{regular expression literal is unused}} } func foo<T>(_ x: T, _ y: T) {} foo(#/(?/#, #/abc/#) // expected-error@:7 {{expected group specifier}} foo(#/(?C/#, #/abc/#) // expected-error@:10 {{expected ')'}} foo(#/(?'/#, #/abc/#) // expected-error@:10 {{expected group name}}
702fa46453596dacf4f054de62dc9216
34.1
94
0.601709
false
false
false
false
biohazardlover/ROer
refs/heads/master
DataDownloader/MaterialDownloader.swift
mit
1
// // MaterialDownloader.swift // DataDownloader // // Created by Li Junlin on 9/1/16. // Copyright © 2016 Li Junlin. All rights reserved. // import Cocoa import SwiftyJSON class MaterialDownloader: NSObject { lazy var baseLocalURL: URL = { let desktopURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true) return desktopURL.appendingPathComponent("Material") }() let baseRemoteURL = URL(string: "http://nozomi.arege.jp/ro")! lazy var body: JSON = { let url = Bundle.main.url(forResource: "Body", withExtension: "json")! let data = try! Data(contentsOf: url) return JSON(data: data) }() lazy var item: JSON = { let url = Bundle.main.url(forResource: "Item", withExtension: "json")! let data = try! Data(contentsOf: url) return JSON(data: data) }() lazy var other: JSON = { let url = Bundle.main.url(forResource: "Other", withExtension: "json")! let data = try! Data(contentsOf: url) return JSON(data: data) }() lazy var session: URLSession = { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = Double.infinity return URLSession(configuration: configuration) }() func download() { downloadBody() downloadItem() downloadOther() } func downloadBody() { downloadMaleBody() downloadFemaleBody() downloadHair() } func downloadMaleBody() { let jobClasses = body["items"][0]["c"].arrayValue for jobClass in jobClasses { let jobs = jobClass["c"].arrayValue for job in jobs { let costumes = job["c"].arrayValue if costumes.count == 0 { let md = job["md"].intValue downloadIfNeeded(remotePath: "body/\(md).txt", localPath: "Body/Body\(md).txt", completionHandler: { (data, _, _) in guard let data = data else { return } let json = JSON(data: data) let i = json["value"]["i"].intValue self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Body/Body\(i).png") }) } else { for costume in costumes { let md = costume["md"].intValue let ms = costume["ms"].intValue downloadIfNeeded(remotePath: "body/\(md).txt", localPath: "Body/Body\(md).txt") downloadIfNeeded(remotePath: "image/\(ms).png", localPath: "Body/Body\(ms).png") } } } } } func downloadFemaleBody() { let jobClasses = body["items"][1]["c"].arrayValue for jobClass in jobClasses { let jobs = jobClass["c"].arrayValue for job in jobs { let costumes = job["c"].arrayValue if costumes.count == 0 { let fd = job["fd"].intValue downloadIfNeeded(remotePath: "body/\(fd).txt", localPath: "Body/Body\(fd).txt", completionHandler: { (data, _, _) in guard let data = data else { return } let json = JSON(data: data) let i = json["value"]["i"].intValue self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Body/Body\(i).png") }) } else { for costume in costumes { let fd = costume["fd"].intValue let fs = costume["fs"].intValue downloadIfNeeded(remotePath: "body/\(fd).txt", localPath: "Body/Body\(fd).txt") downloadIfNeeded(remotePath: "image/\(fs).png", localPath: "Body/Body\(fs).png") } } } } } func downloadHair() { let hairs = body["items"][2]["c"].arrayValue for hair in hairs { let colors = hair["c"].arrayValue for color in colors { let md = color["md"].intValue let ms = color["ms"].intValue let fd = color["fd"].intValue let fs = color["fs"].intValue downloadIfNeeded(remotePath: "body/\(md).txt", localPath: "Hair/Hair\(md).txt") downloadIfNeeded(remotePath: "image/\(ms).png", localPath: "Hair/Hair\(ms).png") downloadIfNeeded(remotePath: "body/\(fd).txt", localPath: "Hair/Hair\(fd).txt") downloadIfNeeded(remotePath: "image/\(fs).png", localPath: "Hair/Hair\(fs).png") } } } func downloadItem() { let types = item["items"].arrayValue for type in types { let items = type["c"].arrayValue for item in items { let m = item["m"].intValue let f = item["f"].intValue downloadIfNeeded(remotePath: "item/\(m).txt", localPath: "Item/Item\(m).txt", completionHandler: { (data, _, _) in guard let data = data else { return } let json = JSON(data: data) let i = json["value"]["i"].intValue if i != 0 { self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Item/Item\(i).png") } }) downloadIfNeeded(remotePath: "item/\(f).txt", localPath: "Item/Item\(f).txt", completionHandler: { (data, _, _) in guard let data = data else { return } let json = JSON(data: data) let i = json["value"]["i"].intValue if i != 0 { self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Item/Item\(i).png") } }) } } } func downloadOther() { let items = other.dictionaryValue for (_, item) in items { let i = item["i"].intValue downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Other/Other\(i).png") } } func downloadIfNeeded(remotePath: String, localPath: String, completionHandler: ((Data?, URLResponse?, Error?) -> Void)? = nil) { let remoteURL = baseRemoteURL.appendingPathComponent(remotePath) let localURL = baseLocalURL.appendingPathComponent(localPath) if FileManager.default.fileExists(atPath: localURL.path, isDirectory: nil) { let data = try! Data(contentsOf: localURL) print(localPath) completionHandler?(data, nil, nil) } else { let task = session.dataTask(with: remoteURL, completionHandler: { (data, response, error) in try! FileManager.default.createDirectory(at: localURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) try! data?.write(to: localURL, options: []) print(remotePath) completionHandler?(data, response, error) }) task.resume() } } }
741fde0adb436956028ac3df556e7f44
38.326531
150
0.49494
false
false
false
false
JohnSansoucie/MyProject2
refs/heads/master
BlueCapKit/Central/Service.swift
mit
1
// // Service.swift // BlueCap // // Created by Troy Stribling on 6/11/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import Foundation import CoreBluetooth public class Service : NSObject { private let profile : ServiceProfile? private var characteristicsDiscoveredPromise = Promise<[Characteristic]>() internal let _peripheral : Peripheral internal let cbService : CBService internal var discoveredCharacteristics = Dictionary<CBUUID, Characteristic>() public var name : String { if let profile = self.profile { return profile.name } else { return "Unknown" } } public var uuid : CBUUID! { return self.cbService.UUID } public var characteristics : [Characteristic] { return self.discoveredCharacteristics.values.array } public var peripheral : Peripheral { return self._peripheral } public func discoverAllCharacteristics() -> Future<[Characteristic]> { Logger.debug("Service#discoverAllCharacteristics") return self.discoverIfConnected(nil) } public func discoverCharacteristics(characteristics:[CBUUID]) -> Future<[Characteristic]> { Logger.debug("Service#discoverCharacteristics") return self.discoverIfConnected(characteristics) } private func discoverIfConnected(services:[CBUUID]!) -> Future<[Characteristic]> { self.characteristicsDiscoveredPromise = Promise<[Characteristic]>() if self.peripheral.state == .Connected { self.peripheral.cbPeripheral.discoverCharacteristics(nil, forService:self.cbService) } else { self.characteristicsDiscoveredPromise.failure(BCError.peripheralDisconnected) } return self.characteristicsDiscoveredPromise.future } internal init(cbService:CBService, peripheral:Peripheral) { self.cbService = cbService self._peripheral = peripheral self.profile = ProfileManager.sharedInstance.serviceProfiles[cbService.UUID] } internal func didDiscoverCharacteristics(error:NSError!) { if let error = error { self.characteristicsDiscoveredPromise.failure(error) } else { self.discoveredCharacteristics.removeAll() if let cbCharacteristics = self.cbService.characteristics { for cbCharacteristic : AnyObject in cbCharacteristics { let bcCharacteristic = Characteristic(cbCharacteristic:cbCharacteristic as CBCharacteristic, service:self) self.discoveredCharacteristics[bcCharacteristic.uuid] = bcCharacteristic bcCharacteristic.didDiscover() Logger.debug("Service#didDiscoverCharacteristics: uuid=\(bcCharacteristic.uuid.UUIDString), name=\(bcCharacteristic.name)") } self.characteristicsDiscoveredPromise.success(self.characteristics) } } } }
cfc465116105bdec8d13380ce34b20f7
35.892857
143
0.653002
false
false
false
false
giaunv/cookiecrunch-swift-spritekit-ios
refs/heads/master
cookiecrunch/GameScene.swift
mit
1
// // GameScene.swift // cookiecrunch // // Created by giaunv on 3/8/15. // Copyright (c) 2015 366. All rights reserved. // import SpriteKit class GameScene: SKScene { var level: Level! let TileWidth: CGFloat = 32.0 let TileHeight: CGFloat = 36.0 let gameLayer = SKNode() let cookiesLayer = SKNode() let tilesLayer = SKNode() var swipeFromColumn: Int? var swipeFromRow: Int? var swipeHandler: ((Swap) -> ())? var selectionSprite = SKSpriteNode() let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false) let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false) let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false) let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false) let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false) let cropLayer = SKCropNode() let maskLayer = SKNode() required init?(coder aDecoder: NSCoder) { fatalError("init(coder) is not used in this app") } override init(size: CGSize){ super.init(size: size) anchorPoint = CGPoint(x: 0.5, y: 0.5) let background = SKSpriteNode(imageNamed: "Background") addChild(background) addChild(gameLayer) gameLayer.hidden = true let layerPosition = CGPoint(x: -TileWidth * CGFloat(NumColumns)/2, y: -TileHeight * CGFloat(NumRows)/2) tilesLayer.position = layerPosition gameLayer.addChild(tilesLayer) gameLayer.addChild(cropLayer) maskLayer.position = layerPosition cropLayer.maskNode = maskLayer cookiesLayer.position = layerPosition cropLayer.addChild(cookiesLayer) swipeFromColumn = nil swipeFromRow = nil SKLabelNode(fontNamed: "GillSans-BoldItalic") } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch = touches.anyObject() as UITouch let location = touch.locationInNode(cookiesLayer) let (success, column, row) = convertPoint(location) if success{ if let cookie = level.cookieAtColumn(column, row: row){ swipeFromColumn = column swipeFromRow = row showSelectionIndicatorForCookie(cookie) } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { if swipeFromColumn == nil {return} let touch = touches.anyObject() as UITouch let location = touch.locationInNode(cookiesLayer) let (success, column, row) = convertPoint(location) if success{ var horzDelta = 0, vertDelta = 0 if column < swipeFromColumn!{ // swipe left horzDelta = -1 } else if column > swipeFromColumn!{ // swipe right horzDelta = 1 } else if row < swipeFromRow!{ // swipe down vertDelta = -1 } else if row > swipeFromRow!{ // swipe up vertDelta = 1 } if horzDelta != 0 || vertDelta != 0{ trySwapHorizontal(horzDelta, vertical: vertDelta) hideSelectionIndicator() swipeFromColumn = nil } } } func trySwapHorizontal(horzDelta: Int, vertical vertDelta: Int){ let toColumn = swipeFromColumn! + horzDelta let toRow = swipeFromRow! + vertDelta if toColumn < 0 || toColumn >= NumColumns {return} if toRow < 0 || toRow >= NumRows {return} if let toCookie = level.cookieAtColumn(toColumn, row: toRow){ if let fromCookie = level.cookieAtColumn(swipeFromColumn!, row: swipeFromRow!){ // println("*** swapping \(fromCookie) with \(toCookie)") if let handler = swipeHandler{ let swap = Swap(cookieA: fromCookie, cookieB: toCookie) handler(swap) } } } } func animateSwap(swap: Swap, completion: () -> ()){ let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.3 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut spriteA.runAction(moveA, completion: completion) let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteB.runAction(moveB) runAction(swapSound) } func animateInvalidSwap(swap: Swap, completion: () -> ()){ let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.2 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteA.runAction(SKAction.sequence([moveA, moveB]), completion: completion) spriteB.runAction(SKAction.sequence([moveB, moveA])) runAction(invalidSwapSound) } func animateMatchedCookies(chains: Set<Chain>, completion: () -> ()){ for chain in chains{ animateScoreForChain(chain) for cookie in chain.cookies{ if let sprite = cookie.sprite{ if sprite.actionForKey("removing") == nil{ let scaleAction = SKAction.scaleTo(0.1, duration: 0.3) scaleAction.timingMode = .EaseOut sprite.runAction(SKAction.sequence([scaleAction, SKAction.removeFromParent()]), withKey: "removing") } } } } runAction(matchSound) runAction(SKAction.waitForDuration(0.3), completion: completion) } func animateFallingCookies(columns: [[Cookie]], completion: () -> ()){ var longestDuration: NSTimeInterval = 0 for array in columns{ for (idx, cookie) in enumerate(array){ let newPosition = pointForColumn(cookie.column, row: cookie.row) let delay = 0.05 + 0.15*NSTimeInterval(idx) let sprite = cookie.sprite! let duration = NSTimeInterval(((sprite.position.y - newPosition.y)/TileHeight)*0.1) longestDuration = max(longestDuration, duration+delay) let moveAction = SKAction.moveTo(newPosition, duration: duration) moveAction.timingMode = .EaseOut sprite.runAction(SKAction.sequence([SKAction.waitForDuration(delay), SKAction.group([moveAction, fallingCookieSound])])) } } runAction(SKAction.waitForDuration(longestDuration), completion: completion) } func animateNewCookies(columns: [[Cookie]], completion: () -> ()){ var longestDuration: NSTimeInterval = 0 for array in columns{ let startRow = array[0].row + 1 for (idx, cookie) in enumerate(array){ let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row: startRow) cookiesLayer.addChild(sprite) cookie.sprite = sprite let delay = 0.1 + 0.2 * NSTimeInterval(array.count - idx - 1) let duration = NSTimeInterval(startRow - cookie.row) * 0.1 longestDuration = max(longestDuration, duration + delay) let newPostion = pointForColumn(cookie.column, row: cookie.row) let moveAction = SKAction.moveTo(newPostion, duration: duration) moveAction.timingMode = .EaseOut sprite.alpha = 0 sprite.runAction(SKAction.sequence([SKAction.waitForDuration(delay), SKAction.group([SKAction.fadeInWithDuration(0.05), moveAction, addCookieSound])])) } } runAction(SKAction.waitForDuration(longestDuration), completion: completion) } func animateScoreForChain(chain: Chain){ // Figure out what the midpoint of the chain is let firstSprite = chain.firstCookie().sprite! let lastSprite = chain.lastCookie().sprite! let centerPosition = CGPoint(x:(firstSprite.position.x + lastSprite.position.x)/2, y:(firstSprite.position.y + lastSprite.position.y)/2 - 8) // Add a label for the score that slowly floats up let scoreLabel = SKLabelNode(fontNamed: "GillSans-BoldItalic") scoreLabel.fontSize = 16 scoreLabel.text = NSString(format: "%ld", chain.score) scoreLabel.position = centerPosition scoreLabel.zPosition = 300 cookiesLayer.addChild(scoreLabel) let moveAction = SKAction.moveBy(CGVector(dx: 0, dy: 0.3), duration: 0.7) moveAction.timingMode = .EaseOut scoreLabel.runAction(SKAction.sequence([moveAction, SKAction.removeFromParent()])) } func animateGameOver(completion: () -> ()){ let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3) action.timingMode = .EaseIn gameLayer.runAction(action, completion: completion) } func animateBeginGame(completion: () -> ()){ gameLayer.hidden = false gameLayer.position = CGPoint(x: 0, y: size.height) let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3) action.timingMode = .EaseOut gameLayer.runAction(action, completion) } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { swipeFromColumn = nil swipeFromRow = nil } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { touchesEnded(touches, withEvent: event) } func pointForColumn(column: Int, row: Int) -> CGPoint{ return CGPoint(x: CGFloat(column) * TileWidth + TileWidth/2, y: CGFloat(row) * TileHeight + TileHeight/2) } func convertPoint(point: CGPoint) -> (success: Bool, column: Int, row: Int){ if point.x >= 0 && point.x < CGFloat(NumColumns) * TileWidth && point.y >= 0 && point.y < CGFloat(NumRows) * TileHeight{ return (true, Int(point.x/TileWidth), Int(point.y/TileHeight)) } else { return (false, 0, 0) // invalid location } } func addTiles(){ for row in 0..<NumRows{ for column in 0..<NumColumns{ if let tile = level.tileAtColumn(column, row: row){ let tileNode = SKSpriteNode(imageNamed: "MaskTile") tileNode.position = pointForColumn(column, row: row) maskLayer.addChild(tileNode) } } } for row in 0...NumRows { for column in 0...NumColumns { let topLeft = (column > 0) && (row < NumRows) && level.tileAtColumn(column - 1, row: row) != nil let bottomLeft = (column > 0) && (row > 0) && level.tileAtColumn(column - 1, row: row - 1) != nil let topRight = (column < NumColumns) && (row < NumRows) && level.tileAtColumn(column, row: row) != nil let bottomRight = (column < NumColumns) && (row > 0) && level.tileAtColumn(column, row: row - 1) != nil // The tiles are named from 0 to 15, according to the bitmask that is made by combining these four values let value = Int(topLeft) | Int(topRight) << 1 | Int(bottomLeft) << 2 | Int(bottomRight) << 3 // Values 0 (no tiles), 6 and 9 (two opposite tiles) are not drawn. if value != 0 && value != 6 && value != 9{ let name = String(format: "Tile_%ld", value) let tileNode = SKSpriteNode(imageNamed: name) var point = pointForColumn(column, row: row) point.x -= TileWidth/2 point.y -= TileHeight/2 tileNode.position = point tilesLayer.addChild(tileNode) } } } } func addSpritesForCookies(cookies: Set<Cookie>){ for cookie in cookies{ let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row: cookie.row) cookiesLayer.addChild(sprite) cookie.sprite = sprite // Give each cookie sprite a small, random delay. Then fade them in sprite.alpha = 0 sprite.xScale = 0.5 sprite.yScale = 0.5 sprite.runAction(SKAction.sequence([SKAction.waitForDuration(0.25, withRange: 0.5), SKAction.group([SKAction.fadeInWithDuration(0.25), SKAction.scaleTo(1.0, duration: 0.25)])])) } } func showSelectionIndicatorForCookie(cookie: Cookie){ if selectionSprite.parent != nil{ selectionSprite.removeFromParent() } if let sprite = cookie.sprite{ let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName) selectionSprite.size = texture.size() selectionSprite.runAction(SKAction.setTexture(texture)) sprite.addChild(selectionSprite) selectionSprite.alpha = 1.0 } } func hideSelectionIndicator(){ selectionSprite.runAction(SKAction.sequence([ SKAction.fadeOutWithDuration(0.3), SKAction.removeFromParent() ])) } func removeAllCookieSprites(){ cookiesLayer.removeAllChildren() } }
0b310eeb55da32d67915f946a7508aef
38.265027
189
0.582324
false
false
false
false
zigdanis/Interactive-Transitioning
refs/heads/master
InteractiveTransitioning/ViewControllers/ThumbImageViewController.swift
mit
1
// // ViewController.swift // InteractiveTransitioning // // Created by Danis Ziganshin on 15/07/16. // Copyright © 2016 Zigdanis. All rights reserved. // import UIKit class ThumbImageViewController: UIViewController { @IBOutlet weak var thumbImageView: RoundedImageView! let transitionController = TransitioningDelegate() var startPoint: CGPoint! override func viewDidLoad() { super.viewDidLoad() setupGestureRecognizers() startPoint = thumbImageView.center view.backgroundColor = UIColor.groupTableViewBackground } func setupGestureRecognizers() { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture)) thumbImageView.addGestureRecognizer(panGesture) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture)) thumbImageView.addGestureRecognizer(tapGesture) } func handlePanGesture(gesture: UIGestureRecognizer) { let location = gesture.location(in: view) let xDist = location.x - startPoint.x let yDist = location.y - startPoint.y let distance = sqrt(xDist * xDist + yDist * yDist) let newFrame = CGRect(x:0,y:0,width:150 + distance,height: 150 + distance) thumbImageView.frame = newFrame thumbImageView.center = startPoint } func handleTapGesture(gesture: UIGestureRecognizer) { guard let secondVC = storyboard?.instantiateViewController(withIdentifier: "FullImageViewController") else { return } let navController = UINavigationController(rootViewController: secondVC) navController.modalPresentationStyle = .custom navController.transitioningDelegate = transitionController present(navController, animated: true) } }
47c167f87e7e0c32b901148ab283d830
35.137255
116
0.704829
false
false
false
false
luckymore0520/leetcode
refs/heads/master
First Missing Positive.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit //Given an unsorted integer array, find the first missing positive integer. // //For example, //Given [1,2,0] return 3, //and [3,4,-1,1] return 2. // //Your algorithm should run in O(n) time and uses constant space. //这题要求 O(n),而且对空间有要求 //遍历数组,把对应数字交换到对应的位置 class Solution { func firstMissingPositive(_ nums: [Int]) -> Int { if (nums.isEmpty) { return 1 } var nums = nums var i = 0 while i < nums.count { if (nums[i] != i+1 && nums[i] <= nums.count && nums[i] > 0 && nums[i] != nums[nums[i]-1]) { (nums[i],nums[nums[i]-1]) = (nums[nums[i]-1], nums[i]) } else { i += 1 } } for i in 0...nums.count-1 { if nums[i] != i+1 { return i+1 } } return nums.count + 1 } } let solution = Solution() solution.firstMissingPositive([3,4,-1,1])
7d244bcdf196628fc418e6528ced30fa
22
103
0.503462
false
false
false
false
Aishwarya-Ramakrishnan/sparkios
refs/heads/master
Tests/TeamTests.swift
mit
1
// Copyright 2016 Cisco Systems Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Quick import Nimble @testable import SparkSDK class TeamSpec: QuickSpec { private func validate(team: Team) { expect(team.id).notTo(beNil()) expect(team.name).notTo(beNil()) expect(team.created).notTo(beNil()) } override func spec() { beforeSuite { print("Config.selfUser.token: \(Config.selfUser.token)") Spark.initWith(accessToken: Config.selfUser.token!) } // MARK: - Create a team describe("create a team") { it("normal") { do { let teamName = "test team" let team = try Spark.teams.create(name: teamName) self.validate(team: team) expect(team.name).to(equal(teamName)) } catch let error as NSError { fail("Failed to create team, \(error.localizedFailureReason)") } } } it("with empty name") { expect{try Spark.teams.create(name: "")}.to(throwError()) } it("with special name") { do { let teamName = "@@@ &&&" let team = try Spark.teams.create(name: teamName) self.validate(team: team) expect(team.name).to(equal(teamName)) } catch let error as NSError { fail("Failed to create team, \(error.localizedFailureReason)") } } // MARK: - List a team describe("list a team") { it("normal") { do { let team = try Spark.teams.create(name: "test team") let teams = try Spark.teams.list() expect(teams.isEmpty).to(beFalse()) expect(teams.contains(){$0 == team}).to(beTrue()) } catch let error as NSError { fail("Failed to list team, \(error.localizedFailureReason)") } } it("with max value") { do { let teams = try Spark.teams.list(max: 1) expect(teams.count).to(beLessThanOrEqualTo(1)) } catch let error as NSError { fail("Failed to list team, \(error.localizedFailureReason)") } } it("with invalid max") { expect{try Spark.teams.list(max: -1)}.to(throwError()) } } // MARK: - Get a team describe("get a team") { it("normal") { do { let teamName = "test team" let team = try Spark.teams.create(name: teamName) let teamFromGet = try Spark.teams.get(teamId: team.id!) self.validate(team: teamFromGet) expect(teamFromGet).to(equal(team)) } catch let error as NSError { fail("Failed to get team, \(error.localizedFailureReason)") } } it("with invalid id") { expect{try Spark.teams.get(teamId: Config.InvalidId)}.to(throwError()) } } // MARK: - Update a team describe("update a team") { it("normal") { do { let teamName = "test team" let team = try Spark.teams.create(name: teamName) let newTeamName = "new test team" let teamFromUpdate = try Spark.teams.update(teamId: team.id!, name: newTeamName) self.validate(team: teamFromUpdate) expect(teamFromUpdate.id).to(equal(team.id)) expect(teamFromUpdate.created).to(equal(team.created)) expect(teamFromUpdate.name).to(equal(newTeamName)) } catch let error as NSError { fail("Failed to update team, \(error.localizedFailureReason)") } } it("with empty name") { do { let team = try Spark.teams.create(name: "test team") let teamFromUpdate = try Spark.teams.update(teamId: team.id!, name: "") self.validate(team: teamFromUpdate) expect(teamFromUpdate.id).to(equal(team.id)) expect(teamFromUpdate.created).to(equal(team.created)) expect(teamFromUpdate.name).to(equal("")) } catch let error as NSError { fail("Failed to update team, \(error.localizedFailureReason)") } } it("with special name") { do { let team = try Spark.teams.create(name: "test team") let teamName = "@@@ &&&" let teamFromUpdate = try Spark.teams.update(teamId: team.id!, name: teamName) self.validate(team: team) expect(teamFromUpdate.name).to(equal(teamName)) } catch let error as NSError { fail("Failed to create team, \(error.localizedFailureReason)") } } it("with invalid id") { expect{try Spark.teams.update(teamId: Config.InvalidId, name: Config.InvalidId)}.to(throwError()) } } // MARK: - Delete a team describe("delete a team") { it("normal") { do { let teamName = "test team" let team = try Spark.teams.create(name: teamName) expect{try Spark.teams.delete(teamId: team.id!)}.notTo(throwError()) } catch let error as NSError { fail("Failed to delete team, \(error.localizedFailureReason)") } } it("with invalid id") { expect{try Spark.teams.delete(teamId: Config.InvalidId)}.to(throwError()) } } } }
75f3b24ee3f0816e944ae47a547d8a70
37.57
113
0.487555
false
false
false
false
iAugux/Zoom-Contacts
refs/heads/master
DGElasticPullToRefresh/DGElasticPullToRefreshExtensions.swift
mit
2
/* The MIT License (MIT) Copyright (c) 2015 Danil Gontovnik 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 import ObjectiveC // MARK: - // MARK: (NSObject) Extension public extension NSObject { // MARK: - // MARK: Vars private struct dg_associatedKeys { static var observersArray = "observers" } private var dg_observers: [[String : NSObject]] { get { if let observers = objc_getAssociatedObject(self, &dg_associatedKeys.observersArray) as? [[String : NSObject]] { return observers } else { let observers = [[String : NSObject]]() self.dg_observers = observers return observers } } set { objc_setAssociatedObject(self, &dg_associatedKeys.observersArray, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - // MARK: Methods public func dg_addObserver(observer: NSObject, forKeyPath keyPath: String) { let observerInfo = [keyPath : observer] if dg_observers.indexOf({ $0 == observerInfo }) == nil { dg_observers.append(observerInfo) addObserver(observer, forKeyPath: keyPath, options: .New, context: nil) } } public func dg_removeObserver(observer: NSObject, forKeyPath keyPath: String) { let observerInfo = [keyPath : observer] if let index = dg_observers.indexOf({ $0 == observerInfo}) { dg_observers.removeAtIndex(index) removeObserver(observer, forKeyPath: keyPath) } } } // MARK: - // MARK: (UIScrollView) Extension public extension UIScrollView { // MARK: - Vars private struct dg_associatedKeys { static var pullToRefreshView = "pullToRefreshView" } private var pullToRefreshView: DGElasticPullToRefreshView? { get { return objc_getAssociatedObject(self, &dg_associatedKeys.pullToRefreshView) as? DGElasticPullToRefreshView } set { objc_setAssociatedObject(self, &dg_associatedKeys.pullToRefreshView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Methods (Public) public func dg_addPullToRefreshWithActionHandler(actionHandler: () -> Void, loadingView: DGElasticPullToRefreshLoadingView?) { multipleTouchEnabled = false panGestureRecognizer.maximumNumberOfTouches = 1 let pullToRefreshView = DGElasticPullToRefreshView() self.pullToRefreshView = pullToRefreshView pullToRefreshView.actionHandler = actionHandler pullToRefreshView.loadingView = loadingView addSubview(pullToRefreshView) pullToRefreshView.observing = true } public func dg_removePullToRefresh() { pullToRefreshView?.disassociateDisplayLink() pullToRefreshView?.observing = false pullToRefreshView?.removeFromSuperview() } public func dg_setPullToRefreshBackgroundColor(color: UIColor) { pullToRefreshView?.backgroundColor = color } public func dg_setPullToRefreshFillColor(color: UIColor) { pullToRefreshView?.fillColor = color } public func dg_stopLoading() { pullToRefreshView?.stopLoading() } } // MARK: - // MARK: (UIView) Extension public extension UIView { func dg_center(usePresentationLayerIfPossible: Bool) -> CGPoint { if usePresentationLayerIfPossible, let presentationLayer = layer.presentationLayer() as? CALayer { // Position can be used as a center, because anchorPoint is (0.5, 0.5) return presentationLayer.position } return center } } // MARK: - // MARK: (UIPanGestureRecognizer) Extension public extension UIPanGestureRecognizer { func dg_resign() { enabled = false enabled = true } } // MARK: - // MARK: (UIGestureRecognizerState) Extension public extension UIGestureRecognizerState { func dg_isAnyOf(values: [UIGestureRecognizerState]) -> Bool { return values.contains({ $0 == self }) } }
6f3ae819fc3bdf50049b14e956d19aad
30.536585
148
0.676141
false
false
false
false
XQS6LB3A/LyricsX
refs/heads/master
LyricsX/Controller/KaraokeLyricsController.swift
gpl-3.0
2
// // KaraokeLyricsController.swift // LyricsX - https://github.com/ddddxxx/LyricsX // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // import Cocoa import CXShim import GenericID import LyricsCore import MusicPlayer import OpenCC import SnapKit import SwiftCF import CoreGraphicsExt class KaraokeLyricsWindowController: NSWindowController { static private let windowFrame = NSWindow.FrameAutosaveName("KaraokeWindow") private var lyricsView = KaraokeLyricsView(frame: .zero) private var cancelBag = Set<AnyCancellable>() init() { let window = NSWindow(contentRect: .zero, styleMask: .borderless, backing: .buffered, defer: true) window.backgroundColor = .clear window.hasShadow = false window.isOpaque = false window.level = .floating window.collectionBehavior = [.canJoinAllSpaces, .stationary] window.setFrameUsingName(KaraokeLyricsWindowController.windowFrame, force: true) super.init(window: window) window.contentView?.addSubview(lyricsView) addObserver() makeConstraints() updateWindowFrame(animate: false) lyricsView.displayLrc("LyricsX") DispatchQueue.main.asyncAfter(deadline: .now() + 3) { self.lyricsView.displayLrc("") AppController.shared.$currentLyrics .signal() .receive(on: DispatchQueue.lyricsDisplay.cx) .invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self) .store(in: &self.cancelBag) AppController.shared.$currentLineIndex .signal() .receive(on: DispatchQueue.lyricsDisplay.cx) .invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self) .store(in: &self.cancelBag) selectedPlayer.playbackStateWillChange .signal() .receive(on: DispatchQueue.lyricsDisplay.cx) .invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self) .store(in: &self.cancelBag) defaults.publisher(for: [.preferBilingualLyrics, .desktopLyricsOneLineMode]) .prepend() .invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self) .store(in: &self.cancelBag) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addObserver() { lyricsView.bind(\.textColor, withDefaultName: .desktopLyricsColor) lyricsView.bind(\.progressColor, withDefaultName: .desktopLyricsProgressColor) lyricsView.bind(\.shadowColor, withDefaultName: .desktopLyricsShadowColor) lyricsView.bind(\.backgroundColor, withDefaultName: .desktopLyricsBackgroundColor) lyricsView.bind(\.isVertical, withDefaultName: .desktopLyricsVerticalMode, options: [.nullPlaceholder: false]) lyricsView.bind(\.drawFurigana, withDefaultName: .desktopLyricsEnableFurigana) let negateOption = [NSBindingOption.valueTransformerName: NSValueTransformerName.negateBooleanTransformerName] window?.contentView?.bind(.hidden, withDefaultName: .desktopLyricsEnabled, options: negateOption) observeDefaults(key: .disableLyricsWhenSreenShot, options: [.new, .initial]) { [unowned self] _, change in self.window?.sharingType = change.newValue ? .none : .readOnly } observeDefaults(keys: [ .hideLyricsWhenMousePassingBy, .desktopLyricsDraggable ], options: [.initial]) { self.lyricsView.shouldHideWithMouse = defaults[.hideLyricsWhenMousePassingBy] && !defaults[.desktopLyricsDraggable] } observeDefaults(keys: [ .desktopLyricsFontName, .desktopLyricsFontSize, .desktopLyricsFontNameFallback ], options: [.initial]) { [unowned self] in self.lyricsView.font = defaults.desktopLyricsFont } observeNotification(name: NSApplication.didChangeScreenParametersNotification, queue: .main) { [unowned self] _ in self.updateWindowFrame(animate: true) } observeNotification(center: workspaceNC, name: NSWorkspace.activeSpaceDidChangeNotification, queue: .main) { [unowned self] _ in self.updateWindowFrame(animate: true) } } private func updateWindowFrame(toScreen: NSScreen? = nil, animate: Bool) { let screen = toScreen ?? window?.screen ?? NSScreen.screens[0] let fullScreen = screen.isFullScreen || defaults.bool(forKey: "DesktopLyricsIgnoreSafeArea") let frame = fullScreen ? screen.frame : screen.visibleFrame window?.setFrame(frame, display: false, animate: animate) window?.saveFrame(usingName: KaraokeLyricsWindowController.windowFrame) } @objc private func handleLyricsDisplay() { guard defaults[.desktopLyricsEnabled], !defaults[.disableLyricsWhenPaused] || selectedPlayer.playbackState.isPlaying, let lyrics = AppController.shared.currentLyrics, let index = AppController.shared.currentLineIndex else { DispatchQueue.main.async { self.lyricsView.displayLrc("", secondLine: "") } return } let lrc = lyrics.lines[index] let next = lyrics.lines[(index + 1)...].first { $0.enabled } let languageCode = lyrics.metadata.translationLanguages.first var firstLine = lrc.content var secondLine: String var secondLineIsTranslation = false if defaults[.desktopLyricsOneLineMode] { secondLine = "" } else if defaults[.preferBilingualLyrics], let translation = lrc.attachments[.translation(languageCode: languageCode)] { secondLine = translation secondLineIsTranslation = true } else { secondLine = next?.content ?? "" } if let converter = ChineseConverter.shared { if lyrics.metadata.language?.hasPrefix("zh") == true { firstLine = converter.convert(firstLine) if !secondLineIsTranslation { secondLine = converter.convert(secondLine) } } if languageCode?.hasPrefix("zh") == true { secondLine = converter.convert(secondLine) } } DispatchQueue.main.async { self.lyricsView.displayLrc(firstLine, secondLine: secondLine) if let upperTextField = self.lyricsView.displayLine1, let timetag = lrc.attachments.timetag { let position = selectedPlayer.playbackTime let timeDelay = AppController.shared.currentLyrics?.adjustedTimeDelay ?? 0 let progress = timetag.tags.map { ($0.time + lrc.position - timeDelay - position, $0.index) } upperTextField.setProgressAnimation(color: self.lyricsView.progressColor, progress: progress) if !selectedPlayer.playbackState.isPlaying { upperTextField.pauseProgressAnimation() } } } } private func makeConstraints() { lyricsView.snp.remakeConstraints { make in make.centerX.equalToSuperview().safeMultipliedBy(defaults[.desktopLyricsXPositionFactor] * 2).priority(.low) make.centerY.equalToSuperview().safeMultipliedBy(defaults[.desktopLyricsYPositionFactor] * 2).priority(.low) make.leading.greaterThanOrEqualToSuperview().priority(.keepWindowSize) make.trailing.lessThanOrEqualToSuperview().priority(.keepWindowSize) make.top.greaterThanOrEqualToSuperview().priority(.keepWindowSize) make.bottom.lessThanOrEqualToSuperview().priority(.keepWindowSize) } } // MARK: Dragging private var vecToCenter: CGVector? override func mouseDown(with event: NSEvent) { let location = lyricsView.convert(event.locationInWindow, from: nil) vecToCenter = CGVector(from: location, to: lyricsView.bounds.center) } override func mouseDragged(with event: NSEvent) { guard defaults[.desktopLyricsDraggable], let vecToCenter = vecToCenter, let window = window else { return } let bounds = window.frame var center = event.locationInWindow + vecToCenter let centerInScreen = window.convertToScreen(CGRect(origin: center, size: .zero)).origin if let screen = NSScreen.screens.first(where: { $0.frame.contains(centerInScreen) }), screen != window.screen { updateWindowFrame(toScreen: screen, animate: false) center = window.convertFromScreen(CGRect(origin: centerInScreen, size: .zero)).origin return } var xFactor = (center.x / bounds.width).clamped(to: 0...1) var yFactor = (1 - center.y / bounds.height).clamped(to: 0...1) if abs(center.x - bounds.width / 2) < 8 { xFactor = 0.5 } if abs(center.y - bounds.height / 2) < 8 { yFactor = 0.5 } defaults[.desktopLyricsXPositionFactor] = xFactor defaults[.desktopLyricsYPositionFactor] = yFactor makeConstraints() window.layoutIfNeeded() } } private extension NSScreen { var isFullScreen: Bool { guard let windowInfoList = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else { return false } return !windowInfoList.contains { info in guard info[kCGWindowOwnerName as String] as? String == "Window Server", info[kCGWindowName as String] as? String == "Menubar", let boundsDict = info[kCGWindowBounds as String] as? NSDictionary as CFDictionary?, let bounds = CGRect(dictionaryRepresentation: boundsDict) else { return false } return frame.contains(bounds) } } } private extension ConstraintMakerEditable { @discardableResult func safeMultipliedBy(_ amount: ConstraintMultiplierTarget) -> ConstraintMakerEditable { var factor = amount.constraintMultiplierTargetValue if factor.isZero { factor = .leastNonzeroMagnitude } return multipliedBy(factor) } } extension ConstraintPriority { static let windowSizeStayPut = ConstraintPriority(NSLayoutConstraint.Priority.windowSizeStayPut.rawValue) static let keepWindowSize = ConstraintPriority.windowSizeStayPut.advanced(by: -1) }
81c868f82bbe1e6123a206430437cb7a
41.367816
136
0.640622
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
refs/heads/master
iOSDFULibrary/Classes/Utilities/Data.swift
bsd-3-clause
1
/* * Copyright (c) 2019, Nordic Semiconductor * 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. * * 3. Neither the name of the copyright holder 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 Foundation // Inspired by: https://stackoverflow.com/a/38024025/2115352 extension Data { /// Converts the required number of bytes, starting from `offset` /// to the value of return type. /// /// - parameter offset: The offset from where the bytes are to be read. /// - returns: The value of type of the return type. func asValue<R>(offset: Int = 0) -> R { let length = MemoryLayout<R>.size #if swift(>=5.0) return subdata(in: offset ..< offset + length).withUnsafeBytes { $0.load(as: R.self) } #else return subdata(in: offset ..< offset + length).withUnsafeBytes { $0.pointee } #endif } } // Source: http://stackoverflow.com/a/35201226/2115352 extension Data { /// Returns the Data as hexadecimal string. var hexString: String { var array: [UInt8] = [] #if swift(>=5.0) withUnsafeBytes { array.append(contentsOf: $0) } #else withUnsafeBytes { array.append(contentsOf: getByteArray($0)) } #endif return array.reduce("") { (result, byte) -> String in result + String(format: "%02x", byte) } } private func getByteArray(_ pointer: UnsafePointer<UInt8>) -> [UInt8] { let buffer = UnsafeBufferPointer<UInt8>(start: pointer, count: count) return [UInt8](buffer) } } // Source: http://stackoverflow.com/a/42241894/2115352 public protocol DataConvertible { static func + (lhs: Data, rhs: Self) -> Data static func += (lhs: inout Data, rhs: Self) } extension DataConvertible { public static func + (lhs: Data, rhs: Self) -> Data { var value = rhs let data = withUnsafePointer(to: &value) { (pointer) -> Data in Data(buffer: UnsafeBufferPointer(start: pointer, count: 1)) } return lhs + data } public static func += (lhs: inout Data, rhs: Self) { lhs = lhs + rhs } } extension UInt8 : DataConvertible { } extension UInt16 : DataConvertible { } extension UInt32 : DataConvertible { } extension Int : DataConvertible { } extension Float : DataConvertible { } extension Double : DataConvertible { } extension String : DataConvertible { public static func + (lhs: Data, rhs: String) -> Data { guard let data = rhs.data(using: .utf8) else { return lhs} return lhs + data } } extension Data : DataConvertible { public static func + (lhs: Data, rhs: Data) -> Data { var data = Data() data.append(lhs) data.append(rhs) return data } }
1b076cbee5fa5e9646984ef7f77711f2
31.453846
94
0.662716
false
false
false
false
dangnguyenhuu/JSQMessagesSwift
refs/heads/master
Sources/Views/JSQMessagesToolbarContentView.swift
apache-2.0
1
// // JSQMessagesToolbarContentView.swift // JSQMessagesViewController // // Created by Sylvain FAY-CHATELARD on 20/08/2015. // Copyright (c) 2015 Dviance. All rights reserved. // import UIKit let kJSQMessagesToolbarContentViewHorizontalSpacingDefault: CGFloat = 8; open class JSQMessagesToolbarContentView: UIView { @IBOutlet fileprivate(set) open var textView: JSQMessagesComposerTextView! @IBOutlet var leftBarButtonContainerView: UIView! @IBOutlet var leftBarButtonContainerViewWidthConstraint: NSLayoutConstraint! @IBOutlet var rightBarButtonContainerView: UIView! @IBOutlet var rightBarButtonContainerViewWidthConstraint: NSLayoutConstraint! @IBOutlet var leftHorizontalSpacingConstraint: NSLayoutConstraint! @IBOutlet var rightHorizontalSpacingConstraint: NSLayoutConstraint! open override var backgroundColor: UIColor? { didSet { self.leftBarButtonContainerView?.backgroundColor = backgroundColor self.rightBarButtonContainerView?.backgroundColor = backgroundColor } } open dynamic var leftBarButtonItem: UIButton? { willSet { self.leftBarButtonItem?.removeFromSuperview() if let newValue = newValue { if newValue.frame.equalTo(CGRect.zero) { newValue.frame = self.leftBarButtonContainerView.bounds } self.leftBarButtonContainerView.isHidden = false self.leftHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault self.leftBarButtonItemWidth = newValue.frame.width newValue.translatesAutoresizingMaskIntoConstraints = false self.leftBarButtonContainerView.addSubview(newValue) self.leftBarButtonContainerView.jsq_pinAllEdgesOfSubview(newValue) self.setNeedsUpdateConstraints() return } self.leftHorizontalSpacingConstraint.constant = 0 self.leftBarButtonItemWidth = 0 self.leftBarButtonContainerView.isHidden = true } } var leftBarButtonItemWidth: CGFloat { get { return self.leftBarButtonContainerViewWidthConstraint.constant } set { self.leftBarButtonContainerViewWidthConstraint.constant = newValue self.setNeedsUpdateConstraints() } } open dynamic var rightBarButtonItem: UIButton? { willSet { self.rightBarButtonItem?.removeFromSuperview() if let newValue = newValue { if newValue.frame.equalTo(CGRect.zero) { newValue.frame = self.rightBarButtonContainerView.bounds } self.rightBarButtonContainerView.isHidden = false self.rightHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault self.rightBarButtonItemWidth = newValue.frame.width newValue.translatesAutoresizingMaskIntoConstraints = false self.rightBarButtonContainerView.addSubview(newValue) self.rightBarButtonContainerView.jsq_pinAllEdgesOfSubview(newValue) self.setNeedsUpdateConstraints() return } self.rightHorizontalSpacingConstraint.constant = 0 self.rightBarButtonItemWidth = 0 self.rightBarButtonContainerView.isHidden = true } } var rightBarButtonItemWidth: CGFloat { get { return self.rightBarButtonContainerViewWidthConstraint.constant } set { self.rightBarButtonContainerViewWidthConstraint.constant = newValue self.setNeedsUpdateConstraints() } } open class func nib() -> UINib { return UINib(nibName: JSQMessagesToolbarContentView.jsq_className, bundle: Bundle(for: JSQMessagesToolbarContentView.self)) } // MARK: - Initialization open override func awakeFromNib() { super.awakeFromNib() self.translatesAutoresizingMaskIntoConstraints = false self.leftHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault self.rightHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault self.backgroundColor = UIColor.clear } // MARK: - UIView overrides open override func setNeedsDisplay() { super.setNeedsDisplay() self.textView?.setNeedsDisplay() } }
46442fffc2539a613d91724fed7d8339
32.373333
131
0.629245
false
false
false
false
haskellswift/swift-package-manager
refs/heads/master
Sources/Basic/CollectionAlgorithms.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright 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 Swift project authors */ extension BidirectionalCollection where Iterator.Element : Comparable { /// Returns the index of the last occurrence of `element` or nil if none. /// /// - Parameters: /// - start: If provided, the `start` index limits the search to a suffix of the collection. // // FIXME: This probably shouldn't take the `from` parameter, the pattern in // the standard library is to use slices for that. public func rindex(of element: Iterator.Element, from start: Index? = nil) -> Index? { let firstIdx = start ?? startIndex var i = endIndex while i > firstIdx { self.formIndex(before: &i) if self[i] == element { return i } } return nil } }
36b55969d8bc43512c35af7d8e4b8083
34.966667
98
0.650602
false
false
false
false
Instagram/IGListKit
refs/heads/main
Examples/Examples-iOS/IGListKitExamples/SectionControllers/DemoSectionController.swift
mit
1
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import IGListKit import UIKit final class DemoItem: NSObject { let name: String let controllerClass: UIViewController.Type let controllerIdentifier: String? init( name: String, controllerClass: UIViewController.Type, controllerIdentifier: String? = nil ) { self.name = name self.controllerClass = controllerClass self.controllerIdentifier = controllerIdentifier } } extension DemoItem: ListDiffable { func diffIdentifier() -> NSObjectProtocol { return name as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { if self === object { return true } guard let object = object as? DemoItem else { return false } return controllerClass == object.controllerClass && controllerIdentifier == object.controllerIdentifier } } final class DemoSectionController: ListSectionController { private var object: DemoItem? override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { let cell: LabelCell = collectionContext.dequeueReusableCell(for: self, at: index) cell.text = object?.name return cell } override func didUpdate(to object: Any) { self.object = object as? DemoItem } override func didSelectItem(at index: Int) { if let identifier = object?.controllerIdentifier { let storyboard = UIStoryboard(name: "Demo", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: identifier) controller.title = object?.name viewController?.navigationController?.pushViewController(controller, animated: true) } else if let controller = object?.controllerClass.init() { controller.title = object?.name viewController?.navigationController?.pushViewController(controller, animated: true) } } }
aa043c22d46c378d4ccde4ea64010af8
30.09589
111
0.681057
false
false
false
false
toggl/superday
refs/heads/develop
teferi/Models/AnnotatedEvent.swift
bsd-3-clause
1
import Foundation struct AnnotatedEvent { let startTime: Date let endTime: Date let type: MotionEventType let location: Location let subEvents: [MotionEvent] var duration: TimeInterval { return endTime.timeIntervalSince(startTime) } } let MAX_MERGING_GAP: TimeInterval = 60 * 15 let MAX_MERGING_DISTANCE: Double = 0.5 extension AnnotatedEvent { init (motionEvent: MotionEvent, location: Location) { self.startTime = motionEvent.start self.endTime = motionEvent.end self.type = motionEvent.type self.location = location self.subEvents = [motionEvent] } func merging(_ newEvent: AnnotatedEvent) -> AnnotatedEvent { return AnnotatedEvent( startTime: self.startTime, endTime: newEvent.endTime, type: self.type, location: self.location, subEvents: self.subEvents + newEvent.subEvents ) } func with(endTime: Date) -> AnnotatedEvent { return AnnotatedEvent( startTime: self.startTime, endTime: endTime, type: self.type, location: self.location, subEvents: self.subEvents ) } func canBeMergedWith(event: AnnotatedEvent) -> Bool { return (event.startTime.timeIntervalSince(self.endTime) < MAX_MERGING_GAP || self.startTime.timeIntervalSince(event.endTime) < MAX_MERGING_GAP) && event.type == self.type // We should consider the possibility of taking the distance into account for most categories (not for movement) } } extension AnnotatedEvent: CustomStringConvertible { var description: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let timeInterval = endTime.timeIntervalSince(startTime) let minutes = floor(timeInterval / 60) let seconds = timeInterval - minutes * 60 return "\(dateFormatter.string(from: startTime)) - \(dateFormatter.string(from: endTime)) : \(type) \(Int(minutes))m \(Int(seconds))s" } }
46045f97b1abb48cb23bea7fbc8c394e
26.871795
142
0.627415
false
false
false
false
xuzhuoyi/EmbControl
refs/heads/master
embcontrol/ytcpsocket.swift
gpl-3.0
1
/* Copyright (c) <2014>, skysent 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. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by skysent. 4. Neither the name of the skysent 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 skysent ''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 skysent 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 Foundation @asmname("ytcpsocket_connect") func c_ytcpsocket_connect(host:UnsafePointer<Int8>,port:Int32,timeout:Int32) -> Int32 @asmname("ytcpsocket_close") func c_ytcpsocket_close(fd:Int32) -> Int32 @asmname("ytcpsocket_send") func c_ytcpsocket_send(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32) -> Int32 @asmname("ytcpsocket_pull") func c_ytcpsocket_pull(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32) -> Int32 @asmname("ytcpsocket_listen") func c_ytcpsocket_listen(addr:UnsafePointer<Int8>,port:Int32)->Int32 @asmname("ytcpsocket_accept") func c_ytcpsocket_accept(onsocketfd:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32 public class TCPClient:YSocket{ /* * connect to server * return success or fail with message */ public func connect(timeout t:Int)->(Bool,String){ var rs:Int32=c_ytcpsocket_connect(self.addr, port: Int32(self.port),timeout: Int32(t)) if rs>0{ self.fd=rs return (true,"connect success") }else{ switch rs{ case -1: return (false,"qeury server fail") case -2: return (false,"connection closed") case -3: return (false,"connect timeout") default: return (false,"unknow err.") } } } /* * close socket * return success or fail with message */ public func close()->(Bool,String){ if let fd:Int32=self.fd{ c_ytcpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } /* * send data * return success or fail with message */ public func send(data d:[UInt8])->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_ytcpsocket_send(fd, buff: d, len: Int32(d.count)) if Int(sendsize)==d.count{ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * send string * return success or fail with message */ public func send(str s:String)->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_ytcpsocket_send(fd, buff: s, len: Int32(strlen(s))) if sendsize==Int32(strlen(s)){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * * send nsdata */ public func send(data d:NSData)->(Bool,String){ if let fd:Int32=self.fd{ var buff:[UInt8] = [UInt8](count:d.length,repeatedValue:0x0) d.getBytes(&buff, length: d.length) var sendsize:Int32=c_ytcpsocket_send(fd, buff: buff, len: Int32(d.length)) if sendsize==Int32(d.length){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * read data with expect length * return success or fail with message */ public func read(expectlen:Int)->[UInt8]?{ if let fd:Int32 = self.fd{ var buff:[UInt8] = [UInt8](count:expectlen,repeatedValue:0x0) var readLen:Int32=c_ytcpsocket_pull(fd, buff: &buff, len: Int32(expectlen)) if readLen<=0{ return nil } var rs=buff[0...Int(readLen-1)] var data:[UInt8] = Array(rs) return data } return nil } } public class TCPServer:YSocket{ public func listen()->(Bool,String){ var fd:Int32=c_ytcpsocket_listen(self.addr, port: Int32(self.port)) if fd>0{ self.fd=fd return (true,"listen success") }else{ return (false,"listen fail") } } public func accept()->TCPClient?{ if let serferfd=self.fd{ var buff:[Int8] = [Int8](count:16,repeatedValue:0x0) var port:Int32=0 let clientfd:Int32=c_ytcpsocket_accept(serferfd, ip: &buff,port: &port) if clientfd<0{ return nil } let tcpClient:TCPClient=TCPClient() tcpClient.fd=clientfd tcpClient.port=Int(port) if let addr=String(CString: buff, encoding: NSUTF8StringEncoding){ tcpClient.addr=addr } return tcpClient } return nil } public func close()->(Bool,String){ if let fd:Int32=self.fd{ c_ytcpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } }
6ba7d967e88b1eb7e669a8590d2f7bb8
34.32973
130
0.607864
false
false
false
false
gu704823/DYTV
refs/heads/master
dytv/dytv/uicollectionbaseview.swift
mit
1
// // uicollectionbaseview.swift // dytv // // Created by jason on 2017/3/29. // Copyright © 2017年 jason. All rights reserved. // import UIKit class uicollectionbaseviewcell: UICollectionViewCell { @IBOutlet weak var iconimageview: UIImageView! @IBOutlet weak var nicknamelabel: UILabel! @IBOutlet weak var onlinebtn: UIButton! var anchor:anchormodel?{ didSet{ guard let anchor = anchor else{ return } //取出在线人数 var onlinepeople:String = "" if anchor.online>10000{ onlinepeople = "\(anchor.online/10000)万人在线" }else{ onlinepeople = "\(anchor.online)人在线" } onlinebtn.setTitle(onlinepeople, for: .normal) nicknamelabel.text = anchor.nickname let url = URL(string: anchor.vertical_src) iconimageview.kf.setImage(with: url) } } }
3c4d99cd258ba4342d1b1a466dca52f5
26.882353
59
0.581224
false
false
false
false
russellladd/Walker
refs/heads/master
Finished Project/Walker/MyWalksViewController.swift
gpl-2.0
1
// // ViewController.swift // Walker // // Created by Russell Ladd on 3/28/15. // Copyright (c) 2015 GRL5. All rights reserved. // import UIKit import CoreData class MyWalksViewController: UIViewController, NSFetchedResultsControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, OnWalkViewControllerDelegate { // MARK: Model var context: NSManagedObjectContext! private lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "Walk") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)] let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil) controller.delegate = self return controller }() func controllerDidChangeContent(controller: NSFetchedResultsController) { collectionView.reloadData() updateNoWalksLabelHidden() } // MARK: View @IBOutlet private weak var collectionView: UICollectionView! @IBOutlet private weak var noWalksLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() do { try fetchedResultsController.performFetch() } catch _ { } collectionView.reloadData() updateNoWalksLabelHidden() } func updateNoWalksLabelHidden() { noWalksLabel.hidden = fetchedResultsController.fetchedObjects!.count > 0 } // MARK: Collection view data source func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return fetchedResultsController.fetchedObjects!.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Walk Cell", forIndexPath: indexPath) as! WalkCell let walk = fetchedResultsController.objectAtIndexPath(indexPath) as! Walk cell.numberOfStepsLabel.text = walk.numberOfSteps.description cell.circleView.alpha = CGFloat(0.5 + 0.5 * walk.fractionToGoal()) return cell } // MARK: Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segue.identifier! { case "Start Walk": let navigationController = segue.destinationViewController as! UINavigationController let onWalkViewController = navigationController.viewControllers.first as! OnWalkViewController onWalkViewController.context = context onWalkViewController.delegate = self default: assertionFailure("Unknown segue identifier") } } // MARK: Walk view controller delegate func onWalkViewControllerDidCancel() { dismissViewControllerAnimated(true, completion: nil) } func onWalkViewController(onWalkViewController: OnWalkViewController, didFinishWithWalk walk: Walk) { dismissViewControllerAnimated(true, completion: nil) } }
65d93cb5b9b2f0a6e094451d4c0dfccf
31.417476
167
0.673255
false
false
false
false
dtp5/OneApp
refs/heads/master
Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel.swift
bsd-3-clause
1
// // LTMorphingLabel.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2014 Lex Tang, http://LexTang.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the “Software”), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit import QuartzCore let LTMorphingPhaseStart = "Start" let LTMorphingPhaseAppear = "Appear" let LTMorphingPhaseDisappear = "Disappear" let LTMorphingPhaseDraw = "Draw" let LTMorphingPhaseManipulateProgress = "ManipulateProgress" let LTMorphingPhaseSkipFrames = "SkipFrames" public enum LTMorphingEffect: Int, Printable { case Scale = 0 case Evaporate case Fall case Pixelate case Sparkle case Burn case Anvil static let allValues = ["Scale", "Evaporate", "Fall", "Pixelate", "Sparkle", "Burn", "Anvil"] public var description: String { get { switch self { case .Evaporate: return "Evaporate" case .Fall: return "Fall" case .Pixelate: return "Pixelate" case .Sparkle: return "Sparkle" case .Burn: return "Burn" case .Anvil: return "Anvil" default: return "Scale" } } } } struct LTCharacterLimbo: DebugPrintable { let char: Character var rect: CGRect var alpha: CGFloat var size: CGFloat var drawingProgress: CGFloat = 0.0 var debugDescription: String { get { return "Character: '\(char)'" + "drawIn (\(rect.origin.x), \(rect.origin.y), " + "\(rect.size.width)x\(rect.size.height) " + "with alpha \(alpha) " + "and \(size)pt font." } } } typealias LTMorphingStartClosure = (Void) -> Void typealias LTMorphingEffectClosure = (Character, index: Int, progress: Float) -> LTCharacterLimbo typealias LTMorphingDrawingClosure = LTCharacterLimbo -> Bool typealias LTMorphingManipulateProgressClosure = (index: Int, progress: Float, isNewChar: Bool) -> Float typealias LTMorphingSkipFramesClosure = (Void) -> Int @objc public protocol LTMorphingLabelDelegate { optional func morphingDidStart(label: LTMorphingLabel) optional func morphingDidComplete(label: LTMorphingLabel) optional func morphingOnProgress(label: LTMorphingLabel, _ progress: Float) } // MARK: - LTMorphingLabel @IBDesignable public class LTMorphingLabel: UILabel { public var morphingProgress: Float = 0.0 public var morphingDuration: Float = 0.6 public var morphingCharacterDelay: Float = 0.026 public var morphingEffect: LTMorphingEffect = .Scale public var delegate: LTMorphingLabelDelegate? var _startClosures = Dictionary<String, LTMorphingStartClosure>() var _effectClosures = Dictionary<String, LTMorphingEffectClosure>() var _drawingClosures = Dictionary<String, LTMorphingDrawingClosure>() var _progressClosures = Dictionary<String, LTMorphingManipulateProgressClosure>() var _skipFramesClosures = Dictionary<String, LTMorphingSkipFramesClosure>() var _diffResults = Array<LTCharacterDiffResult>() var _originText = "" var _currentFrame = 0 var _totalFrames = 0 var _totalDelayFrames = 0 var _totalWidth: Float = 0.0 let _characterOffsetYRatio = 1.1 var _originRects = Array<CGRect>() var _newRects = Array<CGRect>() var _charHeight: CGFloat = 0.0 var _skipFramesCount: Int = 0 #if !TARGET_INTERFACE_BUILDER override public var text:String! { get { return super.text } set { _originText = text ?? "" _diffResults = _originText >> newValue super.text = newValue ?? "" morphingProgress = 0.0 _currentFrame = 0 _totalFrames = 0 self.setNeedsLayout() if _originText != text { displayLink.paused = false if let closure = _startClosures["\(morphingEffect.description)\(LTMorphingPhaseStart)"] { return closure() } if let didStart = delegate?.morphingDidStart { didStart(self) } } } } public override func setNeedsLayout() { super.setNeedsLayout() _originRects = rectsOfEachCharacter(_originText, withFont: self.font) _newRects = rectsOfEachCharacter(self.text ?? "", withFont: self.font) } override public var bounds:CGRect { get { return super.bounds } set { super.bounds = newValue self.setNeedsLayout() } } override public var frame:CGRect { get { return super.frame } set { super.frame = newValue self.setNeedsLayout() } } #endif private lazy var displayLink: CADisplayLink = { let _displayLink = CADisplayLink( target: self, selector: Selector("_displayFrameTick")) _displayLink.addToRunLoop( NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) return _displayLink }() lazy var emitterView: LTEmitterView = { let _emitterView = LTEmitterView(frame: self.bounds) self.addSubview(_emitterView) return _emitterView }() } // MARK: - Animation extension extension LTMorphingLabel { func _displayFrameTick() { if displayLink.duration > 0.0 && _totalFrames == 0 { let frameRate = Float(displayLink.duration) / Float(displayLink.frameInterval) _totalFrames = Int(ceil(morphingDuration / frameRate)) let totalDelay = Float(countElements(self.text!)) * morphingCharacterDelay _totalDelayFrames = Int(ceil(totalDelay / frameRate)) } if _originText != text && _currentFrame++ < _totalFrames + _totalDelayFrames + 5 { morphingProgress += 1.0 / Float(_totalFrames) if let closure = self._skipFramesClosures["\(self.morphingEffect.description)\(LTMorphingPhaseSkipFrames)"] { if ++_skipFramesCount > closure() { _skipFramesCount = 0 setNeedsDisplay() } } else { setNeedsDisplay() } if let onProgress = delegate?.morphingOnProgress { onProgress(self, morphingProgress) } } else { displayLink.paused = true if let complete = delegate?.morphingDidComplete { complete(self) } } } // Could be enhanced by kerning text: // http://stackoverflow.com/questions/21443625/core-text-calculate-letter-frame-in-ios func rectsOfEachCharacter(textToDraw:String, withFont font:UIFont) -> Array<CGRect> { var charRects = Array<CGRect>() var leftOffset: CGFloat = 0.0 if _charHeight == 0.0 { _charHeight = "LEX".sizeWithAttributes([NSFontAttributeName: self.font]).height } var topOffset = (self.bounds.size.height - _charHeight) / 2.0 for (i, char) in enumerate(textToDraw) { let charSize = String(char).sizeWithAttributes([NSFontAttributeName: self.font]) charRects.append(CGRect(origin: CGPointMake(leftOffset, topOffset), size: charSize)) leftOffset += charSize.width } _totalWidth = Float(leftOffset) var stringLeftOffSet: CGFloat = 0.0 switch textAlignment { case .Center: stringLeftOffSet = CGFloat((Float(bounds.size.width) - _totalWidth) / 2.0) case .Right: stringLeftOffSet = CGFloat(Float(bounds.size.width) - _totalWidth) default: () } var offsetedCharRects = Array<CGRect>() for r in charRects { offsetedCharRects.append(CGRectOffset(r, stringLeftOffSet, 0.0)) } return offsetedCharRects } func limboOfOriginalCharacter( char: Character, index: Int, progress: Float) -> LTCharacterLimbo { var currentRect = _originRects[index] let oriX = Float(currentRect.origin.x) var newX = Float(currentRect.origin.x) let diffResult = _diffResults[index] var currentFontSize: CGFloat = font.pointSize var currentAlpha: CGFloat = 1.0 switch diffResult.diffType { // Move the character that exists in the new text to current position case .Move, .MoveAndAdd, .Same: newX = Float(_newRects[index + diffResult.moveOffset].origin.x) currentRect.origin.x = CGFloat(LTEasing.easeOutQuint(progress, oriX, newX - oriX)) default: // Otherwise, remove it // Override morphing effect with closure in extenstions if let closure = _effectClosures["\(morphingEffect.description)\(LTMorphingPhaseDisappear)"] { return closure(char, index: index, progress: progress) } else { // And scale it by default currentFontSize = font.pointSize - CGFloat(LTEasing.easeOutQuint(progress, 0, Float(font.pointSize))) currentAlpha = CGFloat(1.0 - progress) currentRect = CGRectOffset(_originRects[index], 0, CGFloat(font.pointSize - currentFontSize) / CGFloat(_characterOffsetYRatio)) } } return LTCharacterLimbo( char: char, rect: currentRect, alpha: currentAlpha, size: currentFontSize, drawingProgress: 0.0 ) } func limboOfNewCharacter( char: Character, index: Int, progress: Float) -> LTCharacterLimbo { var currentRect = _newRects[index] var newX = Float(currentRect.origin.x) var currentFontSize = CGFloat(LTEasing.easeOutQuint(progress, 0, Float(font.pointSize))) var currentAlpha:CGFloat = CGFloat(morphingProgress) var yOffset: CGFloat = 0.0 if let closure = _effectClosures["\(morphingEffect.description)\(LTMorphingPhaseAppear)"] { return closure(char, index: index, progress: progress) } else { currentFontSize = CGFloat(LTEasing.easeOutQuint(progress, 0.0, Float(font.pointSize))) let yOffset = CGFloat(font.pointSize - currentFontSize) / CGFloat(_characterOffsetYRatio) return LTCharacterLimbo( char: char, rect: CGRectOffset(currentRect, 0.0, yOffset), alpha: CGFloat(morphingProgress), size: currentFontSize, drawingProgress: 0.0 ) } } func limboOfCharacters() -> Array<LTCharacterLimbo> { let fontSize = font.pointSize var limbo = Array<LTCharacterLimbo>() // Iterate original characters for (i, character) in enumerate(_originText) { var progress: Float = 0.0 if let closure = _progressClosures["\(morphingEffect.description)\(LTMorphingPhaseManipulateProgress)"] { progress = closure(index: i, progress: morphingProgress, isNewChar: false) } else { progress = min(1.0, max(0.0, morphingProgress + morphingCharacterDelay * Float(i))) } let limboOfCharacter = limboOfOriginalCharacter(character, index: i, progress: progress) limbo.append(limboOfCharacter) } // Add new characters for (i, character) in enumerate(text!) { if i >= countElements(_diffResults) { break } var progress: Float = 0.0 if let closure = _progressClosures["\(morphingEffect.description)\(LTMorphingPhaseManipulateProgress)"] { progress = closure(index: i, progress: morphingProgress, isNewChar: true) } else { progress = min(1.0, max(0.0, morphingProgress - morphingCharacterDelay * Float(i))) } // Don't draw character that already exists let diffResult = _diffResults[i] if diffResult.skip { continue } switch diffResult.diffType { case .MoveAndAdd, .Replace, .Add, .Delete: let limboOfCharacter = limboOfNewCharacter(character, index: i, progress: progress) limbo.append(limboOfCharacter) default: () } } return limbo } } // MARK: - Drawing extension extension LTMorphingLabel { override public func didMoveToSuperview() { if let s = self.text { self.text = s } // Load all morphing effects for effectName: String in LTMorphingEffect.allValues { let effectFunc = Selector("\(effectName)Load") if respondsToSelector(effectFunc) { NSTimer(timeInterval: 0.0, target: self, selector: effectFunc, userInfo: nil, repeats: false).fire() } } } override public func drawTextInRect(rect: CGRect) { for charLimbo in limboOfCharacters() { var charRect:CGRect = charLimbo.rect let willAvoidDefaultDrawing: Bool = { if let closure = self._drawingClosures["\(self.morphingEffect.description)\(LTMorphingPhaseDraw)"] { return closure($0) } return false }(charLimbo) if !willAvoidDefaultDrawing { let s = String(charLimbo.char) s.drawInRect(charRect, withAttributes: [ NSFontAttributeName: self.font.fontWithSize(charLimbo.size), NSForegroundColorAttributeName: self.textColor.colorWithAlphaComponent(charLimbo.alpha) ]) } } } } // MARK: - LTEmitterView struct LTEmitter { let layer: CAEmitterLayer = { let _layer = CAEmitterLayer() _layer.emitterPosition = CGPointMake(10, 10) _layer.emitterSize = CGSizeMake(10, 1) _layer.renderMode = kCAEmitterLayerOutline _layer.emitterShape = kCAEmitterLayerLine return _layer }() let cell: CAEmitterCell = { let image = UIImage(named:"Sparkle")!.CGImage let _cell = CAEmitterCell() _cell.name = "sparkle" _cell.birthRate = 150.0 _cell.velocity = 50.0 _cell.velocityRange = -80.0 _cell.lifetime = 0.16 _cell.lifetimeRange = 0.1 _cell.emissionLongitude = CGFloat(M_PI_2 * 2.0) _cell.emissionRange = CGFloat(M_PI_2 * 2.0) _cell.contents = image _cell.scale = 0.1 _cell.yAcceleration = 100 _cell.scaleSpeed = -0.06 _cell.scaleRange = 0.1 return _cell }() var _duration: Float = 0.6 init(name: String, duration: Float) { cell.name = name _duration = duration } func play() { if let cells = layer.emitterCells { if cells.count > 0 { return } } layer.emitterCells = [cell] let d: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(_duration * Float(NSEC_PER_SEC))) dispatch_after(d, dispatch_get_main_queue()) { self.layer.birthRate = 0.0 } } func stop() { if (nil != layer.superlayer) { layer.removeFromSuperlayer() } } func update(configureClosure: LTEmitterConfigureClosure? = Optional.None) -> LTEmitter { if let closure = configureClosure { configureClosure!(self.layer, self.cell) } return self } } typealias LTEmitterConfigureClosure = (CAEmitterLayer, CAEmitterCell) -> Void class LTEmitterView: UIView { lazy var emitters: Dictionary<String, LTEmitter> = { var _emitters = Dictionary<String, LTEmitter>() return _emitters }() func createEmitter(name: String, duration: Float, configureClosure: LTEmitterConfigureClosure? = Optional.None) -> LTEmitter { var emitter: LTEmitter if let e = emitterByName(name) { emitter = e } else { emitter = LTEmitter(name: name, duration: duration) if let closure = configureClosure { configureClosure!(emitter.layer, emitter.cell) } layer.addSublayer(emitter.layer) emitters.updateValue(emitter, forKey: name) } return emitter } func emitterByName(name: String) -> LTEmitter? { if let e = emitters[name] { return e } return Optional.None } func removeAllEmit() { for (name, emitter) in emitters { emitter.layer.removeFromSuperlayer() } emitters.removeAll(keepCapacity: false) } }
87f8e3464b784b99156184be0dc315c6
32.594203
130
0.585796
false
false
false
false
qualaroo/QualarooSDKiOS
refs/heads/master
QualarooTests/UserResponseAdapterSpec.swift
mit
1
// // UserResponseAdapterSpec.swift // QualarooTests // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class UserResponseAdapterSpec: QuickSpec { override func spec() { super.spec() describe("UserResponseAdapter") { let adapter = UserResponseAdapter() let answerOneModel = AnswerResponse(id: 111, alias: "answer_111_alias", text: "Answer111") let answerTwoModel = AnswerResponse(id: 222, alias: "answer_222_alias", text: "Answer222") let answerThreeModel = AnswerResponse(id: 333, alias: "answer_333_alias", text: "Answer333") let questionOneModel = QuestionResponse(id: 11, alias: "question_11_alias", answerList: [answerOneModel]) let questionTwoModel = QuestionResponse(id: 11, alias: "question_22_alias", answerList: [answerTwoModel, answerThreeModel]) let questionThreeModel = QuestionResponse(id: 33, alias: nil, answerList: [answerOneModel]) context("LeadGenResponse") { it("creates UserResponse from leadGen response with one question") { let leadGenModel = LeadGenResponse(id: 1, alias: "leadGen_1_alias", questionList: [questionOneModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias")) expect(userResponse.getFilledElements()).to(equal(["question_11_alias"])) expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111")) } it("creates UserResponse from leadGen response with two questions") { let leadGenModel = LeadGenResponse(id: 1, alias: "leadGen_1_alias", questionList: [questionOneModel, questionTwoModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias")) expect(userResponse.getFilledElements()).to(equal(["question_11_alias", "question_22_alias"])) expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111")) expect(userResponse.getElementText("question_22_alias")).to(equal("Answer222")) } it("skips questions with no alias") { let leadGenModel = LeadGenResponse(id: 1, alias: "leadGen_1_alias", questionList: [questionOneModel, questionTwoModel, questionThreeModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias")) expect(userResponse.getFilledElements()).to(equal(["question_11_alias", "question_22_alias"])) expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111")) expect(userResponse.getElementText("question_22_alias")).to(equal("Answer222")) } it("doesn't create UserResponse if there is empty alias") { let leadGenModel = LeadGenResponse(id: 1, alias: nil, questionList: [questionOneModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel) expect(userResponse).to(beNil()) } } context("QuestionResponse") { it("creates UserResponse from question response with one answer") { let responseModel = NodeResponse.question(questionOneModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("question_11_alias")) expect(userResponse.getFilledElements()).to(equal(["answer_111_alias"])) expect(userResponse.getElementText("answer_111_alias")).to(equal("Answer111")) } it("creates UserResponse from question response with two answers") { let responseModel = NodeResponse.question(questionTwoModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("question_22_alias")) expect(userResponse.getFilledElements()).to(equal(["answer_222_alias", "answer_333_alias"])) expect(userResponse.getElementText("answer_222_alias")).to(equal("Answer222")) expect(userResponse.getElementText("answer_333_alias")).to(equal("Answer333")) } it("skips answers with no alias") { let answerModel = AnswerResponse(id: 444, alias: nil, text: "Answer444") let questionModel = QuestionResponse(id: 44, alias: "question_44_alias", answerList: [answerTwoModel, answerThreeModel, answerModel]) let responseModel = NodeResponse.question(questionModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("question_44_alias")) expect(userResponse.getFilledElements()).to(equal(["answer_222_alias", "answer_333_alias"])) expect(userResponse.getElementText("answer_222_alias")).to(equal("Answer222")) expect(userResponse.getElementText("answer_333_alias")).to(equal("Answer333")) } it("doesn't create UserResponse if there is empty alias") { let responseModel = NodeResponse.question(questionThreeModel) let userResponse = adapter.toUserResponse(responseModel) expect(userResponse).to(beNil()) } } } } }
e2f75b9fb19a3884183a6594c0a9d8f9
54.983471
116
0.581636
false
false
false
false
bastiangardel/EasyPayClientSeller
refs/heads/master
TB_Client_Seller/TB_Client_Seller/ViewControllerCheckouts.swift
mit
1
// // CheckoutsViewController.swift // TB_Client_Seller // // Created by Bastian Gardel on 21.06.16. // // Copyright © 2016 Bastian Gardel // // 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 import BButton import MBProgressHUD import SCLAlertView // ** Class ViewControllerCheckouts ** // // View Checkouts List Controller // // Author: Bastian Gardel // Version: 1.0 class ViewControllerCheckouts: UIViewController,UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var logoutButton: BButton! @IBOutlet weak var CheckoutsTable: UITableView! var httpsSession = HTTPSSession.sharedInstance var hud: MBProgressHUD? var checkoutlist: Array<CheckoutDTO>? var index: Int = 0 //View initialisation override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. logoutButton.color = UIColor.bb_dangerColorV2() logoutButton.setStyle(BButtonStyle.BootstrapV2) logoutButton.setType(BButtonType.Danger) logoutButton.addAwesomeIcon(FAIcon.FASignOut, beforeTitle: false) CheckoutsTable.delegate = self CheckoutsTable.dataSource = self hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud?.labelText = "Checkouts List Loading in progress" hud?.labelFont = UIFont(name: "HelveticaNeue", size: 30)! httpsSession.getListCheckout(){ (success: Bool, errorDescription:String, listCheckoutDTO : Array<CheckoutDTO>) in self.hud!.hide(true) let appearance = SCLAlertView.SCLAppearance( kTitleFont: UIFont(name: "HelveticaNeue", size: 30)!, kTextFont: UIFont(name: "HelveticaNeue", size: 30)!, kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 25)!, kWindowWidth: 500.0, kWindowHeight: 500.0, kTitleHeight: 50, showCloseButton: false ) if(success) { self.checkoutlist = listCheckoutDTO if(listCheckoutDTO.count == 0) { let alertView = SCLAlertView(appearance: appearance) alertView.addButton("Logout"){ self.httpsSession.logout() self.performSegueWithIdentifier("logoutSegue", sender: self) } alertView.showInfo("Checkouts List Info", subTitle: "Please, ask your administrator for a new checkout.") } self.CheckoutsTable.reloadData(); } else { let alertView = SCLAlertView(appearance: appearance) alertView.addButton("Logout"){ self.httpsSession.logout() self.performSegueWithIdentifier("logoutSegue", sender: self) } alertView.showError("Checkouts List Loading Error", subTitle: errorDescription) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Prepare transfer value for next view override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "checkoutMenuSegue") { let svc = segue.destinationViewController as! ViewControllerCheckoutMenu; svc.toPass = self.checkoutlist![index]; } } // ***** tableView Delegate ***** func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if checkoutlist != nil { return (checkoutlist?.count)! } return 0; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("checkoutCell", forIndexPath: indexPath) cell.textLabel?.text = (checkoutlist?[indexPath.row].name)! + " : " + (checkoutlist?[indexPath.row].uuid)! cell.backgroundColor = UIColor(colorLiteralRed: 0.88, green: 0.93, blue: 0.91, alpha: 0.7) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { index = indexPath.row self.performSegueWithIdentifier("checkoutMenuSegue", sender: self) } @IBAction func logoutAction(sender: AnyObject) { httpsSession.logout() self.performSegueWithIdentifier("logoutSegue", sender: self) } }
614896619c767ced02c33773fa1e644d
33.654321
120
0.65586
false
false
false
false
ryuichis/swift-lint
refs/heads/master
Sources/Lint/Reporter/HTMLReporter.swift
apache-2.0
2
/* Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import Source class HTMLReporter : Reporter { func handle(issues: [Issue]) -> String { if issues.isEmpty { return "" } var issuesText = """ <hr /> <table> <thead> <tr> <th>File</th> <th>Location</th> <th>Rule Identifier</th> <th>Rule Category</th> <th>Severity</th> <th>Message</th> </tr> </thead> <tbody> """ issuesText += issues.map({ $0.htmlString }).joined(separator: separator) issuesText += "</tbody></table>" return issuesText } func handle(numberOfTotalFiles: Int, issueSummary: IssueSummary) -> String { let numberOfIssueFiles = issueSummary.numberOfFiles var summaryHtml = """ <table> <thead> <tr> <th>Total Files</th> <th>Files with Issues</th> """ summaryHtml += Issue.Severity.allSeverities .map({ "<th>\($0.rawValue.capitalized)</th>" }).joined(separator: "\n") summaryHtml += """ </tr> </thead> <tbody> <tr> <td>\(numberOfTotalFiles)</td> <td>\(numberOfIssueFiles)</td> """ summaryHtml += Issue.Severity.allSeverities.map({ let count = issueSummary.numberOfIssues(withSeverity: $0) return "<th class=\"severity-\($0)\">\(count)</th>" }).joined(separator: "\n") summaryHtml += """ </tr> </tbody> </table> """ return summaryHtml } var header: String { return """ <!DOCTYPE html> <html> <head> <title>Yanagiba's swift-lint Report</title> <style type='text/css'> .severity-critical, .severity-major, .severity-minor, .severity-cosmetic { font-weight: bold; text-align: center; color: #BF0A30; } .severity-critical { background-color: #FFC200; } .severity-major { background-color: #FFD3A6; } .severity-minor { background-color: #FFEEB5; } .severity-cosmetic { background-color: #FFAAB5; } table { border: 2px solid gray; border-collapse: collapse; -moz-box-shadow: 3px 3px 4px #AAA; -webkit-box-shadow: 3px 3px 4px #AAA; box-shadow: 3px 3px 4px #AAA; } td, th { border: 1px solid #D3D3D3; padding: 4px 20px 4px 20px; } th { text-shadow: 2px 2px 2px white; border-bottom: 1px solid gray; background-color: #E9F4FF; } </style> </head> <body> <h1>Yanagiba's swift-lint report</h1> <hr /> """ } var footer: String { let versionInfo = "Yanagiba's \(SWIFT_LINT) v\(SWIFT_LINT_VERSION)" return """ <hr /> <p> \(Date().formatted) | Generated with <a href='http://yanagiba.org/swift-lint'>\(versionInfo)</a>. </p> </body> </html> """ } }
ff11a46d1b5ffcdcbcea8ea6474fa41e
24.708955
81
0.58926
false
false
false
false
rnapier/SwiftCheck
refs/heads/master
SwiftCheckTests/SimpleSpec.swift
mit
1
// // SimpleSpec.swift // SwiftCheck // // Created by Robert Widmann on 8/3/14. // Copyright (c) 2015 TypeLift. All rights reserved. // import XCTest import SwiftCheck public struct ArbitraryFoo { let x : Int let y : Int public static func create(x : Int) -> Int -> ArbitraryFoo { return { y in ArbitraryFoo(x: x, y: y) } } public var description : String { return "Arbitrary Foo!" } } extension ArbitraryFoo : Arbitrary { public static func arbitrary() -> Gen<ArbitraryFoo> { return Int.arbitrary().bind { i in return Int.arbitrary().bind { j in return Gen.pure(ArbitraryFoo(x: i, y: j)) } } } public static func shrink(x : ArbitraryFoo) -> [ArbitraryFoo] { return shrinkNone(x) } } class SimpleSpec : XCTestCase { func testAll() { property["Integer Equality is Reflexive"] = forAll { (i : Int8) in return i == i } property["Unsigned Integer Equality is Reflexive"] = forAll { (i : UInt8) in return i == i } property["Float Equality is Reflexive"] = forAll { (i : Float) in return i == i } property["Double Equality is Reflexive"] = forAll { (i : Double) in return i == i } property["String Equality is Reflexive"] = forAll { (s : String) in return s == s } property["ArbitraryFoo Properties are Reflexive"] = forAll { (i : ArbitraryFoo) in return i.x == i.x && i.y == i.y } } }
020a2a6bbeb14ddaf971beb6928642e0
19.279412
84
0.637418
false
false
false
false
crashoverride777/Swift-AdvertisingHelper
refs/heads/master
Example/SwiftyAdExample/GameScene.swift
mit
3
// // GameScene.swift // SwiftyAds // // Created by Dominik on 04/09/2015. import SpriteKit class GameScene: SKScene { // MARK: - Properties var coins = 0 private lazy var textLabel: SKLabelNode = self.childNode(withName: "textLabel") as! SKLabelNode private lazy var consentLabel: SKLabelNode = self.childNode(withName: "consentLabel") as! SKLabelNode private let swiftyAd: SwiftyAd = .shared private var touchCounter = 15 { didSet { guard touchCounter > 0 else { swiftyAd.isRemoved = true textLabel.text = "Removed all ads" return } textLabel.text = "Remove ads in \(touchCounter) clicks" } } // MARK: - Life Cycle override func didMove(to view: SKView) { textLabel.text = "Remove ads in \(touchCounter) clicks" consentLabel.isHidden = !swiftyAd.isRequiredToAskForConsent } // MARK: - Touches override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let node = atPoint(location) guard let viewController = view?.window?.rootViewController else { return } if node == consentLabel { let gameVC = view?.window?.rootViewController as! GameViewController swiftyAd.askForConsent(from: viewController) } defer { touchCounter -= 1 } swiftyAd.showInterstitial(from: viewController, withInterval: 2) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { } }
5f826fe2a7dfaa00c384f5260fd4bc1a
27.514286
105
0.573647
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Sync/Synchronizers/Downloader.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred private let log = Logger.syncLogger class BatchingDownloader<T: CleartextPayloadJSON> { let client: Sync15CollectionClient<T> let collection: String let prefs: Prefs var batch: [Record<T>] = [] func store(_ records: [Record<T>]) { self.batch += records } func retrieve() -> [Record<T>] { let ret = self.batch self.batch = [] return ret } var _advance: (() -> ())? func advance() { guard let f = self._advance else { return } self._advance = nil f() } init(collectionClient: Sync15CollectionClient<T>, basePrefs: Prefs, collection: String) { self.client = collectionClient self.collection = collection let branchName = "downloader." + collection + "." self.prefs = basePrefs.branch(branchName) log.info("Downloader configured with prefs '\(self.prefs.getBranchPrefix())'.") } static func resetDownloaderWithPrefs(_ basePrefs: Prefs, collection: String) { // This leads to stupid paths like 'profile.sync.synchronizer.history..downloader.history..'. // Sorry, but it's out in the world now... let branchName = "downloader." + collection + "." let prefs = basePrefs.branch(branchName) let lm = prefs.timestampForKey("lastModified") let bt = prefs.timestampForKey("baseTimestamp") log.debug("Resetting downloader prefs \(prefs.getBranchPrefix()). Previous values: \(lm), \(bt).") prefs.removeObjectForKey("nextOffset") prefs.removeObjectForKey("offsetNewer") prefs.removeObjectForKey("baseTimestamp") prefs.removeObjectForKey("lastModified") } /** * Clients should provide the same set of parameters alongside an `offset` as was * provided with the initial request. The only thing that varies in our batch fetches * is `newer`, so we track the original value alongside. */ var nextFetchParameters: (String, Timestamp)? { get { let o = self.prefs.stringForKey("nextOffset") let n = self.prefs.timestampForKey("offsetNewer") guard let offset = o, let newer = n else { return nil } return (offset, newer) } set (value) { if let (offset, newer) = value { self.prefs.setString(offset, forKey: "nextOffset") self.prefs.setTimestamp(newer, forKey: "offsetNewer") } else { self.prefs.removeObjectForKey("nextOffset") self.prefs.removeObjectForKey("offsetNewer") } } } // Set after each batch, from record timestamps. var baseTimestamp: Timestamp { get { return self.prefs.timestampForKey("baseTimestamp") ?? 0 } set (value) { self.prefs.setTimestamp(value ?? 0, forKey: "baseTimestamp") } } // Only set at the end of a batch, from headers. var lastModified: Timestamp { get { return self.prefs.timestampForKey("lastModified") ?? 0 } set (value) { self.prefs.setTimestamp(value ?? 0, forKey: "lastModified") } } /** * Call this when a significant structural server change has been detected. */ func reset() -> Success { self.baseTimestamp = 0 self.lastModified = 0 self.nextFetchParameters = nil self.batch = [] self._advance = nil return succeed() } func go(_ info: InfoCollections, limit: Int) -> Deferred<Maybe<DownloadEndState>> { guard let modified = info.modified(self.collection) else { log.debug("No server modified time for collection \(self.collection).") return deferMaybe(.NoNewData) } log.debug("Modified: \(modified); last \(self.lastModified).") if modified == self.lastModified { log.debug("No more data to batch-download.") return deferMaybe(.NoNewData) } // If the caller hasn't advanced after the last batch, strange things will happen -- // potentially looping indefinitely. Warn. if self._advance != nil && !self.batch.isEmpty { log.warning("Downloading another batch without having advanced. This might be a bug.") } return self.downloadNextBatchWithLimit(limit, infoModified: modified) } func advanceTimestampTo(_ timestamp: Timestamp) { log.debug("Advancing downloader lastModified from \(self.lastModified) to \(timestamp).") self.lastModified = timestamp } // We're either fetching from our current base timestamp with no offset, // or the timestamp we were using when we last saved an offset. func fetchParameters() -> (String?, Timestamp) { if let (offset, since) = self.nextFetchParameters { return (offset, since) } return (nil, max(self.lastModified, self.baseTimestamp)) } func downloadNextBatchWithLimit(_ limit: Int, infoModified: Timestamp) -> Deferred<Maybe<DownloadEndState>> { let (offset, since) = self.fetchParameters() log.debug("Fetching newer=\(since), offset=\(offset).") let fetch = self.client.getSince(since, sort: SortOption.OldestFirst, limit: limit, offset: offset) func handleFailure(_ err: MaybeErrorType) -> Deferred<Maybe<DownloadEndState>> { log.debug("Handling failure.") guard let badRequest = err as? BadRequestError<[Record<T>]>, badRequest.response.metadata.status == 412 else { // Just pass through the failure. return deferMaybe(err) } // Conflict. Start again. log.warning("Server contents changed during offset-based batching. Stepping back.") self.nextFetchParameters = nil return deferMaybe(.Interrupted) } func handleSuccess(_ response: StorageResponse<[Record<T>]>) -> Deferred<Maybe<DownloadEndState>> { log.debug("Handling success.") let nextOffset = response.metadata.nextOffset let responseModified = response.value.last?.modified // Queue up our metadata advance. We wait until the consumer has fetched // and processed this batch; they'll call .advance() on success. self._advance = { // Shift to the next offset. This might be nil, in which case… fine! // Note that we preserve the previous 'newer' value from the offset or the original fetch, // even as we update baseTimestamp. self.nextFetchParameters = nextOffset == nil ? nil : (nextOffset!, since) // If there are records, advance to just before the timestamp of the last. // If our next fetch with X-Weave-Next-Offset fails, at least we'll start here. // // This approach is only valid if we're fetching oldest-first. if let newBase = responseModified { log.debug("Advancing baseTimestamp to \(newBase) - 1") self.baseTimestamp = newBase - 1 } if nextOffset == nil { // If we can't get a timestamp from the header -- and we should always be able to -- // we fall back on the collection modified time in i/c, as supplied by the caller. // In any case where there is no racing writer these two values should be the same. // If they differ, the header should be later. If it's missing, and we use the i/c // value, we'll simply redownload some records. // All bets are off if we hit this case and are filtering somehow… don't do that. let lm = response.metadata.lastModifiedMilliseconds log.debug("Advancing lastModified to \(lm) ?? \(infoModified).") self.lastModified = lm ?? infoModified } } log.debug("Got success response with \(response.metadata.records) records.") // Store the incoming records for collection. self.store(response.value) return deferMaybe(nextOffset == nil ? .Complete : .Incomplete) } return fetch.bind { result in guard let response = result.successValue else { return handleFailure(result.failureValue!) } return handleSuccess(response) } } } public enum DownloadEndState: String { case Complete // We're done. Records are waiting for you. case Incomplete // applyBatch was called, and we think there are more records. case NoNewData // There were no records. case Interrupted // We got a 412 conflict when fetching the next batch. }
13d930272a3610a86ba7d5372ce530f7
39.380952
122
0.600021
false
false
false
false
J-Mendes/Bliss-Assignement
refs/heads/master
Bliss-Assignement/Bliss-Assignement/Core Layer/Network/Client/NetworkClient+Share.swift
lgpl-3.0
1
// // NetworkClient+Share.swift // Bliss-Assignement // // Created by Jorge Mendes on 13/10/16. // Copyright © 2016 Jorge Mendes. All rights reserved. // import Foundation extension NetworkClient { // MARK: - Dhare internal func shareViaEmail(email: String, url: String, completion: (response: AnyObject, error: NSError?) -> Void) { self.httpManager.POST(NetworkClient.baseUrl + "share?destination_email=" + email + "&content_url=" + url) .responseJSON { (response) -> Void in self.httpManager.manager?.session.invalidateAndCancel() let jsonParse: (json: AnyObject?, error: NSError?) = NetworkClient.jsonObjectFromData(response.data) switch response.result { case .Success: if let json: AnyObject = jsonParse.json { completion(response: json, error: nil) } else { completion(response: "", error: jsonParse.error) } break case .Failure: var errorCode: Int = -1 if let httpResponse: NSHTTPURLResponse = response.response { errorCode = httpResponse.statusCode } completion(response: "", error: NSError(domain: NetworkClient.domain + ".Share", code: errorCode, userInfo: nil)) break } } } }
273d29e8e4134cc419a39f7f469db4e1
35.833333
133
0.523594
false
false
false
false
fandongtongxue/Unsplash
refs/heads/master
Unsplash/Model/UnsplashUserProfileModel.swift
mit
1
// // UnsplashUserProfileModel.swift // Unsplash // // Created by 范东 on 17/2/4. // Copyright © 2017年 范东. All rights reserved. // import UIKit class UnsplashUserProfileModel: NSObject { var small:String! var medium:String! var large:String! // "small": "https://images.unsplash.com/profile-1486133918068-ca64a60d96c6?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=32\u0026w=32\u0026s=3ca7e038d4fcaebd3bcfb3d8edc2a0fc", // "medium": "https://images.unsplash.com/profile-1486133918068-ca64a60d96c6?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=64\u0026w=64\u0026s=bc1bea8e0a91f6e112355b1bfa1a5be9", // "large": "https://images.unsplash.com/profile-1486133918068-ca64a60d96c6?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=128\u0026w=128\u0026s=f26ed28d1fcf08201b98fa2ec45a19ca" }
70b60b06b9601fb049d38946160f1001
51.055556
225
0.77588
false
false
false
false
0x73/SugarRecord
refs/heads/develop
library/Core/SugarRecordFinder.swift
mit
2
// // SugarRecordFinder.swift // SugarRecord // // Created by Pedro Piñera Buendia on 07/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation /** Enum that indicates which elements fetch - first: The first one - last: The last one - all: All the elements - firsts: The firsts x - lasts: The lasts x */ public enum SugarRecordFinderElements { case first, last, all case firsts(Int) case lasts(Int) } public class SugarRecordFinder { //MARK: - Attributes /// Filtering NSPredicate public var predicate: NSPredicate? /// Type of stack where the operations are going to executed public var stackType: SugarRecordEngine? /// Class of the object public var objectClass: NSObject.Type? /// Enum that indicates which objects have to be fetched (first/firsts(n)/last/lasts(n)/all) public var elements: SugarRecordFinderElements = .all /// Sort descriptors to sort the fetched results public lazy var sortDescriptors: [NSSortDescriptor] = [NSSortDescriptor] () // MARK - Constructors /** Default initializer :returns: The initialized SugarRecordFinder */ public init () {} /** Initializer passing a predicate :param: predicate To be set in the initialized finder :returns: The initialized SugarRecordFinder */ public init (predicate: NSPredicate) { self.predicate = predicate } /** Initializer passing a sort descriptor :param: sortDescriptor To be appended in the sort descriptors array :returns: The initialized SugarRecordFinder */ public init (sortDescriptor: NSSortDescriptor) { self.sortDescriptors = [sortDescriptor] } // MARK - Concatenators /** Add a predicate to the finder :param: predicate To be set as the finder's predicate :returns: Current finder */ public func by(predicate: NSPredicate) -> SugarRecordFinder { if self.predicate != nil { SugarRecordLogger.logLevelWarn.log("You are overriding an existing predicate") } self.predicate = predicate return self } /** Add a predicate passing it as an String :param: predicateString To be set as the finder's predicate :returns: Current finder */ public func by(predicateString: NSString) -> SugarRecordFinder { if self.predicate != nil { SugarRecordLogger.logLevelWarn.log("You are overriding an existing predicate") } self.setPredicate(predicateString) return self } /** Add a predicate passing it as a key/value pair :param: key Key to be filtered :param: value Value of that key :returns: Current finder */ public func by<T: StringLiteralConvertible, R: StringLiteralConvertible>(key: T, equalTo value: R) -> SugarRecordFinder { if self.predicate != nil { SugarRecordLogger.logLevelWarn.log("You are overriding an existing predicate") } self.setPredicate(byKey: "\(key)", andValue: "\(value)") return self } /** Append a sort descriptor passing a sorting key and an ascending value :param: sortingKey Sorting key :param: ascending Ascending value :returns: Current finder */ public func sorted<T: StringLiteralConvertible>(by sortingKey: T, ascending: Bool) -> SugarRecordFinder { self.addSortDescriptor(byKey: "\(sortingKey)", ascending: ascending) return self } /** Append a sort descriptor passing a NSSortDescriptor directly :param: sortDescriptor Sort descriptor :returns: Current finder */ public func sorted(by sortDescriptor: NSSortDescriptor) -> SugarRecordFinder { self.addSortDescriptor(sortDescriptor) return self } /** Append a sort descriptor passing an array with NSSortDescriptors :param: sortDescriptors Array with sort descriptors :returns: Current finder */ public func sorted(by sortDescriptors: [NSSortDescriptor]) -> SugarRecordFinder { if self.sortDescriptors.count != 0 { SugarRecordLogger.logLevelWarn.log("You are overriding the existing sort descriptors") } self.sortDescriptors = sortDescriptors return self } //MARK: - Sort Descriptors /** Append a NSSortDescriptor to the finder :param: sortDescriptor Sort descriptor to be appended :returns: Current finder */ public func addSortDescriptor(sortDescriptor: NSSortDescriptor) -> SugarRecordFinder { sortDescriptors.append(sortDescriptor) return self } /** Append a NSSortDescriptor using a key and an ascending value :param: key Sorting Key value :param: ascending Sorting value :returns: Current finder */ public func addSortDescriptor<T: StringLiteralConvertible>(byKey key: T, ascending: Bool) -> SugarRecordFinder { sortDescriptors.append(NSSortDescriptor(key: "\(key)", ascending: ascending)) return self } /** Append NSSortDescriptors using an array of them :param: sortDescriptors Array of sort descriptors to be appended :returns: Current finder */ public func setSortDescriptors(sortDescriptors: [NSSortDescriptor]) -> SugarRecordFinder { self.sortDescriptors = sortDescriptors return self } /** Returns the count of sort descriptors in the finder :returns: Int with the count of sort descriptors */ public func sortDescriptorsCount() -> Int { return self.sortDescriptors.count } //MARK: - Predicates /** Set the finder predicate passing the NSPredicate :param: predicate Predicate to be set as the finder predicate :returns: Current finder */ public func setPredicate(predicate: NSPredicate) -> SugarRecordFinder { self.predicate = predicate return self } /** Set the finder predicate passing it in String format :param: predicateString String with the predicate format :returns: Current finder */ public func setPredicate(predicateString: String) -> SugarRecordFinder { self.predicate = NSPredicate(format: predicateString) return self } /** Set the finder predicate passing it in a key/value format :param: key Predicate key value :param: value Predicate value :returns: Current finder */ public func setPredicate<T: StringLiteralConvertible, R: StringLiteralConvertible>(byKey key: T, andValue value: R) -> SugarRecordFinder { self.predicate = NSPredicate(format: "\(key) == \(value)") return self } //MARK: - Elements /** Set the elements as .all :returns: Current finder */ public func all() -> SugarRecordFinder { self.elements = SugarRecordFinderElements.all return self } /** Set the elements as .first :returns: Current finder */ public func first() -> SugarRecordFinder { self.elements = SugarRecordFinderElements.first return self } /** Set the elements as .last :returns: Current finder */ public func last() -> SugarRecordFinder { self.elements = SugarRecordFinderElements.last return self } /** Set the elements as .firsts(n) :param: number Number of firsts elements :returns: Current finder */ public func firsts(number: Int) -> SugarRecordFinder { self.elements = SugarRecordFinderElements.firsts(number) return self } /** Set the elements as .lasts(n) :param: number Number of lasts elements :returns: Current finder */ public func lasts(number: Int) -> SugarRecordFinder { self.elements = SugarRecordFinderElements.lasts(number) return self } // MARK - Finder /** Execute the finder request in the SugarRecord stack :returns: Fetch result */ public func find() -> SugarRecordResults { var objects: SugarRecordResults! SugarRecord.operation(stackType!, closure: { (context) -> () in objects = context.find(self) }) return objects } public func find(inContext context:SugarRecordContext) -> SugarRecordResults { return context.find(self) } // MARK - Deletion /** Deletes the object in the SugarRecord stack :returns: If the deletion has been successful */ public func delete () -> () { delete(true, completion: { () -> () in }) } /** Deletes the object asynchronously ( or not ) :param: asynchronously Indicates if the deletion has to be asynchronous :param: completion Completion closure with a successful indicator as input parameter */ public func delete (asynchronously: Bool, completion: () -> ()) { SugarRecord.operation(inBackground: asynchronously, stackType: stackType!) { (context) -> () in let objects: SugarRecordResults! = context.find(self) if objects == nil { SugarRecordLogger.logLevelInfo.log("No objects have been deleted") return } context.beginWriting() context.deleteObjects(objects!) context.endWriting() dispatch_async(dispatch_get_main_queue(), { () -> Void in completion() }) } } //MARK : Count /** Returns the count of items that match the criteria :returns: Int with the count */ public func count() -> Int { var count: Int = 0 SugarRecord.operation(stackType!, closure: { (context) -> () in count = self.count(inContext: context) }) return count } /** Returns the count of items that match the criteria in the given context :param: context Context where the count is executed :returns: Int with the count */ public func count(inContext context:SugarRecordContext) -> Int { if (stackType == SugarRecordEngine.SugarRecordEngineCoreData) { return (context as SugarRecordCDContext).count(self.objectClass!, predicate: self.predicate) } else { return find().count } } }
48a4d50cecfe324b2745c04c15f78394
24.527187
140
0.619709
false
false
false
false
faimin/Tropos
refs/heads/master
Sources/TroposCore/Models/WeatherUpdateCache.swift
mit
2
import Foundation import os.log private let cacheQueue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 queue.name = "com.thoughtbot.carlweathers.CacheQueue" return queue }() @objc(TRWeatherUpdateCache) public final class WeatherUpdateCache: NSObject { @objc public static let latestWeatherUpdateFileName = "TRLatestWeatherUpdateFile" private let cacheURL: URL @objc public init(fileName: String, inDirectory directory: URL) { self.cacheURL = directory.appendingPathComponent(fileName) } @objc public convenience init?(fileName: String) { guard let cachesURL = FileManager.default .containerURL(forSecurityApplicationGroupIdentifier: "group.com.thoughtbot.carlweathers") else { return nil } self.init(fileName: fileName, inDirectory: cachesURL) } @objc public var latestWeatherUpdate: WeatherUpdate? { do { return try NSFileCoordinator(filePresenter: self).coordinateReadingItem(at: cacheURL) { cacheURL in NSKeyedUnarchiver.unarchiveObject(withFile: cacheURL.path) as? WeatherUpdate } } catch { if #available(iOS 10.0, iOSApplicationExtension 10.0, *) { os_log("Failed to read cached weather update: %{public}@", type: .error, error.localizedDescription) } else { NSLog("Failed to read cached weather update: %@", error.localizedDescription) } return nil } } @objc public func archiveWeatherUpdate( _ weatherUpdate: WeatherUpdate, completionHandler: @escaping (Bool, Error?) -> Void ) { let writingIntent = NSFileAccessIntent.writingIntent(with: cacheURL) NSFileCoordinator(filePresenter: self).coordinate(with: [writingIntent], queue: cacheQueue) { error in if let error = error { completionHandler(false, error) } else { let success = NSKeyedArchiver.archiveRootObject(weatherUpdate, toFile: writingIntent.url.path) completionHandler(success, nil) } } } } extension WeatherUpdateCache: NSFilePresenter { public var presentedItemURL: URL? { return cacheURL } public var presentedItemOperationQueue: OperationQueue { return cacheQueue } }
8a6c2357ea9f0d5e74214038b2dd8186
35.227273
116
0.66123
false
false
false
false