repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
JohnUni/SensorTester
network/RemoteMessageHandler.swift
1
3964
/* * RemoteMessageHandler.swift * SensorTester * * Created by John Wong on 8/09/2015. * Copyright (c) 2015-2015, John Wong <john dot innovation dot au at gmail dot com> * * All rights reserved. * * http://www.bitranslator.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 public class RemoteMessageHandler : BaseMessageHandler { override public func handle(message: IDataMessage ) -> Bool { let bRet: Bool = false let messageType: enumRemoteCommand = message.getMessageType() //let messageSubType: enumRemoteSubCommand = message.getMessageSubType() let nMessageId: Int32 = message.getMessageId() switch( messageType ) { case .MESSAGE_TYPE_REMOTE_COMMAND: print("WHY COMMAND MESSAGE? \n", terminator: "") break case .MESSAGE_TYPE_REMOTE_COMMAND_ACK: print("command ack: id=\(nMessageId) \n", terminator: "") break case .MESSAGE_TYPE_SENSOR_COLOR: break case .MESSAGE_TYPE_SENSOR_GYRO: break case .MESSAGE_TYPE_SENSOR_SONIC: break case .MESSAGE_TYPE_SENSOR_TOUCH: break case .MESSAGE_TYPE_SENSOR_RAWCOLOR: break case .MESSAGE_TYPE_UNKNOWN, .MESSAGE_TYPE_UNKNOWN_ACK, .MESSAGE_TYPE_SENSOR_COLOR_ACK, .MESSAGE_TYPE_SENSOR_GYRO_ACK, .MESSAGE_TYPE_SENSOR_SONIC_ACK, .MESSAGE_TYPE_SENSOR_TOUCH_ACK, .MESSAGE_TYPE_SENSOR_RAWCOLOR_ACK: print("not processed message:\(messageType.rawValue) \n", terminator: "") let n: Int32 = -2 break default: print("WHAT message? \(messageType.rawValue) \n", terminator: "") let n: Int32 = -1 break } return bRet } }
apache-2.0
9d3a9a20cd272306979c964fbdac281a
37.862745
85
0.678103
4.43897
false
false
false
false
LawrenceHan/iOS-project-playground
FacialRecognition-master/FacialRecognition/ViewController.swift
1
3551
// // ViewController.swift // FacialRecognition // // Created by Fumitoshi Ogata on 2014/06/30. // Copyright (c) 2014年 Fumitoshi Ogata. All rights reserved. // import UIKit import CoreImage class ViewController: UIViewController { @IBOutlet var imageView : UIImageView! override func viewDidLoad() { super.viewDidLoad() var ciImage = CIImage(CGImage:imageView.image!.CGImage) var ciDetector = CIDetector(ofType:CIDetectorTypeFace ,context:nil ,options:[ CIDetectorAccuracy:CIDetectorAccuracyHigh, CIDetectorSmile:true ] ) var features = ciDetector.featuresInImage(ciImage) UIGraphicsBeginImageContext(imageView.image!.size) imageView.image!.drawInRect(CGRectMake(0,0,imageView.image!.size.width,imageView.image!.size.height)) for feature in features{ //context var drawCtxt = UIGraphicsGetCurrentContext() //face var faceRect = (feature as CIFaceFeature).bounds faceRect.origin.y = imageView.image!.size.height - faceRect.origin.y - faceRect.size.height CGContextSetStrokeColorWithColor(drawCtxt, UIColor.redColor().CGColor) CGContextStrokeRect(drawCtxt,faceRect) //mouse if((feature.hasMouthPosition) != nil){ var mouseRectY = imageView.image!.size.height - feature.mouthPosition.y var mouseRect = CGRectMake(feature.mouthPosition.x - 5,mouseRectY - 5,10,10) CGContextSetStrokeColorWithColor(drawCtxt,UIColor.blueColor().CGColor) CGContextStrokeRect(drawCtxt,mouseRect) } //hige var higeImg = UIImage(named:"hige_100.png") var mouseRectY = imageView.image!.size.height - feature.mouthPosition.y //ヒゲの横幅は顔の4/5程度 var higeWidth = faceRect.size.width * 4/5 var higeHeight = higeWidth * 0.3 // 元画像が100:30なのでWidthの30%が縦幅 var higeRect = CGRectMake(feature.mouthPosition.x - higeWidth/2,mouseRectY - higeHeight/2,higeWidth,higeHeight) CGContextDrawImage(drawCtxt,higeRect,higeImg!.CGImage) //leftEye if((feature.hasLeftEyePosition) != nil){ var leftEyeRectY = imageView.image!.size.height - feature.leftEyePosition.y var leftEyeRect = CGRectMake(feature.leftEyePosition.x - 5,leftEyeRectY - 5,10,10) CGContextSetStrokeColorWithColor(drawCtxt, UIColor.blueColor().CGColor) CGContextStrokeRect(drawCtxt,leftEyeRect) } //rightEye if((feature.hasRightEyePosition) != nil){ var rightEyeRectY = imageView.image!.size.height - feature.rightEyePosition.y var rightEyeRect = CGRectMake(feature.rightEyePosition.x - 5,rightEyeRectY - 5,10,10) CGContextSetStrokeColorWithColor(drawCtxt, UIColor.blueColor().CGColor) CGContextStrokeRect(drawCtxt,rightEyeRect) } } var drawedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() imageView.image = drawedImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
174b038f8cd1851f3a872f4759002ab6
39.310345
124
0.621614
4.732794
false
false
false
false
rlacaze/LAB-iOS-T9-L210
LOG210-App-iOS-2.0/remise_tableviewcell.swift
1
3616
// // remise_tableviewcell.swift // LOG210-App-iOS-2.0 // // Created by Romain LACAZE on 16-04-03. // Copyright © 2016 Romain LACAZE. All rights reserved. // // // remise_search2.swift // LOG210-App-iOS-2.0 // // Created by Romain LACAZE on 2016-03-09. // Copyright © 2016 Romain LACAZE. All rights reserved. // import UIKit class remise_tableviewcell: UITableViewController { @IBOutlet weak var cell: UITableViewCell! var idUser: String? var data: NSString? var items = ["one","two"] var nbLivres: Int = 0 var dataArray: [String] = [] var dataTitle: [String] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //titre nav bar self.title = "Resultats" data = checkingApi() //print(data!) parseJson(data!) self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") self.tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataTitle.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = self.tableView .dequeueReusableCellWithIdentifier("cell")! as UITableViewCell cell.textLabel?.text = dataTitle[indexPath.row] return cell } func parseJson(dataBrut: NSString) { var dataString: String dataString = dataBrut as String //print(dataString) //let dataArray: [String] dataArray = dataString.componentsSeparatedByString("\"") var count: Int for count = 7; count <= dataArray.count; count = count + 10 { dataTitle.append(dataArray[count]) nbLivres += 1 } print("\(nbLivres) livres") } func checkingApi() -> NSString{ var result: NSString = "" let headers = [ "cache-control": "no-cache", "postman-token": "6b9b9816-6dae-aade-504a-9545ec1baef2" ] idUser = idUser!.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) let url: NSURL = NSURL(string: "http://livreechangerest20160318115916.azurewebsites.net/api/tbl_exemplaireLivre/Post_ExemplaireEtudiantNonRecu/?IdUser=\(idUser!)")! let request:NSMutableURLRequest = NSMutableURLRequest(URL:url) request.HTTPMethod = "POST" request.allHTTPHeaderFields = headers let session = NSURLSession.sharedSession() let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { //let httpResponse = response as? NSHTTPURLResponse let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)! //print("strData: \(strData)") result = strData } }) dataTask.resume() sleep(2) return result } }
gpl-3.0
f7a8bec2c743ac2ce354db2523fdae71
27.464567
172
0.585501
4.755263
false
false
false
false
a1exb1/ABToolKit-pod
Pod/Classes/JsonRequest/JsonRequest.swift
1
6221
// // Test.swift // jsonreaderoptimizations // // Created by Alex Bechmann on 22/04/2015. // Copyright (c) 2015 Alex Bechmann. All rights reserved. // import UIKit import Alamofire import SwiftyJSON public class JsonRequest: NSObject { internal var urlString = "" internal var method: Alamofire.Method = .GET internal var parameters: Dictionary<String, AnyObject>? public var alamofireRequest: Request? internal var succeedDownloadClosures: [(json: JSON, request: JsonRequest) -> ()] = [] internal var succeedDownloadClosuresWithRequestInfo: [(json: JSON, request: JsonRequest, httpUrlRequest: NSURLRequest?, httpUrlResponse: NSHTTPURLResponse?) -> ()] = [] internal var succeedContextClosures: [() -> ()] = [] internal var failDownloadClosures: [(error: NSError, alert: UIAlertController) -> ()] = [] internal var failContextClosures: [() -> ()] = [] internal var finishDownloadClosures: [() -> ()] = [] internal var active = false public var isLoading = false public class func create< T : JsonRequest >(urlString:String, parameters:Dictionary<String, AnyObject>?, method:Alamofire.Method) -> T { return JsonRequest(urlString: urlString, parameters: parameters, method: method) as! T } internal convenience init(urlString:String, parameters:Dictionary<String, AnyObject>?, method:Alamofire.Method) { self.init() self.urlString = urlString.urlEncode() self.parameters = parameters self.method = method exec() } public func onDownloadSuccess(success: (json: JSON, request: JsonRequest) -> ()) -> Self { self.succeedDownloadClosures.append(success) return self } public func onDownloadSuccessWithRequestInfo(success: (json: JSON, request: JsonRequest, httpUrlRequest: NSURLRequest?, httpUrlResponse: NSHTTPURLResponse?) -> ()) -> Self { self.succeedDownloadClosuresWithRequestInfo.append(success) return self } public func onContextSuccess(success: () -> ()) -> Self { self.succeedContextClosures.append(success) return self } public func onDownloadFailure(failure: (error: NSError, alert: UIAlertController) -> ()) -> Self { self.failDownloadClosures.append(failure) return self } public func onContextFailure(failure: () -> ()) -> Self { self.failContextClosures.append(failure) return self } public func onDownloadFinished(finished: () -> ()) -> Self { self.finishDownloadClosures.append(finished) return self } func succeedDownload(json: JSON, httpUrlRequest: NSURLRequest?, httpUrlResponse: NSHTTPURLResponse?) { for closure in self.succeedDownloadClosures { closure(json: json, request: self) } for closure in self.succeedDownloadClosuresWithRequestInfo { closure(json: json, request: self, httpUrlRequest: httpUrlRequest, httpUrlResponse: httpUrlResponse) } } public func succeedContext() { for closure in self.succeedContextClosures { closure() } } func failDownload(error: NSError, alert: UIAlertController) { for closure in self.failDownloadClosures { closure(error: error, alert: alert) } } public func failContext() { for closure in self.failContextClosures { closure() } } func finishDownload() { for closure in self.finishDownloadClosures { closure() } } internal func exec() { isLoading = true active = true UIApplication.sharedApplication().networkActivityIndicatorVisible = true self.alamofireRequest = Alamofire.request(method, urlString, parameters: parameters, encoding: ParameterEncoding.URL) .response{ (request, response, data, error) in if let e = error { var alert = self.alertControllerForError(e, completion: { (retry) -> () in if retry { self.cancel() self.exec() } }) if self.active { self.failDownload(e, alert: alert) } } else{ let json = JSON(data: data! as! NSData) if self.active { self.succeedDownload(json, httpUrlRequest: request, httpUrlResponse: response) } } if self.active { self.finishDownload() } self.isLoading = false UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } internal func alertControllerForError(error: NSError, completion: (retry: Bool) -> ()) -> UIAlertController { let alertController = UIAlertController(title: nil, message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "OK", style: .Cancel) { (action) in completion(retry: false) } alertController.addAction(cancelAction) let retryAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default) { (action) in completion(retry: true) } alertController.addAction(retryAction) return alertController } public func cancel() { active = false self.alamofireRequest?.cancel() } }
mit
f0decefe4922f87222a670b126ff3b03
30.105
177
0.555055
5.650318
false
false
false
false
wanghhh/HHScrollView
HHScrollView/HHScrollView/HHScrollView.swift
1
10104
// // HHScrollView.swift // HHScrollView // // Created by 王龙辉 on 2017/8/13. // Copyright © 2017年 onePieceDW. All rights reserved. // http://www.jianshu.com/p/fee4d10feefd import UIKit fileprivate let placeholder:String = "ic_bannerPlace" @objc protocol HHScrollViewDelegate:NSObjectProtocol { //点击代理方法 @objc optional func hhScrollView(_ scrollView: HHScrollView, didSelectRowAt index: NSInteger) } fileprivate let collectionViewCellId = "collectionViewCellId" class HHScrollView: UICollectionView,UICollectionViewDelegate,UICollectionViewDataSource { //代理 weak var hhScrollViewDelegae:HHScrollViewDelegate? //分页指示器页码颜色 var pageControlColor:UIColor? //分页指示器当前页颜色 var currentPageControlColor:UIColor? //分页指示器位置 var pageControlPoint:CGPoint? //分页指示器 fileprivate var pageControl:UIPageControl? //自动滚动时间默认为3.0 var autoScrollDelay:TimeInterval = 3 { didSet{ removeTimer() setUpTimer() } } //图片是否来自网络,默认是 var isFromNet:Bool = true //占位图 var placeholderImage:String = placeholder //设置图片资源url字符串。 var imgUrls = NSArray(){ didSet{ pageControl?.numberOfPages = imgUrls.count self.reloadData() } } fileprivate var itemCount:NSInteger?//cellNum fileprivate var timer:Timer?//定时器 //便利构造方法 convenience init(frame:CGRect) { self.init(frame: frame, collectionViewLayout: HHCollectionViewFlowLayout.init()) } convenience init(frame:CGRect,imageUrls:NSArray) { self.init(frame: frame, collectionViewLayout: HHCollectionViewFlowLayout.init()) imgUrls = imageUrls } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.backgroundColor = UIColor.white self.dataSource = self self.delegate = self self.register(HHCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellId) setUpTimer() //在collectionView加载完成后默认滚动到索引为imgUrls.count的位置,这样cell就可以向左或右滚动 DispatchQueue.main.async { //注意:在轮播器视图添加到控制器的view上以后,这样是为了将分页指示器添加到self.superview上(如果将分页指示器直接添加到collectionView上的话,指示器将不能正常显示) self.setUpPageControl() let indexpath = NSIndexPath.init(row: self.imgUrls.count, section: 0) //滚动位置 self.scrollToItem(at: indexpath as IndexPath, at: .left, animated: false) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //itemNum 设置为图片数组的n倍数(n>1),当未设置imgUrls时,随便返回一个数6 return imgUrls.count > 0 ? imgUrls.count*1000 : 6 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell:HHCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId, for: indexPath) as! HHCollectionViewCell cell.backgroundColor = UIColor.lightGray if imgUrls.count > 0 { if let urlStr = self.imgUrls[indexPath.row % imgUrls.count] as? String { if isFromNet { let url:URL = URL.init(string: urlStr)! cell.imageView?.sd_setImage(with: url, placeholderImage: UIImage.init(named: placeholderImage), options: SDWebImageOptions.refreshCached) }else{ cell.imageView?.image = UIImage.init(named: urlStr) } } } itemCount = self.numberOfItems(inSection: 0) return cell } //MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if imgUrls.count != 0 { hhScrollViewDelegae?.hhScrollView!(self, didSelectRowAt: indexPath.row % imgUrls.count) }else{ print("图片数组为空!") } } //MARK: - UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { //当前的索引 var offset:NSInteger = NSInteger(scrollView.contentOffset.x / scrollView.bounds.size.width) //第0页时,跳到索引imgUrls.count位置;最后一页时,跳到索引imgUrls.count-1位置 if offset == 0 || offset == (self.numberOfItems(inSection: 0) - 1) { if offset == 0 { offset = imgUrls.count }else { offset = imgUrls.count - 1 } } //跳转方式一: // let indexpath = NSIndexPath.init(row: offset, section: 0) // //滚动位置 // self.scrollToItem(at: indexpath as IndexPath, at: .left, animated: false) //跳转方式二: scrollView.contentOffset = CGPoint.init(x: CGFloat(offset) * scrollView.bounds.size.width, y: 0) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { setUpTimer() } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 设置分页指示器索引 let currentPage:NSInteger = NSInteger(scrollView.contentOffset.x / scrollView.bounds.size.width) let currentPageIndex = imgUrls.count > 0 ? currentPage % imgUrls.count : 0 self.pageControl?.currentPage = currentPageIndex } //MARK: - ACTIONS @objc private func setUpPageControl(){ pageControl = UIPageControl.init() pageControl?.frame = (pageControlPoint != nil) ? CGRect.init(x: (pageControlPoint?.x)!, y: (pageControlPoint?.y)!, width: self.bounds.size.width - (pageControlPoint?.x)!, height: 8) : CGRect.init(x: 0, y: self.frame.maxY - 16, width: self.bounds.size.width, height: 8) pageControl?.pageIndicatorTintColor = pageControlColor ?? UIColor.lightGray pageControl?.currentPageIndicatorTintColor = currentPageControlColor ?? UIColor.orange pageControl?.numberOfPages = imgUrls.count pageControl?.currentPage = 0 //一定要将指示器添加到superview上 self.superview?.addSubview(pageControl!) } //添加定时器 @objc private func setUpTimer(){ timer = Timer.init(timeInterval: autoScrollDelay, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true) RunLoop.current.add(timer!, forMode: .commonModes) } //移除定时器 @objc private func removeTimer(){ if (timer != nil) { timer?.invalidate() timer = nil } } //自动滚动 @objc private func autoScroll(){ //当前的索引 var offset:NSInteger = NSInteger(self.contentOffset.x / self.bounds.size.width) //第0页时,跳到索引imgUrls.count位置;最后一页时,跳到索引imgUrls.count-1位置 if offset == 0 || offset == (itemCount! - 1) { if offset == 0 { offset = imgUrls.count }else { offset = imgUrls.count - 1 } self.contentOffset = CGPoint.init(x: CGFloat(offset) * self.bounds.size.width, y: 0) //再滚到下一页 self.setContentOffset(CGPoint.init(x: CGFloat(offset + 1) * self.bounds.size.width, y: 0), animated: true) }else{ //直接滚到下一页 self.setContentOffset(CGPoint.init(x: CGFloat(offset + 1) * self.bounds.size.width, y: 0), animated: true) } } deinit { removeTimer() } } //MARK: - 用CollectionViewFlowLayout布局cell class HHCollectionViewFlowLayout:UICollectionViewFlowLayout{ //prepare方法在collectionView第一次布局的时候被调用 override func prepare() { super.prepare()//必须写 collectionView?.backgroundColor = UIColor.white //通过打印可以看到此时collectionView的frame就是我们前面设置的frame print("self.collectionView:\(String(describing: self.collectionView))") // 通过collectionView 的属性布局cell self.itemSize = (self.collectionView?.bounds.size)! self.minimumInteritemSpacing = 0 //cell之间最小间距 self.minimumLineSpacing = 0 //最小行间距 self.scrollDirection = .horizontal; self.collectionView?.bounces = false //禁用弹簧效果 self.collectionView?.isPagingEnabled = true //分页 self.collectionView?.showsHorizontalScrollIndicator = false self.collectionView?.showsVerticalScrollIndicator = false } } //MARK: -自定义cell class HHCollectionViewCell:UICollectionViewCell{ var imageView:UIImageView? override init(frame: CGRect) { super.init(frame: frame) self.clipsToBounds = true //通过打印可以看到此时cell的frame就是我们在flowLayout中设置的结果 print("self.collectionView:\(String(describing: self))") imageView = UIImageView.init(frame: self.bounds) imageView?.image = UIImage.init(named: placeholder) imageView?.contentMode = .scaleAspectFill contentView.addSubview(imageView!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
3451b2a4fabb26c3f7e90092e9d101ca
36.192771
276
0.644963
4.59375
false
false
false
false
TLOpenSpring/TLTabBarSpring
TLTabBarSpring/Classes/Animations/TLBaseAnimation.swift
1
1751
// // TLBaseAnimation.swift // Pods // // Created by Andrew on 16/5/27. // // import UIKit public let TLScreen_width = UIScreen.main.bounds.width public let TLScreen_height = UIScreen.main.bounds.height protocol TLAnimationProtocol { func startAnimation(_ icon:UIImageView,textLb:UILabel) -> Void; /** 取消选定 - parameter icon: TabBar的图标 - parameter textLb: TabBar的标题 - parameter defaultTextColor: TabBar默认文字颜色 - parameter defaultIconColor: TabBar默认图标的颜色 - returns: */ func deSelectAnimation(_ icon:UIImageView,textLb:UILabel,defaultTextColor:UIColor, defaultIconColor:UIColor) -> Void; /** 选中的状态 - parameter icon: 图标 - parameter textLb: 标题 - returns: <#return value description#> */ func selectState(_ icon:UIImageView,textLb:UILabel) -> Void; } open class TLBaseAnimation: NSObject,TLAnimationProtocol { public struct AnimationKeys{ static let Scale = "transform.scale" static let Rotation = "transform.rotation" static let KeyFrame = "contents" static let PositionY = "position.y" } //MARK: - properties open var duration:CGFloat=0.5 open var textSelctedColor:UIColor! open var iconSelectedColor:UIColor! open func startAnimation(_ icon:UIImageView,textLb:UILabel) -> Void{ } open func deSelectAnimation(_ icon:UIImageView,textLb:UILabel,defaultTextColor:UIColor, defaultIconColor:UIColor) -> Void{ } open func selectState(_ icon:UIImageView,textLb:UILabel) -> Void{ } }
mit
78c06f4f036864a7888bd8dfb21e08b8
20.628205
90
0.632484
4.427822
false
false
false
false
blinksh/blink
Blink/SmarterKeys/KeyViews/KBKeyViewSymbol.swift
1
3556
//////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import UIKit class KBKeyViewSymbol: KBKeyView { var _imageView: UIImageView override init(key: KBKey, keyDelegate: KBKeyViewDelegate) { _imageView = UIImageView( image: UIImage( systemName: key.shape.primaryValue.symbolName ?? "questionmark.diamond" ) ) super.init(key: key, keyDelegate: keyDelegate) isAccessibilityElement = true accessibilityValue = key.shape.primaryValue.accessibilityLabel accessibilityTraits.insert(UIAccessibilityTraits.keyboardKey) let kbSizes = keyDelegate.kbSizes _imageView.contentMode = .center _imageView.preferredSymbolConfiguration = .init(pointSize: kbSizes.key.fonts.symbol, weight: .regular) _imageView.tintColor = UIColor.label addSubview(_imageView) } override func layoutSubviews() { super.layoutSubviews() _imageView.frame = bounds.inset(by: keyDelegate.kbSizes.key.insets.symbol) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if key.isModifier { self.backgroundColor = .white _imageView.tintColor = UIColor.darkText } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = trackingTouch, touches.contains(touch) else { super.touchesEnded(touches, with: event) return } guard keyDelegate.keyViewCanGoOff(keyView: self, value: key.shape.primaryValue) else { return } if !shouldAutoRepeat { keyDelegate.keyViewTriggered(keyView: self, value: key.shape.primaryValue) } super.touchesEnded(touches, with: event) } override var shouldAutoRepeat: Bool { switch key.shape.primaryValue { case .esc, .left, .right, .up, .down, .tab: return true default: return super.shouldAutoRepeat } } override func turnOff() { super.turnOff() _imageView.tintColor = UIColor.label if key.shape.primaryValue.isModifier { accessibilityTraits.remove([.selected]) } } override func turnOn() { super.turnOn() if key.shape.primaryValue.isModifier { accessibilityTraits.insert([.selected]) } } }
gpl-3.0
0ef5f40b8138fd7be3aee41f0f1ffa8b
28.882353
88
0.651294
4.51269
false
false
false
false
ChenWeiLee/Black-Fu
Black-Fu/Black-Fu/ViewController.swift
1
11921
// // ViewController.swift // Black-Fu // // Created by Li Chen wei on 2015/11/30. // Copyright © 2015年 TWML. All rights reserved. // import UIKit import Alamofire import SDWebImage import NVActivityIndicatorView class ViewController: UIViewController,UIGestureRecognizerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UISearchBarDelegate { @IBOutlet var collectionView: UICollectionView! @IBOutlet var searchCancelBtn: UIButton! @IBOutlet var searchBar: UISearchBar! @IBOutlet var scanButton: UIButton! var longTouching:Bool = false var longCell:ProductionCollectionCell = ProductionCollectionCell() var tableShowAry:[Dictionary<String, String>] = [Dictionary<String, String>]() var imageDic:[String:UIImage] = [String:UIImage]() let singletonProducts = singletonObject.sharedInstance var loadingActivity:NVActivityIndicatorView = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .BallClipRotatePulse, color: UIColor(red: 0.49, green: 0.87, blue: 0.47, alpha: 1.0), size: CGSizeMake(100, 100)) lazy var lasyProducts:[String:AnyObject] = { do { let productPath:String = NSBundle.mainBundle().pathForResource("Products", ofType: "json")! let jsonData:NSData = NSData(contentsOfFile: productPath)! let anyObj:AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) print("\(anyObj)") return anyObj as! [String : AnyObject] } catch let error as NSError { print("json error: \(error.localizedDescription)") return [String:AnyObject]() } }() //MARK: - ViewController 生命週期 override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(loadingActivity) loadingActivity.center = self.view.center loadingActivity.startAnimation() self.getData() collectionView.backgroundColor = UIColor.whiteColor() collectionView.delaysContentTouches = false collectionView.canCancelContentTouches = true searchCancelBtn.addTarget(self, action: "cancelSearchBtn", forControlEvents: .TouchUpInside) scanButton.layer.masksToBounds = true scanButton.layer.cornerRadius = scanButton.frame.width/2 let gesture = UILongPressGestureRecognizer(target: self, action: "longTouchEvent:") gesture.delegate = self gesture.delaysTouchesBegan = true collectionView.addGestureRecognizer(gesture) // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = true searchCancelBtn.enabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Detail View & 毛玻璃 func longTouchEvent(gestureRecognizer: UILongPressGestureRecognizer) { if gestureRecognizer.state == .Ended { longTouching = false longCell.cancel() lasyEffectView.removeFromSuperview() return }else if longTouching == false{ longTouching = true let pointCollection:CGPoint = gestureRecognizer.locationInView(collectionView) let pointScreen:CGPoint = gestureRecognizer.locationInView(self.view) let indexPath = collectionView.indexPathForItemAtPoint(pointCollection) if indexPath != nil { longCell = collectionView.cellForItemAtIndexPath(indexPath!) as! ProductionCollectionCell self.view.addSubview(lasyEffectView) longCell.show(pointScreen) searchBar.resignFirstResponder() } } } lazy var lasyEffectView:UIVisualEffectView = { // iOS8 系统才有 let tempEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) tempEffectView.frame = self.view.bounds tempEffectView.alpha = 0.9 tempEffectView.userInteractionEnabled = true return tempEffectView }() // MARK: - Button Event @IBAction func scanBarcode(sender: AnyObject) { let scanViewController = self.storyboard!.instantiateViewControllerWithIdentifier("Scan") as! ScanViewController self.navigationController?.pushViewController(scanViewController, animated: true) } @IBAction func moreNewList(sender: UIButton) { } func cancelSearchBtn(){ searchBar.text = "" self.searchBar(searchBar, textDidChange: "") searchBar.resignFirstResponder() searchBar.showsCancelButton = false searchCancelBtn.enabled = false } // MARK: - UISearchBar Delegate func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool{ searchCancelBtn.enabled = true return true } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { tableShowAry.removeAll() if searchText == "" { tableShowAry = singletonProducts.productsDic as! [Dictionary<String, String>] }else{ for tableString:Dictionary<String, String> in singletonProducts.productsDic as! [Dictionary<String, String>]{ if tableString["Title"]!.rangeOfString(searchText) != nil { tableShowAry.append(tableString) } } } collectionView.reloadData() } // MARK: - UICollectionView Delegate & DataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{ return 1; } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return tableShowAry.count; } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ProductCollectionCell", forIndexPath: indexPath) as! ProductionCollectionCell cell.image.sd_setImageWithURL(NSURL(string: tableShowAry[indexPath.row]["ImageURL"]! as String), placeholderImage: UIImage(named: "icon 6.png")) cell.productName.text = tableShowAry[indexPath.row]["Title"] cell.company = tableShowAry[indexPath.row]["Company"] as String! cell.tag = indexPath.row cell.superController = self return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){ let productDetailViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ProductDetail") as! ProductDetailViewController productDetailViewController.navigationTitle = tableShowAry[indexPath.row]["Title"] self.navigationController?.pushViewController(productDetailViewController, animated: true) } //MARK : - Get Data func getData() { Alamofire.request(.GET, "https://dl.dropboxusercontent.com/u/52019782/Products.json") .responseJSON { response in if let JSON = response.result.value { print("JSON: \(JSON)") self.singletonProducts.productsDic = JSON["Product"] as! NSArray self.tableShowAry = (JSON["Product"] as! NSArray)as! [Dictionary<String, String>] self.collectionView.reloadData() } self.loadingActivity.stopAnimation() } } } class ProductionCollectionCell: UICollectionViewCell { @IBOutlet var image: UIImageView! @IBOutlet var productName: UILabel! var superController:UIViewController? var company:String = "" var startPoint:CGPoint = CGPoint() var isAddEvent:Bool = false var isMoveOut:Bool = true var productView:ProductDetailView = ProductDetailView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width-40, height: UIScreen.mainScreen().bounds.size.height/2)) func show(point:CGPoint) { productView.productTitle.text = productName.text productView.productImage.image = image.image productView.productBrand.text = company productView.bringSubviewToFront((superController?.view)!) productView.frame = calculateAnimateFrame(point) superController?.view.addSubview(productView) UIView.animateWithDuration(0.3, animations: { () -> Void in self.productView.frame = self.calculateDirection(point) }) } func cancel(){ productView.removeFromSuperview() } func calculateDirection(point:CGPoint) -> CGRect{ var viewFrame = CGRect() viewFrame.origin.x = 20 viewFrame.size.height = UIScreen.mainScreen().bounds.size.height/2 viewFrame.size.width = UIScreen.mainScreen().bounds.size.width-40 if point.y < UIScreen.mainScreen().bounds.size.height/2 { viewFrame.origin.y = point.y }else{ viewFrame.origin.y = point.y - UIScreen.mainScreen().bounds.size.height/2 } return viewFrame } func calculateAnimateFrame(originalPoint:CGPoint) -> CGRect{ var viewFrame = CGRect() viewFrame.size.height = UIScreen.mainScreen().bounds.size.height/4 viewFrame.size.width = (UIScreen.mainScreen().bounds.size.width-40)/2 if originalPoint.x < UIScreen.mainScreen().bounds.size.width/2 { viewFrame.origin.x = originalPoint.x }else{ viewFrame.origin.x = originalPoint.x - viewFrame.size.width } if originalPoint.y < UIScreen.mainScreen().bounds.size.height/2 { viewFrame.origin.y = originalPoint.y }else{ viewFrame.origin.y = originalPoint.y - viewFrame.size.height } return viewFrame } } class ProductDetailView: UIView { var productTitle:UILabel = UILabel() var productImage:UIImageView = UIImageView() var productBrand:UILabel = UILabel() override init(frame: CGRect) { super.init(frame:frame) self.backgroundColor = UIColor(red: 0.49, green: 0.87, blue: 0.83, alpha: 1.0) self.layer.masksToBounds = true self.layer.cornerRadius = 15.0 productTitle.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: 45) productTitle.textAlignment = .Center productTitle.font = UIFont.boldSystemFontOfSize(17.0) self.addSubview(productTitle) productImage.frame = CGRect(x:10 , y: productTitle.frame.height + productTitle.frame.origin.y+5, width: frame.height-20, height: frame.height - 100) productImage.contentMode = .ScaleAspectFit self.addSubview(productImage) productBrand.frame = CGRect(x: 0, y: frame.height - 45, width: frame.size.width, height: 45) productBrand.textAlignment = .Center productBrand.textColor = UIColor.redColor() productBrand.font = UIFont.boldSystemFontOfSize(17.0) self.addSubview(productBrand) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
gpl-2.0
f30ee38f184d99ca8f5744ba8a2315a9
33.88563
245
0.641392
5.190227
false
false
false
false
djwbrown/swift
test/SILGen/builtins.swift
6
42026
// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck %s // RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CANONICAL %s import Swift protocol ClassProto : class { } struct Pointer { var value: Builtin.RawPointer } // CHECK-LABEL: sil hidden @_T08builtins3foo{{[_0-9a-zA-Z]*}}F func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 { // CHECK: builtin "cmp_eq_Int1" return Builtin.cmp_eq_Int1(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8load_pod{{[_0-9a-zA-Z]*}}F func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_T08builtins8load_obj{{[_0-9a-zA-Z]*}}F func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_T08builtins12load_raw_pod{{[_0-9a-zA-Z]*}}F func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_T08builtins12load_raw_obj{{[_0-9a-zA-Z]*}}F func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_T08builtins18load_invariant_pod{{[_0-9a-zA-Z]*}}F func load_invariant_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadInvariant(x) } // CHECK-LABEL: sil hidden @_T08builtins18load_invariant_obj{{[_0-9a-zA-Z]*}}F func load_invariant_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadInvariant(x) } // CHECK-LABEL: sil hidden @_T08builtins8load_gen{{[_0-9a-zA-Z]*}}F func load_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}} return Builtin.load(x) } // CHECK-LABEL: sil hidden @_T08builtins8move_pod{{[_0-9a-zA-Z]*}}F func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_T08builtins8move_obj{{[_0-9a-zA-Z]*}}F func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [take] [[ADDR]] // CHECK-NOT: copy_value [[VAL]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_T08builtins8move_gen{{[_0-9a-zA-Z]*}}F func move_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}} return Builtin.take(x) } // CHECK-LABEL: sil hidden @_T08builtins11destroy_pod{{[_0-9a-zA-Z]*}}F func destroy_pod(_ x: Builtin.RawPointer) { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box // CHECK-NOT: pointer_to_address // CHECK-NOT: destroy_addr // CHECK-NOT: destroy_value // CHECK: destroy_value [[XBOX]] : ${{.*}}{ // CHECK-NOT: destroy_value return Builtin.destroy(Builtin.Int64, x) // CHECK: return } // CHECK-LABEL: sil hidden @_T08builtins11destroy_obj{{[_0-9a-zA-Z]*}}F func destroy_obj(_ x: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(Builtin.NativeObject, x) } // CHECK-LABEL: sil hidden @_T08builtins11destroy_gen{{[_0-9a-zA-Z]*}}F func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(T.self, x) } // CHECK-LABEL: sil hidden @_T08builtins10assign_pod{{[_0-9a-zA-Z]*}}F func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { var x = x var y = y // CHECK: alloc_box // CHECK: alloc_box // CHECK-NOT: alloc_box // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value // CHECK: destroy_value // CHECK-NOT: destroy_value Builtin.assign(x, y) // CHECK: return } // CHECK-LABEL: sil hidden @_T08builtins10assign_obj{{[_0-9a-zA-Z]*}}F func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_T08builtins12assign_tuple{{[_0-9a-zA-Z]*}}F func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject), y: Builtin.RawPointer) { var x = x var y = y // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject) // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_T08builtins10assign_gen{{[_0-9a-zA-Z]*}}F func assign_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] {{%.*}} to [[ADDR]] : Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8init_pod{{[_0-9a-zA-Z]*}}F func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: store {{%.*}} to [trivial] [[ADDR]] // CHECK-NOT: destroy_value [[ADDR]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8init_obj{{[_0-9a-zA-Z]*}}F func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK-NOT: load [[ADDR]] // CHECK: store [[SRC:%.*]] to [init] [[ADDR]] // CHECK-NOT: destroy_value [[SRC]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8init_gen{{[_0-9a-zA-Z]*}}F func init_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]] // CHECK: destroy_addr [[OTHER_LOC]] Builtin.initialize(x, y) } class C {} class D {} // CHECK-LABEL: sil hidden @_T08builtins22class_to_native_object{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $C): // CHECK-NEXT: debug_value // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[COPY_BORROWED_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: [[OBJ:%.*]] = unchecked_ref_cast [[COPY_BORROWED_ARG:%.*]] to $Builtin.NativeObject // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[OBJ]] func class_to_native_object(_ c:C) -> Builtin.NativeObject { return Builtin.castToNativeObject(c) } // CHECK-LABEL: sil hidden @_T08builtins23class_to_unknown_object{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $C): // CHECK-NEXT: debug_value // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[COPY_BORROWED_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: [[OBJ:%.*]] = unchecked_ref_cast [[COPY_BORROWED_ARG:%.*]] to $Builtin.UnknownObject // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[OBJ]] func class_to_unknown_object(_ c:C) -> Builtin.UnknownObject { return Builtin.castToUnknownObject(c) } // CHECK-LABEL: sil hidden @_T08builtins32class_archetype_to_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_T08builtins33class_archetype_to_unknown_object{{[_0-9a-zA-Z]*}}F func class_archetype_to_unknown_object<T : C>(_ t: T) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_T08builtins34class_existential_to_native_object{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $ClassProto): // CHECK-NEXT: debug_value // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[COPY_BORROWED_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: [[REF:%[0-9]+]] = open_existential_ref [[COPY_BORROWED_ARG]] : $ClassProto // CHECK-NEXT: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[PTR]] func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject { return Builtin.unsafeCastToNativeObject(t) } // CHECK-LABEL: sil hidden @_T08builtins35class_existential_to_unknown_object{{[_0-9a-zA-Z]*}}F func class_existential_to_unknown_object(_ t:ClassProto) -> Builtin.UnknownObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_T08builtins24class_from_native_object{{[_0-9a-zA-Z]*}}F func class_from_native_object(_ p: Builtin.NativeObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_T08builtins25class_from_unknown_object{{[_0-9a-zA-Z]*}}F func class_from_unknown_object(_ p: Builtin.UnknownObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_T08builtins34class_archetype_from_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_T08builtins35class_archetype_from_unknown_object{{[_0-9a-zA-Z]*}}F func class_archetype_from_unknown_object<T : C>(_ p: Builtin.UnknownObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_T08builtins41objc_class_existential_from_native_object{{[_0-9a-zA-Z]*}}F func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_T08builtins42objc_class_existential_from_unknown_object{{[_0-9a-zA-Z]*}}F func objc_class_existential_from_unknown_object(_ p: Builtin.UnknownObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_T08builtins20class_to_raw_pointer{{[_0-9a-zA-Z]*}}F func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(t) } protocol CP: class {} func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins18obj_to_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } // CHECK-LABEL: sil hidden @_T08builtins22class_from_raw_pointer{{[_0-9a-zA-Z]*}}F func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T { return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins20obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins28unknown_obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F func unknown_obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.UnknownObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins28existential_from_raw_pointer{{[_0-9a-zA-Z]*}}F func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins9gep_raw64{{[_0-9a-zA-Z]*}}F func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int64(p, i) } // CHECK-LABEL: sil hidden @_T08builtins9gep_raw32{{[_0-9a-zA-Z]*}}F func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int32(p, i) } // CHECK-LABEL: sil hidden @_T08builtins3gep{{[_0-9a-zA-Z]*}}F func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word // CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]] // CHECK: return [[A2P]] return Builtin.gep_Word(p, i, e) } public final class Header { } // CHECK-LABEL: sil hidden @_T08builtins20allocWithTailElems_1{{[_0-9a-zA-Z]*}}F func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_1(Header.self, n, ty) } // CHECK-LABEL: sil hidden @_T08builtins20allocWithTailElems_3{{[_0-9a-zA-Z]*}}F func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3) } // CHECK-LABEL: sil hidden @_T08builtins16projectTailElems{{[_0-9a-zA-Z]*}}F func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer { // CHECK: bb0([[ARG1:%.*]] : @owned $Header // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1_COPY]] : $Header // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: destroy_value [[ARG1_COPY]] // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[A2P]] return Builtin.projectTailElems(h, ty) } // CHECK: } // end sil function '_T08builtins16projectTailElemsBpAA6HeaderC1h_xm2tytlF' // CHECK-LABEL: sil hidden @_T08builtins11getTailAddr{{[_0-9a-zA-Z]*}}F func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2 // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.getTailAddr_Word(start, i, ty1, ty2) } // CHECK-LABEL: sil hidden @_T08builtins8condfail{{[_0-9a-zA-Z]*}}F func condfail(_ i: Builtin.Int1) { Builtin.condfail(i) // CHECK: cond_fail {{%.*}} : $Builtin.Int1 } struct S {} @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} protocol P {} // CHECK-LABEL: sil hidden @_T08builtins10canBeClass{{[_0-9a-zA-Z]*}}F func canBeClass<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(O.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(OP1.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompo = OP1 & OP2 // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(ObjCCompo.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(S.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(C.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(P.self) typealias MixedCompo = OP1 & P // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompo.self) // CHECK: builtin "canBeClass"<T> Builtin.canBeClass(T.self) } // FIXME: "T.Type.self" does not parse as an expression // CHECK-LABEL: sil hidden @_T08builtins18canBeClassMetatype{{[_0-9a-zA-Z]*}}F func canBeClassMetatype<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 0 typealias OT = O.Type Builtin.canBeClass(OT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias OP1T = OP1.Type Builtin.canBeClass(OP1T.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompoT = (OP1 & OP2).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(ObjCCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias ST = S.Type Builtin.canBeClass(ST.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias CT = C.Type Builtin.canBeClass(CT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias PT = P.Type Builtin.canBeClass(PT.self) typealias MixedCompoT = (OP1 & P).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias TT = T.Type Builtin.canBeClass(TT.self) } // CHECK-LABEL: sil hidden @_T08builtins11fixLifetimeyAA1CCF : $@convention(thin) (@owned C) -> () { func fixLifetime(_ c: C) { // CHECK: bb0([[ARG:%.*]] : @owned $C): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: fix_lifetime [[ARG_COPY]] : $C // CHECK: destroy_value [[ARG_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] Builtin.fixLifetime(c) } // CHECK: } // end sil function '_T08builtins11fixLifetimeyAA1CCF' // CHECK-LABEL: sil hidden @_T08builtins20assert_configuration{{[_0-9a-zA-Z]*}}F func assert_configuration() -> Builtin.Int32 { return Builtin.assert_configuration() // CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32 // CHECK: return [[APPLY]] : $Builtin.Int32 } // CHECK-LABEL: sil hidden @_T08builtins17assumeNonNegativeBwBwF func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word { return Builtin.assumeNonNegative_Word(x) // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word // CHECK: return [[APPLY]] : $Builtin.Word } // CHECK-LABEL: sil hidden @_T08builtins11autoreleaseyAA1OCF : $@convention(thin) (@owned O) -> () { // ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it? // CHECK: bb0([[ARG:%.*]] : @owned $O): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: unmanaged_autorelease_value [[ARG_COPY]] // CHECK: destroy_value [[ARG_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T08builtins11autoreleaseyAA1OCF' func autorelease(_ o: O) { Builtin.autorelease(o) } // The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during // diagnostics. // CHECK-LABEL: sil hidden @_T08builtins11unreachable{{[_0-9a-zA-Z]*}}F // CHECK: builtin "unreachable"() // CHECK: return // CANONICAL-LABEL: sil hidden @_T08builtins11unreachableyyF : $@convention(thin) () -> () { func unreachable() { Builtin.unreachable() } // CHECK-LABEL: sil hidden @_T08builtins15reinterpretCastBw_AA1DCAA1CCSgAFtAF_Bw1xtF : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C) // CHECK: bb0([[ARG1:%.*]] : @owned $C, [[ARG2:%.*]] : @trivial $Builtin.Word): // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: [[BORROWED_ARG1_1:%.*]] = begin_borrow [[ARG1]] // CHECK-NEXT: [[ARG1_COPY1:%.*]] = copy_value [[BORROWED_ARG1_1]] : $C // CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1_COPY1]] : $C to $Builtin.Word // CHECK-NEXT: [[BORROWED_ARG1_2:%.*]] = begin_borrow [[ARG1]] // CHECK-NEXT: [[ARG1_COPY2:%.*]] = copy_value [[BORROWED_ARG1_2]] : $C // CHECK-NEXT: [[ARG1_COPY2_CASTED:%.*]] = unchecked_ref_cast [[ARG1_COPY2]] : $C to $D // CHECK-NEXT: [[BORROWED_ARG1_3:%.*]] = begin_borrow [[ARG1]] // CHECK-NEXT: [[ARG1_COPY3:%.*]] = copy_value [[BORROWED_ARG1_3]] // CHECK-NEXT: [[ARG1_COPY3_CAST:%.*]] = unchecked_ref_cast [[ARG1_COPY3]] : $C to $Optional<C> // CHECK-NEXT: [[ARG2_OBJ_CASTED:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C // CHECK-NEXT: [[ARG2_OBJ_CASTED_COPIED:%.*]] = copy_value [[ARG2_OBJ_CASTED]] : $C // CHECK-NEXT: end_borrow [[BORROWED_ARG1_3]] from [[ARG1]] // CHECK-NEXT: end_borrow [[BORROWED_ARG1_2]] from [[ARG1]] // CHECK-NEXT: destroy_value [[ARG1_COPY1]] // CHECK-NEXT: end_borrow [[BORROWED_ARG1_1]] from [[ARG1]] // CHECK-NEXT: destroy_value [[ARG1]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_COPY2_CASTED]] : $D, [[ARG1_COPY3_CAST]] : $Optional<C>, [[ARG2_OBJ_CASTED_COPIED:%.*]] : $C) // CHECK: return [[RESULT]] func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) { return (Builtin.reinterpretCast(c) as Builtin.Word, Builtin.reinterpretCast(c) as D, Builtin.reinterpretCast(c) as C?, Builtin.reinterpretCast(x) as C) } // CHECK-LABEL: sil hidden @_T08builtins19reinterpretAddrOnly{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnly<T, U>(_ t: T) -> U { // CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_T08builtins28reinterpretAddrOnlyToTrivial{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int { // CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]] // CHECK: destroy_addr [[INPUT]] return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_T08builtins27reinterpretAddrOnlyLoadable{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) { // CHECK: [[BUF:%.*]] = alloc_stack $Int // CHECK: store {{%.*}} to [trivial] [[BUF]] // CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T // CHECK: copy_addr [[RES1]] to [initialization] return (Builtin.reinterpretCast(a) as T, // CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int // CHECK: load [trivial] [[RES]] Builtin.reinterpretCast(b) as Int) } // CHECK-LABEL: sil hidden @_T08builtins18castToBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word // CHECK: return [[BO]] func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject { return Builtin.castToBridgeObject(c, w) } // CHECK-LABEL: sil hidden @_T08builtins23castRefFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C { return Builtin.castReferenceFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_T08builtins30castBitPatternFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word // CHECK: destroy_value [[BO]] func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word { return Builtin.castBitPatternFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_T08builtins8pinUnpin{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @owned $Builtin.NativeObject): // CHECK-NEXT: debug_value func pinUnpin(_ object : Builtin.NativeObject) { // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[HANDLE:%.*]] = strong_pin [[ARG_COPY]] : $Builtin.NativeObject // CHECK-NEXT: debug_value // CHECK-NEXT: destroy_value [[ARG_COPY]] : $Builtin.NativeObject // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] let handle : Builtin.NativeObject? = Builtin.tryPin(object) // CHECK-NEXT: [[BORROWED_HANDLE:%.*]] = begin_borrow [[HANDLE]] // CHECK-NEXT: [[HANDLE_COPY:%.*]] = copy_value [[BORROWED_HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: strong_unpin [[HANDLE_COPY]] : $Optional<Builtin.NativeObject> // ==> SEMANTIC ARC TODO: This looks like a mispairing or a weird pairing. Builtin.unpin(handle) // CHECK-NEXT: tuple () // CHECK-NEXT: end_borrow [[BORROWED_HANDLE]] from [[HANDLE]] // CHECK-NEXT: destroy_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // NativeObject // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Optional<Builtin.NativeObject>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Builtin.NativeObject> // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.NativeObject> // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject nonNull // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.NativeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.NativeObject // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject pinned // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Optional<Builtin.NativeObject>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[WRITE]] : $*Optional<Builtin.NativeObject> // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // NativeObject pinned nonNull // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.NativeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[WRITE]] : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // UnknownObject (ObjC) // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Optional<Builtin.UnknownObject>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.UnknownObject> // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) nonNull // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.UnknownObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.UnknownObject // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) pinned nonNull // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.UnknownObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[WRITE]] : $*Builtin.UnknownObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.BridgeObject // CHECK: return func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject pinned nonNull // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[WRITE]] : $*Builtin.BridgeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull native // CHECK-LABEL: sil hidden @_T08builtins15isUnique_native{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[CAST:%.*]] = unchecked_addr_cast [[WRITE]] : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: return func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique_native(&ref)) } // BridgeObject pinned nonNull native // CHECK-LABEL: sil hidden @_T08builtins23isUniqueOrPinned_native{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[CAST:%.*]] = unchecked_addr_cast [[WRITE]] : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned_native(&ref)) } // ---------------------------------------------------------------------------- // Builtin.castReference // ---------------------------------------------------------------------------- class A {} protocol PUnknown {} protocol PClass : class {} // CHECK-LABEL: sil hidden @_T08builtins19refcast_generic_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject func refcast_generic_any<T>(_ o: T) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins17refcast_class_anyyXlAA1ACF : // CHECK: bb0([[ARG:%.*]] : @owned $A): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_CASTED:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $A to $AnyObject // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CASTED]] // CHECK: } // end sil function '_T08builtins17refcast_class_anyyXlAA1ACF' func refcast_class_any(_ o: A) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins20refcast_punknown_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject func refcast_punknown_any(_ o: PUnknown) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins18refcast_pclass_anyyXlAA6PClass_pF : // CHECK: bb0([[ARG:%.*]] : @owned $PClass): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_CAST:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $PClass to $AnyObject // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CAST]] // CHECK: } // end sil function '_T08builtins18refcast_pclass_anyyXlAA6PClass_pF' func refcast_pclass_any(_ o: PClass) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins20refcast_any_punknown{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown func refcast_any_punknown(_ o: AnyObject) -> PUnknown { return Builtin.castReference(o) } // => SEMANTIC ARC TODO: This function is missing a borrow + extract + copy. // // CHECK-LABEL: sil hidden @_T08builtins22unsafeGuaranteed_class{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @owned $A): // CHECK: [[BORROWED_P:%.*]] = begin_borrow [[P]] // CHECK: [[P_COPY:%.*]] = copy_value [[BORROWED_P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A) // CHECK: [[BORROWED_T:%.*]] = begin_borrow [[T]] // CHECK: [[R:%.*]] = tuple_extract [[BORROWED_T]] : $(A, Builtin.Int8), 0 // CHECK: [[COPY_R:%.*]] = copy_value [[R]] // CHECK: [[K:%.*]] = tuple_extract [[BORROWED_T]] : $(A, Builtin.Int8), 1 // CHECK: destroy_value [[COPY_R]] : $A // CHECK: end_borrow [[BORROWED_T]] from [[T]] // CHECK: destroy_value [[T]] // CHECK: end_borrow [[BORROWED_P]] from [[P]] // CHECK: [[BORROWED_P:%.*]] = begin_borrow [[P]] // CHECK: [[P_COPY:%.*]] = copy_value [[BORROWED_P]] // CHECK: end_borrow [[BORROWED_P]] from [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_COPY]] : $A // CHECK: } func unsafeGuaranteed_class(_ a: A) -> A { Builtin.unsafeGuaranteed(a) return a } // => SEMANTIC ARC TODO: This function is missing a borrow + extract + copy. // // CHECK-LABEL: _T08builtins24unsafeGuaranteed_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @owned $T): // CHECK: [[BORROWED_P:%.*]] = begin_borrow [[P]] // CHECK: [[P_COPY:%.*]] = copy_value [[BORROWED_P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[BORROWED_T:%.*]] = begin_borrow [[T]] // CHECK: [[R:%.*]] = tuple_extract [[BORROWED_T]] : $(T, Builtin.Int8), 0 // CHECK: [[COPY_R:%.*]] = copy_value [[R]] // CHECK: [[K:%.*]] = tuple_extract [[BORROWED_T]] : $(T, Builtin.Int8), 1 // CHECK: destroy_value [[COPY_R]] : $T // CHECK: end_borrow [[BORROWED_T]] from [[T]] // CHECK: destroy_value [[T]] // CHECK: end_borrow [[BORROWED_P]] from [[P]] // CHECK: [[BORROWED_P:%.*]] = begin_borrow [[P]] // CHECK: [[P_RETURN:%.*]] = copy_value [[BORROWED_P]] // CHECK: end_borrow [[BORROWED_P]] from [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_RETURN]] : $T // CHECK: } func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T { Builtin.unsafeGuaranteed(a) return a } // CHECK_LABEL: sil hidden @_T08builtins31unsafeGuaranteed_generic_return{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @owned $T): // CHECK: [[BORROWED_P:%.*]] = begin_borrow [[P]] // CHECK: [[P_COPY:%.*]] = copy_value [[BORROWED_P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[BORROWED_T:%.*]] = begin_borrow [[T]] // CHECK: [[R]] = tuple_extract [[BORROWED_T]] : $(T, Builtin.Int8), 0 // CHECK: [[COPY_R:%.*]] = copy_value [[R]] // CHECK: [[K]] = tuple_extract [[BORROWED_T]] : $(T, Builtin.Int8), 1 // CHECK: end_borrow [[BORROWED_T]] from [[T]] // CHECK: destroy_value [[T]] // CHECK: end_borrow [[BORROWED_P]] from [[P]] // CHECK: destroy_value [[P]] // CHECK: [[S:%.*]] = tuple ([[COPY_R]] : $T, [[K]] : $Builtin.Int8) // CHECK: return [[S]] : $(T, Builtin.Int8) // CHECK: } func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) { return Builtin.unsafeGuaranteed(a) } // CHECK-LABEL: sil hidden @_T08builtins19unsafeGuaranteedEnd{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @trivial $Builtin.Int8): // CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8) // CHECK: [[S:%.*]] = tuple () // CHECK: return [[S]] : $() // CHECK: } func unsafeGuaranteedEnd(_ t: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(t) } // CHECK-LABEL: sil hidden @_T08builtins10bindMemory{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @trivial $Builtin.RawPointer, [[I:%.*]] : @trivial $Builtin.Word, [[T:%.*]] : @trivial $@thick T.Type): // CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T // CHECK: return {{%.*}} : $() // CHECK: } func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) { Builtin.bindMemory(ptr, idx, T.self) } //===----------------------------------------------------------------------===// // RC Operations //===----------------------------------------------------------------------===// // SILGen test: // // CHECK-LABEL: sil hidden @_T08builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned Builtin.NativeObject) -> () { // CHECK: bb0([[P:%.*]] : @owned $Builtin.NativeObject): // CHECK: [[BORROWED_P:%.*]] = begin_borrow [[P]] // CHECK: [[COPIED_P:%.*]] = copy_value [[BORROWED_P]] // CHECK: unmanaged_retain_value [[COPIED_P]] // CHECK: destroy_value [[COPIED_P]] // CHECK: end_borrow [[BORROWED_P]] from [[P]] // CHECK: destroy_value [[P]] // CHECK: } // end sil function '_T08builtins6retain{{[_0-9a-zA-Z]*}}F' // SIL Test. This makes sure that we properly clean up in -Onone SIL. // CANONICAL-LABEL: sil hidden @_T08builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned Builtin.NativeObject) -> () { // CANONICAL: bb0([[P:%.*]] : @owned $Builtin.NativeObject): // CANONICAL-NOT: retain // CANONICAL-NOT: release // CANONICAL: } // end sil function '_T08builtins6retain{{[_0-9a-zA-Z]*}}F' func retain(ptr: Builtin.NativeObject) { Builtin.retain(ptr) } // SILGen test: // // CHECK-LABEL: sil hidden @_T08builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned Builtin.NativeObject) -> () { // CHECK: bb0([[P:%.*]] : @owned $Builtin.NativeObject): // CHECK: [[BORROWED_P:%.*]] = begin_borrow [[P]] // CHECK: [[COPIED_P:%.*]] = copy_value [[BORROWED_P]] // CHECK: unmanaged_release_value [[COPIED_P]] // CHECK: destroy_value [[COPIED_P]] // CHECK: end_borrow [[BORROWED_P]] from [[P]] // CHECK: destroy_value [[P]] // CHECK: } // end sil function '_T08builtins7release{{[_0-9a-zA-Z]*}}F' // SIL Test. Make sure even in -Onone code, we clean this up properly: // CANONICAL-LABEL: sil hidden @_T08builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned Builtin.NativeObject) -> () { // CANONICAL: bb0([[P:%.*]] : @owned $Builtin.NativeObject): // CANONICAL-NEXT: debug_value // CANONICAL-NEXT: tuple // CANONICAL-NEXT: strong_release [[P]] // CANONICAL-NEXT: strong_release [[P]] // CANONICAL-NEXT: tuple // CANONICAL-NEXT: return // CANONICAL: } // end sil function '_T08builtins7release{{[_0-9a-zA-Z]*}}F' func release(ptr: Builtin.NativeObject) { Builtin.release(ptr) }
apache-2.0
cf2b8a7f8a8d25d72afdb02a2fb90978
42.10359
188
0.627683
3.201005
false
false
false
false
AutomationStation/BouncerBuddy
BouncerBuddyV6/BouncerBuddy/RegisterViewController.swift
1
9911
// // RegisterViewController.swift // BouncerBuddy // // Created by Sha Wu on 16/3/2. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import UIKit class RegisterViewController: UIViewController { @IBOutlet weak var userEmailtextfield: UITextField! @IBOutlet weak var usernameTextfield: UITextField! @IBOutlet weak var userPasswordTextfield: UITextField! @IBOutlet weak var reenterpassword: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Registertapped(sender: AnyObject) { let userEmail = userEmailtextfield.text; let userName = usernameTextfield.text; let userPassword = userPasswordTextfield.text; let repeatPassword = reenterpassword.text; //Check empty fields& check if password match // Check for empty fields if(userEmail!.isEmpty || userPassword!.isEmpty || repeatPassword!.isEmpty) { // Display alert message displayMyAlertMessage("All fields are required"); return; } //Check if passwords match if(userPassword != repeatPassword) { // Display an alert message displayMyAlertMessage("Passwords do not match"); return; } //Check if email valid if isValidEmail(userEmail!) { print("Validate EmailID") } else { print("invalide EmailID") displayMyAlertMessage("Invalid E-mail"); return; } //store data to mysql let post:NSString = "user_email=\(userEmail!)&user_name=\(userName!)&user_password=\(userPassword!)&c_password=\(repeatPassword)" NSLog("PostData: %@",post); let url:NSURL = NSURL(string: "https://cgi.soic.indiana.edu/~hong43/connect.php")! let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! let postLength:NSString = String( postData.length ) let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? do { urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch let error as NSError { reponseError = error urlData = nil } if ( urlData != nil ) { let res = response as! NSHTTPURLResponse!; NSLog("Response code: %ld", res.statusCode); if (res.statusCode >= 200 && res.statusCode < 300) { let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)! NSLog("Response ==> %@", responseData); var error: NSError? let jsonData:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers )) as! NSDictionary let success:NSInteger = jsonData.valueForKey("success") as! NSInteger //[jsonData[@"success"] integerValue]; NSLog("Success: %ld", success); if(success == 1) { NSLog("Sign Up SUCCESS"); self.dismissViewControllerAnimated(true, completion: nil) } else { var error_msg:NSString if jsonData["error_message"] as? NSString != nil { error_msg = jsonData["error_message"] as! NSString } else { error_msg = "Unknown Error" } let alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = error_msg as String alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { let alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Connection Failed" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { let alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Connection Failure" if let error = reponseError { alertView.message = (error.localizedDescription) } alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } /** let myUrl = NSURL(string: "https://cgi.soic.indiana.edu/~hong43/userRegister.php"); let request = NSMutableURLRequest(URL:myUrl!); request.HTTPMethod = "POST"; let postString = "email=\(userEmail!)&name=\(userName!)&password=\(userPassword!)"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in dispatch_async(dispatch_get_main_queue()) { //spinningActivity.hide(true) if error != nil { self.displayMyAlertMessage(error!.localizedDescription) return } do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary if let parseJSON = json { let resultValue = parseJSON["status"] as? String var isUserRegistered:Bool = false; if( resultValue == "Success"){ isUserRegistered = true; } var messageToDisplay:String = parseJSON["message"] as! String!; if(!isUserRegistered) { messageToDisplay = parseJSON["message"] as! String!; } let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in self.dismissViewControllerAnimated(true, completion: nil) } myAlert.addAction(okAction); self.presentViewController(myAlert, animated: true, completion: nil); } } catch{ print(error) } } }).resume() */ } // alert function func displayMyAlertMessage(userMessage:String) { let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.Alert); let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default, handler:nil); myAlert.addAction(okAction); self.presentViewController(myAlert, animated:true, completion:nil); } //validate email func isValidEmail(testStr:String) -> Bool { print("validate emilId: \(testStr)") let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" var emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) var result = emailTest.evaluateWithObject(testStr) print(result) return result } //back to sign in @IBAction func backtosignin(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } /* // 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. } */ }
apache-2.0
01241fe22376709b35a6494b715631d5
34.010601
165
0.512313
6.211912
false
false
false
false
leeaken/LTMap
LTMap/LTLocationMap/LocationManager/LTLocationManager.swift
1
3991
// // LTLocationManager.swift // LTMap // // 定位管理类 // Created by aken on 2017/6/2. // Copyright © 2017年 LTMap. All rights reserved. // import UIKit struct LTLocationManagerDefaultConfig { static let defaultLocationTimeout: NSInteger = 6 static let defaultReGeocodeTimeout: NSInteger = 3 } final class LTLocationManager : NSObject { lazy var locationManager = AMapLocationManager() var completionBlock: AMapLocatingCompletionBlock! // MARK -- 公共属性 // 经纬度 var location:CLLocationCoordinate2D? // 当前地址 var address:String? // 省/直辖市 var province:String? // 当前城市 var city:String? // 区 var district:String? // 国家 var country:String? // 单例实例化 static let shared = LTLocationManager() private override init(){ super.init() createCompleteBlock() configLocationManager() } // MARK -- 公共方法 func startUpdatingLocation() { locationManager.requestLocation(withReGeocode: true, completionBlock: completionBlock) } // MARK -- 私有方法 fileprivate func configLocationManager() { AMapServices.shared().apiKey = LTLocationMapCommon.AMapServicesApiKey locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters locationManager.pausesLocationUpdatesAutomatically = false // locationManager.allowsBackgroundLocationUpdates = true locationManager.locationTimeout = LTLocationManagerDefaultConfig.defaultLocationTimeout locationManager.reGeocodeTimeout = LTLocationManagerDefaultConfig.defaultReGeocodeTimeout } fileprivate func createCompleteBlock() { completionBlock = { [weak self] (location: CLLocation?, regeocode: AMapLocationReGeocode?, error: Error?) in if let error = error { let error = error as NSError if error.code == AMapLocationErrorCode.locateFailed.rawValue { //定位错误:此时location和regeocode没有返回值,不进行annotation的添加 print("定位错误:{\(error.code) - \(error.localizedDescription)};") return } else if error.code == AMapLocationErrorCode.reGeocodeFailed.rawValue || error.code == AMapLocationErrorCode.timeOut.rawValue || error.code == AMapLocationErrorCode.cannotFindHost.rawValue || error.code == AMapLocationErrorCode.badURL.rawValue || error.code == AMapLocationErrorCode.notConnectedToInternet.rawValue || error.code == AMapLocationErrorCode.cannotConnectToHost.rawValue { //逆地理错误:在带逆地理的单次定位中,逆地理过程可能发生错误,此时location有返回值,regeocode无返回值,进行annotation的添加 print("逆地理错误:{\(error.code) - \(error.localizedDescription)};") } } if let location = location { self?.location = location.coordinate if let regeocode = regeocode { self?.address = regeocode.formattedAddress self?.city = regeocode.city self?.district = regeocode.district self?.province = regeocode.province self?.country = regeocode.country } } } } } extension LTLocationManager : AMapLocationManagerDelegate { }
mit
4cecf5cb03ac9a10e01bf182c45e81aa
27.892308
116
0.574015
5.622754
false
false
false
false
soapyigu/LeetCode_Swift
DP/FrogJump.swift
1
1470
/** * Question Link: https://leetcode.com/problems/frog-jump/ * Primary idea: Dynamic Programming, a dictionary to keep all steps that the position * can jump, and a dp array to keep max step that the position can take * Time Complexity: O(n^2), Space Complexity: O(n) * */ class FrogJump { func canCross(_ stones: [Int]) -> Bool { guard stones.count > 1 else { return true } var indexSteps = [Int: Set<Int>](), maxStep = Array(repeating: 0, count: stones.count) var k = 0 insert(&indexSteps, 0, 0) for i in 1..<stones.count { while maxStep[k] + 1 < stones[i] - stones[k] { k += 1 } for j in k..<i { let distance = stones[i] - stones[j] if let steps = indexSteps[j], steps.contains(distance - 1) || steps.contains(distance) || steps.contains(distance + 1) { insert(&indexSteps, distance, i) maxStep[i] = max(maxStep[i], distance) } } } return maxStep.last! > 0 } private func insert(_ dict: inout [Int: Set<Int>], _ num: Int, _ index: Int) { if dict[index] != nil { dict[index]!.insert(num) } else { var set = Set<Int>() set.insert(num) dict[index] = set } } }
mit
acfd701cded2ead370299a4ef474f59e
30.276596
136
0.482993
3.951613
false
false
false
false
ls1intum/sReto
Source/sReto/Core/Utils/Timing/Timer.swift
1
12024
/** // Copyright (c) 2014 - 2016 Chair for Applied Software Engineering // // Licensed under the MIT License // // 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. // 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 /** This class offers several class methods for timer-related tasks. All of the following examples take a dispatch queue as an optional parameter to run the action on. Examples: Execute an action after a fixed delay: Timer.delay(1, action: { print("Hello 1 second later!") }) Execute an action in a fixed interval and firing prematurely / stopping the timer: let timer = Timer.repeatAction(interval: 0.5) { (timer, executionCount) -> () in print("Hello, this is execution #\(executionCount + 1)") } //... timer.fire() //... timer.stop() Execute an action in fixed intervals for a certain number of times: Timer.repeatAction(interval: 0.5, maximumExecutionCount: 5) { (timer, executionCount) -> () in print("Hello, this is execution #\(executionCount + 1)") } Execute an action an arbitrary number of times, and stop at some point: Timer.repeatAction(interval: 0.5) { (timer, executionCount) -> () in print("Hello, this is execution #\(executionCount + 1)") if someCondition { print("Stopping now.") timer.stop() } } Execute an action with growing delays. For example, when requesting data from a server that doesn't respond, it makes sense to have growing delays between each attempt. If it's your own server, it might save you from DDOSing yourself. It also limits the computation power wasted on the device. In this example, the action is executed with delays of 0.2, 0.4, 0.8, 1.6, ... seconds, but with a maximum of 10 seconds. Timer.repeatActionWithBackoff(initialDelay: 0.2, backOffFactor: 2.0, maximumDelay: 10.0, action: { (timer, executionCount) -> () in print("This action is executed in growing delays.") } ) Execute an action with user-specified delays (you figure out something to do with that). let digitsOfΠ: [Timer.TimeInterval] = [3,1,4,1,5,9,2,6,5,3] Timer.repeatAction( delayBlock: { (executionCount) -> Timer.TimeInterval in return digitsOfΠ[executionCount % 10] }, action: { (timer, executionCount) -> () in print("What is this!") } ) */ open class Timer { /** Represents a time interval in seconds */ public typealias TimeInterval = Double /** An action executed by a Timer if it is repeated. A Timer object is passed to allow stopping of the timer, as well as the number of executions. */ public typealias TimerAction = (_ timer: Timer, _ executionCount: Int) -> () /** An function that returns a time interval. */ public typealias DelayBlock = (_ executionCount: Int) -> TimeInterval /** Executes a block after a given delay. - parameter delay: The delay in seconds after which the action block is executed - parameter dispatchQueue: Optional. A dispatch queue on which to execute the action. The main dispatch queue is used by default. - parameter action: The action to execute. */ open class func delay( _ delay: TimeInterval, dispatchQueue: DispatchQueue = DispatchQueue.main, action: @escaping () -> ()) -> Timer { return Timer( delayBlock: { _ in delay }, dispatchQueue: dispatchQueue, maximumExecutions: 1, action: { _, _ in action() } ) } /** Executes a block in regular intervals. - parameter interval: The interval in seconds in which the action will be executed. - parameter dispatchQueue: Optional. A dispatch queue on which to execute the action. The main dispatch queue is used by default. - parameter maximumExecutionCount: Optional. The maximum number of times the action will be executed. Pass nil to not have a limit. Nil by default. - parameter action: The action to execute. */ open class func repeatAction( interval: TimeInterval, dispatchQueue: DispatchQueue = DispatchQueue.main, maximumExecutionCount: Int? = nil, action: @escaping TimerAction) -> Timer { return Timer( delayBlock: { _ in interval }, dispatchQueue: dispatchQueue, maximumExecutions: maximumExecutionCount, action: action ) } /** Executes a block in growing intervals. For example, with an initialDelay of 1 and a backOffFactor of 2, the action will be executed using the following intervals: 1, 2, 4, 8, 16, ... - parameter initialDelay: The delay in seconds after which the action will be executed the first time. - parameter backOffFactor: Optional. The delay will be increased by this factor with each execution of the action. 1.5 by default. - parameter maximumDelay: Optional. The delay will not increase past this maximum delay (also passed in seconds). Pass nil to not use a maximum delay. Nil by default. - parameter dispatchQueue: Optional. A dispatch queue on which to execute the action. The main dispatch queue is used by default. - parameter maximumExecutionCount: Optional. The maximum number of times the action will be executed. Pass nil to not have a limit. Nil by default. - parameter action: The action to execute. */ open class func repeatActionWithBackoff ( initialDelay: TimeInterval, backOffFactor: Double = 1.5, maximumDelay: TimeInterval? = nil, dispatchQueue: DispatchQueue = DispatchQueue.main, maximumExecutionCount: Int? = nil, action: @escaping TimerAction) -> Timer { return Timer( delayBlock: { executionCount in let timeInterval = TimeInterval(initialDelay * pow(backOffFactor, Double(executionCount))) if let maximum = maximumDelay { return min(timeInterval, maximum) } return timeInterval }, dispatchQueue: dispatchQueue, maximumExecutions: maximumExecutionCount, action: action ) } public typealias BackoffTimerSettings = (initialInterval: TimeInterval, backOffFactor: Double, maximumDelay: TimeInterval?) open class func repeatActionWithBackoff ( timerSettings: BackoffTimerSettings, dispatchQueue: DispatchQueue = DispatchQueue.main, maximumExecutionCount: Int? = nil, action: @escaping TimerAction) -> Timer { return repeatActionWithBackoff(initialDelay: timerSettings.initialInterval, backOffFactor: timerSettings.backOffFactor, maximumDelay: timerSettings.maximumDelay, dispatchQueue: dispatchQueue, maximumExecutionCount: maximumExecutionCount, action: action) } /** Executes a block with user-specified delays. - parameter delayBlock: Should return the delay in seconds in which the next execution of the action should occur. - parameter dispatchQueue: Optional. A dispatch queue on which to execute the action. The main dispatch queue is used by default. - parameter maximumExecutionCount: Optional. The maximum number of times the action will be executed. Pass nil to not have a limit. Nil by default. - parameter action: The action to execute. */ open class func repeatAction ( delayBlock: @escaping DelayBlock, dispatchQueue: DispatchQueue = DispatchQueue.main, maximumExecutionCount: Int? = nil, action: @escaping TimerAction) -> Timer { return Timer( delayBlock: delayBlock, dispatchQueue: dispatchQueue, maximumExecutions: maximumExecutionCount, action: action ) } fileprivate let dispatchQueue: DispatchQueue fileprivate let delayBlock: DelayBlock fileprivate let action: TimerAction fileprivate let maximumExecutions: Int? fileprivate var currentExecutionCount: Int = 0 fileprivate var isDone: Bool = false fileprivate var selfRetain: Timer? fileprivate init(delayBlock: @escaping DelayBlock, dispatchQueue: DispatchQueue, maximumExecutions: Int?, action: @escaping TimerAction) { self.delayBlock = delayBlock self.dispatchQueue = dispatchQueue self.maximumExecutions = maximumExecutions self.action = action self.selfRetain = self self.startTimer() } /** Stops the Timer. No actions will be executed anymore. */ open func stop() { self.isDone = true self.selfRetain = nil } /** Fires the timer prematurely. The action is only executed if the Timer is still running. */ open func fire() { if self.isDone { return } self.action(self, self.currentExecutionCount) self.currentExecutionCount += 1 if let maximum = self.maximumExecutions { if self.currentExecutionCount >= maximum { self.isDone = true } } if !self.isDone { self.startTimer() } else { self.selfRetain = nil } } fileprivate func startTimer() { let delay = Int64(self.delayBlock(self.currentExecutionCount) * Double(NSEC_PER_SEC)) self.dispatchQueue.asyncAfter( deadline: DispatchTime.now() + Double(delay) / Double(NSEC_PER_SEC)) { [weak self] in if let weakSelf = self { weakSelf.fire() } } } }
mit
9c7af8bc8b73eb9deb6ec182f27b8133
36.68652
293
0.660872
4.849536
false
false
false
false
ostatnicky/kancional-ios
Pods/BonMot/Sources/StringStyle+Part.swift
1
12207
// // StringStyle+Part.swift // BonMot // // Created by Brian King on 9/1/16. // Copyright © 2016 Raizlabs. All rights reserved. // #if os(OSX) import AppKit #else import UIKit #endif extension StringStyle { /// Each `Part` encapsulates one setting in a `StringStyle`. It is used /// in a DSL for building `StringStyle` across BonMot. public enum Part { case extraAttributes(StyleAttributes) case font(BONFont) case link(URL) case backgroundColor(BONColor) case color(BONColor) case underline(NSUnderlineStyle, BONColor?) case strikethrough(NSUnderlineStyle, BONColor?) case baselineOffset(CGFloat) #if os(iOS) || os(tvOS) || os(watchOS) /// If set to `true`, when the string is read aloud, all punctuation will /// be spoken aloud as well. case speaksPunctuation(Bool) /// The BCP 47 language code that you would like the system to use when /// reading this string aloud. A BCP 47 language code is generally of /// the form “language-REGION”, e.g. “en-US”. You can see a [list of /// languages and regions](http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry) /// and learn more about [BCP 47](https://www.rfc-editor.org/rfc/rfc5646.txt). case speakingLanguage(String) /// The pitch of the voice used to read the text aloud. The range is /// 0 to 2, where 0 is the lowest, 2 is the highest, and 1 is the default. case speakingPitch(Double) /// The IPA pronunciation of the given range. case speakingPronunciation(String) /// Whether the spoken text is queued behind, or interrupts, existing spoken content. case shouldQueueSpeechAnnouncement(Bool) /// The accessibility heading level of the text. case headingLevel(HeadingLevel) #endif case ligatures(Ligatures) case alignment(NSTextAlignment) case tracking(Tracking) case lineSpacing(CGFloat) case paragraphSpacingAfter(CGFloat) case firstLineHeadIndent(CGFloat) case headIndent(CGFloat) case tailIndent(CGFloat) case lineBreakMode(NSParagraphStyle.LineBreakMode) case minimumLineHeight(CGFloat) case maximumLineHeight(CGFloat) case baseWritingDirection(NSWritingDirection) case lineHeightMultiple(CGFloat) case paragraphSpacingBefore(CGFloat) /// Values from 0 to 1 will result in varying levels of hyphenation, /// with higher values resulting in more aggressive (i.e. more frequent) /// hyphenation. /// /// Hyphenation is attempted when the ratio of the text width (as broken /// without hyphenation) to the width of the line fragment is less than /// the hyphenation factor. When the paragraph’s hyphenation factor is /// 0.0, the layout manager’s hyphenation factor is used instead. When /// both are 0.0, hyphenation is disabled. case hyphenationFactor(Float) case xml case xmlRules([XMLStyleRule]) case xmlStyler(XMLStyler) case transform(Transform) #if os(iOS) || os(tvOS) || os(OSX) case fontFeature(FontFeatureProvider) case numberSpacing(NumberSpacing) case numberCase(NumberCase) case fractions(Fractions) case superscript(Bool) case `subscript`(Bool) case ordinals(Bool) case scientificInferiors(Bool) case smallCaps(SmallCaps) case stylisticAlternates(StylisticAlternates) case contextualAlternates(ContextualAlternates) #endif #if os(iOS) || os(tvOS) case textStyle(BonMotTextStyle) #endif #if os(iOS) || os(tvOS) case adapt(AdaptiveStyle) #endif case emphasis(Emphasis) // An advanced part that allows combining multiple parts as a single part case style(StringStyle) } /// Create a `StringStyle` from zero or more `Part`s. /// /// - Parameter parts: Zero or more `Part`s public init(_ parts: Part...) { self.init(parts) } /// Create a `StringStyle` from an array of parts /// /// - Parameter parts: An array of `StylePart`s public init(_ parts: [Part]) { self.init() for part in parts { update(part: part) } } /// Derive a new `StringStyle` based on this style, updated with zero or /// more `Part`s. /// /// - Parameter parts: Zero or more `Part`s /// - Returns: A newly configured `StringStyle` public func byAdding(_ parts: Part...) -> StringStyle { return byAdding(parts) } /// Derive a new `StringStyle` based on this style, updated with zero or /// more `Part`s. /// /// - Parameter parts: an array of `Part`s /// - Returns: A newly configured `StringStyle` public func byAdding(_ parts: [Part]) -> StringStyle { var style = self for part in parts { style.update(part: part) } return style } //swiftlint:disable function_body_length //swiftlint:disable cyclomatic_complexity /// Update the style with the specified style part. /// /// - Parameter stylePart: The style part with which to update the receiver. mutating func update(part stylePart: Part) { switch stylePart { case let .extraAttributes(attributes): self.extraAttributes = attributes case let .font(font): self.font = font case let .link(link): self.link = link case let .backgroundColor(backgroundColor): self.backgroundColor = backgroundColor case let .color(color): self.color = color case let .underline(underline): self.underline = underline case let .strikethrough(strikethrough): self.strikethrough = strikethrough case let .baselineOffset(baselineOffset): self.baselineOffset = baselineOffset case let .ligatures(ligatures): self.ligatures = ligatures case let .alignment(alignment): self.alignment = alignment case let .tracking(tracking): self.tracking = tracking case let .lineSpacing(lineSpacing): self.lineSpacing = lineSpacing case let .paragraphSpacingAfter(paragraphSpacingAfter): self.paragraphSpacingAfter = paragraphSpacingAfter case let .firstLineHeadIndent(firstLineHeadIndent): self.firstLineHeadIndent = firstLineHeadIndent case let .headIndent(headIndent): self.headIndent = headIndent case let .tailIndent(tailIndent): self.tailIndent = tailIndent case let .lineBreakMode(lineBreakMode): self.lineBreakMode = lineBreakMode case let .minimumLineHeight(minimumLineHeight): self.minimumLineHeight = minimumLineHeight case let .maximumLineHeight(maximumLineHeight): self.maximumLineHeight = maximumLineHeight case let .baseWritingDirection(baseWritingDirection): self.baseWritingDirection = baseWritingDirection case let .lineHeightMultiple(lineHeightMultiple): self.lineHeightMultiple = lineHeightMultiple case let .paragraphSpacingBefore(paragraphSpacingBefore): self.paragraphSpacingBefore = paragraphSpacingBefore case .xml: self.xmlStyler = NSAttributedString.defaultXMLStyler case var .xmlRules(rules): rules.append(contentsOf: Special.insertionRules) self.xmlStyler = XMLStyleRule.Styler(rules: rules) case let .xmlStyler(xmlStyler): self.xmlStyler = xmlStyler case let .transform(transform): self.transform = transform case let .style(style): self.add(stringStyle: style) case let .emphasis(emphasis): self.emphasis = emphasis default: // interaction between `#if` and `switch` is disappointing. This case // is in `default:` to remove a warning that default won't be accessed // on some platforms. switch stylePart { case let .hyphenationFactor(hyphenationFactor): self.hyphenationFactor = hyphenationFactor default: #if os(iOS) || os(tvOS) || os(watchOS) switch stylePart { case let .speaksPunctuation(speaksPunctuation): self.speaksPunctuation = speaksPunctuation return case let .speakingLanguage(speakingLanguage): self.speakingLanguage = speakingLanguage return case let .speakingPitch(speakingPitch): self.speakingPitch = speakingPitch return case let .speakingPronunciation(speakingPronunciation): self.speakingPronunciation = speakingPronunciation return case let .shouldQueueSpeechAnnouncement(shouldQueueSpeechAnnouncement): self.shouldQueueSpeechAnnouncement = shouldQueueSpeechAnnouncement return case let .headingLevel(headingLevel): self.headingLevel = headingLevel return default: break } #endif #if os(OSX) || os(iOS) || os(tvOS) switch stylePart { case let .numberCase(numberCase): self.numberCase = numberCase case let .numberSpacing(numberSpacing): self.numberSpacing = numberSpacing case let .fractions(fractions): self.fractions = fractions case let .superscript(superscript): self.superscript = superscript case let .`subscript`(`subscript`): self.`subscript` = `subscript` case let .ordinals(ordinals): self.ordinals = ordinals case let .scientificInferiors(scientificInferiors): self.scientificInferiors = scientificInferiors case let .smallCaps(smallCaps): self.smallCaps.insert(smallCaps) case let .stylisticAlternates(stylisticAlternates): self.stylisticAlternates.add(other: stylisticAlternates) case let .contextualAlternates(contextualAlternates): self.contextualAlternates.add(other: contextualAlternates) case let .fontFeature(featureProvider): self.fontFeatureProviders.append(featureProvider) default: #if os(iOS) || os(tvOS) switch stylePart { case let .adapt(style): self.adaptations.append(style) case let .textStyle(textStyle): self.font = UIFont.bon_preferredFont(forTextStyle: textStyle, compatibleWith: nil) default: fatalError("StylePart \(stylePart) should have been caught by an earlier case.") } #else fatalError("StylePart \(stylePart) should have been caught by an earlier case.") #endif } #else fatalError("StylePart \(stylePart) should have been caught by an earlier case.") #endif } } } //swiftlint:enable function_body_length //swiftlint:enable cyclomatic_complexity }
mit
5d0c478ac4752a4f995851228dbb8c7f
39.377483
117
0.589962
5.269663
false
false
false
false
danghoa/GGModules
GGModules/Controllers/GGNetwork/GGCore/GGExtensionDictionary+Array.swift
1
5593
// // GGExtensionDictionary+Array.swift // GGStructureSwift // // Created by Đăng Hoà on 9/15/15. // Copyright (c) 2015 ___GREENGLOBAL___. All rights reserved. // import Foundation public extension NSMutableArray { func kRemoveObjectAtIndex(_ index: Int) -> Void { if self.count > 0 { if index < self.count { self.removeObject(at: index) } else { print("Extension: Don't remove object") } } else { print("Extension: Don't remove object") } } func kReplaceObjectAtIndex(_ index: Int, withObject object: AnyObject?) -> Void { if self.count > 0 { if index < self.count && object != nil { self.replaceObject(at: index, with: object!) } else { print("Extension: Don't replace object") } } else { print("Extension: Don't replace object") } } func kInsertObject(_ object: AnyObject?, atIndex index: Int) -> Void { if self.count > 0 { if index < self.count && object != nil { self.insert(object!, at: index) } else { print("Extension: Don't insert object") } } else { print("Extension: Don't insert object") } } } public extension NSArray { func isEmpty() -> Bool { if self.count > 0 { return false } else { return true } } func kObjectAtIndex(_ index: Int) -> AnyObject? { if self.isEmpty() == true { return nil } else { return self.object(at: index) as AnyObject? } } } public extension NSDictionary { func checkNumeric(_ s: String) -> Bool { let sc: Scanner = Scanner(string: s) if sc.scanFloat(nil) { return sc.isAtEnd } else { return false } } func parseObjectForKey(_ key: String) -> AnyObject { return self.object(forKey: key)! as AnyObject } func dictionaryForKey(_ key: String) -> NSDictionary? { if self.object(forKey: key) != nil { return self.object(forKey: key) as? NSDictionary } else { return nil } } func arrayForKey(_ key: String) -> NSArray? { if (self.object(forKey: key) as AnyObject).isKind(of: NSArray.classForCoder()) == true { return self.object(forKey: key) as? NSArray } else { return nil } } func stringForKey(_ key: String) -> String { if self.object(forKey: key) != nil { if (self.object(forKey: key) as AnyObject).isKind(of: NSString.classForCoder()) == true { let temp: String = self.object(forKey: key) as! String if temp == "null" || temp == "<null>" || temp == "(null)" || temp == "" || temp.isEmpty { return "" } else { return NSDictionary.stringByStrippingHTML(temp) } } else { return "" } } else { return "" } } func intForKey(_ key: String) -> Int { let temp = self.object(forKey: key) if temp == nil { return 0 } else { if (self.object(forKey: key)! as AnyObject).isKind(of: NSNumber.classForCoder()) == true { let num: NSNumber = self.object(forKey: key) as! NSNumber return num.intValue } else { return 0 } } } func floatForKey(_ key: String) -> Float { let temp = self.object(forKey: key) if temp == nil { return 0.0 } else { if (self.object(forKey: key)! as AnyObject).isKind(of: NSNumber.classForCoder()) == true { let num: NSNumber = self.object( forKey: key) as! NSNumber let temp: String = String(format: "%f", num.floatValue) if temp == "null" || temp == "<null>" || temp == "(null)" || temp == "" || temp.isEmpty { return 0.0 } else { return NSString(string: temp).floatValue } } else if (self.object(forKey: key)! as AnyObject).isKind(of: NSString.classForCoder()) { let temp: String = self.object(forKey: key) as! String if temp == "null" || temp == "<null>" || temp == "(null)" || temp == "" || temp.isEmpty { return 0.0 } else { return NSString(string: temp).floatValue } } else { return 0.0 } } } func doubleForKey(_ key: String) -> Double { let temp = self.object(forKey: key) if temp == nil { return 0.0000000 } else { if (self.object(forKey: key)! as AnyObject).isKind(of: NSNumber.classForCoder()) == true { let num: NSNumber = self.object( forKey: key) as! NSNumber let temp: String = String(format: "%f", num.floatValue) if temp == "null" || temp == "<null>" || temp == "(null)" || temp == "" || temp.isEmpty { return 0.0000000 } else { return NSString(string: temp).doubleValue } } else if (self.object(forKey: key)! as AnyObject).isKind(of: NSString.classForCoder()) { let temp: String = self.object(forKey: key) as! String if temp == "null" || temp == "<null>" || temp == "(null)" || temp == "" || temp.isEmpty { return 0.0000000 } else { return NSString(string: temp).doubleValue } } else { return 0.0000000 } } } fileprivate class func stringByStrippingHTML(_ string: String) -> String { var r: NSRange var s: NSString = NSString(string: string) r = s.range(of: "<[^>]+>", options: NSString.CompareOptions.regularExpression) while r.location != NSNotFound { s = s.replacingCharacters(in: r, with: "") as NSString r = s.range(of: "<[^>]+>", options: NSString.CompareOptions.regularExpression) } return s as String; } }
mit
b6af7d5fe776bbd6e0893d7e61a60986
24.642202
97
0.564043
3.931083
false
false
false
false
airfight/ATAnimatons
ATAnimatons/OznerTools.swift
1
2955
// // OznerTools.swift // OznerLibrarySwiftyDemo // // Created by 赵兵 on 2017/1/5. // Copyright © 2017年 net.ozner. All rights reserved. // import UIKit class OznerTools: NSObject { class func dataFromInt16(number:UInt16)->Data { let data = NSMutableData() // var val = CFSwapInt16HostToBig(number) var val = CFSwapInt16LittleToHost(number) data.append(&val, length: MemoryLayout<UInt16>.size) return data as Data } class func dataFromInt(number:CLongLong,length:Int)->Data{ var data=Data() if length<1 { return data } var tmpValue = CLongLong(0) for i in 0...(length-1) { let powInt = CLongLong(pow(CGFloat(256), CGFloat(i))) let needEle=(number-tmpValue)/powInt%256 data.append(UInt8(needEle)) tmpValue+=CLongLong(needEle)*powInt } return data } class func hexStringFromData(data:Data)->String{ var hexStr="" for i in 0..<data.count { if Int(data[i])<16 { hexStr=hexStr.appendingFormat("0") } hexStr=hexStr.appendingFormat("%x",Int(data[i])) } return hexStr } class func hexStringToData(strHex:String)->Data{ var data=Data() if strHex.characters.count%2 != 0 { return data } for i in 0..<strHex.characters.count/2 { let range1 = strHex.index(strHex.startIndex, offsetBy: i*2) let range2 = strHex.index(strHex.startIndex, offsetBy: i*2+2) let hexString = strHex.substring(with: Range(range1..<range2)) var result1:UInt32 = 0 Scanner(string: hexString).scanHexInt32(&result1) data.insert(UInt8(result1), at: i) } return data } } extension Data{ func subInt(starIndex:Int,count:Int) -> Int { if starIndex+count>self.count { return 0 } var dataValue = 0 for i in 0..<count { dataValue+=Int(Float(self[i+starIndex])*powf(256, Float(i))) } return dataValue } func subString(starIndex:Int,count:Int) -> String { if starIndex+count>self.count { return "" } let range1 = self.index(self.startIndex, offsetBy: starIndex) let range2 = self.index(self.startIndex, offsetBy: starIndex+count) let valueData=self.subdata(in: Range(range1..<range2)) return String.init(data: valueData, encoding: String.Encoding.utf8)! } func subData(starIndex:Int,count:Int) -> Data { if starIndex+count>self.count { return Data.init() } let range1 = self.index(self.startIndex, offsetBy: starIndex) let range2 = self.index(self.startIndex, offsetBy: starIndex+count) return self.subdata(in: Range(range1..<range2)) } }
mit
5450e65b2aa38f7666e60f6bcd3dc321
30.361702
76
0.578358
3.848564
false
false
false
false
mirrorinf/BrenchMark
MetalScore/MetalScore/AlignedFloatArray.swift
1
790
// // AlignedFloatArray.swift // DeveloperAid // // Created by 褚晓敏 on 2/6/16. // Copyright © 2016 Levity. All rights reserved. // import Foundation class AlignedFloatArray { let size: Int let managing: UnsafeMutableBufferPointer<Float> let raw: UnsafeMutablePointer<Void> init(size: Int) { self.size = size var temp: UnsafeMutablePointer<Void> = nil let originalSize = sizeof(Float) * size posix_memalign(&temp, 0x4000, Int(originalSize / 4096 + 1) * 4096) self.raw = temp let pptr = COpaquePointer(temp) let nptr = UnsafeMutablePointer<Float>(pptr) self.managing = UnsafeMutableBufferPointer<Float>(start: nptr, count: size) } subscript (index: Int) -> Float { get { return managing[index] } set { managing[index] = newValue } } }
apache-2.0
8d472873dd0c413d53abc199215f99cf
20.189189
77
0.693487
3.209016
false
false
false
false
Eitot/vienna-rss
Vienna/Sources/Shared/Constants.swift
1
1466
// // Constants.swift // Vienna // // Copyright 2020 // // 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 // // https://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. // /// New articles notification method (managed as an array of binary flags) @objc enum VNANewArticlesNotification: Int { case bounce = 2 } /// Filtering options @objc enum VNAFilter: Int { case all = 0 case unread = 1 case lastRefresh = 2 case today = 3 case time48h = 4 case flagged = 5 case unreadOrFlagged = 6 } /// Refresh folder options @objc enum VNARefresh: Int { case redrawList = 0 case reapplyFilter = 1 case sortAndRedraw = 3 } /// Layout styles @objc enum VNALayout: Int { case report = 1 case condensed = 2 case unified = 3 } /// Folders tree sort method @objc enum VNAFolderSort: Int { case manual = 0 case byName = 1 } /// Empty trash option on quitting @objc enum VNAEmptyTrash: Int { case none = 0 case withoutWarning = 1 case withWarning = 2 }
apache-2.0
9711704ba22c1796aab55389183dd4bd
20.880597
76
0.684175
3.683417
false
false
false
false
fhbystudy/TYMutiTaskKit
TYMutiTaskKit/Tasks/TYTaskManager.swift
1
9461
// // TYTaskManager.swift // TYMutiTaskKit // // Created by Tonny.hao on 2/12/15. // Copyright (c) 2015 Tonny.hao. All rights reserved. // import UIKit private var concurrentContext = 0 private var serialContext = 1 private let kMutiTaskQueque = "tonny.hao.TYMutiTaskQueque" class TYTaskManager: NSObject { private var concurrentQueque:NSOperationQueue = NSOperationQueue() private var serialQueque:NSOperationQueue { var serialThreadQueque = NSOperationQueue() serialThreadQueque.maxConcurrentOperationCount = 1 return serialThreadQueque } private let workQueue = dispatch_queue_create(kMutiTaskQueque, DISPATCH_QUEUE_SERIAL) private var concurrentArray:[TYBaseTask] = [] private var serialArray:[TYBaseTask] = [] var concurrentNum:NSInteger = 5 { didSet { self.concurrentQueque.maxConcurrentOperationCount = self.concurrentNum } } // A shared instance of `TYTaskManager` class var sharedInstance: TYTaskManager { struct Singleton { static let instance = TYTaskManager() } return Singleton.instance } required override init() { super.init() concurrentQueque.addObserver(self, forKeyPath:"operationCount", options: .New, context: &concurrentContext) serialQueque.addObserver(self, forKeyPath:"operationCount", options: .New, context: &serialContext) } deinit{ } func resumeAll() { self.serialQueque.suspended = false self.concurrentQueque.suspended = false } func PauseAll() { self.serialQueque.suspended = true self.concurrentQueque.suspended = true } func stopAll() { self.serialQueque.cancelAllOperations() self.concurrentQueque.cancelAllOperations() } override func observeValueForKeyPath(keyPath:String,ofObject:AnyObject,change:[NSObject:AnyObject],context:UnsafeMutablePointer<Void>){ if(context == &concurrentContext){ println("Changed to:\(change[NSKeyValueChangeNewKey]!)") var newOperationCount: AnyObject = change[NSKeyValueChangeNewKey]! var newNumber = (newOperationCount as NSNumber).integerValue if newNumber < self.concurrentNum { fetchConcurrentTask() } } else if (context == &serialContext) { println("Changed to:\(change[NSKeyValueChangeNewKey]!)") } } func setConcurrenceNum(aNum:Int){ self.concurrentNum = aNum } /** * from this method ,the task is added in the concurrent queque,and can be * processed base on task perioty and the task may not be processed immedately * * @param aTask:TYBaseTask subclass object * * @return boolean value indicate the add action whether succeed! */ func addTask(aTask:TYBaseTask) -> Bool { var isAddSuc = true var isBlockFinished = -1 dispatch_async(self.workQueue , { if self.concurrentArray.count < 1 { if self.concurrentQueque.operationCount < self.concurrentNum { self.concurrentQueque.addOperation(aTask) isBlockFinished = 1 return } self.concurrentArray.append(aTask) isBlockFinished = 1 return } var filterArray = self.concurrentArray.filter({ (task:TYBaseTask) -> Bool in if task.taskID == aTask.taskID { return true }else{ return false } }) if filterArray.count < 1{ self.concurrentArray.append(aTask) }else{ var filterTask = filterArray[0] filterTask.priority = aTask.priority isAddSuc = false } isBlockFinished = 1 }) while isBlockFinished < 1 { NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceReferenceDate:0.01)) } return isAddSuc } /** * if a task need to be processed immediately,we should use this method * * @param aTask:TYBaseTask subclass object * * @return boolean value indicate the add action whether succeed! */ func addSyncTask(aTask:TYBaseTask) -> Bool { var isAddSuc = true var isBlockFinished = -1 dispatch_async(self.workQueue , { if self.serialArray.count < 1 { self.serialArray.append(aTask) isBlockFinished = 1 return } var filterArray = self.serialArray.filter({ (task:TYBaseTask) -> Bool in if task.taskID == aTask.taskID { return true }else{ return false } }) if filterArray.count < 1{ self.serialArray.append(aTask) }else{ var filterTask = filterArray[0] filterTask.priority = aTask.priority isAddSuc = false } isBlockFinished = 1 }) while isBlockFinished < 1 { NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceReferenceDate:0.01)) } return isAddSuc } /** * remove the task in the queque or in the array * * @param aTask:TYBaseTask subclass object * * @return boolean value indicate the remove action whether succeed! */ func removeTask(aTask:TYBaseTask) -> Bool { var isRemoveSuc = false var isBlockFinished = -1 dispatch_async(self.workQueue , { //find the task from concurrent array (the task has not been added to concurrent thread queque) isRemoveSuc = self.removeTaskElementInArray(aTask, elementArray: &self.concurrentArray) /* find the task from concurrent thread queque, if finded,cancel the operation will cause the thread queque remove it form the queque */ var quequeFilterArray = self.concurrentQueque.operations as [TYBaseTask] if quequeFilterArray.count > 0 { var index = -1 var isFind = false for value:TYBaseTask in quequeFilterArray { index += 1 if value.taskID == aTask.taskID { isFind = true value.cancel() break } } if isFind { isRemoveSuc = true } } // find the task from serial array and remove it var isRemoveSerialSuc = self.removeTaskElementInArray(aTask, elementArray: &self.serialArray) if isRemoveSerialSuc { isRemoveSuc = isRemoveSerialSuc } isBlockFinished = 1 }) while isBlockFinished < 1 { NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceReferenceDate:0.01)) } return isRemoveSuc } private func removeTaskElementInArray(aTask:TYBaseTask, inout elementArray:[TYBaseTask])->Bool{ var isRemoveSuc = false var index = -1 var isFind = false for value:TYBaseTask in elementArray { index += 1 if value.taskID == aTask.taskID { isFind = true break } } if isFind { elementArray.removeAtIndex(index) isRemoveSuc = true } return isRemoveSuc } private func fetchConcurrentTask() { dispatch_async(self.workQueue , { println("courrent concurrent operate count is \(self.concurrentQueque.operationCount) ") if self.concurrentQueque.operationCount >= self.concurrentNum { return } if self.concurrentArray.count > 0 { println("concurrent array count is \(self.concurrentArray.count)") self.concurrentArray.sort({ (t1:TYBaseTask, t2:TYBaseTask) -> Bool in if t1.priority < t1.priority { return true } else{ return false } }) var removedTask = self.concurrentArray.removeAtIndex(0) self.concurrentQueque.addOperation(removedTask) } }) } private func fetchSerialTask() { dispatch_async(self.workQueue , { if self.serialArray.count > 0 { var count = self.serialArray.count var removedTask = self.serialArray.removeAtIndex(count-1) self.serialQueque.addOperation(removedTask) } }) } /** * query the task in the queque or in the array * * @param aTaskId , task id that the unique indicating for the task * * @return TYBaseTask that queryed task, return value maybe nil */ func queryTask(aTaskId:String!) -> TYBaseTask? { var task:TYBaseTask? return task; } }
apache-2.0
8159fd1e57f7f54682fa478e300874da
32.073427
140
0.561899
4.936848
false
false
false
false
einsteinx2/iSub
Carthage/Checkouts/KSHLSPlayer/Carthage/Checkouts/swifter/Sources/DemoServer.swift
1
3938
// // DemoServer.swift // Swifter // Copyright (c) 2015 Damian Kołakowski. All rights reserved. // import Foundation public func demoServer(publicDir: String?) -> HttpServer { let server = HttpServer() if let publicDir = publicDir { server["/resources/:file"] = HttpHandlers.directory(publicDir) } server["/files/:path"] = HttpHandlers.directoryBrowser("~/") server["/"] = { r in var listPage = "Available services:<br><ul>" for services in server.routes { if services.isEmpty { listPage += "<li><a href=\"/\">/</a></li>" } else { listPage += "<li><a href=\"\(services)\">\(services)</a></li>" } } listPage += "</ul>" return .OK(.Html(listPage)) } server["/magic"] = { .OK(.Html("You asked for " + $0.path)) } server["/test/:param1/:param2"] = { r in var headersInfo = "" for (name, value) in r.headers { headersInfo += "\(name) : \(value)<br>" } var queryParamsInfo = "" for (name, value) in r.queryParams { queryParamsInfo += "\(name) : \(value)<br>" } var pathParamsInfo = "" for token in r.params { pathParamsInfo += "\(token.0) : \(token.1)<br>" } return .OK(.Html("<h3>Address: \(r.address)</h3><h3>Url:</h3> \(r.path)<h3>Method:</h3>\(r.method)<h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)<h3>Path params:</h3>\(pathParamsInfo)")) } server.GET["/upload"] = { r in if let rootDir = publicDir, html = NSData(contentsOfFile:"\(rootDir)/file.html") { var array = [UInt8](count: html.length, repeatedValue: 0) html.getBytes(&array, length: html.length) return HttpResponse.RAW(200, "OK", nil, { $0.write(array) }) } return .NotFound } server.POST["/upload"] = { r in var response = "" for multipart in r.parseMultiPartFormData() { response += "Name: \(multipart.name) File name: \(multipart.fileName) Size: \(multipart.body.count)<br>" } return HttpResponse.OK(.Html(response)) } server.GET["/login"] = { r in if let rootDir = publicDir, html = NSData(contentsOfFile:"\(rootDir)/login.html") { var array = [UInt8](count: html.length, repeatedValue: 0) html.getBytes(&array, length: html.length) return HttpResponse.RAW(200, "OK", nil, { $0.write(array) }) } return .NotFound } server.POST["/login"] = { r in let formFields = r.parseUrlencodedForm() return HttpResponse.OK(.Html(formFields.map({ "\($0.0) = \($0.1)" }).joinWithSeparator("<br>"))) } server["/demo"] = { r in return .OK(.Html("<center><h2>Hello Swift</h2><img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br></center>")) } server["/raw"] = { r in return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], { $0.write([UInt8]("test".utf8)) }) } server["/json"] = { r in let jsonObject: NSDictionary = [NSString(string: "foo"): NSNumber(int: 3), NSString(string: "bar"): NSString(string: "baz")] return .OK(.Json(jsonObject)) } server["/redirect"] = { r in return .MovedPermanently("http://www.google.com") } server["/long"] = { r in var longResponse = "" for k in 0..<1000 { longResponse += "(\(k)),->" } return .OK(.Html(longResponse)) } server["/wildcard/*/test/*/:param"] = { r in return .OK(.Html(r.path)) } server["/stream"] = { r in return HttpResponse.RAW(200, "OK", nil, { w in for i in 0...100 { w.write([UInt8]("[chunk \(i)]".utf8)); } }) } return server }
gpl-3.0
c0457334b4acbe7907fdd4ab33a19996
33.234783
211
0.531623
3.774688
false
false
false
false
EasySwift/EasySwift
Carthage/Checkouts/swiftScan/swiftScan/ViewController.swift
2
13202
// // ViewController.swift // swiftScan // // Created by xialibing on 15/11/25. // Copyright © 2015年 xialibing. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate { var tableView: UITableView! var arrayItems:Array<Array<String>> = [ ["模拟qq扫码界面","qqStyle"], ["模仿支付宝扫码区域","ZhiFuBaoStyle"], ["模仿微信扫码区域","weixinStyle"], ["无边框,内嵌4个角","InnerStyle"], ["4个角在矩形框线上,网格动画","OnStyle"], ["自定义颜色","changeColor"], ["只识别框内","recoCropRect"], ["改变尺寸","changeSize"], ["条形码效果","notSquare"], ["二维码/条形码生成","myCode"], ["相册","openLocalPhotoAlbum"] ]; override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height)) self.title = "swift 扫一扫" tableView.delegate = self tableView.dataSource = self self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") view.addSubview(tableView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return arrayItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath) // Configure the cell... cell.textLabel?.text = arrayItems[indexPath.row].first return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //objc_msgSend对应方法好像没有 let sel = NSSelectorFromString(arrayItems[indexPath.row].last!) if responds(to: sel) { perform(sel) } tableView.deselectRow(at: indexPath as IndexPath, animated: true) } //MARK: ----模仿qq扫码界面--------- func qqStyle() { print("qqStyle") let vc = QQScanViewController(); var style = LBXScanViewStyle() style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } //MARK: ---模仿支付宝------ func ZhiFuBaoStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 60; style.xScanRetangleOffset = 30; if UIScreen.main.bounds.size.height <= 480 { //3.5inch 显示的扫码缩小 style.centerUpOffset = 40; style.xScanRetangleOffset = 20; } style.red_notRecoginitonArea = 0.4 style.green_notRecoginitonArea = 0.4 style.blue_notRecoginitonArea = 0.4 style.alpa_notRecoginitonArea = 0.4 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 2.0; style.photoframeAngleW = 16; style.photoframeAngleH = 16; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid; style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_full_net") let vc = LBXScanViewController(); vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } func createImageWithColor(color:UIColor)->UIImage { let rect=CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0); UIGraphicsBeginImageContext(rect.size); let context = UIGraphicsGetCurrentContext(); context!.setFillColor(color.cgColor); context!.fill(rect); let theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage!; } //MARK: -------条形码扫码界面 --------- func notSquare() { //设置扫码区域参数 //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 4; style.photoframeAngleW = 28; style.photoframeAngleH = 16; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.LineStill; style.animationImage = createImageWithColor(color: UIColor.red) //非正方形 //设置矩形宽高比 style.whRatio = 4.3/2.18; //离左边和右边距离 style.xScanRetangleOffset = 30; let vc = LBXScanViewController(); vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } //MARK: ----无边框,内嵌4个角 ----- func InnerStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 3; style.photoframeAngleW = 18; style.photoframeAngleH = 18; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; //qq里面的线条图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") let vc = LBXScanViewController(); vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } //MARK: ---无边框,内嵌4个角------ func weixinStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 2; style.photoframeAngleW = 18; style.photoframeAngleH = 18; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0) style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_Scan_weixin_Line") let vc = LBXScanViewController(); vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } //MARK: ----框内区域识别 func recoCropRect() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid; //矩形框离左边缘及右边缘的距离 style.xScanRetangleOffset = 80; //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net") let vc = LBXScanViewController(); vc.scanStyle = style vc.isOpenInterestRect = true //TODO:待设置框内识别 self.navigationController?.pushViewController(vc, animated: true) } //MARK: -----4个角在矩形框线上,网格动画 func OnStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid; //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net"); let vc = LBXScanViewController(); vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } //MARK: -------自定义4个角及矩形框颜色 func changeColor() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green"); //4个角的颜色 style.colorAngle = UIColor(red: 65.0/255.0, green: 174.0/255.0, blue: 57.0/255.0, alpha: 1.0) //矩形框颜色 style.colorRetangleLine = UIColor(red: 247.0/255.0, green: 202.0/255.0, blue: 15.0/255.0, alpha: 1.0) //非矩形框区域颜色 style.red_notRecoginitonArea = 247.0/255.0; style.green_notRecoginitonArea = 202.0/255.0; style.blue_notRecoginitonArea = 15.0/255.0; style.alpa_notRecoginitonArea = 0.2; let vc = LBXScanViewController(); vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } //MARK: ------改变扫码区域位置 func changeSize() { //设置扫码区域参数 var style = LBXScanViewStyle() //矩形框向上移动 style.centerUpOffset = 60; //矩形框离左边缘及右边缘的距离 style.xScanRetangleOffset = 100; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; //qq里面的线条图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") let vc = LBXScanViewController(); vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } //MARK: -------- 相册 func openLocalPhotoAlbum() { let picker = UIImagePickerController() picker.sourceType = UIImagePickerControllerSourceType.photoLibrary picker.delegate = self; picker.allowsEditing = true present(picker, animated: true, completion: nil) } //MARK: -----相册选择图片识别二维码 (条形码没有找到系统方法) private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { picker.dismiss(animated: true, completion: nil) var image:UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage if (image == nil ) { image = info[UIImagePickerControllerOriginalImage] as? UIImage } if(image == nil) { return } if(image != nil) { let arrayResult = LBXScanWrapper.recognizeQRImage(image: image!) if arrayResult.count > 0 { let result = arrayResult[0]; showMsg(title: result.strBarCodeType, message: result.strScanned) return } } showMsg(title: "", message: "识别失败") } func showMsg(title:String?,message:String?) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.alert) let alertAction = UIAlertAction(title: "知道了", style: UIAlertActionStyle.default) { (alertAction) -> Void in } alertController.addAction(alertAction) present(alertController, animated: true, completion: nil) } func myCode() { let vc = MyCodeViewController() self.navigationController?.pushViewController(vc, animated: true) } }
apache-2.0
5f490b316e087cf9327fcecad3318bfc
29.414216
147
0.592151
5.040211
false
false
false
false
jenasubodh/tasky-ios
Pods/APESuperHUD/Source/APESuperHUD.swift
1
12913
// APESuperHUD.swift // // The MIT License (MIT) // // Copyright (c) 2016 apegroup // // 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 /** Default icons - HappyFace: An icon with a smiling face. - SadFace: An icon with a sad face. - CheckMark: An icon with a standard checkmark. - Email: An icon with a letter. */ public enum IconType: String { case info = "info_icon" case happyFace = "happy_face_icon" case sadFace = "sad_face_icon" case checkMark = "checkmark_icon" case email = "email_icon" } /** Layout of the loading indicator - Standard: Apple standard spinner loading indicator. */ public enum LoadingIndicatorType: Int { case standard } /** Enum for setting language for default messages in the HUD - English: English */ public enum LanguageType: Int { case english } open class APESuperHUD { /// Property for setting up the HUD appearance open static var appearance = HUDAppearance() // MARK: API With UIImage /** Show or update the HUD. - parameter icon: The icon image in the HUD. - parameter message: The text in the HUD. - parameter particleEffectFileName: The name of the Sprite Kit particle file in your project that you want to show in the HUD background. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ icon: UIImage, message: String, particleEffectFileName: String? = nil, presentingView: UIView, completion: (() -> Void)?) { showHud(text: Array(arrayLiteral: message), icon: icon, duration: appearance.defaultDurationTime, sksFileName: particleEffectFileName, presentingView: presentingView, completion: completion) } /** Show or update the HUD. - parameter icon: The icon image in the HUD. - parameter message: The text in the HUD. - parameter duration: Set how long the HUD will be displayed in seconds (override the default value). - parameter particleEffectFileName: The name of the Sprite Kit particle file in your project that you want to show in the HUD background. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ icon: UIImage, message: String, duration: Double, particleEffectFileName: String? = nil, presentingView: UIView, completion: (() -> Void)?) { showHud(text: Array(arrayLiteral: message), icon: icon, duration: duration, sksFileName: particleEffectFileName, presentingView: presentingView, completion: completion) } // MARK: API With IconType /** Show or update the HUD. - parameter icon: The icon type icon in the HUD. - parameter message: The text in the HUD. - parameter particleEffectFileName: The name of the Sprite Kit particle file in your project that you want to show in the HUD background. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ icon: IconType, message: String, particleEffectFileName: String? = nil, presentingView: UIView, completion: (() -> Void)?) { let duration = appearance.defaultDurationTime let defaultIcon = iconImage(icon.rawValue) showHud(text: Array(arrayLiteral: message), icon: defaultIcon, duration: duration, sksFileName: particleEffectFileName, presentingView: presentingView, funnyMessagesLanguage: nil, completion: completion) } /** Show or update the HUD. - parameter icon: The icon type icon in the HUD. - parameter message: The text in the HUD. - parameter duration: Set how long the HUD will be displayed in seconds (override the default value). - parameter particleEffectFileName: The name of the Sprite Kit particle file in your project that you want to show in the HUD background. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ icon: IconType, message: String, duration: Double, particleEffectFileName: String? = nil, presentingView: UIView, completion: (() -> Void)?) { let defaultIcon = iconImage(icon.rawValue) showHud(text: Array(arrayLiteral: message), icon: defaultIcon, duration: duration, sksFileName: particleEffectFileName , presentingView: presentingView, completion: completion) } // MARK: API With Title /** Show or update the HUD. - parameter title: The title in the HUD. - parameter message: The text in the HUD. - parameter particleEffectFileName: The name of the Sprite Kit particle file in your project that you want to show in the HUD background. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ title: String, message: String, particleEffectFileName: String? = nil, presentingView: UIView, completion: (() -> Void)?) { showHud(title, text: Array(arrayLiteral: message), icon: nil, duration: appearance.defaultDurationTime, sksFileName: particleEffectFileName, presentingView: presentingView, completion: completion) } /** Show or update the HUD. - parameter title: The title in the HUD. - parameter message: The text in the HUD. - parameter duration: Set how long the HUD will be displayed in seconds (override the default value). - parameter particleEffectFileName: The name of the Sprite Kit particle file in your project that you want to show in the HUD background. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ title: String, message: String, duration: Double, particleEffectFileName: String? = nil, presentingView: UIView, completion: (() -> Void)?) { showHud(title, text: Array(arrayLiteral: message), icon: nil, duration: duration, sksFileName: particleEffectFileName, presentingView: presentingView, completion: completion) } // MARK: API With LoadingIndicator /** Show or update the HUD. - parameter loadingIndicator: The type of loading indicator in the HUD. - parameter message: The text in the HUD. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ loadingIndicator: LoadingIndicatorType, message: String, presentingView: UIView) { if loadingIndicator == .standard { showHud(text: Array(arrayLiteral: message), presentingView: presentingView, completion: nil) } } /** Show or update the HUD. - parameter loadingIndicator: The type of loading indicator in the HUD. - parameter funnyMessagesLanguage: The language of the funny messages. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ loadingIndicator: LoadingIndicatorType, funnyMessagesLanguage: LanguageType, presentingView: UIView) { if loadingIndicator == .standard { showHud(presentingView: presentingView, funnyMessagesLanguage: funnyMessagesLanguage, completion: nil) } } /** Show or update the HUD. - parameter loadingIndicator: The type of loading indicator in the HUD. - parameter messages: A array of messages that will be displayed one by one. - parameter presentingView: The view that the HUD will be located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func showOrUpdateHUD(_ loadingIndicator: LoadingIndicatorType, messages: [String], presentingView: UIView) { if loadingIndicator == .standard { showHud(text: messages, presentingView: presentingView, completion: nil) } } // MARK: API Remove /** Removes the HUD. - parameter animated: If the remove action should be animated or not. - parameter presentingView: The view that the HUD is located in. - parameter completion: Will be trigger when the HUD is removed. */ open static func removeHUD(_ animated: Bool, presentingView: UIView, completion: (() -> Void)?) { if let hudView = getHudView(presentingView) { hudView.removeHud(animated: animated, onDone: { _ in completion?() }) } } // MARK: - Private functions fileprivate static func showHud(_ title: String = "", text: [String] = [""], icon: UIImage? = nil, duration: Double = -1, sksFileName: String? = nil, presentingView: UIView, funnyMessagesLanguage: LanguageType? = nil, completion: (() -> Void)? = nil) { let hudView = createHudViewIfNeeded(presentingView) if hudView.isActivityIndicatorSpinnning { // Hide HUD view, and call same function when it's done hudView.hideLoadingActivityIndicator(completion: { _ in showHud(text: text, icon: icon, duration: duration, sksFileName: sksFileName, presentingView: presentingView, completion: completion) return }) return } if let fileName = sksFileName { hudView.addParticleEffect(sksfileName: fileName) } let isFunnyMessages = funnyMessagesLanguage != nil let isMessages = text.count > 1 hudView.isActiveTimer = isFunnyMessages || isMessages if isFunnyMessages { hudView.showFunnyMessages(languageType: funnyMessagesLanguage!) } else if isMessages { hudView.showMessages(messages: text) } else if icon != nil { hudView.showMessage(title: nil, message: text.first, icon: icon, completion: nil) } else if title != "" { hudView.showMessage(title: title, message: text.first, icon: nil, completion: nil) } else { hudView.showLoadingActivityIndicator(text: text.first, completion: nil) } if duration > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: { hudView.removeHud(animated: true, onDone: completion) }) } } fileprivate static func iconImage(_ imageName: String) -> UIImage? { let iconImage = UIImage(named: imageName, in: Bundle(for: APESuperHUD.self), compatibleWith: nil) return iconImage } static func createHudViewIfNeeded(_ presentingView: UIView) -> HudView { if let hudView = getHudView(presentingView) { return hudView } let hudView = HudView.create() presentingView.addSubview(hudView) return hudView } static func createHudView(_ presentingView: UIView) -> HudView { let hudView = HudView.create() presentingView.addSubview(hudView) return hudView } fileprivate static func getHudView(_ presentingView: UIView) -> HudView? { for subview in presentingView.subviews { if let hudview = subview as? HudView { return hudview } } return nil } }
mit
84fdab564003ee3944e6077941d84ebf
38.368902
256
0.673662
4.882042
false
false
false
false
riteshiosdev/iOS-UIKit
Advance Code/AdvancedNSOperations/Earthquakes/SplitViewController.swift
1
999
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A UISplitViewController subclass that is its own delegate. */ import UIKit class SplitViewController: UISplitViewController { // MARK: Life Cycle override func awakeFromNib() { super.awakeFromNib() preferredDisplayMode = .AllVisible delegate = self } } extension SplitViewController: UISplitViewControllerDelegate { func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { guard let navigation = secondaryViewController as? UINavigationController else { return false } guard let detail = navigation.viewControllers.first as? EarthquakeTableViewController else { return false } return detail.earthquake == nil } }
apache-2.0
1badcc73e160ce34e753acb65ddca9f9
32.233333
224
0.749248
6.310127
false
false
false
false
yannickl/Cocarde
Example/Cocarde/MasterViewController.swift
1
2052
// // MasterViewController.swift // Cocarde // // Created by Yannick Loriot on 13/03/15. // Copyright (c) 2015 Yannick Loriot. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var cocardeStyles = CocardeStyle.allValues override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() self.title = "Styles" } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail", let indexPath = self.tableView.indexPathForSelectedRow { let object = cocardeStyles[indexPath.row] as CocardeStyle let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.cocardeStyle = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cocardeStyles.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = cocardeStyles[indexPath.row] as CocardeStyle cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } }
mit
2256bcec42ca5e82d4bdb1f9aeb054d0
30.569231
126
0.724659
5.104478
false
false
false
false
trill-lang/LLVMSwift
Sources/LLVM/DWARFExpression.swift
1
40155
#if SWIFT_PACKAGE import cllvm #endif /// DWARF expressions describe how to compute a value or specify a location. /// They are expressed in terms of DWARF operations that operate on a stack of /// values. /// /// A DWARF expression is encoded as a stream of operations, each consisting of /// an opcode followed by zero or more literal operands. public enum DWARFExpression { // MARK: Literals /// Encodes a single machine address value whose size is the size of an /// address on the target machine. case addr(UInt64) /// Encodes the unsigned literal value 0. case lit0 /// Encodes the unsigned literal value 1. case lit1 /// Encodes the unsigned literal value 2. case lit2 /// Encodes the unsigned literal value 3. case lit3 /// Encodes the unsigned literal value 4. case lit4 /// Encodes the unsigned literal value 5. case lit5 /// Encodes the unsigned literal value 6. case lit6 /// Encodes the unsigned literal value 7. case lit7 /// Encodes the unsigned literal value 8. case lit8 /// Encodes the unsigned literal value 9. case lit9 /// Encodes the unsigned literal value 10. case lit10 /// Encodes the unsigned literal value 11. case lit11 /// Encodes the unsigned literal value 12. case lit12 /// Encodes the unsigned literal value 13. case lit13 /// Encodes the unsigned literal value 14. case lit14 /// Encodes the unsigned literal value 15. case lit15 /// Encodes the unsigned literal value 16. case lit16 /// Encodes the unsigned literal value 17. case lit17 /// Encodes the unsigned literal value 18. case lit18 /// Encodes the unsigned literal value 19. case lit19 /// Encodes the unsigned literal value 20. case lit20 /// Encodes the unsigned literal value 21. case lit21 /// Encodes the unsigned literal value 22. case lit22 /// Encodes the unsigned literal value 23. case lit23 /// Encodes the unsigned literal value 24. case lit24 /// Encodes the unsigned literal value 25. case lit25 /// Encodes the unsigned literal value 26. case lit26 /// Encodes the unsigned literal value 27. case lit27 /// Encodes the unsigned literal value 28. case lit28 /// Encodes the unsigned literal value 29. case lit29 /// Encodes the unsigned literal value 30. case lit30 /// Encodes the unsigned literal value 31. case lit31 /// Encodes a 1-byte unsigned integer constant. case const1u(UInt8) /// Encodes a 1-byte signed integer constant. case const1s(Int8) /// Encodes a 2-byte unsigned integer constant. case const2u(UInt16) /// Encodes a 2-byte signed integer constant. case const2s(Int16) /// Encodes a 4-byte unsigned integer constant. case const4u(UInt32) /// Encodes a 4-byte signed integer constant. case const4s(Int32) /// Encodes a 8-byte unsigned integer constant. case const8u(UInt64) /// Encodes a 8-byte signed integer constant. case const8s(Int64) /// Encodes a little-endian base-128 unsigned integer constant. case constu(UInt64) /// Encodes a little-endian base-128 signed integer constant. case consts(Int64) /// Encodes an unsigned little-endian base-128 value, which is a zero-based /// index into the `.debug_addr` section where a machine address is stored. /// This index is relative to the value of the `DW_AT_addr_base` attribute /// of the associated compilation unit. case addrx(UInt64) /// Encodes an unsigned little-endian base-128 value, which is a zero-based /// index into the `.debug_addr` section where a constant, the size of a /// machine address, is stored. This index is relative to the value of the /// `DW_AT_addr_base` attribute of the associated compilation unit. /// /// This operation is provided for constants that require link-time relocation /// but should not be interpreted by the consumer as a relocatable address ( /// for example, offsets to thread-local storage). case constx(UInt64) // MARK: Register Values /// Provides a signeed little-endian base-128 offset from the address /// specified by the location description in the `DW_AT_frame_base` attribute /// of the current function. case fbreg(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 0. case breg0(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 1. case breg1(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 2. case breg2(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 3. case breg3(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 4. case breg4(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 5. case breg5(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 6. case breg6(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 7. case breg7(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 8. case breg8(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 9. case breg9(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 10. case breg10(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 11. case breg11(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 12. case breg12(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 13. case breg13(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 14. case breg14(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 15. case breg15(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 16. case breg16(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 17. case breg17(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 18. case breg18(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 19. case breg19(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 20. case breg20(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 21. case breg21(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 22. case breg22(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 23. case breg23(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 24. case breg24(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 25. case breg25(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 26. case breg26(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 27. case breg27(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 28. case breg28(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 29. case breg29(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 30. case breg30(Int64) /// The single operand of the breg operation provides a signed little-endian /// base-128 offset from the contents of register 31. case breg31(Int64) /// Provides the sum of two values specified by its two operands. The first /// operand being a register number which is in unsigned little-endian /// base-128 form. The second being an offset in signed little-endian /// base-128 form. case bregx(UInt64, Int64) /// Provides an operation with three operands: The first is an unsigned /// little-endian base-128 integer that represents the offset of a debugging /// information entry in the current compilation unit, which must be /// a base type entry that provides the type of the constant provided. /// The second operand is a 1-byte unsigned integer that specifies the /// size of the constant value, which is the same size as the base type /// referenced by the first operand. The third operand is a sequence of bytes /// of the given size that is interpreted as a value of the referenced type. case constType(DIAttributeTypeEncoding, UInt8, [UInt8]) /// Provides the contents of a given register interpreted as a value of a /// given type. The first operand is an unsigned little-endian base-128 /// number which identifies a register whose contents are pushed onto the /// stack. The second operand is an unsigned little-endian base-128 number /// that represents the offset of a debugging information entry in the current /// compilation unit which must have base type. case regvalType(UInt64, DIAttributeTypeEncoding) // MARK: Stack Operations /// Duplicates the value (including its type identifier) at the top of the /// stack. case dup /// Pops the value (including its type identifier) at the top of the stack. case drop /// Provides a 1-byte index that is used to index into the stack. A copy of /// stack entry at that index is pushed onto the stack. case pick(UInt8) /// Duplicates the entry currently second in the stack and pushes it onto the /// stack. /// /// This operation is equivalent to `.pick(1)`. case over /// Swaps the top two stack entries. The entry at the top of the stack /// (including its type identifier) becomes the second stack entry, and the /// second entry (including its type identifier) becomes the top of the stack. case swap /// Rotates the first three stack entries. The entry at the top of the stack /// (including its type identifier) becomes the third stack entry, the second /// stack entry (including its type identifier) becomes the top of the stack, /// and the third entry (including its type identifier) becomes the second /// entry. case rot /// Pops the top stack entry and treats it as an address. /// /// The popped value must have an integral type. The value retrieved from /// that address is pushed, and has the generic type. The size of the data /// retrieved from the dereferenced address is the size of an address on the /// target machine. case deref /// Pops the top stack entry and treats it as an address. /// /// The popped value must have an integral type. The value retrieved from /// that address is pushed, and has the generic type. The size of the data /// retrieved from the dereferenced address is specified by the /// operand, whose value is a 1-byte unsigned integral constant. The data /// retrieved is zero-extended to the size of an address on the target machine /// before being pushed onto the expression stack. case derefSize(UInt8) /// Pops the top stack entry and treats it as an address. /// /// The popped value must have an integral type. The size of the data /// retrieved from the dereferenced address is specified by the first /// operand, whose value is a 1-byte unsigned integral constant. The data /// retrieved is zero-extended to the size of an address on the target machine /// before being pushed onto the expression stack. The second operand is an /// unsigned little-endian base-128 integer that represents the offset of a /// debugging information entry in the current compilation unit which must /// have a base type entry that provides the type of the data pushed. case derefType(UInt8, UInt64) /// Provides an extended dereference mechanism. /// /// The entry at the top of the stack is treated as an address. The second /// stack entry is treated as an "address space identifier" for those /// architectures that support multiple address spaces. Both of these /// entries must have integral type identifiers. /// /// The top two stack elements are popped, and a data item is retrieved /// through an implementation-defined address calculation and pushed as the /// new stack top together with the generic type identifier. The size of the /// data retrieved from the dereferenced address is the size of the /// generic type. case xderef /// Provides an extended dereference mechanism. /// /// The entry at the top of the stack is treated as an address. The second /// stack entry is treated as an "address space identifier" for those /// architectures that support multiple address spaces. Both of these /// entries must have integral type identifiers. /// /// The top two stack elements are popped, and a data item is retrieved /// through an implementation-defined address calculation and pushed as the /// new stack top together with the generic type identifier. The size of the /// data retrieved from the dereferenced address is specified by the /// operand, whose value is a 1-byte unsigned integral constant. The data /// retrieved is zero-extended to the size of an address on the target machine /// before being pushed onto the expression stack. case xderefSize(UInt8) /// Pops the top two stack entries, treats them as an address and an address /// space identifier, and pushes the value retrieved. /// The size of the data retrieved from the dereferenced address is specified /// by the first operand, whose value is a 1-byte unsigned integral constant. /// The data retrieved is zero-extended to the size of an address on the /// target machine before being pushed onto the expression stack. The second /// operand is an unsigned little-endian base-128 integer that represents the /// offset of a debugging information entry in the current compilation unit, /// which must have base type that provides the type of the data pushed. case xderefType(UInt8, UInt64) /// Pushes the address of the object currently being evaluated as part of /// evaluationo of a user-presented expression. The object may correspond /// to an indepdendent variable deescribed by its own debugging information /// entry or it may be a component of an array, structure, or class whose /// address has been dynamically determined by an earlier step during /// user expression evaluation. case pushObjectAddress /// Pops a value from the stack, which must have an integral type identifier, /// translates this value into an address in the thread-local storage for a /// thread, and pushes the addreess onto the stack together with the generic /// type identifier. The meaning of the value on the top of the stack prior /// to this operation is defined by the run-time environment. If the run-time /// environment supports multiple thread-local storage blocks for a single /// thread, then the block corresponding to the executable or shared library /// containing this DWARF expreession is used. case formTLSAddress /// Pushes the value of the Canonical Frame Address (CFA), obtained from the /// Call Frame Information. case callFrameCFA // MARK: Arithmetic and Logical Operations /// Pops the top stack entry, interprets it as a signed value and pushes its /// absolute value. If the absolute value cannot be represented, the result /// is undefined. case abs /// Pops the top two stack values, performs a bitwise and operation on the /// two, and pushes the result. case and /// Pops the top two stack values, divides the former second entry by the /// former top of the stack using signed division, and pushes the result. case div /// Pops the top two stack values, subtracts the former second entry by the /// former top of the stack, and pushes the result. case minus /// Pops the top two stack values, performs a modulo operation on the /// two, and pushes the result. case mod /// Pops the top two stack values, multiplies the former second entry by the /// former top of the stack, and pushes the result. case mul /// Pops the top stack entry, interprets it as a signed value, and pushes its /// negation. If the negation cannot be represented, the result is undefined. case neg /// Pops the top stack entry, and pushes its bitwise complement. case not /// Pops the top two stack entries, performs a bitwise or operation on the /// two, and pushes the result. case or /// Pops the top two stack entries, adds them together, and pushes the result. case plus /// Pops the top stack entry, adds it to the unsigned little-endian base-128 /// constant operand interpreted as the same type as the operand popped from /// the top of the stack and pushes the result. case plus_uconst(UInt64) /// Pops the top twoo stack entries, shifts the former second entry left /// (filling with zero bits) by the number of bits specified by the former /// top of the stack, and pushes the result. case shl /// Pops the top two stack entries, shifts the former second entry right /// logically (filling with zero bits) by the number of bits specified by /// the former top of the stack, and pushes the result. case shr /// Pops the top two stack entries, shifts the former second entry right /// arithmetically (divides the magnitude by 2, keeps the same sign for the /// result) by the number of bits specified by the former top of the stack, /// and pushes the result. case shra /// Pops the top two stack entries, performs a bitwise exclusive-or operation /// on the two, and pushes the result. case xor // MARK: Control Flow Operations /// Pops the top two stack values, which must have the same type, either /// the base type or the generic type, compares them using the `=` relational /// operator, and pushes the constant 1 onto the stack if the result is /// true, else pushes the constnat value 0 if the result is false. case eq /// Pops the top two stack values, which must have the same type, either /// the base type or the generic type, compares them using the `>=` relational /// operator, and pushes the constant 1 onto the stack if the result is /// true, else pushes the constnat value 0 if the result is false. case ge /// Pops the top two stack values, which must have the same type, either /// the base type or the generic type, compares them using the `>` relational /// operator, and pushes the constant 1 onto the stack if the result is /// true, else pushes the constnat value 0 if the result is false. case gt /// Pops the top two stack values, which must have the same type, either /// the base type or the generic type, compares them using the `<=` relational /// operator, and pushes the constant 1 onto the stack if the result is /// true, else pushes the constnat value 0 if the result is false. case le /// Pops the top two stack values, which must have the same type, either /// the base type or the generic type, compares them using the `<` relational /// operator, and pushes the constant 1 onto the stack if the result is /// true, else pushes the constnat value 0 if the result is false. case lt /// Pops the top two stack values, which must have the same type, either /// the base type or the generic type, compares them using the `!=` relational /// operator, and pushes the constant 1 onto the stack if the result is /// true, else pushes the constnat value 0 if the result is false. case ne /// Unconditionally branches forward or backward by the number of bytes /// specified in its operand. case skip(Int16) /// Conditionally branches forward or backward by the number of bytes /// specified in its operand according to the value at the top of the stack. /// The top of the stack is popped, and if it is non-zero then the branch is /// performed. case bra(Int16) /// Performs a DWARF procedure call during the evaluation of a DWARF /// expression or location description. The operand is the 2-byte unsigned /// offset of a debugging information entry in the current compilation unit. /// /// For references from one executable or shared object file to another, /// the relocation must be performed by the consumer. /// /// This operation transfers control of DWARF expression evaluation to the /// `DW_AT_location` attribute of the referenced debugging information entry. /// If there is no such attribute, then there is no effect. Execution /// returns to the point following the call when the end of the attribute /// is reached. case call2(UInt16) /// Performs a DWARF procedure call during the evaluation of a DWARF /// expression or location description. The operand is the 4-byte unsigned /// offset of a debugging information entry in the current compilation unit. /// /// For references from one executable or shared object file to another, /// the relocation must be performed by the consumer. /// /// This operation transfers control of DWARF expression evaluation to the /// `DW_AT_location` attribute of the referenced debugging information entry. /// If there is no such attribute, then there is no effect. Execution /// returns to the point following the call when the end of the attribute /// is reached. case call4(UInt32) /// Performs a DWARF procedure call during the evaluation of a DWARF /// expression or location description. The operand is used as the offset of /// a debugging information entry in a `.debug_info` section which may be /// contained in an executable or shared object file rather than that /// containing the operator. /// /// For references from one executable or shared object file to another, /// the relocation must be performed by the consumer. /// /// This operation transfers control of DWARF expression evaluation to the /// `DW_AT_location` attribute of the referenced debugging information entry. /// If there is no such attribute, then there is no effect. Execution /// returns to the point following the call when the end of the attribute /// is reached. case callRef(UInt64) // MARK: Type Conversions /// Pops the top stack entry, converts it to a different type, then pushes the /// result. /// /// The operand is an unsigned little-endian base-128 integer that represents /// the offset of a debugging information entry in the current compilation /// unit, or value 0 which represents the generic type. If the operand is /// non-zero, the referenced entry must be a base type entry that provides the /// type to which the value is converted. case convert(UInt64) /// Pops the top stack entry, reinterprets the bits in its value as a value of /// a different type, then pushes the result. /// /// The operand is an unsigned little-endian base-128 integer that represents /// the offset of a debugging information entry in the current compilation /// unit, or value 0 which represents the generic type. If the operand is /// non-zero, the referenced entry must be a base type entry that provides the /// type to which the value is converted. case reinterpret(UInt64) // MARK: Special Operations /// This operation has no effect on the location stack or any of its values. case nop /// Pushes the value that the described location held upon entering the /// current subprogram. The first operand is an unsigned little-endian /// base-128 number expressing the length of the second operand in bytes. The /// second operand is a block containing a DWARF expression or a register /// location description. indirect case entryValue(UInt64, DWARFExpression) // MARK: Location Descriptions /// Encodes the name of the register numbered 0. case reg0 /// Encodes the name of the register numbered 1. case reg1 /// Encodes the name of the register numbered 2. case reg2 /// Encodes the name of the register numbered 3. case reg3 /// Encodes the name of the register numbered 4. case reg4 /// Encodes the name of the register numbered 5. case reg5 /// Encodes the name of the register numbered 6. case reg6 /// Encodes the name of the register numbered 7. case reg7 /// Encodes the name of the register numbered 8. case reg8 /// Encodes the name of the register numbered 9. case reg9 /// Encodes the name of the register numbered 10. case reg10 /// Encodes the name of the register numbered 11. case reg11 /// Encodes the name of the register numbered 12. case reg12 /// Encodes the name of the register numbered 13. case reg13 /// Encodes the name of the register numbered 14. case reg14 /// Encodes the name of the register numbered 15. case reg15 /// Encodes the name of the register numbered 16. case reg16 /// Encodes the name of the register numbered 17. case reg17 /// Encodes the name of the register numbered 18. case reg18 /// Encodes the name of the register numbered 19. case reg19 /// Encodes the name of the register numbered 20. case reg20 /// Encodes the name of the register numbered 21. case reg21 /// Encodes the name of the register numbered 22. case reg22 /// Encodes the name of the register numbered 23. case reg23 /// Encodes the name of the register numbered 24. case reg24 /// Encodes the name of the register numbered 25. case reg25 /// Encodes the name of the register numbered 26. case reg26 /// Encodes the name of the register numbered 27. case reg27 /// Encodes the name of the register numbered 28. case reg28 /// Encodes the name of the register numbered 29. case reg29 /// Encodes the name of the register numbered 30. case reg30 /// Encodes the name of the register numbered 31. case reg31 /// Contains a single unsigned little-endian base-128 literal operand that /// encodes the name of a register. case regx(UInt64) // MARK: Implicit Location Descriptionos /// Specifies an immediate value using two operands: an unsigned little-endian /// base-128 length, followed by a sequence of bytes of the given length that /// contain the value. case implicitValue(UInt64, [UInt8]) /// Specifies that the object does not exist in memory, but its value is /// nonetheless known and is at the top of the DWARF expression stack. In /// this form of location description, the DWARF expression represents the /// actual value of the object, rather than its location. /// /// `stackValue` acts as an expression terminator. case stackValue // MARK: Composite Location Descriptions /// Takes a single operand in little-endian base-128 form. This operand /// describes the size in bytes of the piece of the object referenced by the /// preceding simple location description. If the piece is located in a /// register, but does not occupy the entire register, the placement of /// the piece within that register is defined by the ABI. case piece(UInt64) /// Takes two operands, an unsigned little-endian base-128 form number that /// gives the size in bits of the piece. The second is an unsigned little- /// endian base-128 number that gives the offset in bits from the location /// defined by the preceding DWARF location description. /// /// `bitPiece` is used instead of `piece` when the piece to be assembled into /// a value or assigned to is not byte-sized or is not at the start of a /// register or addressable unit of memory. /// /// Interpretation of the offset depends on the location description. If the /// location description is empty, the offset doesn’t matter and the /// `bitPiece` operation describes a piece consisting of the given number of /// bits whose values are undefined. If the location is a register, the offset /// is from the least significant bit end of the register. If the location is /// a memory address, the `bitPiece` operation describes a sequence of bits /// relative to the location whose address is on the top of the DWARF stack /// using the bit numbering and direction conventions that are appropriate to /// the current language on the target system. If the location is any implicit /// value or stack value, the `bitPiece` operation describes a sequence of /// bits using the least significant bits of that value. case bitPiece(UInt64, UInt64) /// Specifies that the object is a pointer that cannot be represented as a /// real pointer, even though the value it would point to can be described. /// /// In this form of location description, the DWARF expression refers to a /// debugging information entry that represents the actual value of the object /// to which the pointer would point. Thus, a consumer of the debug /// information would be able to show the value of the dereferenced pointer, /// even when it cannot show the value of the pointer itself. /// /// The first operand is used as the offset of a debugging information entry /// in a `.debug_info` section, which may be contained in an executable or /// shared object file other than that containing the operator. /// /// For references from one executable or shared object file to another, the /// relocation must be performed by the consumer. case implicitPointer(UInt64, Int64) } extension DWARFExpression { var rawValue: [UInt64] { switch self { case let .addr(val): return [ 0x03, val ] case .deref: return [ 0x06 ] case let .const1u(val): return [ 0x08, UInt64(val) ] case let .const1s(val): return [ 0x09, UInt64(bitPattern: Int64(val)) ] case let .const2u(val): return [ 0x0a, UInt64(val) ] case let .const2s(val): return [ 0x0b, UInt64(bitPattern: Int64(val)) ] case let .const4u(val): return [ 0x0c, UInt64(val) ] case let .const4s(val): return [ 0x0d, UInt64(bitPattern: Int64(val)) ] case let .const8u(val): return [ 0x0e, val ] case let .const8s(val): return [ 0x0f, UInt64(bitPattern: Int64(val)) ] case let .constu(val): return [ 0x10, val ] case let .consts(val): return [ 0x11, UInt64(bitPattern: val) ] case .dup: return [ 0x12 ] case .drop: return [ 0x13 ] case .over: return [ 0x14 ] case let .pick(val): return [ 0x15, UInt64(val) ] case .swap: return [ 0x16 ] case .rot: return [ 0x17 ] case .xderef: return [ 0x18 ] case .abs: return [ 0x19 ] case .and: return [ 0x1a ] case .div: return [ 0x1b ] case .minus: return [ 0x1c ] case .mod: return [ 0x1d ] case .mul: return [ 0x1e ] case .neg: return [ 0x1f ] case .not: return [ 0x20 ] case .or: return [ 0x21 ] case .plus: return [ 0x22 ] case let .plus_uconst(val): return [ 0x23, val ] case .shl: return [ 0x24 ] case .shr: return [ 0x25 ] case .shra: return [ 0x26 ] case .xor: return [ 0x27 ] case .skip: return [ 0x2f ] case .bra: return [ 0x28 ] case .eq: return [ 0x29 ] case .ge: return [ 0x2a ] case .gt: return [ 0x2b ] case .le: return [ 0x2c ] case .lt: return [ 0x2d ] case .ne: return [ 0x2e ] case .lit0: return [ 0x30 ] case .lit1: return [ 0x31 ] case .lit2: return [ 0x32 ] case .lit3: return [ 0x33 ] case .lit4: return [ 0x34 ] case .lit5: return [ 0x35 ] case .lit6: return [ 0x36 ] case .lit7: return [ 0x37 ] case .lit8: return [ 0x38 ] case .lit9: return [ 0x39 ] case .lit10: return [ 0x3a ] case .lit11: return [ 0x3b ] case .lit12: return [ 0x3c ] case .lit13: return [ 0x3d ] case .lit14: return [ 0x3e ] case .lit15: return [ 0x3f ] case .lit16: return [ 0x40 ] case .lit17: return [ 0x41 ] case .lit18: return [ 0x42 ] case .lit19: return [ 0x43 ] case .lit20: return [ 0x44 ] case .lit21: return [ 0x45 ] case .lit22: return [ 0x46 ] case .lit23: return [ 0x47 ] case .lit24: return [ 0x48 ] case .lit25: return [ 0x49 ] case .lit26: return [ 0x4a ] case .lit27: return [ 0x4b ] case .lit28: return [ 0x4c ] case .lit29: return [ 0x4d ] case .lit30: return [ 0x4e ] case .lit31: return [ 0x4f ] case .reg0: return [ 0x50 ] case .reg1: return [ 0x51 ] case .reg2: return [ 0x52 ] case .reg3: return [ 0x53 ] case .reg4: return [ 0x54 ] case .reg5: return [ 0x55 ] case .reg6: return [ 0x56 ] case .reg7: return [ 0x57 ] case .reg8: return [ 0x58 ] case .reg9: return [ 0x59 ] case .reg10: return [ 0x5a ] case .reg11: return [ 0x5b ] case .reg12: return [ 0x5c ] case .reg13: return [ 0x5d ] case .reg14: return [ 0x5e ] case .reg15: return [ 0x5f ] case .reg16: return [ 0x60 ] case .reg17: return [ 0x61 ] case .reg18: return [ 0x62 ] case .reg19: return [ 0x63 ] case .reg20: return [ 0x64 ] case .reg21: return [ 0x65 ] case .reg22: return [ 0x66 ] case .reg23: return [ 0x67 ] case .reg24: return [ 0x68 ] case .reg25: return [ 0x69 ] case .reg26: return [ 0x6a ] case .reg27: return [ 0x6b ] case .reg28: return [ 0x6c ] case .reg29: return [ 0x6d ] case .reg30: return [ 0x6e ] case .reg31: return [ 0x6f ] case let .breg0(val): return [ 0x70, UInt64(bitPattern: val)] case let .breg1(val): return [ 0x71, UInt64(bitPattern: val) ] case let .breg2(val): return [ 0x72, UInt64(bitPattern: val) ] case let .breg3(val): return [ 0x73, UInt64(bitPattern: val) ] case let .breg4(val): return [ 0x74, UInt64(bitPattern: val) ] case let .breg5(val): return [ 0x75, UInt64(bitPattern: val) ] case let .breg6(val): return [ 0x76, UInt64(bitPattern: val) ] case let .breg7(val): return [ 0x77, UInt64(bitPattern: val) ] case let .breg8(val): return [ 0x78, UInt64(bitPattern: val) ] case let .breg9(val): return [ 0x79, UInt64(bitPattern: val) ] case let .breg10(val): return [ 0x7a, UInt64(bitPattern: val) ] case let .breg11(val): return [ 0x7b, UInt64(bitPattern: val) ] case let .breg12(val): return [ 0x7c, UInt64(bitPattern: val) ] case let .breg13(val): return [ 0x7d, UInt64(bitPattern: val) ] case let .breg14(val): return [ 0x7e, UInt64(bitPattern: val) ] case let .breg15(val): return [ 0x7f, UInt64(bitPattern: val) ] case let .breg16(val): return [ 0x80, UInt64(bitPattern: val) ] case let .breg17(val): return [ 0x81, UInt64(bitPattern: val) ] case let .breg18(val): return [ 0x82, UInt64(bitPattern: val) ] case let .breg19(val): return [ 0x83, UInt64(bitPattern: val) ] case let .breg20(val): return [ 0x84, UInt64(bitPattern: val) ] case let .breg21(val): return [ 0x85, UInt64(bitPattern: val) ] case let .breg22(val): return [ 0x86, UInt64(bitPattern: val) ] case let .breg23(val): return [ 0x87, UInt64(bitPattern: val) ] case let .breg24(val): return [ 0x88, UInt64(bitPattern: val) ] case let .breg25(val): return [ 0x89, UInt64(bitPattern: val) ] case let .breg26(val): return [ 0x8a, UInt64(bitPattern: val) ] case let .breg27(val): return [ 0x8b, UInt64(bitPattern: val) ] case let .breg28(val): return [ 0x8c, UInt64(bitPattern: val) ] case let .breg29(val): return [ 0x8d, UInt64(bitPattern: val) ] case let .breg30(val): return [ 0x8e, UInt64(bitPattern: val) ] case let .breg31(val): return [ 0x8f, UInt64(bitPattern: val) ] case let .regx(val): return [ 0x90, val ] case let .fbreg(val): return [ 0x91, UInt64(bitPattern: val) ] case let .bregx(val1, val2): return [ 0x92, val1 , UInt64(bitPattern: val2) ] case let .piece(val): return [ 0x93, val ] case let .derefSize(val): return [ 0x94, UInt64(val) ] case let .xderefSize(val): return [ 0x95, UInt64(val) ] case .nop: return [ 0x96 ] case .pushObjectAddress: return [ 0x97 ] case let .call2(val): return [ 0x98, UInt64(val) ] case let .call4(val): return [ 0x99, UInt64(val) ] case let .callRef(val): return [ 0x9a, val ] case .formTLSAddress: return [ 0x9b ] case .callFrameCFA: return [ 0x9c ] case let .bitPiece(val1, val2): return [ 0x9d, val1, val2 ] case let .implicitValue(val, bytes): return [ 0x9e, val ] + packBytes(bytes) case .stackValue: return [ 0x9f ] case let .implicitPointer(val1, val2): return [ 0xa0, val1, UInt64(bitPattern: val2) ] case let .addrx(val): return [ 0xa1, val ] case let .constx(val): return [ 0xa2, val ] case let .entryValue(val1, val2): return [ 0xa3, val1 ] + val2.rawValue case let .constType(ate, n, bytes): assert(Int(n) == bytes.count) return [ 0xa4, UInt64(ate.llvm), UInt64(n) ] + packBytes(bytes) case let .regvalType(reg, ate): return [ 0xa5, reg, UInt64(ate.llvm) ] case let .derefType(val, ty): return [ 0xa6, UInt64(val), ty ] case let .xderefType(val, ty): return [ 0xa7, UInt64(val), ty ] case let .convert(ty): return [ 0xa7, ty ] case let .reinterpret(ty): return [ 0xa7, ty ] } } } private func packBytes(_ bytes: [UInt8]) -> [UInt64] { guard !bytes.isEmpty else { return [] } var res = [UInt64]() res.reserveCapacity(bytes.count/MemoryLayout<UInt64>.size) var accum: UInt64 = 0 for (idx, val) in bytes.enumerated() { // If we've packed all the way through the accumulator, append it and // start afresh. if idx != 0 && idx % MemoryLayout<UInt64>.size == 0 { res.append(accum) accum = 0 } accum <<= MemoryLayout<UInt64>.size accum |= UInt64(val) } // Pack on the straggler if we're not packing a perfect multiple. if bytes.count % MemoryLayout<UInt64>.size != 0 { res.append(accum) } return res }
mit
89101ad0040e2714843586555ea0cae5
38.363725
80
0.687579
3.980075
false
false
false
false
OscarSwanros/swift
test/SILGen/objc_currying.swift
2
14862
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -enable-sil-ownership -emit-silgen %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo func curry_pod(_ x: CurryTest) -> (Int) -> Int { return x.pod } // CHECK-LABEL: sil hidden @_T013objc_currying9curry_podS2icSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_FOO_1:_T0So9CurryTestC3podS2iFTcTO]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int // CHECK: [[COPIED_ARG1:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[FN:%.*]] = apply [[THUNK]]([[COPIED_ARG1]]) // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[FN]] // CHECK: } // end sil function '_T013objc_currying9curry_podS2icSo9CurryTestCF' // CHECK: sil shared [serializable] [thunk] @[[THUNK_FOO_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_FOO_2:_T0So9CurryTestC3podS2iFTO]] // CHECK: [[FN:%.*]] = partial_apply [[THUNK]](%0) // CHECK: return [[FN]] // CHECK: } // end sil function '[[THUNK_FOO_1]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK_FOO_2]] : $@convention(method) (Int, @guaranteed CurryTest) -> Int // CHECK: bb0([[ARG1:%.*]] : @trivial $Int, [[ARG2:%.*]] : @guaranteed $CurryTest): // CHECK: [[COPIED_ARG2:%.*]] = copy_value [[ARG2]] // CHECK: [[METHOD:%.*]] = objc_method [[COPIED_ARG2]] : $CurryTest, #CurryTest.pod!1.foreign // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[ARG1]], [[COPIED_ARG2]]) // CHECK: destroy_value [[COPIED_ARG2]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '[[THUNK_FOO_2]]' func curry_bridged(_ x: CurryTest) -> (String!) -> String! { return x.bridged } // CHECK-LABEL: sil hidden @_T013objc_currying13curry_bridgedSQySSGACcSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String> // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_BAR_1:_T0So9CurryTestC7bridgedSQySSGADFTcTO]] // CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[FN:%.*]] = apply [[THUNK]]([[ARG1_COPY]]) // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[FN]] // CHECK: } // end sil function '_T013objc_currying13curry_bridgedSQySSGACcSo9CurryTestCF' // CHECK: sil shared [serializable] [thunk] @[[THUNK_BAR_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String> // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest): // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_BAR_2:_T0So9CurryTestC7bridgedSQySSGADFTO]] // CHECK: [[FN:%.*]] = partial_apply [[THUNK]]([[ARG1]]) // CHECK: return [[FN]] // CHECK: } // end sil function '[[THUNK_BAR_1]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK_BAR_2]] : $@convention(method) (@owned Optional<String>, @guaranteed CurryTest) -> @owned Optional<String> // CHECK: bb0([[OPT_STRING:%.*]] : @owned $Optional<String>, [[SELF:%.*]] : @guaranteed $CurryTest): // CHECK: switch_enum [[OPT_STRING]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], // // CHECK: [[SOME_BB]]([[STRING:%.*]] : @owned $String): // CHECK: [[BRIDGING_FUNC:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[NSSTRING:%.*]] = apply [[BRIDGING_FUNC]]([[BORROWED_STRING]]) // CHECK: [[OPT_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTRING]] : $NSString // CHECK: end_borrow [[BORROWED_STRING]] from [[STRING]] // CHECK: destroy_value [[STRING]] // CHECK: br bb3([[OPT_NSSTRING]] : $Optional<NSString>) // CHECK: bb2: // CHECK: [[OPT_NONE:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt // CHECK: br bb3([[OPT_NONE]] : $Optional<NSString>) // CHECK: bb3([[OPT_NSSTRING:%.*]] : @owned $Optional<NSString>): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF_COPY]] : $CurryTest, #CurryTest.bridged!1.foreign // CHECK: [[RESULT_OPT_NSSTRING:%.*]] = apply [[METHOD]]([[OPT_NSSTRING]], [[SELF_COPY]]) : $@convention(objc_method) (Optional<NSString>, CurryTest) -> @autoreleased Optional<NSString> // CHECK: switch_enum [[RESULT_OPT_NSSTRING]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], // CHECK: [[SOME_BB]]([[RESULT_NSSTRING:%.*]] : @owned $NSString): // CHECK: [[BRIDGE_FUNC:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[REWRAP_RESULT_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTRING]] // CHECK: [[RESULT_STRING:%.*]] = apply [[BRIDGE_FUNC]]([[REWRAP_RESULT_NSSTRING]] // CHECK: [[WRAPPED_RESULT_STRING:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[RESULT_STRING]] // CHECK: br bb6([[WRAPPED_RESULT_STRING]] : $Optional<String>) // CHECK: bb5: // CHECK: [[OPT_NONE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb6([[OPT_NONE]] : $Optional<String>) // CHECK: bb6([[FINAL_RESULT:%.*]] : @owned $Optional<String>): // CHECK: destroy_value [[SELF_COPY]] // CHECK: destroy_value [[OPT_NSSTRING]] // CHECK: return [[FINAL_RESULT]] : $Optional<String> // CHECK: } // end sil function '[[THUNK_BAR_2]]' func curry_returnsInnerPointer(_ x: CurryTest) -> () -> UnsafeMutableRawPointer! { return x.returnsInnerPointer } // CHECK-LABEL: sil hidden @_T013objc_currying25curry_returnsInnerPointerSQySvGycSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> { // CHECK: bb0([[SELF:%.*]] : @owned $CurryTest): // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_RETURNSINNERPOINTER:_T0So9CurryTestC19returnsInnerPointerSQySvGyFTcTO]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[BORROWED_SELF]] // CHECK: [[FN:%.*]] = apply [[THUNK]]([[SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] // CHECK: return [[FN]] // CHECK: } // end sil function '_T013objc_currying25curry_returnsInnerPointerSQySvGycSo9CurryTestCF' // CHECK: sil shared [serializable] [thunk] @[[THUNK_RETURNSINNERPOINTER]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_RETURNSINNERPOINTER_2:_T0So9CurryTestC19returnsInnerPointerSQySvGyFTO]] // CHECK: [[FN:%.*]] = partial_apply [[THUNK]](%0) // CHECK: return [[FN]] // CHECK: } // end sil function '[[THUNK_RETURNSINNERPOINTER]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK_RETURNSINNERPOINTER_2]] : $@convention(method) (@guaranteed CurryTest) -> Optional<UnsafeMutableRawPointer> // CHECK: bb0([[ARG1:%.*]] : @guaranteed $CurryTest): // CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]] // CHECK: [[METHOD:%.*]] = objc_method [[ARG1_COPY]] : $CurryTest, #CurryTest.returnsInnerPointer!1.foreign // CHECK: [[RES:%.*]] = apply [[METHOD]]([[ARG1_COPY]]) : $@convention(objc_method) (CurryTest) -> @unowned_inner_pointer Optional<UnsafeMutableRawPointer> // CHECK: autorelease_value // CHECK: return [[RES]] // CHECK: } // end sil function '[[THUNK_RETURNSINNERPOINTER_2]]' // CHECK-LABEL: sil hidden @_T013objc_currying19curry_pod_AnyObjectS2icyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (Int) -> Int // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.pod!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying19curry_pod_AnyObjectS2icyXlF' func curry_pod_AnyObject(_ x: AnyObject) -> (Int) -> Int { return x.pod! } // normalOwnership requires a thunk to bring the method to Swift conventions // CHECK-LABEL: sil hidden @_T013objc_currying31curry_normalOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<CurryTest>) -> @owned Optional<CurryTest> { // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.normalOwnership!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (Optional<CurryTest>, @opened({{.*}}) AnyObject) -> @autoreleased Optional<CurryTest>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: [[THUNK:%.*]] = function_ref @_T0So9CurryTestCSgACIexyo_A2CIexxo_TR // CHECK: partial_apply [[THUNK]]([[PA]]) // CHECK: } // end sil function '_T013objc_currying31curry_normalOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF' func curry_normalOwnership_AnyObject(_ x: AnyObject) -> (CurryTest!) -> CurryTest! { return x.normalOwnership! } // weirdOwnership is NS_RETURNS_RETAINED and NS_CONSUMES_SELF so already // follows Swift conventions // CHECK-LABEL: sil hidden @_T013objc_currying30curry_weirdOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<CurryTest>) -> @owned Optional<CurryTest> // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[SELF:%.*]] : $@opened({{.*}}) AnyObject, #CurryTest.weirdOwnership!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: bb1([[METHOD:%.*]] : @trivial $@convention(objc_method) (@owned Optional<CurryTest>, @owned @opened({{.*}}) AnyObject) -> @owned Optional<CurryTest>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying30curry_weirdOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF' func curry_weirdOwnership_AnyObject(_ x: AnyObject) -> (CurryTest!) -> CurryTest! { return x.weirdOwnership! } // bridged requires a thunk to handle bridging conversions // CHECK-LABEL: sil hidden @_T013objc_currying23curry_bridged_AnyObjectSQySSGACcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String> // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.bridged!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (Optional<NSString>, @opened({{.*}}) AnyObject) -> @autoreleased Optional<NSString>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCSgACIexyo_SSSgADIexxo_TR // CHECK: partial_apply [[THUNK]]([[PA]]) // CHECK: } // end sil function '_T013objc_currying23curry_bridged_AnyObjectSQySSGACcyXlF' func curry_bridged_AnyObject(_ x: AnyObject) -> (String!) -> String! { return x.bridged! } // check that we substitute Self = AnyObject correctly for Self-returning // methods // CHECK-LABEL: sil hidden @_T013objc_currying27curry_returnsSelf_AnyObjectSQyyXlGycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned () -> @owned Optional<AnyObject> { // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.returnsSelf!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased Optional<AnyObject>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying27curry_returnsSelf_AnyObjectSQyyXlGycyXlF' func curry_returnsSelf_AnyObject(_ x: AnyObject) -> () -> AnyObject! { return x.returnsSelf! } // CHECK-LABEL: sil hidden @_T013objc_currying35curry_returnsInnerPointer_AnyObjectSQySvGycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> { // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.returnsInnerPointer!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @unowned_inner_pointer Optional<UnsafeMutableRawPointer>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying35curry_returnsInnerPointer_AnyObjectSQySvGycyXlF' func curry_returnsInnerPointer_AnyObject(_ x: AnyObject) -> () -> UnsafeMutableRawPointer! { return x.returnsInnerPointer! }
apache-2.0
a8ce79aed1596dcd9d6a7cec83a2e380
65.64574
228
0.650047
3.445861
false
true
false
false
VBVMI/VerseByVerse-iOS
VBVMI/TopicViewController.swift
1
7839
// // TopicViewController.swift // VBVMI // // Created by Thomas Carey on 27/03/16. // Copyright © 2016 Tom Carey. All rights reserved. // import UIKit class TopicViewController: UIViewController { let segmentedControl = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: 200, height: 20)) var topic: Topic! var selectedSegment: TypeSelection = .studies enum TypeSelection: Int { case studies = 0 case articles = 1 case answers = 2 var title: String { return "\(self)" } func viewController(_ topic: Topic) -> UIViewController { switch self { case .articles: let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "Articles") as! ArticlesViewController viewController.topic = topic return viewController case .answers: let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "Answers") as! AnswersViewController viewController.topic = topic return viewController default: return UIViewController() } } } var segmentToIndexMap = [TypeSelection : Int]() var indexToSegmentMap = [Int: TypeSelection]() override func encodeRestorableState(with coder: NSCoder) { coder.encode(topic.identifier, forKey: "topicIdentifier") coder.encode(selectedSegment.rawValue, forKey: "selectedSegment") super.encodeRestorableState(with: coder) } override func decodeRestorableState(with coder: NSCoder) { guard let identifier = coder.decodeObject(forKey: "topicIdentifier") as? String else { fatalError() } let context = ContextCoordinator.sharedInstance.managedObjectContext! guard let topic: Topic = Topic.findFirstWithPredicate(NSPredicate(format: "%K == %@", TopicAttributes.identifier.rawValue, identifier), context: context) else { fatalError() } self.topic = topic self.selectedSegment = TypeSelection(rawValue: coder.decodeInteger(forKey: "selectedSegment"))! super.decodeRestorableState(with: coder) configureForTopic() configureSegmentedControl() } fileprivate func configureForTopic() { var currentIndex = 0 // if topic.studies.count > 0 || topic.lessons.count > 0 { // segmentedControl.insertSegmentWithTitle(TypeSelection.Studies.title, atIndex: currentIndex, animated: false) // segmentToIndexMap[.Studies] = currentIndex // indexToSegmentMap[currentIndex] = .Studies // currentIndex += 1 // } if topic.articles.count > 0 { segmentedControl.insertSegment(withTitle: TypeSelection.articles.title, at: currentIndex, animated: false) segmentToIndexMap[.articles] = currentIndex indexToSegmentMap[currentIndex] = .articles currentIndex += 1 } if topic.answers.count > 0 { segmentedControl.insertSegment(withTitle: TypeSelection.answers.title, at: currentIndex, animated: false) segmentToIndexMap[.answers] = currentIndex indexToSegmentMap[currentIndex] = .answers currentIndex += 1 } self.navigationItem.titleView = segmentedControl // self.navigationItem.prompt = topic.name } fileprivate func configureSegmentedControl() { if let index = segmentToIndexMap[selectedSegment] { segmentedControl.selectedSegmentIndex = index } else { segmentedControl.selectedSegmentIndex = 0 } segmentedControl.addTarget(self, action: #selector(TopicViewController.segmentedControlChanged(_:)), for: .valueChanged) self.segmentedControlChanged(segmentedControl) } override func viewDidLoad() { super.viewDidLoad() restorationIdentifier = "TopicViewController" restorationClass = TopicViewController.self if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .never } else { // Fallback on earlier versions } if let _ = topic { configureForTopic() configureSegmentedControl() } } fileprivate var currentViewController : UIViewController? fileprivate func configureSubviewController(_ viewController: UIViewController) { if let current = currentViewController { current.willMove(toParentViewController: nil) current.removeFromParentViewController() current.view.removeFromSuperview() } viewController.willMove(toParentViewController: self) self.addChildViewController(viewController) // viewController.view.frame = self.view.bounds self.view.addSubview(viewController.view) viewController.view.snp.makeConstraints { (make) in make.edges.equalTo(0) } viewController.didMove(toParentViewController: self) currentViewController = viewController if #available(iOS 11.0, *) { } else { if let tableViewController = currentViewController as? UITableViewController { let insets = UIEdgeInsetsMake(topLayoutGuide.length, 0, bottomLayoutGuide.length, 0) tableViewController.tableView.contentInset = insets tableViewController.tableView.scrollIndicatorInsets = insets tableViewController.tableView.contentOffset = CGPoint(x: 0, y: -topLayoutGuide.length) } } // viewController.view.layoutIfNeeded() } override func viewDidLayoutSubviews() { if #available(iOS 11.0, *) { } else { if let tableViewController = currentViewController as? UITableViewController { let insets = UIEdgeInsetsMake(topLayoutGuide.length, 0, bottomLayoutGuide.length, 0) tableViewController.tableView.contentInset = insets tableViewController.tableView.scrollIndicatorInsets = insets tableViewController.tableView.contentOffset = CGPoint(x: 0, y: -topLayoutGuide.length) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func segmentedControlChanged(_ sender: UISegmentedControl) { // logger.info("🍕value: \(sender.selectedSegmentIndex)") self.selectedSegment = indexToSegmentMap[sender.selectedSegmentIndex]! let viewController = self.selectedSegment.viewController(topic) configureSubviewController(viewController) } /* // 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. } */ } extension TopicViewController : UIViewControllerRestoration { static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { let vc = TopicViewController(nibName: "TopicViewController", bundle: nil) return vc } }
mit
9196f2f3cbb57b3e863a68b352a3dc9c
38.371859
168
0.639438
5.744135
false
false
false
false
rizumita/CTFeedbackSwift
CTFeedbackSwiftTests/CellFactoryTests.swift
1
2881
import XCTest @testable import CTFeedbackSwift class CellFactoryTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testReuseIdentifier() { XCTAssertEqual(TestCellFactory.reuseIdentifier, "TestCellFactory") } } class AnyCellFactoryTests: XCTestCase { func testSuitable() { let concreteFactory = TestCellFactory.self let factory = AnyCellFactory(concreteFactory) XCTAssertTrue(factory.suitable(for: "")) } func testConfigure() { let concreteFactory = TestCellFactory.self let factory = AnyCellFactory(concreteFactory) let cell = UITableViewCell() let indexPath = IndexPath(row: 0, section: 0) _ = factory.configure(cell, with: "test", for: indexPath, eventHandler: "Handler") XCTAssertTrue(concreteFactory.cell === cell) XCTAssertEqual(concreteFactory.item, "test") XCTAssertEqual(concreteFactory.indexPath, indexPath) XCTAssertEqual(concreteFactory.eventHandler, "Handler") } } class UITableView_ExtensionsTests: XCTestCase { func testDequeueCell() { let concreteFactory = TestCellFactory.self let factory = AnyCellFactory(concreteFactory) let tableView = UITableView() tableView.register(with: factory) let indexPath = IndexPath(row: 0, section: 0) let cell: UITableViewCell = tableView.dequeueCell(to: "Item", from: [factory], for: indexPath, eventHandler: "EventHandler") XCTAssertTrue(concreteFactory.cell === cell) XCTAssertEqual(concreteFactory.item, "Item") XCTAssertEqual(concreteFactory.indexPath, indexPath) XCTAssertEqual(concreteFactory.eventHandler, "EventHandler") } } class TestCellFactory: CellFactoryProtocol { static var cell: UITableViewCell? static var item: String? static var indexPath: IndexPath? static var eventHandler: String? static func configure(_ cell: UITableViewCell, with item: String, for indexPath: IndexPath, eventHandler: String?) { self.cell = cell self.item = item self.indexPath = indexPath self.eventHandler = eventHandler } }
mit
7f672c7dd7f06c27ac92694b5d5a141d
36.907895
111
0.589726
5.540385
false
true
false
false
rharri/EventsAndFestivals
Sources/App/Models/Event.swift
1
2007
// // Event.swift // EventsAndFestivals // // Created by Ryan Harri on 2017-01-30. // // import Foundation import MongoKitten struct Event { var recID: String = "" var name: String = "" var description: String = "" var website: String = "" var email: String = "" var phone: String = "" var phoneExtension: String = "" var categories: String = "" var isAccessible: Bool = false var freeParking: Bool = false var paidParking: Bool = false var publicWashrooms: Bool = false var foodAndBeverages: Bool = false var start: String = "" var end: String = "" var month: String = "" var year: Int = 0 var latitude: Double = 0.0 var longitude: Double = 0.0 var locationName: String = "" var address: String = "" var isFree: Bool = false var otherCostInfo: String = "" var organization: String = "" var imageURL: String = "" var document: Document { return [ "recId": "\(recID)", "name": "\(name)", "description": "\(description)", "website": "\(website)", "email": "\(email)", "phone": "\(phone)", "phoneExtension": "\(phoneExtension)", "categories": "\(categories)", "isAccessible": isAccessible, "freeParking": freeParking, "paidParking": paidParking, "publicWashrooms": publicWashrooms, "foodAndBeverages": foodAndBeverages, "start": "\(start)", "end": "\(end)", "month": "\(month)", "year": year, "latitude": latitude, "longitude": longitude, "locationName": "\(locationName)", "address": "\(address)", "isFree": isFree, "otherCostInfo": "\(otherCostInfo)", "organization": "\(organization)", "imageURL": "\(imageURL)" ] } init() { } }
mit
d5277ce5c9e3e4adbb168c791f7dad68
25.064935
50
0.512207
4.391685
false
false
false
false
szehnder/AERecord
AERecordExample/DetailViewController.swift
1
5462
// // DetailViewController.swift // AERecordExample // // Created by Marko Tadic on 11/3/14. // Copyright (c) 2014 ae. All rights reserved. // import UIKit import CoreData import AERecord let yellow = UIColor(red: 0.969, green: 0.984, blue: 0.745, alpha: 1) let blue = UIColor(red: 0.918, green: 0.969, blue: 0.984, alpha: 1) class DetailViewController: CoreDataCollectionViewController { // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // setup UISplitViewController displayMode button navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem() navigationItem.leftItemsSupplementBackButton = true // setup options button let optionsButton = UIBarButtonItem(title: "Options", style: .Plain, target: self, action: "showOptions:") self.navigationItem.rightBarButtonItem = optionsButton // setup fetchedResultsController property refreshFetchedResultsController() } // MARK: - CoreData func showOptions(sender: AnyObject) { let optionsAlert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) optionsAlert.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem let addFewAction = UIAlertAction(title: "Add Few", style: .Default) { (action) -> Void in // create few objects for i in 1...5 { Event.createWithAttributes(["timeStamp" : NSDate()]) } AERecord.saveContextAndWait() } let deleteAllAction = UIAlertAction(title: "Delete All", style: .Destructive) { (action) -> Void in // delete all objects Event.deleteAll() AERecord.saveContextAndWait() } let updateAllAction = UIAlertAction(title: "Update All", style: .Default) { (action) -> Void in if NSProcessInfo.instancesRespondToSelector("isOperatingSystemAtLeastVersion:") { // >= iOS 8 // batch update all objects (directly in persistent store) then refresh objects in context Event.batchUpdateAndRefreshObjects(properties: ["timeStamp" : NSDate()]) // note that if using NSFetchedResultsController you have to call performFetch after batch updating self.performFetch() } else { // < iOS 8 println("Batch updating is new in iOS 8.") // update all objects through context if let events = Event.all() as? [Event] { for e in events { e.timeStamp = NSDate() } AERecord.saveContextAndWait() } } } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in self.dismissViewControllerAnimated(true, completion: nil) } optionsAlert.addAction(addFewAction) optionsAlert.addAction(deleteAllAction) optionsAlert.addAction(updateAllAction) optionsAlert.addAction(cancelAction) presentViewController(optionsAlert, animated: true, completion: nil) } func refreshFetchedResultsController() { let sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: true)] let request = Event.createFetchRequest(sortDescriptors: sortDescriptors) fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: AERecord.defaultContext, sectionNameKeyPath: nil, cacheName: nil) } // MARK: - Collection View override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as CustomCollectionViewCell self.configureCell(cell, atIndexPath: indexPath) return cell } func configureCell(cell: CustomCollectionViewCell, atIndexPath indexPath: NSIndexPath) { if let frc = fetchedResultsController { if let event = frc.objectAtIndexPath(indexPath) as? Event { cell.backgroundColor = event.selected ? yellow : blue cell.textLabel.text = event.timeStamp.description } } } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCollectionViewCell { // update value if let frc = fetchedResultsController { if let event = frc.objectAtIndexPath(indexPath) as? Event { cell.backgroundColor = yellow // deselect previous if let previous = Event.firstWithAttribute("selected", value: true) as? Event { previous.selected = false AERecord.saveContextAndWait() } // select current and refresh timestamp event.selected = true event.timeStamp = NSDate() AERecord.saveContextAndWait() } } } } }
mit
0fd38c08399a98099ecce2cc9d95ab02
40.378788
172
0.623398
5.898488
false
false
false
false
bingoogolapple/SwiftNote-PartTwo
NSThread加载图像/NSThread加载图像/MainViewController.swift
1
9187
// // MainViewController.swift // NSThread加载图像 // // Created by bingoogol on 14/9/18. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit /* NSThread 优点:简单 缺点:控制线程的生命周期比较困难,控制并发线程数,先后顺序困难 */ class MainViewController: UIViewController { var imageViewSet:NSSet! var queue:NSOperationQueue! override func viewDidLoad() { super.viewDidLoad() setupUI() // 实例化操作队列 self.queue = NSOperationQueue() } func setupUI() { var imageViewSet = NSMutableSet(capacity: 28) // 一共17张图片,每行显示4张,一共显示7行 var w = 640 / 8 var h = 400 / 8 for row in 0 ... 6 { for col in 0 ... 3 { var x = CGFloat(col * w) var y = CGFloat(row * h) var imageView = UIImageView(frame: CGRectMake(x, y, CGFloat(w), CGFloat(h))) // 顺序填充图像 var num = (row * 4 + col) % 17 + 1 if num < 10 { imageView.image = UIImage(named: "NatGeo0\(num).png") } else { imageView.image = UIImage(named: "NatGeo\(num).png") } self.view.addSubview(imageView) imageViewSet.addObject(imageView) } } self.imageViewSet = imageViewSet // 添加按钮 var button = UIButton.buttonWithType(UIButtonType.System) as UIButton button.frame = CGRectMake(110, 390, 100, 40) button.setTitle("刷新图片", forState: UIControlState.Normal) button.addTarget(self, action: Selector("click"), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) println("setupUI 当前线程为\(NSThread.currentThread())") } func click() { println("click me") //threadLoad() //invocationOperationLoad() //blockOpreationLoad() operationLoad() //operationDemo() gcdLoad() //gcdDemo() } func threadLoad() { for imageView in imageViewSet { // 类方法,直接新建线程调用threadLoadImage NSThread.detachNewThreadSelector(Selector("threadLoadImage:"), toTarget: self, withObject: imageView) // var thread = NSThread(target: self, selector: Selector("threadLoadImage:"), object: imageView) // thread.start() } } func threadLoadImage(imageView:UIImageView) { autoreleasepool{ NSLog("threadLoadImage 当前线程为\(NSThread.currentThread())") // println("threadLoadImage 当前线程为\(NSThread.currentThread())") NSThread.sleepForTimeInterval(1) var num = arc4random_uniform(17) + 1 var image:UIImage if num < 10 { image = UIImage(named: "NatGeo0\(num).png") } else { image = UIImage(named: "NatGeo\(num).png") } // 在主线程队列上更新UI NSOperationQueue.mainQueue().addOperationWithBlock({ imageView.image = image }) } } func invocationOperationLoad() { // 队列可以设置同事并发线程的数量 self.queue.maxConcurrentOperationCount = 2 for imageView in imageViewSet { var invocationOperation = NSInvocationOperation(target: self, selector: Selector("operationLoadImage:"), object: imageView) // 如果直接调用opreation的start方法,是在主线程队列上运行的,不会开启新的线程 // operation.start() // Invocation添加到队列,一添加到队列,就会开启新的线程执行任务 self.queue.addOperation(invocationOperation) } } func blockOpreationLoad() { for imageView in imageViewSet { // 这种实现方式可以传多个参数 var blockOperation = NSBlockOperation({ self.operationLoadImage(imageView as UIImageView) }) self.queue.addOperation(blockOperation) } } func operationLoad() { for imageView in imageViewSet { // 这种实现方式可以传多个参数 self.queue.addOperationWithBlock({ self.operationLoadImage(imageView as UIImageView) }) } } func operationLoadImage(imageView:UIImageView) { NSLog("threadLoadImage 当前线程为\(NSThread.currentThread())") // println("threadLoadImage 当前线程为\(NSThread.currentThread())") NSThread.sleepForTimeInterval(1) var num = arc4random_uniform(17) + 1 var image:UIImage if num < 10 { image = UIImage(named: "NatGeo0\(num).png") } else { image = UIImage(named: "NatGeo\(num).png") } // 在主线程队列上更新UI NSOperationQueue.mainQueue().addOperationWithBlock({ imageView.image = image }) } // NSOpreation操作之间的顺序 func operationDemo() { var op1 = NSBlockOperation({ NSLog("下载\(NSThread.currentThread())") }) var op2 = NSBlockOperation({ NSLog("美化\(NSThread.currentThread())") }) var op3 = NSBlockOperation({ NSLog("更新\(NSThread.currentThread())") }) // 依赖关系可以多重依赖 op2.addDependency(op1) op3.addDependency(op2) // 注意:不要建立循环依赖,加上下面这一句后系统不会报错,但是会不工作 // op1.addDependency(op3) self.queue.addOperation(op1) self.queue.addOperation(op3) self.queue.addOperation(op2) //self.queue.addOperationWithBlock({ // 这样也是在子线程中执行的 // NSLog("完成\(NSThread.currentThread())") // }) } func gcdLoad() { /* 1.全局队列(可能会开启多条线程):所有任务是并发(异步)执行的 2.串行队列(只会开启一条线程) 3.主队列:主线程队列 在gcd中,同步还是异步取决于任务执行所在的队列,跟方法名没有关系(全局队列中才分async和sync) */ // 派发dispatch // 异步async,并发执行 // 1)获取全局队列,全局调度队列是由系统负责的,开发时不用考虑并发线程数量问题 var que = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) for imageView in imageViewSet { // 2)在全局队列上异步调用方法,加载并更新图像 dispatch_async(que, { NSLog("GCD-\(NSThread.currentThread())") var num = arc4random_uniform(17) + 1 var image:UIImage // 通常此处的image是从网络上获取的 if num < 10 { image = UIImage(named: "NatGeo0\(num).png") } else { image = UIImage(named: "NatGeo\(num).png") } // 3)在主线程队列中,调用同步方法设置UI dispatch_sync(dispatch_get_main_queue(), { (imageView as UIImageView).image = image }) }) } } // 3.串行队列 func gcdDemo() { // sync卡死,async永远都是 线程主线程 任务1-》任务2-》任务3 // var que = dispatch_get_main_queue() // sync永远都是 线程主线程 任务1-》任务2-》任务3,async 多个线程 乱序 // var que = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) // 1)串行队列需要创建 // 队列名称可以随意 // sync永远都是 线程主线程 任务1-》任务2-》任务3,async永远都是 任务1-》任务2-》任务3 点击多次时,可能有多个线程,但是每一次点击的所有任务都是在同一个线程中执行 var que = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL) // 2)在队列中执行异步任务 async(que) } func sync(que:dispatch_queue_t) { dispatch_sync(que, { NSLog("任务1-\(NSThread.currentThread())") }) dispatch_sync(que, { NSLog("任务2-\(NSThread.currentThread())") }) dispatch_sync(que, { NSLog("任务3-\(NSThread.currentThread())") }) } func async(que:dispatch_queue_t) { dispatch_async(que, { NSLog("任务1-\(NSThread.currentThread())") }) dispatch_async(que, { NSLog("任务2-\(NSThread.currentThread())") }) dispatch_async(que, { NSLog("任务3-\(NSThread.currentThread())") }) } }
apache-2.0
c4b69d01e1bfffde532194c68c737f80
30.52988
135
0.54025
4.164737
false
false
false
false
sarahspins/Loop
Loop/Managers/KeychainManager.swift
2
8235
// // KeychainManager.swift // Loop // // Created by Nate Racklyeft on 6/26/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import Security /** Influenced by https://github.com/marketplacer/keychain-swift */ struct KeychainManager { typealias Query = [String: NSObject] var accessibility: CFString = kSecAttrAccessibleAfterFirstUnlock var accessGroup: String? enum Error: ErrorType { case add(OSStatus) case copy(OSStatus) case delete(OSStatus) case unknownResult } struct InternetCredentials { let username: String let password: String let URL: NSURL } // MARK: - Convenience methods private func queryByClass(`class`: CFString) -> Query { var query: Query = [kSecClass as String: `class`] if let accessGroup = accessGroup { query[kSecAttrAccessGroup as String] = accessGroup } return query } private func queryForGenericPasswordByService(service: String) -> Query { var query = queryByClass(kSecClassGenericPassword) query[kSecAttrService as String] = service return query } private func queryForInternetPassword(account account: String? = nil, URL: NSURL? = nil) -> Query { var query = queryByClass(kSecClassInternetPassword) if let account = account { query[kSecAttrAccount as String] = account } if let URL = URL, components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) { for (key, value) in components.keychainAttributes { query[key] = value } } return query } private func updatedQuery(query: Query, withPassword password: String) throws -> Query { var query = query guard let value = password.dataUsingEncoding(NSUTF8StringEncoding) else { throw Error.add(errSecDecode) } query[kSecValueData as String] = value query[kSecAttrAccessible as String] = accessibility return query } func delete(query: Query) throws { let statusCode = SecItemDelete(query) guard statusCode == errSecSuccess || statusCode == errSecItemNotFound else { throw Error.delete(statusCode) } } // MARK: – Generic Passwords func replaceGenericPassword(password: String?, forService service: String) throws { var query = queryForGenericPasswordByService(service) try delete(query) guard let password = password else { return } query = try updatedQuery(query, withPassword: password) let statusCode = SecItemAdd(query, nil) guard statusCode == errSecSuccess else { throw Error.add(statusCode) } } func getGenericPasswordForService(service: String) throws -> String { var query = queryForGenericPasswordByService(service) query[kSecReturnData as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne var result: NSData? let statusCode: OSStatus = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } guard statusCode == errSecSuccess else { throw Error.copy(statusCode) } guard let passwordData = result, password = String(data: passwordData, encoding: NSUTF8StringEncoding) else { throw Error.unknownResult } return password } // MARK – Internet Passwords func setInternetPassword(password: String, forAccount account: String, atURL url: NSURL) throws { var query = try updatedQuery(queryForInternetPassword(account: account, URL: url), withPassword: password) query[kSecAttrAccount as String] = account if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) { for (key, value) in components.keychainAttributes { query[key] = value } } let statusCode = SecItemAdd(query, nil) guard statusCode == errSecSuccess else { throw Error.add(statusCode) } } func replaceInternetCredentials(credentials: InternetCredentials?, forAccount account: String) throws { let query = queryForInternetPassword(account: account) try delete(query) if let credentials = credentials { try setInternetPassword(credentials.password, forAccount: credentials.username, atURL: credentials.URL) } } func replaceInternetCredentials(credentials: InternetCredentials?, forURL URL: NSURL) throws { let query = queryForInternetPassword(URL: URL) try delete(query) if let credentials = credentials { try setInternetPassword(credentials.password, forAccount: credentials.username, atURL: credentials.URL) } } func getInternetCredentials(account account: String? = nil, URL: NSURL? = nil) throws -> InternetCredentials { var query = queryForInternetPassword(account: account, URL: URL) query[kSecReturnData as String] = kCFBooleanTrue query[kSecReturnAttributes as String] = kCFBooleanTrue query[kSecMatchLimit as String] = kSecMatchLimitOne var result: CFDictionary? let statusCode: OSStatus = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } guard statusCode == errSecSuccess else { throw Error.copy(statusCode) } let resultDict = result as [NSObject: AnyObject]? if let result = resultDict, passwordData = result[kSecValueData as String] as? NSData, password = String(data: passwordData, encoding: NSUTF8StringEncoding), URL = NSURLComponents(keychainAttributes: result)?.URL, username = result[kSecAttrAccount as String] as? String { return InternetCredentials(username: username, password: password, URL: URL) } throw Error.unknownResult } } private enum SecurityProtocol { case HTTP case HTTPS init?(scheme: String?) { switch scheme?.lowercaseString { case "http"?: self = .HTTP case "https"?: self = .HTTPS default: return nil } } init?(secAttrProtocol: CFString) { if secAttrProtocol == kSecAttrProtocolHTTP { self = .HTTP } else if secAttrProtocol == kSecAttrProtocolHTTPS { self = .HTTPS } else { return nil } } var scheme: String { switch self { case .HTTP: return "http" case .HTTPS: return "https" } } var secAttrProtocol: CFString { switch self { case .HTTP: return kSecAttrProtocolHTTP case .HTTPS: return kSecAttrProtocolHTTPS } } } private extension NSURLComponents { convenience init?(keychainAttributes: [NSObject: AnyObject]) { self.init() if let secAttProtocol = keychainAttributes[kSecAttrProtocol as String] { scheme = SecurityProtocol(secAttrProtocol: secAttProtocol as! CFString)?.scheme } host = keychainAttributes[kSecAttrServer as String] as? String if let port = keychainAttributes[kSecAttrPort as String] as? NSNumber where port.integerValue > 0 { self.port = port } path = keychainAttributes[kSecAttrPath as String] as? String } var keychainAttributes: [String: NSObject] { var query: [String: NSObject] = [:] if let `protocol` = SecurityProtocol(scheme: scheme) { query[kSecAttrProtocol as String] = `protocol`.secAttrProtocol } if let host = host { query[kSecAttrServer as String] = host } if let port = port { query[kSecAttrPort as String] = port } if let path = path { query[kSecAttrPath as String] = path } return query } }
apache-2.0
2cf7d2c2d52fae89a781e70479c5f8cd
27.085324
117
0.6262
5.281772
false
false
false
false
dominicpr/GuillotineMenu
GuillotineMenu/GuillotineMenuViewController.swift
13
4994
// // GuillotineViewController.swift // GuillotineMenu // // Created by Maksym Lazebnyi on 3/24/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit class GuillotineMenuViewController: UIViewController { var hostNavigationBarHeight: CGFloat! var hostTitleText: NSString! var menuButton: UIButton! var menuButtonLeadingConstraint: NSLayoutConstraint! var menuButtonTopConstraint: NSLayoutConstraint! private let menuButtonLandscapeLeadingConstant: CGFloat = 1 private let menuButtonPortraitLeadingConstant: CGFloat = 7 private let hostNavigationBarHeightLandscape: CGFloat = 32 private let hostNavigationBarHeightPortrait: CGFloat = 44 override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition(nil) { (context) -> Void in if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { self.menuButtonLeadingConstraint.constant = self.menuButtonLandscapeLeadingConstant self.menuButtonTopConstraint.constant = self.menuButtonPortraitLeadingConstant } else { let statusbarHeight = UIApplication.sharedApplication().statusBarFrame.size.height self.menuButtonLeadingConstraint.constant = self.menuButtonPortraitLeadingConstant; self.menuButtonTopConstraint.constant = self.menuButtonPortraitLeadingConstant+statusbarHeight } } } // MARK: Actions func closeMenuButtonTapped() { self.dismissViewControllerAnimated(true, completion: nil) } func setMenuButtonWithImage(image: UIImage) { let statusbarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let buttonImage = UIImage(CGImage: image.CGImage, scale: 1.0, orientation: .Right) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { menuButton = UIButton(frame: CGRectMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight, 30.0, 30.0)) } else { menuButton = UIButton(frame: CGRectMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight, 30.0, 30.0)) } menuButton.setImage(image, forState: .Normal) menuButton.setImage(image, forState: .Highlighted) menuButton.imageView!.contentMode = .Center menuButton.addTarget(self, action: Selector("closeMenuButtonTapped"), forControlEvents: .TouchUpInside) menuButton.setTranslatesAutoresizingMaskIntoConstraints(false) menuButton.transform = CGAffineTransformMakeRotation( ( 90 * CGFloat(M_PI) ) / 180 ); self.view.addSubview(menuButton) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { var (leading, top) = self.view.addConstraintsForMenuButton(menuButton, offset: UIOffsetMake(menuButtonLandscapeLeadingConstant, menuButtonPortraitLeadingConstant)) menuButtonLeadingConstraint = leading menuButtonTopConstraint = top } else { var (leading, top) = self.view.addConstraintsForMenuButton(menuButton, offset: UIOffsetMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight)) menuButtonLeadingConstraint = leading menuButtonTopConstraint = top } } } extension GuillotineMenuViewController: GuillotineAnimationProtocol { func anchorPoint() -> CGPoint { if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { //In this case value is calculated manualy as the method is called before viewDidLayourSubbviews when the menuBarButton.frame is updated. return CGPointMake(16, 16) } return self.menuButton.center } func navigationBarHeight() -> CGFloat { if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { return hostNavigationBarHeightLandscape } else { return hostNavigationBarHeightPortrait } } func hostTitle () -> NSString { return hostTitleText } }
mit
a7552cd30d62bd4f2b5f013a1e11e123
42.051724
190
0.70845
5.760092
false
false
false
false
cocoaswifty/TVLive
TVLive/AppDelegate.swift
1
4527
// // AppDelegate.swift // TVLive // // Created by jianhao on 2016/11/13. // Copyright © 2016年 cocoaswifty. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "TVLive") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
c0105f0a76b30104de94848e50e35a77
48.173913
285
0.683908
5.81491
false
false
false
false
R0uter/polyv-ios-client-swift-demo
polyv-ios-client-swift-demo/UploadDemoViewController.swift
1
7933
// // UploadDemoViewController.swift // polyv-ios-client-swift-demo // // Created by R0uter on 2017/3/31. // Copyright © 2017年 R0uter. All rights reserved. // import UIKit import MobileCoreServices import AssetsLibrary import AVFoundation let PLVRemoteURLDefaultsKey = "PLVRemoteURL" class UploadDemoViewController:UIViewController { var assetsLibrary = ALAssetsLibrary() lazy var videoPlayer:SkinVideoViewController = { let width = self.view.bounds.size.width let vp:SkinVideoViewController = SkinVideoViewController(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: width, height: width*(9.0/16.0)))! vp.dimissCompleteBlock = { vp.stop() } return vp }() var vid = "" @IBOutlet weak var imageOverlay:UIView! @IBOutlet weak var imageView:UIImageView! @IBOutlet weak var urlTextView:UITextView! @IBOutlet weak var statusLabel:UILabel! @IBOutlet weak var progressBar:UIProgressView! @IBOutlet weak var chooseFileButton:UIButton! override func viewDidLoad() { super.viewDidLoad() imageOverlay.isHidden = true progressBar.progress = 0 UserDefaults.standard.register(defaults: [PLVRemoteURLDefaultsKey:"https://upload.polyv.net:1081/files/"]) let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap)) singleTap.numberOfTapsRequired = 1 urlTextView.addGestureRecognizer(singleTap) } @IBAction func chooseFile (_ sender:Any) { let imagePicker = UIImagePickerController() imagePicker.sourceType = .photoLibrary imagePicker.mediaTypes = [kUTTypeMovie as String] imagePicker.delegate = self present(imagePicker, animated: true, completion: nil) } @IBAction func closeButtonAction(_ sender:Any) { self.dismiss(animated: true, completion: nil) } func handleSingleTap () { if let video = PolyvSettings.getVideo(vid) { if video.available() { videoPlayer.showInWindow() videoPlayer.setVid(vid, level: .standard) } else { let alert = UIAlertView(title: "提示", message: "视频还没有准备好", delegate: nil, cancelButtonTitle: "好") alert.show() } } } } //MARK:UIImagePickerDelegate Methods extension UploadDemoViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let videoUrl = info[UIImagePickerControllerMediaURL] as! URL let outputUrl = URL(fileURLWithPath: NSTemporaryDirectory().appending("temp.mov")) let hudView = UIView(frame: CGRect(x: 75, y: 155, width: 170, height: 170)) hudView.backgroundColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.5) hudView.clipsToBounds = true hudView.layer.cornerRadius = 10.0 let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) activityIndicatorView.frame = CGRect(x: 65, y: 40, width: activityIndicatorView.bounds.size.width, height: activityIndicatorView.bounds.size.width) hudView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() let captionLabel = UILabel(frame: CGRect(x: 20, y: 115, width: 130, height: 22)) captionLabel.backgroundColor = UIColor.clear captionLabel.textColor = UIColor.white captionLabel.adjustsFontSizeToFitWidth = true captionLabel.textAlignment = .center captionLabel.text = "正在压缩视频..." hudView.addSubview(captionLabel) picker.view.addSubview(hudView) self.convertVideoToLowQuailty(withInputURL: videoUrl, outputURL: outputUrl) { DispatchQueue.main.async { hudView.removeFromSuperview() } if $0.status == .completed { self.urlTextView.text = "" self.imageView = nil self.dismiss(animated: true) { let type = info[UIImagePickerControllerMediaType] let typeDescription = UTTypeCopyDeclaration(type as! CFString) let text = String(format: "Uploading %@...", typeDescription as! CVarArg) self.statusLabel.text = text self.imageOverlay.isHidden = false self.chooseFileButton.isEnabled = false } }else { LogPrint("error!") } } } /**压缩视频大小*/ func convertVideoToLowQuailty(withInputURL inputURL:URL, outputURL:URL, handler:@escaping (AVAssetExportSession)->()) { try? FileManager.default.removeItem(at: outputURL) let asset = AVURLAsset(url: inputURL) let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality) exportSession?.outputURL = outputURL exportSession?.outputFileType = AVFileTypeQuickTimeMovie exportSession?.exportAsynchronously { handler(exportSession!) } } /**使用文件地址上传*/ var endpoint:String {return UserDefaults.standard.value(forKey: PLVRemoteURLDefaultsKey) as! String} var progressBlock:PLVUploadProgressBlock { return { var progress = Float($0)/Float($1) if progress.isNaN {progress = 0.0} DispatchQueue.main.async { self.progressBar.progress = progress } } } var failureBlock:PLVUploadFailureBlock { return { e in DispatchQueue.main.async { LogPrint("Failed to upload file due to:\(String(describing: e?.localizedDescription))") self.chooseFileButton.isEnabled = true var text = self.urlTextView.text text = text?.appending("\n\(String(describing: e?.localizedDescription))") self.urlTextView.text = text self.statusLabel.text = "Failed!" UIAlertView(title: "Error", message: e?.localizedDescription, delegate: nil, cancelButtonTitle: "好").show() } } } var resultBlock:PLVUploadResultBlock { return { vid in DispatchQueue.main.async { self.chooseFileButton.isEnabled = true self.imageOverlay.isHidden = true self.imageView.alpha = 1 self.urlTextView.text = "点击播放 \(String(describing: vid))" self.vid = vid! } } } func uploadVideo(fromURL url:URL) { let uploadData = PLVData(data: try! Data(contentsOf: url)) let upload = PLVResumableUpload(url: endpoint, data: uploadData, fingerprint: url.absoluteString) let extraInfo = [ "ext":"mov", "cataid":"1357359024647", "title":"polyvsdk", "desc":"polyvsdk upload demo video" , ] upload?.setExtraInfo(extraInfo as! NSMutableDictionary) upload?.progressBlock = progressBlock upload?.resultBlock = resultBlock upload?.failureBlock = failureBlock upload?.start() } /**Asset上传**/ func uploadVideo(fromAsset info:NSDictionary) { } } //MARK:页面旋转 extension UploadDemoViewController { override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations:UIInterfaceOrientationMask { return .portrait } override var preferredInterfaceOrientationForPresentation:UIInterfaceOrientation { return .portrait } }
mit
25dbfbfe2ede1899f9175f3147762443
38.034826
178
0.631022
5.065203
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01291-swift-type-walk.swift
1
1052
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<e>() -> (e, e -> e) -> e { { { } } protocol f { } class e: f { class funT>: NSObject { init(foo: T) { B>(t: T) { } x x) { } class a { var _ = i() { } } func i(c: () -> ()) { } class a { var _ = i() { } } } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } } func n<q>() { b b { } } func n(j: Any, t: Any) -> (((Any, Any) -> Any) -> Any) { k { } } var d = b protocol a { } protocol b : a { } protocol c : a { } protocol d { } struct e : d { } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } protocol b { } struct c { func e() { } } struct c<e> { } func b(g: f) -> <e>(()-> e) -> i
apache-2.0
a03bed467e11953d3f76de8db00421a5
13.611111
79
0.55038
2.429561
false
false
false
false
rcasanovan/Social-Feed
Social Feed/Social Feed/Extensions/SFDate.swift
1
1047
// // SFDate.swift // Social Feed // // Created by Ricardo Casanova on 06/08/2017. // Copyright © 2017 Social Feed. All rights reserved. // import Foundation extension Date { func currentTimeZoneDate() -> String { let dtf = DateFormatter() dtf.timeZone = TimeZone.current dtf.dateFormat = "yyyy-MM-dd HH:mm:ss" return dtf.string(from: self) } func ddMMMyyyyFormat() -> String { // change to a readable time format and change to local time zone let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MMM/yyyy" dateFormatter.timeZone = TimeZone.current return dateFormatter.string(from: self) } static func getDateFromTwitterFormart(stringDate: String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss +0000 yyyy" dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") let date = dateFormatter.date(from: stringDate) return date! } }
apache-2.0
e28135fb0f50c94d57e3fe78cc4811af
29.764706
73
0.648184
4.200803
false
false
false
false
nacuteodor/ProcessTestSummaries
XCResultKit/XCResultDouble.swift
1
625
// // File.swift // // // Created by David House on 7/3/19. // import Foundation extension Double: XCResultObject { public init?(_ json: [String: AnyObject]) { // Ensure we have the correct type here guard let type = json["_type"] as? [String: AnyObject], let name = type["_name"] as? String, name == "Double" else { print("Incorrect type, expecting Int") return nil } guard let actualValue = json["_value"] as? NSString else { print("Unable to get double value") return nil } self = actualValue.doubleValue } }
mit
17ac44bdbbbfbbc9a8d45c78d492bf1a
23.038462
124
0.568
4.194631
false
false
false
false
netguru-hackathon/props-ios
Props/GiveTableViewController.swift
1
1472
// // GiveTableViewController.swift // // Copyright (c) 2014 Netguru Sp. z o.o. All rights reserved. // import UIKit import Alamofire class GiveTableViewController: UITableViewController, UsersTableViewControllerDelegate, UITextViewDelegate { var receiver: User? @IBOutlet weak var reveiversLabel: UILabel! @IBOutlet weak var bodyTextView: UITextView! @IBAction func giveButtonTapped(sender: AnyObject) { let params: [String: AnyObject] = [ "propser_id": "3", "prop": [ "user_id": "\(self.receiver!.identifier)", "body": self.bodyTextView.text, ], ] Alamofire.request(.POST, "http://shielded-sea-7211.herokuapp.com/api/props.json", parameters: params, encoding: .JSON) self.navigationController?.dismissViewControllerAnimated(true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "ShowUsers" { if let vc = segue.destinationViewController as? UsersTableViewController { vc.delegate = self } } } } func usersTableViewControllerDidFinishWithUsers(users: [User]) { self.receiver = users[0] self.reveiversLabel.text = self.receiver!.displayName self.navigationController!.popViewControllerAnimated(true) } }
mit
0749a9a62a6ee07cbaec1a2874aae525
31.711111
126
0.639266
4.779221
false
false
false
false
jadekler/git-swift-midpointer
midpointer/ViewController.swift
1
4108
import UIKit class ViewController: UIViewController { @IBOutlet weak var mainImageView: UIImageView! @IBOutlet weak var tempImageView: UIImageView! var lastPoint = CGPoint.zero var brushWidth: CGFloat = 2.0 var opacity: CGFloat = 1.0 var swiped = false var lineCoordinates: Array<Array<CGFloat>> = [] let colors: [(CGFloat, CGFloat, CGFloat)] = [ (0, 0, 0), (105.0 / 255.0, 105.0 / 255.0, 105.0 / 255.0), (1.0, 0, 0), (0, 0, 1.0), (51.0 / 255.0, 204.0 / 255.0, 1.0), (102.0 / 255.0, 204.0 / 255.0, 0), (102.0 / 255.0, 1.0, 0), (160.0 / 255.0, 82.0 / 255.0, 45.0 / 255.0), (1.0, 102.0 / 255.0, 0), (1.0, 1.0, 0), (1.0, 1.0, 1.0), ] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { swiped = false if let touch = touches.first! as UITouch? { lastPoint = touch.locationInView(self.view) } } func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) { UIGraphicsBeginImageContext(view.frame.size) let context = UIGraphicsGetCurrentContext() tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)) CGContextMoveToPoint(context, fromPoint.x, fromPoint.y) CGContextAddLineToPoint(context, toPoint.x, toPoint.y) let coordinate: Array<CGFloat> = [toPoint.x, toPoint.y] lineCoordinates.append(coordinate) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, brushWidth) CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0) CGContextSetBlendMode(context, CGBlendMode.Normal) CGContextStrokePath(context) tempImageView.image = UIGraphicsGetImageFromCurrentImageContext() tempImageView.alpha = opacity UIGraphicsEndImageContext() } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { swiped = true if let touch = touches.first! as UITouch? { let currentPoint = touch.locationInView(view) drawLineFrom(lastPoint, toPoint: currentPoint) lastPoint = currentPoint } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if !swiped { // draw a single point drawLineFrom(lastPoint, toPoint: lastPoint) } // Merge tempImageView into mainImageView UIGraphicsBeginImageContext(mainImageView.frame.size) tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: CGBlendMode.Normal, alpha: opacity) mainImageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() tempImageView.image = nil drawMidpoint() lineCoordinates = [] } func drawMidpoint() { var totalX: CGFloat = 0 var totalY: CGFloat = 0 for coordinate in lineCoordinates { totalX += coordinate[0] totalY += coordinate[1] } let midpointX = totalX / CGFloat(lineCoordinates.count) let midpointY = totalY / CGFloat(lineCoordinates.count) drawCircle(midpointX, y: midpointY) } func drawCircle(x: CGFloat, y: CGFloat) { let circlePath = UIBezierPath(arcCenter: CGPoint(x: x, y: y), radius: CGFloat(5), startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.CGPath shapeLayer.fillColor = UIColor.redColor().CGColor shapeLayer.strokeColor = UIColor.redColor().CGColor shapeLayer.lineWidth = 3.0 mainImageView.layer.sublayers = nil mainImageView.layer.addSublayer(shapeLayer) } }
mit
91f3c7c8b99b47b630f035ea43bafb7d
32.672131
168
0.625365
4.436285
false
false
false
false
slightair/SwiftGraphics
Demos/SwiftGraphics_OSX_UITest/OmniGraffle.swift
2
4653
// // OmniGraffle.swift // Sketch // // Created by Jonathan Wight on 8/31/14. // Copyright (c) 2014 schwa.io. All rights reserved. // import CoreGraphics import Foundation import SwiftUtilities class OmniGraffleDocumentModel { let path: String var frame: CGRect! var rootNode: OmniGraffleGroup! var nodesByID: [Int: OmniGraffleNode] = [:] init(path: String) throws { self.path = path try self.load() } } @objc class OmniGraffleNode: Node { weak var parent: Node? var dictionary: NSDictionary! var ID: Int { return dictionary["ID"] as! Int } init() { } } @objc class OmniGraffleGroup: OmniGraffleNode, GroupNode { var children: [Node] = [] init(children: [Node]) { self.children = children } } @objc class OmniGraffleShape: OmniGraffleNode { var shape: String? { return dictionary["Shape"] as? String } var bounds: CGRect { return try! StringToRect(dictionary["Bounds"] as! String) } lazy var lines: [OmniGraffleLine] = [] } @objc class OmniGraffleLine: OmniGraffleNode { var start: CGPoint { let strings = dictionary["Points"] as! [String] return try! StringToPoint(strings[0]) } var end: CGPoint { let strings = dictionary["Points"] as! [String] return try! StringToPoint(strings[1]) } var head: OmniGraffleNode? var tail: OmniGraffleNode? } extension OmniGraffleDocumentModel { func load() throws { let data = NSData(contentsOfCompressedFile: path) // TODO: Swift 2 if let d = try NSPropertyListSerialization.propertyListWithData(data, options: NSPropertyListReadOptions(), format: nil) as? NSDictionary { _processRoot(d) let origin = try! StringToPoint(d["CanvasOrigin"] as! String) let size = try! StringToSize(d["CanvasSize"] as! String) frame = CGRect(origin: origin, size: size) // print(nodesByID) let nodes = nodesByID.values.filter { (node: Node) -> Bool in return node is OmniGraffleLine } for node in nodes { let line = node as! OmniGraffleLine var headID: Int? var tailID: Int? if let headDictionary = line.dictionary["Head"] as? NSDictionary { headID = headDictionary["ID"] as? Int } if let tailDictionary = line.dictionary["Tail"] as? NSDictionary { tailID = tailDictionary["ID"] as? Int } if headID != nil && tailID != nil { let head = nodesByID[headID!] as! OmniGraffleShape line.head = head head.lines.append(line) let tail = nodesByID[headID!] as! OmniGraffleShape line.tail = tail tail.lines.append(line) } } } } func _processRoot(d: NSDictionary) { let graphicslist = d["GraphicsList"] as! [NSDictionary] var children: [Node] = [] for graphic in graphicslist { if let node = _processDictionary(graphic) { children.append(node) } } let group = OmniGraffleGroup(children: children) rootNode = group } func _processDictionary(d: NSDictionary) -> OmniGraffleNode! { if let className = d["Class"] as? String { switch className { case "Group": var children: [Node] = [] if let graphics = d["Graphics"] as? [NSDictionary] { children = graphics.map { (d: NSDictionary) -> OmniGraffleNode in return self._processDictionary(d) } } let group = OmniGraffleGroup(children: children) group.dictionary = d nodesByID[group.ID] = group return group case "ShapedGraphic": let shape = OmniGraffleShape() shape.dictionary = d nodesByID[shape.ID] = shape return shape case "LineGraphic": let line = OmniGraffleLine() line.dictionary = d nodesByID[line.ID] = line return line default: print("Unknown: \(className)") } } return nil } }
bsd-2-clause
9c2d3e2a7e5d86867993b83a88d3eab8
31.3125
147
0.528906
4.478345
false
false
false
false
devandsev/theTVDB-iOS
tvShows/Source/Services/Networking/HTTPService.swift
1
5520
// // HTTPService.swift // Services // // Created by Andrey Sevrikov on 10/07/2017. // Copyright © 2017 devandsev. All rights reserved. // import Foundation protocol HasHTTPService { var httpService: HTTPService { get } } class HTTPService: HasDependencies { typealias Dependencies = HasLoggerService var di: Dependencies! enum HTTPMethod: String { case get = "GET" case post = "POST" case put = "PUT" case patch = "PATCH" } enum HTTPResult { case success(json: HTTPJSON, code: Int) case failure(error: HTTPError) } let session: URLSession = { let conf = URLSessionConfiguration.default conf.timeoutIntervalForRequest = 10 conf.requestCachePolicy = .reloadIgnoringLocalCacheData conf.urlCache = nil return URLSession(configuration: conf) }() var headers: [String: String] = [:] init() { headers = ["Content-Type": "application/json"] } @discardableResult func request(url: String, method: HTTPMethod, parameters: [String: Any] = [:], configuration: URLSessionConfiguration? = nil, completion: @escaping (HTTPResult) -> Void) -> URLSessionDataTask? { let (createdRequest, error) = self.createRequest(url: url, method: method, parameters: parameters) guard var request = createdRequest else { completion(.failure(error: error ?? .internalError(message: "Couldn't create a request"))) return nil } for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } let requestSession: URLSession if let configuration = configuration { requestSession = URLSession(configuration: configuration) } else { requestSession = self.session } let task = requestSession.dataTask(with: request) { data, response, error in self.handleResponse(data: data, response: response, error: error, completion: completion) } task.resume() return task } // MARK: - Private private func createRequest(url: String, method: HTTPMethod, parameters: [String: Any]) -> (URLRequest?, HTTPError?) { guard var requestUrl = URL(string: url) else { return (nil, .internalError(message: "Request URL is incorrect")) } var httpBody: Data? switch method { case .get: guard let urlComponents = NSURLComponents(string: url) else { return (nil, .internalError(message: "Request URL is incorrect")) } urlComponents.queryItems = [] for (key, value) in parameters { urlComponents.queryItems?.append(URLQueryItem(name: key, value: String(describing: value))) } guard let urlComponentsUrl = urlComponents.url else { return (nil, .internalError(message: "Request parameters are in incorrect format")) } requestUrl = urlComponentsUrl if parameters.count == 0 { requestUrl = URL(string: url)! } default: guard let payload = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else { return (nil, .internalError(message: "Request parameters are in incorrect format")) } httpBody = payload } var request = URLRequest(url: requestUrl) request.httpMethod = method.rawValue request.httpBody = httpBody di.loggerService.logRequest(url: url, method: method, parameters: parameters) return(request, nil) } private func handleResponse(data: Data?, response: URLResponse?, error: Error?, completion: @escaping (HTTPResult) -> Void) { guard let response = response as? HTTPURLResponse else { completion(.failure(error: .internalError(message: "Couldn't get HTTP info from server response"))) return } if let error = error { completion(.failure(error: .serverError(message: error.localizedDescription, code: response.statusCode))) return } guard let data = data else { completion(.success(json: .dictionary(json: [:]), code: response.statusCode)) return } guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else { completion(.failure(error: .parserError(message: "Couldn't serialize"))) return } let httpJson: HTTPJSON? switch json { case let json as [String: Any]: httpJson = .dictionary(json: json) case let json as [Any]: httpJson = .array(json: json) default: httpJson = nil } guard let serializedJson = httpJson else { completion(.failure(error: .parserError(message: "Couldn't serialize"))) return } di.loggerService.log(response: response, responseJSON: serializedJson) completion(.success(json: serializedJson, code: response.statusCode)) } }
mit
7400298803667114688d3e3888ca4426
31.087209
198
0.572205
5.226326
false
false
false
false
prebid/prebid-mobile-ios
Example/PrebidDemo/PrebidDemoSwift/Examples/GAM/OriginalAPI/GAMOriginalAPIVideoRewardedViewController.swift
1
3043
/* Copyright 2019-2022 Prebid.org, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import PrebidMobile import GoogleMobileAds fileprivate let storedResponseVideoRewarded = "response-prebid-video-rewarded-320-480-original-api" fileprivate let storedImpVideoRewarded = "imp-prebid-video-rewarded-320-480" fileprivate let gamAdUnitVideoRewardedOriginal = "/21808260008/prebid-demo-app-original-api-video-interstitial" class GAMOriginalAPIVideoRewardedViewController: InterstitialBaseViewController, GADFullScreenContentDelegate { // Prebid private var adUnit: RewardedVideoAdUnit! // GAM private let gamRequest = GAMRequest() override func loadView() { super.loadView() Prebid.shared.storedAuctionResponse = storedResponseVideoRewarded createAd() } func createAd() { // 1. Create an RewardedVideoAdUnit adUnit = RewardedVideoAdUnit(configId: storedImpVideoRewarded) // 2. Configure video parameters let parameters = VideoParameters() parameters.mimes = ["video/mp4"] parameters.protocols = [Signals.Protocols.VAST_2_0] parameters.playbackMethod = [Signals.PlaybackMethod.AutoPlaySoundOff] adUnit.parameters = parameters // 3. Make a bid request to Prebid Server adUnit.fetchDemand(adObject: gamRequest) { [weak self] resultCode in PrebidDemoLogger.shared.info("Prebid demand fetch for GAM \(resultCode.name())") // 4. Load the GAM rewarded ad GADRewardedAd.load(withAdUnitID: gamAdUnitVideoRewardedOriginal, request: self?.gamRequest) { [weak self] ad, error in guard let self = self else { return } if let error = error { PrebidDemoLogger.shared.error("Failed to load rewarded ad with error: \(error.localizedDescription)") } else if let ad = ad { // 5. Present the interstitial ad ad.fullScreenContentDelegate = self ad.present(fromRootViewController: self, userDidEarnRewardHandler: { _ = ad.adReward }) } } } } // MARK: - GADFullScreenContentDelegate func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { PrebidDemoLogger.shared.error("Failed to present rewarded ad with error: \(error.localizedDescription)") } }
apache-2.0
285079c747b007f9b2fe85261dff9d9a
39.573333
130
0.673349
4.784591
false
false
false
false
jingkecn/WatchWorker
src/ios/WatchWorker.swift
1
7834
import JavaScriptCore import ObjectiveC /** * Class WatchWorker * This class is aimed to deliver the abilities to communicate with Apple Watch by HTML5 Worker API */ @objc(WatchWorker) class WatchWorker : CDVPlugin { static let sharedInstance = WatchWorker() private var targetDelegate: EventTargetDelegate? private var scope: SharedWorkerGlobalScope? private var worker: SharedWatchWorker? private var initialized: Bool { return self.scope != nil && self.worker != nil } /** Worker initializer, processing model: 1. Delegate this worker itself to an event target delegator to support event system 2. Initialize an application scope for SharedWatchWorker 3. Initialize a SharedWatchWorker with the application scope 4. Add message listener to message port of SharedWatchWorker in outside scope to listen messages from the message port(s) of inside scope 5. Start the outside message port - parameter url: script url */ func initializeWatchWorker(withUrl url: String) { self.targetDelegate = EventTargetDelegate() self.scope = SharedWorkerGlobalScope.create(withUrl: url, withName: "") self.worker = SharedWatchWorker.create(self.scope!, scriptURL: url) self.worker!.port.addEventListener("message", listener: EventListener.create(withHandler: { self.dispatchMessage(($0 as! MessageEvent).data) })) self.worker!.port.start() } } // MARK: - Exposed plugin API extension WatchWorker { /** Initialization: Initialize WatchWorker with an execution script url - parameter command: cordova plugin command */ func initialize(command: CDVInvokedUrlCommand) { self.commandDelegate.runInBackground({ var result = CDVPluginResult(status: CDVCommandStatus_ERROR) guard let initializer = command.arguments[0] as? NSDictionary else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid initialier") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } guard let url = initializer["url"] as? String else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid script URL") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } self.initializeWatchWorker(withUrl: url) result = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) }) } /** Message sender: send message to Apple Watch through a asynchronous worker scope - parameter command: cordova plugin command */ func postMessage(command: CDVInvokedUrlCommand) { self.commandDelegate.runInBackground({ guard self.initialized else { return } var result = CDVPluginResult(status: CDVCommandStatus_ERROR) guard let initializer = command.arguments[0] as? NSDictionary else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid initialier") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } guard let message = initializer["message"] as? String else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid message") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } guard let worker = self.worker else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid worker") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } worker.port.postMessage(message) }) } /** Event listener handler: add event listener such as message listener - parameter command: cordova command */ func addEventListener(command: CDVInvokedUrlCommand) { self.commandDelegate.runInBackground({ guard self.initialized else { return } var result = CDVPluginResult(status: CDVCommandStatus_ERROR) guard let initializer = command.arguments[0] as? NSDictionary else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid initialier") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } guard let type = initializer["type"] as? String else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid event type") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } self.addEventListener(byType: type, withListener: EventListener.create(withHandler: { if let event = $0 as? MessageEvent { result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: event.data) } if let event = $0 as? ErrorEvent { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: event.message) } result.setKeepCallbackAsBool(true) self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) })) }) } /** Event listener handler: remove event listener - parameter command: cordova command */ func removeEventListener(command: CDVInvokedUrlCommand) { self.commandDelegate.runInBackground({ guard self.initialized else { return } var result = CDVPluginResult(status: CDVCommandStatus_ERROR) guard let initializer = command.arguments[0] as? NSDictionary else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid initialier") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } guard let type = initializer["type"] as? String else { result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsString: "Invalid event type") self.commandDelegate.sendPluginResult(result, callbackId: command.callbackId) return } self.removeEventListener(byType: type) }) } } // MARK: - Worker dispatchers extension WatchWorker { /** Message dispatcher: this method is called whenever a message is received by the worker's outside port. It'll then dispatch a message event inside this worker scope. - parameter message: message received */ private func dispatchMessage(message: String) { guard let scope = self.scope else { return } let event = MessageEvent.create(scope, type: "message", initDict: [ "data": message ]) self.dispatchEvent(event) } } // MARK: - Event handlers extension WatchWorker { private func addEventListener(byType type: String, withListener listener: EventListener) { self.targetDelegate?.addEventListener(type, listener: listener) } private func removeEventListener(byType type: String?) { self.targetDelegate?.removeEventListener(type, listener: nil) } private func dispatchEvent(event: Event) { self.targetDelegate?.dispatchEvent(event) } }
mit
8a44320c19cbf89df4a92a22e1261239
40.675532
152
0.652285
5.322011
false
false
false
false
LoveAlwaysYoung/EnjoyUniversity
EnjoyUniversity/EnjoyUniversity/Classes/View/Profile/EUActivityCollectionController.swift
1
3587
// // EUActivityCollectionController.swift // EnjoyUniversity // // Created by lip on 17/4/18. // Copyright © 2017年 lip. All rights reserved. // import UIKit class EUActivityCollectionController: EUBaseViewController { /// cell ID let ACTIVITYCOLLECTIONCELL = "ACTIVITYCOLLECTIONCELL" lazy var viewmodellist = ActivityListViewModel() override func viewDidLoad() { super.viewDidLoad() navitem.title = "活动收藏" tableview.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) tableview.register(UINib(nibName: "EUActivityCell", bundle: nil), forCellReuseIdentifier: ACTIVITYCOLLECTIONCELL) tableview.tableFooterView = UIView() } override func loadData() { refreshControl?.beginRefreshing() viewmodellist.loadMyCollectedActivity { (isSuccess, hasValue) in self.refreshControl?.endRefreshing() if !isSuccess{ SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1) return } if !hasValue{ // 没有数据,显示暂无数据 return } self.tableview.reloadData() } } } // MARK: - 代理方法 extension EUActivityCollectionController{ override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewmodellist.collectedlist.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = (tableview.dequeueReusableCell(withIdentifier: ACTIVITYCOLLECTIONCELL) as? EUActivityCell) ?? EUActivityCell() cell.activityVM = viewmodellist.collectedlist[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { super.tableView(tableView, didSelectRowAt: indexPath) let vc = EUActivityViewController() vc.viewmodel = viewmodellist.collectedlist[indexPath.row] navigationController?.pushViewController(vc, animated: true) } /// 左滑删除 func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .delete } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } /// 定义文字 func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "取消收藏" } /// 取消收藏 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let avid = viewmodellist.collectedlist[indexPath.row].activitymodel.avid SwiftyProgressHUD.showLoadingHUD() EUNetworkManager.shared.discollectActivity(avid: avid) { (netsuccess, discollectsuccess) in SwiftyProgressHUD.hide() if !netsuccess{ SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1) return } if !discollectsuccess{ SwiftyProgressHUD.showWarnHUD(text: "已取消收藏", duration: 1) return } SwiftyProgressHUD.showSuccessHUD(duration: 1) self.viewmodellist.collectedlist.remove(at: indexPath.row) self.tableview.reloadData() } } }
mit
51720060206f34bb2cab65ef932b4557
31.924528
129
0.641547
5.232384
false
false
false
false
cxchope/NyaaCatAPP_iOS
nyaacatapp/WaitVC.swift
1
6113
// // WaitVC.swift // nyaacatapp // // Created by 神楽坂雅詩 on 16/2/10. // Copyright © 2016年 KagurazakaYashi. All rights reserved. // import UIKit protocol WaitVCDelegate { func 返回登录请求(_ 用户名:String?,密码:String?) func 弹出代理提示框(_ 提示框:UIAlertController) func 重试按钮点击() } class WaitVC: UIViewController { @IBOutlet weak var 图标: UIImageView! @IBOutlet weak var 副标题: UILabel! @IBOutlet weak var 网点: UIView! @IBOutlet weak var 登录按钮: UIButton! var 图标原始位置:CGRect? = nil var 图标缩小位置:CGRect? = nil var 停止:Bool = false var 代理:WaitVCDelegate? = nil var 提示框:UIAlertController? = nil var 用户名:String = 全局_喵窩API["测试动态地图用户名"]! var 密码:String = 全局_喵窩API["测试动态地图密码"]! var 重试:Bool = false override func viewDidLoad() { super.viewDidLoad() self.view.alpha = 1 登录按钮.isHidden = true 网点.backgroundColor = UIColor(patternImage: UIImage(contentsOfFile: Bundle.main.path(forResource: "dot", ofType: "png")!)!) 登录按钮.backgroundColor = UIColor(red: 0.5372549, green: 0.6745098, blue: 0.84705882, alpha: 0.8) 图标原始位置 = 图标.frame 图标缩小位置 = CGRect(x: 图标原始位置!.origin.x, y: 图标原始位置!.origin.y + (图标原始位置!.size.height * 0.1), width: 图标原始位置!.size.width, height: 图标原始位置!.size.height * 0.9) //图标动画(true) } @IBAction func 登录按钮点击(_ sender: UIButton) { 登录按钮.isHidden = true if (重试 == true) { 重试按钮模式(false) 代理!.重试按钮点击() } else { 提示框 = UIAlertController(title: "请输入用户名和密码", message: nil, preferredStyle: UIAlertControllerStyle.alert) let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: { (动作:UIAlertAction) -> Void in self.提示框处理(false) }) let okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in self.提示框处理(true) }) 提示框!.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "用户名" textField.text = self.用户名 } 提示框!.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "密码" textField.isSecureTextEntry = true textField.text = self.密码 } 提示框!.addAction(okAction) 提示框!.addAction(cancelAction) 代理!.弹出代理提示框(提示框!) } } func 重试按钮模式(_ 重试模式:Bool) { if (重试模式 == true) { 登录按钮.setTitle("重试", for: UIControlState()) } else { 登录按钮.setTitle("登录", for: UIControlState()) } 重试 = 重试模式 } @IBAction func 顶部按钮一点击(_ sender: UIButton) { } @IBAction func 顶部按钮二点击(_ sender: UIButton) { } @IBAction func 顶部按钮三点击(_ sender: UIButton) { 登录按钮.isHidden = true self.代理!.返回登录请求(nil, 密码: nil) NotificationCenter.default.post(name: Notification.Name(rawValue: "guest"), object: nil) } func 退出() { UIApplication.shared.isNetworkActivityIndicatorVisible = false UIView.animate(withDuration: 0.5, animations: { self.view.frame = CGRect(x: 0.5, y: self.view.frame.size.height, width: self.view.frame.size.width, height: self.view.frame.size.height) }, completion: { (aniok:Bool) in self.view.removeFromSuperview() }) } func 提示框处理(_ 确定:Bool) { if (确定 == true) { let 用户名输入框:UITextField = 提示框!.textFields!.first! as UITextField let 密码输入框:UITextField = 提示框!.textFields!.last! as UITextField 用户名 = 用户名输入框.text! 密码 = 密码输入框.text! self.代理!.返回登录请求(用户名, 密码: 密码) } else { 登录按钮.isHidden = false } 提示框 = nil } func 图标动画(_ 前半段:Bool) { if (停止 == false) { UIView.animate(withDuration: 3.0, animations: { () -> Void in if (前半段) { self.图标.frame = self.图标缩小位置! } else { self.图标.frame = self.图标原始位置! } }) { (已完成:Bool) -> Void in self.图标动画(!前半段) } } else { UIView.animate(withDuration: 0.6, animations: { () -> Void in self.view.alpha = 0 self.view.frame = CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y + self.view.frame.size.height, width: self.view.frame.size.width, height: self.view.frame.size.height) }) { (已完成:Bool) -> Void in self.view.removeFromSuperview() } } } 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. } */ }
gpl-3.0
a5db9bc4d0ad8f1c625fba5773efac6c
32.617834
201
0.561008
3.889462
false
false
false
false
tomisacat/HelloMetal
HelloMetal/float4x4+Extension.swift
1
3073
import Foundation import simd import GLKit extension float4x4 { init() { self = unsafeBitCast(GLKMatrix4Identity, to: float4x4.self) } static func makeScale(_ x: Float, _ y: Float, _ z: Float) -> float4x4 { return unsafeBitCast(GLKMatrix4MakeScale(x, y, z), to: float4x4.self) } static func makeRotate(_ radians: Float, _ x: Float, _ y: Float, _ z: Float) -> float4x4 { return unsafeBitCast(GLKMatrix4MakeRotation(radians, x, y, z), to: float4x4.self) } static func makeTranslation(_ x: Float, _ y: Float, _ z: Float) -> float4x4 { return unsafeBitCast(GLKMatrix4MakeTranslation(x, y, z), to: float4x4.self) } static func makePerspectiveViewAngle(_ fovyRadians: Float, aspectRatio: Float, nearZ: Float, farZ: Float) -> float4x4 { var q = unsafeBitCast(GLKMatrix4MakePerspective(fovyRadians, aspectRatio, nearZ, farZ), to: float4x4.self) let zs = farZ / (nearZ - farZ) q[2][2] = zs q[3][2] = zs * nearZ return q } static func makeFrustum(_ left: Float, _ right: Float, _ bottom: Float, _ top: Float, _ nearZ: Float, _ farZ: Float) -> float4x4 { return unsafeBitCast(GLKMatrix4MakeFrustum(left, right, bottom, top, nearZ, farZ), to: float4x4.self) } static func makeOrtho(_ left: Float, _ right: Float, _ bottom: Float, _ top: Float, _ nearZ: Float, _ farZ: Float) -> float4x4 { return unsafeBitCast(GLKMatrix4MakeOrtho(left, right, bottom, top, nearZ, farZ), to: float4x4.self) } static func makeLookAt(_ eyeX: Float, _ eyeY: Float, _ eyeZ: Float, _ centerX: Float, _ centerY: Float, _ centerZ: Float, _ upX: Float, _ upY: Float, _ upZ: Float) -> float4x4 { return unsafeBitCast(GLKMatrix4MakeLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ), to: float4x4.self) } mutating func scale(_ x: Float, y: Float, z: Float) { self = self * float4x4.makeScale(x, y, z) } mutating func rotate(_ radians: Float, x: Float, y: Float, z: Float) { self = float4x4.makeRotate(radians, x, y, z) * self } mutating func rotateAroundX(_ x: Float, y: Float, z: Float) { var rotationM = float4x4.makeRotate(x, 1, 0, 0) rotationM = rotationM * float4x4.makeRotate(y, 0, 1, 0) rotationM = rotationM * float4x4.makeRotate(z, 0, 0, 1) self = self * rotationM } mutating func translate(_ x: Float, y: Float, z: Float) { self = self * float4x4.makeTranslation(x, y, z) } static func numberOfElements() -> Int { return 16 } static func degrees(toRad angle: Float) -> Float { return Float(Double(angle) * .pi / 180) } mutating func multiplyLeft(_ matrix: float4x4) { let glMatrix1 = unsafeBitCast(matrix, to: GLKMatrix4.self) let glMatrix2 = unsafeBitCast(self, to: GLKMatrix4.self) let result = GLKMatrix4Multiply(glMatrix1, glMatrix2) self = unsafeBitCast(result, to: float4x4.self) } }
mit
89a52ff9be4071148da54188e29ce853
38.909091
181
0.621217
3.311422
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/FindFriends/Views/Cells/FindFriendsStatsCell.swift
1
3050
import KsApi import Library import Prelude import ReactiveSwift import UIKit protocol FindFriendsStatsCellDelegate: AnyObject { func findFriendsStatsCellShowFollowAllFriendsAlert(friendCount: Int) } internal final class FindFriendsStatsCell: UITableViewCell, ValueCell { @IBOutlet fileprivate var backedProjectsLabel: UILabel! @IBOutlet fileprivate var bulletSeparatorView: UIView! @IBOutlet fileprivate var friendsLabel: UILabel! @IBOutlet fileprivate var friendsCountLabel: UILabel! @IBOutlet fileprivate var backedProjectsCountLabel: UILabel! @IBOutlet fileprivate var followAllButton: UIButton! internal weak var delegate: FindFriendsStatsCellDelegate? fileprivate let viewModel: FindFriendsStatsCellViewModelType = FindFriendsStatsCellViewModel() func configureWith(value: (stats: FriendStatsEnvelope, source: FriendsSource)) { self.viewModel.inputs.configureWith(stats: value.stats, source: value.source) } override func bindViewModel() { super.bindViewModel() self.friendsCountLabel.rac.text = self.viewModel.outputs.friendsCountText self.backedProjectsCountLabel.rac.text = self.viewModel.outputs.backedProjectsCountText self.followAllButton.rac.hidden = self.viewModel.outputs.hideFollowAllButton self.followAllButton.rac.title = self.viewModel.outputs.followAllText self.viewModel.outputs.notifyDelegateShowFollowAllFriendsAlert .observeForUI() .observeValues { [weak self] count in self?.delegate?.findFriendsStatsCellShowFollowAllFriendsAlert(friendCount: count) } } override func bindStyles() { super.bindStyles() _ = self.friendsLabel |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.font .~ .ksr_subhead() |> UILabel.lens.text %~ { _ in Strings.social_following_stats_friends() } _ = self.friendsCountLabel |> UILabel.lens.textColor .~ .ksr_support_700 |> UILabel.lens.font .~ .ksr_title2() _ = self.backedProjectsLabel |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.font .~ .ksr_subhead() |> UILabel.lens.text %~ { _ in Strings.social_following_stats_backed_projects() } _ = self.self.backedProjectsCountLabel |> UILabel.lens.textColor .~ .ksr_support_700 |> UILabel.lens.font .~ .ksr_title2() _ = self.followAllButton |> greenButtonStyle |> UIButton.lens.targets .~ [(self, action: #selector(self.followAllButtonTapped), .touchUpInside)] _ = self.bulletSeparatorView |> UIView.lens.backgroundColor .~ .ksr_support_300 |> UIView.lens.alpha .~ 0.7 _ = self |> baseTableViewCellStyle() |> UITableViewCell.lens.backgroundColor .~ .ksr_white |> UITableViewCell.lens.contentView.layoutMargins %~~ { _, cell in cell.traitCollection.isRegularRegular ? .init(topBottom: Styles.grid(4), leftRight: Styles.grid(20)) : .init(all: Styles.grid(4)) } } @objc func followAllButtonTapped() { self.viewModel.inputs.followAllButtonTapped() } }
apache-2.0
062d8d43b84b48dcaa4a679b6a03cca9
34.057471
105
0.723279
4.375897
false
false
false
false
S2dentik/Taylor
TaylorFramework/Modules/scissors/ComponentFinder.swift
4
4823
// // ComponentFinder.swift // Scissors // // Created by Alex Culeva on 10/2/15. // Copyright © 2015 com.yopeso.aculeva. All rights reserved. // import Foundation import SourceKittenFramework struct ComponentFinder { let text: String let syntaxMap: SyntaxMap init(text: String, syntaxMap: SyntaxMap = SyntaxMap(tokens: [])) { self.text = text self.syntaxMap = syntaxMap } /** Finds all comments, logical operators (`??`, `? :`, `&&`, `||`) and empty lines in **text**. */ var additionalComponents: [ExtendedComponent] { return findComments() + findLogicalOperators() + findEmptyLines() } func findLogicalOperators() -> [ExtendedComponent] { var operators = findOROperators() operators.append(contentsOf: findANDOperators()) operators.append(contentsOf: findTernaryOperators()) operators.append(contentsOf: findNilCoalescingOperators()) return operators } func findOROperators() -> [ExtendedComponent] { return text.findMatchRanges("(\\|\\|)").map { ExtendedComponent(type: .or, range: $0) } } func findANDOperators() -> [ExtendedComponent] { return text.findMatchRanges("(\\&\\&)").map { ExtendedComponent(type: .and, range: $0) } } func findTernaryOperators() -> [ExtendedComponent] { return text.findMatchRanges("(\\s+\\?(?!\\?).*?:)").map { ExtendedComponent(type: .ternary, range: $0) } } func findNilCoalescingOperators() -> [ExtendedComponent] { return text.findMatchRanges("(\\?\\?)").map { ExtendedComponent(type: .nilCoalescing, range: $0) } } func findComments() -> [ExtendedComponent] { return syntaxMap.tokens.filter { componentTypeUIDs[$0.type] == .comment }.reduce([ExtendedComponent]()) { $0 + ExtendedComponent(dict: $1.dictionaryValue as [String : AnyObject]) } } func findEmptyLines() -> [ExtendedComponent] { return text.findMatchRanges("(\\n[ \\t\\n]*\\n)").map { return ExtendedComponent(type: .emptyLines, range: ($0 as OffsetRange).toEmptyLineRange()) } } //Ending points of getters and setters will most probably be wrong unless a nice coding-style is being used "} set {" func findGetters(_ components: [ExtendedComponent]) -> [ExtendedComponent] { return components.filter({ $0.type.isA(.variable) }) .reduce([ExtendedComponent]()) { reduceFindGetterAndSetter(components: $0, component: $1) } } func reduceFindGetterAndSetter(components: [ExtendedComponent], component: ExtendedComponent) -> [ExtendedComponent] { let range: Range = component.offsetRange.start..<component.offsetRange.end return findGetterAndSetter(text.substring(with: range)).reduce(components) { $1.offsetRange.start += component.offsetRange.start $1.offsetRange.end += component.offsetRange.start return $0 + $1 } } func findGetterAndSetter(_ text: String) -> [ExtendedComponent] { var accessors = [ExtendedComponent]() guard let _ : OffsetRange = text.findMatchRanges("(get($|[ \\t\\n{}]))").first else { return findObserverGetters(text) } accessors.addIfFind(component: .get, from: text) accessors.addIfFind(component: .set, from: text) return accessors.changeSortedOffset(of: text) } func findObserverGetters(_ text: String) -> [ExtendedComponent] { var observers = [ExtendedComponent]() observers.addIfFind(component: .willSet, from: text) observers.addIfFind(component: .didSet, from: text) return observers.changeSortedOffset(of: text) } } private extension Array where Element: ExtendedComponent { mutating func addIfFind(component: PropertyComponents, from text: String) { let range: [OffsetRange] = text.findMatchRanges("(\(component.rawValue)($|[ \\t\\n{}]))") if let first = range.first { append(Element(type: .function, range: first, names: (component.rawValue, nil))) } } mutating func changeSortedOffset(of text: String) -> [ExtendedComponent] { sort { $0.offsetRange.start < $1.offsetRange.start } if count == 1 { first?.offsetRange.end = text.characters.count - 1 } else if let second = second { first?.offsetRange.end = second.offsetRange.start - 1 second.offsetRange.end = text.characters.count - 1 } return self } }
mit
b0203232d26be132a0584cfb79b1c354
33.942029
121
0.602655
4.614354
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-2ancestor-1du-1st_ancestor_nongeneric-fileprivate-2nd_ancestor_generic.swift
1
1338
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir -I %t -L %t %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios fileprivate class Ancestor1<First> { let first_Ancestor1: First init(first: First) { self.first_Ancestor1 = first } } fileprivate class Ancestor2 : Ancestor1<Int> { let first_Ancestor2: Int override init(first: Int) { self.first_Ancestor2 = first super.init(first: first) } } fileprivate class Value<First> : Ancestor2 { let first_Value: First init(first: First) { self.first_Value = first super.init(first: 7373748) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } func doit() { consume( Value(first: 13) ) } doit() // TODO: Prespecialize Value<Int>. // CHECK-LABEL: define hidden swiftcc void @"$s4main4doityyF"() // CHECK: call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s4main5Value{{[A-Za-z_0-9]+}}LLCySiGMD") // CHECK: }
apache-2.0
530890e4d12635aab5be2d3706fbfc74
25.235294
242
0.660688
3.178147
false
false
false
false
arnaudbenard/npm-stats
Pods/Charts/Charts/Classes/Renderers/ChartXAxisRenderer.swift
36
11512
// // ChartXAxisRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 3/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 public class ChartXAxisRenderer: ChartAxisRendererBase { internal var _xAxis: ChartXAxis! public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, transformer: transformer) _xAxis = xAxis } public func computeAxis(#xValAverageLength: Double, xValues: [String?]) { var a = "" var max = Int(round(xValAverageLength + Double(_xAxis.spaceBetweenLabels))) for (var i = 0; i < max; i++) { a += "h" } var widthText = a as NSString _xAxis.labelWidth = widthText.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width _xAxis.labelHeight = _xAxis.labelFont.lineHeight _xAxis.values = xValues } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled) { return } var yoffset = CGFloat(4.0) if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset) } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.5) } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentBottom - _xAxis.labelHeight - yoffset) } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.offsetTop + yoffset) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset) drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.6) } } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, _xAxis.axisLineWidth) if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat) { var paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paraStyle.alignment = .Center var labelAttrs = [NSFontAttributeName: _xAxis.labelFont, NSForegroundColorAttributeName: _xAxis.labelTextColor, NSParagraphStyleAttributeName: paraStyle] var valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) var labelMaxSize = CGSize() if (_xAxis.isWordWrapEnabled) { labelMaxSize.width = _xAxis.wordWrapWidthPercent * valueToPixelMatrix.a } for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { var label = _xAxis.values[i] if (label == nil) { continue } position.x = CGFloat(i) position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (viewPortHandler.isInBoundsX(position.x)) { var labelns = label! as NSString if (_xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == _xAxis.values.count - 1 && _xAxis.values.count > 1) { var width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width if (width > viewPortHandler.offsetRight * 2.0 && position.x + width > viewPortHandler.chartWidth) { position.x -= width / 2.0 } } else if (i == 0) { // avoid clipping of the first var width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width position.x += width / 2.0 } } ChartUtils.drawMultilineText(context: context, text: label!, point: CGPoint(x: position.x, y: pos), align: .Center, attributes: labelAttrs, constrainedToSize: labelMaxSize) } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(#context: CGContext) { if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor) CGContextSetLineWidth(context, _xAxis.gridLineWidth) if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i) position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (position.x >= viewPortHandler.offsetLeft && position.x <= viewPortHandler.chartWidth) { _gridLineSegmentsBuffer[0].x = position.x _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop _gridLineSegmentsBuffer[1].x = position.x _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(#context: CGContext) { var limitLines = _xAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) var trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i] position.x = CGFloat(l.limit) position.y = 0.0 position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = position.x _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop _limitLineSegmentsBuffer[1].x = position.x _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) var label = l.label // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight let add = CGFloat(4.0) var xOffset: CGFloat = l.lineWidth var yOffset: CGFloat = add / 2.0 if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
mit
6c42b7375130a1495510d405c1c96568
35.782748
188
0.557245
5.724515
false
false
false
false
Stitch7/Instapod
Instapod/Feed/Entities/Podcast.swift
1
3708
// // Feed.swift // Instapod // // Created by Christopher Reitz on 02.04.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import CoreData struct Podcast { // MARK: - Properties var id: URL? let uuid: String var nextPage: URL? var url: URL var author: String? var category: String? var desc: String? var explicit: Bool? var generator: String? var language: String? var lastBuildDate: Date? var pubDate: Date? var sortIndex: NSNumber? var subtitle: String? var summary: String? var title: String? var image: Image? var episodes: [Episode]? // MARK: - Initializers init(uuid: String, url: URL) { self.uuid = uuid self.url = url } var allImagesAreFetched: Bool { guard image != nil else { return false } guard let episodes = self.episodes else { return true } for episode in episodes { guard let episodeImage = episode.image else { continue } if episodeImage.isFetched == false { return false } } return true } mutating func updateEpisode(with newEpisode: Episode) { guard let episodes = self.episodes else { return } for (key, episode) in episodes.enumerated() { if episode.title == newEpisode.title && episode.desc == newEpisode.desc { self.episodes![key] = newEpisode } } } func createPodcast(fromContext context: NSManagedObjectContext) -> PodcastManagedObject { let podcast = context.createEntityWithName("Podcast") as! PodcastManagedObject podcast.url = url.absoluteString podcast.author = author podcast.category = category podcast.desc = desc podcast.explicit = explicit as NSNumber? podcast.generator = generator podcast.language = language podcast.lastBuildDate = lastBuildDate podcast.pubDate = pubDate podcast.subtitle = subtitle podcast.summary = summary podcast.title = title podcast.image = image?.createImage(fromContext: context) if let episodes = self.episodes { for feedEpisode in episodes { let episode = feedEpisode.createEpisode(fromContext: context) podcast.addObject(episode, forKey: "episodes") } } return podcast } } extension Podcast { init(managedObject: PodcastManagedObject) { id = managedObject.objectID.uriRepresentation() uuid = UUID().uuidString url = URL(string: managedObject.url!)! author = managedObject.author category = managedObject.category desc = managedObject.desc explicit = managedObject.explicit as Bool? generator = managedObject.generator language = managedObject.language lastBuildDate = managedObject.lastBuildDate as Date? pubDate = managedObject.pubDate as Date? sortIndex = managedObject.sortIndex subtitle = managedObject.subtitle summary = managedObject.summary title = managedObject.title if let managedImage = managedObject.image { image = Image(managedObject: managedImage) } episodes = [Episode]() if let managedEpisodes = managedObject.episodes { for managedEpisode in managedEpisodes { var episode = Episode(managedObject: managedEpisode) var podcast = self podcast.episodes = nil episode.podcast = podcast episodes?.append(episode) } } } }
mit
b501fc096811a2d2fb40f9a2997d271c
28.420635
93
0.611276
5.002699
false
false
false
false
southfox/JFAlgo
Example/JFAlgo/AlgorithmViewController.swift
1
2585
// // AlgorithmViewController.swift // JFAlgo // // Created by Javier Fuchs on 9/10/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import JFAlgo class AlgorithmViewController : BaseCollectionViewController { internal var currentAlgorithm : Int? override func viewDidLoad() { super.viewDidLoad() if let dict = currentAlgorithmDict(), let title = dict["title"] { self.title = String(title) } } func currentAlgorithmDict() -> [String : AnyObject]? { if let n = currentAlgorithm { let dict = JFAlgo.algorithms[n] return dict } return nil } @IBAction override func runAction() { super.runAction() guard let text = numberField.text, number = Int(text) else { return } guard let dict = currentAlgorithmDict(), let algo = dict["algorithm"] else { return } let algorithm = algo as! Algorithm if algorithm.checkDomainGenerator(number) == false { self.showAlert(algorithm.domainErrorMessage(), completion: closure) return } guard var array = A else { self.showAlert("\(number) generates a nil array.", completion: closure) return } let solution = algorithm.solution(&array) if solution != 0 { self.showAlert("\(number) generates an array with 1 unpaired element \(solution).", completion: closure) } else { self.showAlert("No Solution for \(number)", completion: closure) } } @IBAction override func generateAction(sender: AnyObject) { super.generateAction(sender) guard let text = numberField.text, number = Int(text) else { return } guard let dict = currentAlgorithmDict(), let algo = dict["algorithm"] else { return } let algorithm = algo as! Algorithm if algorithm.checkDomainGenerator(number) == false { self.showAlert(algorithm.domainErrorMessage(), completion: closure) return } guard let array = algorithm.generateDomain(number) else { self.showAlert("\(number) generates a nil array.", completion: closure) return } A = array self.reload() } }
mit
ffb581d76ca5242e734d55e93e116960
26.210526
116
0.543731
5.209677
false
false
false
false
TangentMicroServices/HoursService.iOSClient
HoursService.iOSClient/HoursService.iOSClient/ProjectModel.swift
1
1885
// // ProjectModel.swift // HoursService.iOSClient // // Created by Jhpassion0621 on 4/9/15. // Copyright (c) 2015 Ian Roberts. All rights reserved. // import UIKit class TaskSet:NSObject{ var m_id:Int? var m_title:NSString? var m_dueDate:NSString? var m_estimatedHours:NSString? var m_createdTimeDate:NSString? var m_updatedTimeDate:NSString? var m_project:Int? func createWithDictionary(taskInfo:NSDictionary){ m_id = taskInfo["id"] as? Int m_title = taskInfo["title"] as? NSString m_dueDate = taskInfo["due_date"] as? NSString m_estimatedHours = taskInfo["estimate_hours"] as? NSString m_createdTimeDate = taskInfo["created"] as? NSString m_updatedTimeDate = taskInfo["updated"] as? NSString m_project = taskInfo["project"] as? Int } } class ProjectModel: NSObject { var m_pk:Int? var m_title:NSString? var m_description:NSString? var m_startDate:NSString? var m_endDate:NSString? var m_bBillable:Bool? var m_bActive:Bool? var m_taskSetArray:NSMutableArray? func createWithDictionary(projectInfo:NSDictionary){ m_pk = projectInfo["pk"] as? Int m_title = projectInfo["title"] as? NSString m_description = projectInfo["description"] as? NSString m_startDate = projectInfo["start_date"] as? NSString m_endDate = projectInfo["end_date"] as? NSString m_bBillable = projectInfo["is_billable"] as? Bool m_bActive = projectInfo["is_active"] as? Bool var taskSetDicArray = projectInfo["task_set"] as? NSArray m_taskSetArray = NSMutableArray() for dict in taskSetDicArray!{ var taskModel = TaskSet() taskModel.createWithDictionary(dict as NSDictionary) m_taskSetArray?.addObject(taskModel) } } }
mit
af6e49ea36804b1f07b978d1a06be509
30.416667
66
0.645093
3.777555
false
false
false
false
notohiro/NowCastMapView
NowCastMapView/TileModel+Task.swift
1
7475
// // TileModel+Task.swift // NowCastMapView // // Created by Hiroshi Noto on 2017/05/06. // Copyright © 2017 Hiroshi Noto. All rights reserved. // import Foundation import MapKit import UIKit extension TileModel { open class Task { // MARK: - Public Properties open private(set) var originalRequest: Request open private(set) var currentRequest: Request public let baseTime: BaseTime open private(set) weak var delegate: TileModelDelegate? open private(set) var processingTiles = [URL: Tile]() open private(set) var completedTiles = [Tile]() open private(set) var state = State.initialized public let model: TileModel open private(set) var completionHandler: (([Tile]) -> Void)? public let hashValue = Date().hashValue // MARK: - Private Properties private var session: URLSession private var suspendedTasks = [URLSessionTask]() private let semaphore = DispatchSemaphore(value: 1) private let queue = OperationQueue() // MARK: - Functions public init(model: TileModel, request: Request, baseTime: BaseTime, delegate: TileModelDelegate?, completionHandler: (([Tile]) -> Void)?) throws { self.model = model self.originalRequest = request self.baseTime = baseTime self.delegate = delegate self.completionHandler = completionHandler let configuration = URLSessionConfiguration.default configuration.httpMaximumConnectionsPerHost = 4 let session = URLSession(configuration: configuration) self.session = session guard let newCoordinates = request.coordinates.intersecting(TileModel.serviceAreaCoordinates) else { throw NCError.outOfService } currentRequest = TileModel.Request(range: request.range, scale: request.scale, coordinates: newCoordinates, withoutProcessing: request.withoutProcessing) try configureTasks() } public func resume() { semaphore.wait() defer { semaphore.signal() } if state == .initialized && processingTiles.isEmpty { state = .completed if let handler = completionHandler { queue.addOperation { handler(self.completedTiles) } } finalizeTask() } else if state == .initialized { state = .processing while !suspendedTasks.isEmpty { let task = suspendedTasks.removeFirst() task.resume() } } } public func invalidateAndCancel() { semaphore.wait() defer { semaphore.signal() } if state == .initialized || state == .processing { state = .canceled finalizeTask() } } // MARK: - Private Functions private func configureTasks() throws { let zoomLevel = ZoomLevel(zoomScale: currentRequest.scale) guard let originModifiers = Tile.Modifiers(zoomLevel: zoomLevel, coordinate: currentRequest.coordinates.origin) else { let reason = NCError.TileFailedReason.modifiersInitializationFailedCoordinate(zoomLevel: zoomLevel, coordinate: currentRequest.coordinates.origin) throw NCError.tileFailed(reason: reason) } guard let terminalModifiers = Tile.Modifiers(zoomLevel: zoomLevel, coordinate: currentRequest.coordinates.terminal) else { let reason = NCError.TileFailedReason.modifiersInitializationFailedCoordinate(zoomLevel: zoomLevel, coordinate: currentRequest.coordinates.terminal) throw NCError.tileFailed(reason: reason) } for index in currentRequest.range { for latMod in originModifiers.latitude ... terminalModifiers.latitude { for lonMod in originModifiers.longitude ... terminalModifiers.longitude { guard let mods = Tile.Modifiers(zoomLevel: zoomLevel, latitude: latMod, longitude: lonMod) else { let reason = NCError.TileFailedReason.modifiersInitializationFailedMods(zoomLevel: zoomLevel, latitiude: latMod, longitude: lonMod) throw NCError.tileFailed(reason: reason) } guard let url = URL(baseTime: baseTime, index: index, modifiers: mods) else { throw NCError.tileFailed(reason: .urlInitializationFailed) } let tile = Tile(image: nil, baseTime: baseTime, index: index, modifiers: mods, url: url) if currentRequest.withoutProcessing && model.isProcessing(tile) { continue } suspendedTasks.append(makeDataTask(with: session, url: url)) processingTiles[url] = tile } } } } // should be called only once per instance and within semaphore private func finalizeTask() { session.invalidateAndCancel() delegate = nil completionHandler = nil model.remove(self) } private func makeDataTask(with session: URLSession, url: URL) -> URLSessionDataTask { return session.dataTask(with: url) { data, _, sessionError in self.semaphore.wait() // process data only when state == .processing if self.state != .processing { self.semaphore.signal() return } var error: Error? defer { if let error = error, let delegate = self.delegate { self.queue.addOperation { delegate.tileModel(self.model, task: self, failed: url, error: error) } } if self.processingTiles.isEmpty { self.state = .completed if let handler = self.completionHandler { self.queue.addOperation { handler(self.completedTiles) } } self.finalizeTask() } self.semaphore.signal() } if let sessionError = sessionError { error = sessionError return } guard var tile = self.processingTiles.removeValue(forKey: url) else { error = NCError.tileFailed(reason: .internalError) return } guard let data = data, let image = UIImage(data: data) else { error = NCError.tileFailed(reason: .imageProcessingFailed) return } tile.image = image self.completedTiles.append(tile) if let delegate = self.delegate { self.queue.addOperation { delegate.tileModel(self.model, task: self, added: tile) } } } } } } public extension TileModel.Task { enum State { case initialized case processing case canceled case completed } } // MARK: - Hashable extension TileModel.Task: Hashable { } extension TileModel.Task: Equatable { public static func == (lhs: TileModel.Task, rhs: TileModel.Task) -> Bool { return lhs.hashValue == rhs.hashValue } public static func != (lhs: TileModel.Task, rhs: TileModel.Task) -> Bool { return !(lhs == rhs) } }
mit
bafcb7945f592b33ed20bf273f437b23
29.757202
158
0.591116
4.435608
false
false
false
false
Neft-io/neft
packages/neft-request/native/ios/RequestExtension.swift
1
2577
import JavaScriptCore extension Extension.Request { static let app = App.getApp() static func register() { app.client.addCustomFunction("NeftRequest/request") { (args: [Any?]) in let uid = args[0] as? String ?? "" let uri = args[1] as? String ?? "" let method = args[2] as? String ?? "" let headersJson = args[3] as? String ?? "{}" let body = args[4] as? String ?? "" let timeout = (args[5] as? Number)?.int() ?? 0 let headers: [String: String] = (try? JSONDecoder().decode([String: String].self, from: headersJson.data(using: String.Encoding.utf8)!)) ?? [:] request(uri, method, headers, body, timeout) { (error: String, code: Int, data: String, headers: [String: String]) in let headersData = try? JSONEncoder().encode(headers) let headersJson = headersData == nil ? "{}" : String(data: headersData!, encoding: .utf8) app.client.pushEvent("NeftRequest/response", args: [uid, error, code, data, headersJson] as [Any?]?) } } } // @export Request.request(string, string, string, string, number) => Promise as request static func request(_ uri: String, _ method: String, _ headers: [String: String], _ body: String, _ timeout: Int, _ completion: @escaping (_ error: String, _ code: Int, _ data: String, _ headers: [String: String]) -> Void) { var req = URLRequest(url: URL(string: uri)!) let session = URLSession.shared req.timeoutInterval = Double(timeout) / 1000 req.httpMethod = method.lowercased() for (name, val) in headers { req.setValue(val, forHTTPHeaderField: name) } if method.lowercased() != "get" { req.httpBody = body.data(using: String.Encoding.utf8) } let task = session.dataTask(with: req, completionHandler: { (data, response, error) in let httpResponse = response as? HTTPURLResponse let errMsg = error != nil ? String(describing: error) : "" let status = httpResponse != nil ? httpResponse!.statusCode : 0 let headers = httpResponse?.allHeaderFields as? [String: String] let httpData = data != nil ? NSString(data: data!, encoding: String.Encoding.utf8.rawValue)! : "" let httpHeaders: [String: String] = headers != nil ? headers! : [:] completion(errMsg, status, httpData as String, httpHeaders) }) task.resume() } }
apache-2.0
bb4fbda9ffdfb99b3cb17c88108d51fb
45.017857
228
0.57858
4.217676
false
false
false
false
soffes/GradientView
GradientView/GradientView.swift
1
6553
// // GradientView.swift // Gradient View // // Created by Sam Soffes on 10/27/09. // Copyright (c) 2009-2014 Sam Soffes. All rights reserved. // import UIKit /// Simple view for drawing gradients and borders. @IBDesignable open class GradientView: UIView { // MARK: - Types /// The mode of the gradient. @objc public enum Mode: Int { /// A linear gradient. case linear /// A radial gradient. case radial } /// The direction of the gradient. @objc public enum Direction: Int { /// The gradient is vertical. case vertical /// The gradient is horizontal case horizontal } // MARK: - Properties /// An optional array of `UIColor` objects used to draw the gradient. If the value is `nil`, the `backgroundColor` /// will be drawn instead of a gradient. The default is `nil`. open var colors: [UIColor]? { didSet { updateGradient() } } /// An array of `UIColor` objects used to draw the dimmed gradient. If the value is `nil`, `colors` will be /// converted to grayscale. This will use the same `locations` as `colors`. If length of arrays don't match, bad /// things will happen. You must make sure the number of dimmed colors equals the number of regular colors. /// /// The default is `nil`. open var dimmedColors: [UIColor]? { didSet { updateGradient() } } /// Automatically dim gradient colors when prompted by the system (i.e. when an alert is shown). /// /// The default is `true`. open var automaticallyDims: Bool = true /// An optional array of `CGFloat`s defining the location of each gradient stop. /// /// The gradient stops are specified as values between `0` and `1`. The values must be monotonically increasing. If /// `nil`, the stops are spread uniformly across the range. /// /// Defaults to `nil`. open var locations: [CGFloat]? { didSet { updateGradient() } } /// The mode of the gradient. The default is `.Linear`. @IBInspectable open var mode: Mode = .linear { didSet { setNeedsDisplay() } } /// The direction of the gradient. Only valid for the `Mode.Linear` mode. The default is `.Vertical`. @IBInspectable open var direction: Direction = .vertical { didSet { setNeedsDisplay() } } /// 1px borders will be drawn instead of 1pt borders. The default is `true`. @IBInspectable open var drawsThinBorders: Bool = true { didSet { setNeedsDisplay() } } /// The top border color. The default is `nil`. @IBInspectable open var topBorderColor: UIColor? { didSet { setNeedsDisplay() } } /// The right border color. The default is `nil`. @IBInspectable open var rightBorderColor: UIColor? { didSet { setNeedsDisplay() } } /// The bottom border color. The default is `nil`. @IBInspectable open var bottomBorderColor: UIColor? { didSet { setNeedsDisplay() } } /// The left border color. The default is `nil`. @IBInspectable open var leftBorderColor: UIColor? { didSet { setNeedsDisplay() } } // MARK: - UIView override open func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let size = bounds.size // Gradient if let gradient = gradient { let options: CGGradientDrawingOptions = [.drawsAfterEndLocation] if mode == .linear { let startPoint = CGPoint.zero let endPoint = direction == .vertical ? CGPoint(x: 0, y: size.height) : CGPoint(x: size.width, y: 0) context?.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: options) } else { let center = CGPoint(x: bounds.midX, y: bounds.midY) context?.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: min(size.width, size.height) / 2, options: options) } } let screen: UIScreen = window?.screen ?? UIScreen.main let borderWidth: CGFloat = drawsThinBorders ? 1.0 / screen.scale : 1.0 // Top border if let color = topBorderColor { context?.setFillColor(color.cgColor) context?.fill(CGRect(x: 0, y: 0, width: size.width, height: borderWidth)) } let sideY: CGFloat = topBorderColor != nil ? borderWidth : 0 let sideHeight: CGFloat = size.height - sideY - (bottomBorderColor != nil ? borderWidth : 0) // Right border if let color = rightBorderColor { context?.setFillColor(color.cgColor) context?.fill(CGRect(x: size.width - borderWidth, y: sideY, width: borderWidth, height: sideHeight)) } // Bottom border if let color = bottomBorderColor { context?.setFillColor(color.cgColor) context?.fill(CGRect(x: 0, y: size.height - borderWidth, width: size.width, height: borderWidth)) } // Left border if let color = leftBorderColor { context?.setFillColor(color.cgColor) context?.fill(CGRect(x: 0, y: sideY, width: borderWidth, height: sideHeight)) } } override open func tintColorDidChange() { super.tintColorDidChange() if automaticallyDims { updateGradient() } } override open func didMoveToWindow() { super.didMoveToWindow() contentMode = .redraw } // MARK: - Private fileprivate var gradient: CGGradient? fileprivate func updateGradient() { gradient = nil setNeedsDisplay() let colors = gradientColors() if let colors = colors { let colorSpace = CGColorSpaceCreateDeviceRGB() let colorSpaceModel = colorSpace.model let gradientColors = colors.map { (color: UIColor) -> AnyObject in let cgColor = color.cgColor let cgColorSpace = cgColor.colorSpace ?? colorSpace // The color's color space is RGB, simply add it. if cgColorSpace.model == colorSpaceModel { return cgColor as AnyObject } // Convert to RGB. There may be a more efficient way to do this. var red: CGFloat = 0 var blue: CGFloat = 0 var green: CGFloat = 0 var alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: red, green: green, blue: blue, alpha: alpha).cgColor as AnyObject } as NSArray gradient = CGGradient(colorsSpace: colorSpace, colors: gradientColors, locations: locations) } } fileprivate func gradientColors() -> [UIColor]? { if tintAdjustmentMode == .dimmed { if let dimmedColors = dimmedColors { return dimmedColors } if automaticallyDims { if let colors = colors { return colors.map { var hue: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 $0.getHue(&hue, saturation: nil, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: 0, brightness: brightness, alpha: alpha) } } } } return colors } }
mit
21b1db6053ef879aae3f0b7c04c94894
25.530364
160
0.68213
3.698081
false
false
false
false
RxSwiftCommunity/RxSwiftExt
Source/RxCocoa/UIScrollView+reachedBottom.swift
2
1102
// // UIScrollView+reachedBottom.swift // RxSwiftExt // // Created by Anton Nazarov on 09/05/2019. // Copyright © 2019 RxSwift Community. All rights reserved. // #if os(iOS) import UIKit import RxSwift import RxCocoa public extension Reactive where Base: UIScrollView { /** Shows if the bottom of the UIScrollView is reached. - parameter offset: A threshhold indicating the bottom of the UIScrollView. - returns: ControlEvent that emits when the bottom of the base UIScrollView is reached. */ func reachedBottom(offset: CGFloat = 0.0) -> ControlEvent<Void> { let source = contentOffset.map { contentOffset in let visibleHeight = self.base.frame.height - self.base.contentInset.top - self.base.contentInset.bottom let y = contentOffset.y + self.base.contentInset.top let threshold = max(offset, self.base.contentSize.height - visibleHeight) return y >= threshold } .distinctUntilChanged() .filter { $0 } .map { _ in () } return ControlEvent(events: source) } } #endif
mit
ecf3d0947efa0eeb85105e63c961a445
32.363636
115
0.667575
4.369048
false
false
false
false
myhgew/CodePractice
iOS/SwiftAssignment/Assignment1/Calculator/Calculator/ViewController.swift
1
2041
// // ViewController.swift // Calculator // // Created by yuhumai on 3/20/15. // Copyright (c) 2015 yuhumai. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var display: UILabel! var userIsInTheMiddleOfTypingNumber: Bool = false @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddleOfTypingNumber { display.text = display.text! + digit } else { display.text = digit userIsInTheMiddleOfTypingNumber = true } } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingNumber { enter() } switch operation { case "×": performOperation { $0 * $1 } case "÷": performOperation { $1 / $0 } case "+": performOperation { $0 + $1 } case "−": performOperation { $1 - $0 } case "√": performOperationForOneOperator { sqrt($0) } default: break } } func performOperation(operation: (Double, Double) -> Double) { if operandStack.count >= 2 { displayValue = operation(operandStack.removeLast(), operandStack.removeLast()) enter() } } func performOperationForOneOperator(operation: Double -> Double) { if operandStack.count >= 1 { displayValue = operation(operandStack.removeLast()) enter() } } // TODO: Video 2 - 44:29 var operandStack = Array<Double>() @IBAction func enter() { userIsInTheMiddleOfTypingNumber = false operandStack.append(displayValue) println("operandStack = \(operandStack)") } var displayValue : Double { get { return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { display.text = "\(newValue)" userIsInTheMiddleOfTypingNumber = false } } }
mit
ff849d72f422e12cbf2e988eb7e62642
24.759494
90
0.588698
5.012315
false
false
false
false
Thomvis/GoodProgress
GoodProgressTests/UseCaseTests.swift
1
2126
// The MIT License (MIT) // // Copyright (c) 2015 Thomas Visser // // 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 import GoodProgress class UseCaseTests: GoodProgressTestCase { func testSimpleProgress() { let p = progress(self.asynchronousTaskWithProgress(3)) let e = self.expectation() p.onProgress { fraction in if fraction == 1.0 { e.fulfill() } } self.waitForExpectationsWithTimeout(2, handler: nil) } func testProgressCapturing() { let e = self.expectation() progress(100) { p in p.captureProgress(80) { self.asynchronousTaskWithProgress(12) } p.captureProgress(20) { self.asynchronousTaskWithProgress(3) } }.onProgress { fraction in println(fraction) if (fraction == 1.0) { e.fulfill() } } self.waitForExpectationsWithTimeout(10, handler: nil) } }
mit
93252ba8882d45170952cc7bf9b74a73
33.852459
81
0.643932
4.831818
false
true
false
false
justindarc/firefox-ios
Shared/Functions.swift
9
6606
/* 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 SwiftyJSON // Pipelining. precedencegroup PipelinePrecedence { associativity: left } infix operator |> : PipelinePrecedence public func |> <T, U>(x: T, f: (T) -> U) -> U { return f(x) } // Basic currying. public func curry<A, B>(_ f: @escaping (A) -> B) -> (A) -> B { return { a in return f(a) } } public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C { return { a in return { b in return f(a, b) } } } public func curry<A, B, C, D>(_ f: @escaping (A, B, C) -> D) -> (A) -> (B) -> (C) -> D { return { a in return { b in return { c in return f(a, b, c) } } } } public func curry<A, B, C, D, E>(_ f: @escaping (A, B, C, D) -> E) -> (A, B, C) -> (D) -> E { return { (a, b, c) in return { d in return f(a, b, c, d) } } } // Function composition. infix operator • public func •<T, U, V>(f: @escaping (T) -> U, g: @escaping (U) -> V) -> (T) -> V { return { t in return g(f(t)) } } public func •<T, V>(f: @escaping (T) -> Void, g: @escaping () -> V) -> (T) -> V { return { t in f(t) return g() } } public func •<V>(f: @escaping () -> Void, g: @escaping () -> V) -> () -> V { return { f() return g() } } // Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse. // This is enough to catch arrays, which Swift will delegate to element-==. public func optArrayEqual<T: Equatable>(_ lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: // This delegates to Swift's own array '==', which calls T's == on each element. return lhs! == rhs! } } /** * Given an array, return an array of slices of size `by` (possibly excepting the last slice). * * If `by` is longer than the input, returns a single chunk. * If `by` is less than 1, acts as if `by` is 1. * If the length of the array isn't a multiple of `by`, the final slice will * be smaller than `by`, but never empty. * * If the input array is empty, returns an empty array. */ public func chunk<T>(_ arr: [T], by: Int) -> [ArraySlice<T>] { var result = [ArraySlice<T>]() var chunk = -1 let size = max(1, by) for (index, elem) in arr.enumerated() { if index % size == 0 { result.append(ArraySlice<T>()) chunk += 1 } result[chunk].append(elem) } return result } public func chunkCollection<E, X, T: Collection>(_ items: T, by: Int, f: ([E]) -> [X]) -> [X] where T.Iterator.Element == E { assert(by >= 0) let max = by > 0 ? by : 1 var i = 0 var acc: [E] = [] var results: [X] = [] var iter = items.makeIterator() while let item = iter.next() { if i >= max { results.append(contentsOf: f(acc)) acc = [] i = 0 } acc.append(item) i += 1 } if !acc.isEmpty { results.append(contentsOf: f(acc)) } return results } public extension Sequence { // [T] -> (T -> K) -> [K: [T]] // As opposed to `groupWith` (to follow Haskell's naming), which would be // [T] -> (T -> K) -> [[T]] func groupBy<Key, Value>(_ selector: (Self.Iterator.Element) -> Key, transformer: (Self.Iterator.Element) -> Value) -> [Key: [Value]] { var acc: [Key: [Value]] = [:] for x in self { let k = selector(x) var a = acc[k] ?? [] a.append(transformer(x)) acc[k] = a } return acc } func zip<S: Sequence>(_ elems: S) -> [(Self.Iterator.Element, S.Iterator.Element)] { var rights = elems.makeIterator() return self.compactMap { lhs in guard let rhs = rights.next() else { return nil } return (lhs, rhs) } } } public func optDictionaryEqual<K, V: Equatable>(_ lhs: [K: V]?, rhs: [K: V]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: return lhs! == rhs! } } /** * Return members of `a` that aren't nil, changing the type of the sequence accordingly. */ public func optFilter<T>(_ a: [T?]) -> [T] { return a.compactMap { $0 } } /** * Return a new map with only key-value pairs that have a non-nil value. */ public func optFilter<K, V>(_ source: [K: V?]) -> [K: V] { var m = [K: V]() for (k, v) in source { if let v = v { m[k] = v } } return m } /** * Map a function over the values of a map. */ public func mapValues<K, T, U>(_ source: [K: T], f: ((T) -> U)) -> [K: U] { var m = [K: U]() for (k, v) in source { m[k] = f(v) } return m } public func findOneValue<K, V>(_ map: [K: V], f: (V) -> Bool) -> V? { for v in map.values { if f(v) { return v } } return nil } /** * Take a JSON array, returning the String elements as an array. * It's usually convenient for this to accept an optional. */ public func jsonsToStrings(_ arr: [JSON]?) -> [String]? { return arr?.compactMap { $0.stringValue } } // Encapsulate a callback in a way that we can use it with NSTimer. private class Callback { private let handler:() -> Void init(handler:@escaping () -> Void) { self.handler = handler } @objc func go() { handler() } } /** * Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call * Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires. **/ public func debounce(_ delay: TimeInterval, action:@escaping () -> Void) -> () -> Void { let callback = Callback(handler: action) var timer: Timer? return { // If calling again, invalidate the last timer. if let timer = timer { timer.invalidate() } timer = Timer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false) RunLoop.current.add(timer!, forMode: RunLoop.Mode.default) } }
mpl-2.0
9d0738b74bcce2fc7a0be50fd40fcfef
25.079051
139
0.530161
3.366327
false
false
false
false
avjinder/FotoForReddit
FotoForReddit/SubredditSectionViewController.swift
1
4688
// // SubredditSectionViewController.swift // FotoForReddit // // Created by Avjinder Singh Sekhon on 4/10/17. // Copyright © 2017 Avjinder Singh Sekhon. All rights reserved. // import UIKit import Alamofire class SubredditSectionViewController: UIViewController{ @IBOutlet var sectionCollectionView: UICollectionView! var subredditName: String! var subredditItems: [SubredditItem] = [SubredditItem]() var paginationRequest: Alamofire.DataRequest? override func viewDidLoad() { super.viewDidLoad() if let validItems = Subreddits.user_subreddit_items[subredditName]{ subredditItems = validItems sectionCollectionView.reloadData() } sectionCollectionView.dataSource = self sectionCollectionView.delegate = self navigationItem.title = subredditName } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) // paginationRequest?.cancel() } } extension SubredditSectionViewController: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return subredditItems.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SectionCell", for: indexPath) as! PhotosCollectionViewCell let item = subredditItems[indexPath.row] if let image = SubredditImageGetter.fetchImage(imageURL: item.thumbnailURL){ cell.setImage(image) } else{ SubredditImageGetter.downloadImage(url: item.thumbnailURL){ result in switch result{ case let .failure(reason): print("Error fetching image: \(reason)") case .success: for (index, subItem) in self.subredditItems.enumerated(){ if item.id == subItem.id{ let indexPath = IndexPath(row: index, section: 0) self.sectionCollectionView.reloadItems(at: [indexPath]) } } default: return } } } return cell } } extension SubredditSectionViewController: UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == subredditItems.count - 1{ print("Row: \(indexPath.row) and subcount: \(subredditItems.count)") let lastItem = subredditItems[indexPath.row] let paginatedURL = SubredditGetter.makeSubredditPaginationURL(sub: subredditName, lastItemId: lastItem.id) if let validRequest = paginationRequest{ if validRequest.request!.url!.absoluteString == paginatedURL{ return } } print("Make pagination request for: \(paginatedURL)") paginationRequest = SubredditGetter.getSubreddit(subUrl: paginatedURL){ response in switch response{ case let .failure(reason): print("Failure fetching paginated data for \(self.subredditName): \(reason)") case let .success(items, subName): if Subreddits.user_subreddit_items[subName] != nil{ Subreddits.user_subreddit_items[subName]! += items self.subredditItems = Subreddits.user_subreddit_items[subName]! } self.sectionCollectionView.reloadData() } } // SubredditGetter.nextPageItems(subName: subredditName){ // response in // switch response{ // case let .failure(reason): // print("Failure fetching paginated data for \(self.subredditName): \(reason)") // case let .success(items, subName): // if Subreddits.user_subreddit_items[subName] != nil{ // Subreddits.user_subreddit_items[subName]! += items // } // self.sectionCollectionView.reloadData() // } // // } } } }
mit
b81e379cd2b567f9b3114eff153183fb
36.798387
134
0.569447
5.640193
false
false
false
false
Aymarick/DisplayKit
Sources/Application.swift
1
1601
// // Application.swift // DisplayKit // // Created by Aymeric De Abreu on 14/03/2017. // // import Foundation import CSDL2 class Application { var running = true var windows = [Window]() let framerate = UInt32(60) let framerateManagerPointer = UnsafeMutablePointer<FPSmanager>.allocate(capacity: 1) init?() { if SDL_Init(UInt32(SDL_INIT_VIDEO)) == -1 { print("Error while initialzing SDL") return nil } } func add(window: Window) { windows.append(window) } func start() -> Int { SDL_initFramerate(framerateManagerPointer) SDL_setFramerate(framerateManagerPointer, framerate) while running { let eventPointer = UnsafeMutablePointer<SDL_Event>.allocate(capacity: 1) while SDL_PollEvent(eventPointer) == 1 { let event : SDL_Event = eventPointer.pointee switch SDL_EventType(rawValue:event.type) { case SDL_FINGERUP: break case SDL_MOUSEBUTTONDOWN: print("Did click at \(event.button.x)x\(event.button.y)") if event.button.clicks == 2 { running = false } default: break } } windows.first?.draw() SDL_framerateDelay(framerateManagerPointer) } SDL_Quit() return 0 } }
mit
d32615cffd2ad80012a7e5c0d65d5ea4
24.015625
88
0.499063
4.386301
false
false
false
false
eppeo/FYSliderView
FYBannerView/Classes/Manager/TimerDelegate.swift
2
757
// // TimerDelegate.swift // FYBannerView // // Created by 武飞跃 on 2016/10/2. // import Foundation @objc protocol TimerDelegate: class { var timer: Timer? { set get } @objc func timerElamsed() } extension TimerDelegate { public func setupTimer(timeInterval: TimeInterval) { if timer == nil { let timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerElamsed), userInfo: nil, repeats: true) RunLoop.main.add(timer, forMode: RunLoop.Mode.common) self.timer = timer } } /// 停止定时器 public func invalidateTimer() { timer?.invalidate() timer = nil } } extension FYBannerView: TimerDelegate { }
mit
901f4a76c2b034408eb1c1d77f38d866
22.15625
151
0.630229
4.071429
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/_UIKitDelegate/UITableViewDelegate/TrackingTheRemovalOfViews/UITableViewDelegateRemove.swift
1
1701
// // UITableViewDelegateRemove.swift // OOUIKit // // Created by Karsten Litsche on 04.11.17. // import UIKit import OOBase public final class UITableViewDelegateRemove: NSObject, UITableViewDelegate { // MARK: - init public init( didEndDisplaying: @escaping (UITableView, IndexPath) -> OOExecutable = { _,_ in DoNothing() }, didEndDisplayingHeaderView: @escaping (UITableView, Int) -> OOExecutable = { _,_ in DoNothing() }, didEndDisplayingFooterView: @escaping (UITableView, Int) -> OOExecutable = { _,_ in DoNothing() } ) { self.didEndDisplaying = didEndDisplaying self.didEndDisplayingHeaderView = didEndDisplayingHeaderView self.didEndDisplayingFooterView = didEndDisplayingFooterView super.init() } // MARK: - protocol: UITableViewDelegate public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { didEndDisplaying(tableView, indexPath).execute() } public func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) { didEndDisplayingHeaderView(tableView, section).execute() } public func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) { didEndDisplayingFooterView(tableView, section).execute() } // MARK: - private private let didEndDisplaying: (UITableView, IndexPath) -> OOExecutable private let didEndDisplayingHeaderView: (UITableView, Int) -> OOExecutable private let didEndDisplayingFooterView: (UITableView, Int) -> OOExecutable }
mit
9d0553b9914da92005d4d9818044003e
35.978261
124
0.703116
5.417197
false
false
false
false
xivol/Swift-CS333
playgrounds/uiKit/UIKitCatalog.playground/Pages/UICollectionView.xcplaygroundpage/Contents.swift
2
5653
//: # UICollectionView //: Manages an ordered collection of data items and presents them using customizable layouts. //: //: [Collection View API Reference](https://developer.apple.com/reference/uikit/uicollectionview) import UIKit import PlaygroundSupport class Model: NSObject, UICollectionViewDataSource { let cellReuseIdentifier = "Cell" let headerReuseIdentifier = "Header" var data = [[String]]() var titles = [String]() func numberOfSections(in collectionView: UICollectionView) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data[section].count } // Mark: Cells func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) // Collection View Cells contain several subviews cell.backgroundView = UIView(frame: cell.bounds) cell.backgroundView?.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1) cell.selectedBackgroundView = UIView(frame: cell.bounds) cell.selectedBackgroundView?.backgroundColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1) // Content Mode manages subview layout cell.contentMode = .scaleAspectFit // Content View: views to be displayed cell.contentView.subviews.last?.removeFromSuperview() // clear for reuse // There are no default labels, so we need to add one cell.contentView.addSubview(cellLabel(for: indexPath, of: cell.bounds.size)) // Add Shadow cell.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor cell.layer.shadowRadius = 5 cell.layer.shadowOpacity = 0.5 cell.layer.shadowOffset = CGSize.zero return cell } func cellLabel(for indexPath: IndexPath, of size: CGSize) -> UILabel { let titleFrame = CGRect(origin: CGPoint.zero, size: size) let title = UILabel(frame: titleFrame) title.text = data[indexPath.section][indexPath.row] title.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) title.textAlignment = .center return title } // MARK: Section Header and Footer func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerReuseIdentifier, for: indexPath) header.subviews.last?.removeFromSuperview() // clear for reuse header.addSubview(headerLabel(for: indexPath.section, of: header.bounds.size)) return header case UICollectionElementKindSectionFooter: fallthrough // are not set up default: print("Wrong kind of element!") PlaygroundPage.current.finishExecution() } } func headerLabel(for section: Int, of size: CGSize) -> UILabel { let titleFrame = CGRect(origin: CGPoint.zero, size: size) let title = UILabel(frame: titleFrame) title.text = titles.count > section ? titles[section] : "???" title.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) title.textAlignment = .center return title } } class Controller: NSObject, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let dataSource = collectionView.dataSource as? Model else { print("Unexpected data source!") PlaygroundPage.current.finishExecution() } dataSource.data[indexPath.section][indexPath.row] = "👻" collectionView.reloadItems(at: [indexPath]) } } //: ### Create Layout let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() //: Cell Margins layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) //: Cell Size layout.itemSize = CGSize(width: 50, height: 50) //: Header size layout.headerReferenceSize = CGSize(width: 50, height: 25) //: Scroll Direction layout.scrollDirection = .vertical //: ### Initialize Collection View let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 250, height: 500), collectionViewLayout: layout) collectionView.backgroundView = UIImageView(image: #imageLiteral(resourceName: "gradient.png")) //: ### Initialize Data let dataSource = Model() dataSource.titles.append("Bees") dataSource.data.append([String](repeating: "🐝", count: 8)) dataSource.titles.append("Flowers") dataSource.data.append([String](repeating: "🌺", count: 8)) dataSource.titles.append("Candies") dataSource.data.append([String](repeating: "🍭", count: 8)) //: ### Register Reuseable Classes collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: dataSource.cellReuseIdentifier) collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: dataSource.headerReuseIdentifier) collectionView.dataSource = dataSource //: ### Setup Controller let delegate = Controller() collectionView.delegate = delegate PlaygroundPage.current.liveView = collectionView
mit
358a200377d7a8430070e1b295f76d66
44.861789
175
0.70679
4.948246
false
false
false
false
YQqiang/Nunchakus
Nunchakus/Nunchakus/Profile/ViewController/ProfileViewController.swift
1
5526
// // ProfileViewController.swift // Nunchakus // // Created by sungrow on 2017/4/7. // Copyright © 2017年 sungrow. All rights reserved. // import UIKit import Kingfisher import Toaster let cellID = "cell" let imageHeight: CGFloat = 240 class ProfileViewController: BaseViewController { fileprivate lazy var iconImageV: UIImageView = UIImageView() fileprivate lazy var tableView: UITableView = UITableView(frame: CGRect.zero, style: .grouped) fileprivate var firstScroll: Bool = true fileprivate var dataItems: [[String]] = { return [["清除缓存"], ["关于", "反馈", "联系作者", "开源组件"]] }() override func viewDidLoad() { super.viewDidLoad() emptyDataView.isHidden = true navigationItem.title = "我的" createUI() } } extension ProfileViewController { fileprivate func createUI() { tableView.addSubview(iconImageV) iconImageV.image = UIImage(named: "webwxgetmsgimg (12)") iconImageV.frame = CGRect(x: 0, y: -imageHeight, width: UIScreen.main.bounds.size.width, height: imageHeight) iconImageV.contentMode = .scaleAspectFill tableView.contentInset = UIEdgeInsetsMake(imageHeight, 0, 0, 0) tableView.contentOffset.y = -imageHeight view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.showsVerticalScrollIndicator = false tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } } // MARK:- UITableViewDelegate extension ProfileViewController: UITableViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetY = scrollView.contentOffset.y if offsetY < -imageHeight, scrollView == tableView { iconImageV.frame = CGRect(x: iconImageV.frame.origin.x, y: offsetY, width: iconImageV.frame.width, height: -offsetY) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) switch (indexPath.section, indexPath.row) { case (0, 0): let alertVC = UIAlertController(title: NSLocalizedString("提示", comment: ""), message: NSLocalizedString("确定清除缓存?", comment: ""), preferredStyle: .alert) let cancel = UIAlertAction(title: NSLocalizedString("取消", comment: ""), style: .cancel, handler: nil) let confirm = UIAlertAction(title: NSLocalizedString("确定", comment: ""), style: .destructive, handler: { (action) in let cache = KingfisherManager.shared.cache cache.clearDiskCache()//清除硬盘缓存 cache.clearMemoryCache()//清理网络缓存 cache.cleanExpiredDiskCache()//清理过期的,或者超过硬盘限制大小的 Toast(text: NSLocalizedString("清理成功", comment: "")).show() }) alertVC.addAction(cancel) alertVC.addAction(confirm) present(alertVC, animated: true, completion: nil) break case (1, 0): let alertVC = UIAlertController(title: NSLocalizedString("说明", comment: ""), message: NSLocalizedString("该APP中所有视频资源均来自双节棍吧(www.sjg8.com), 感谢双节棍吧站长的支持", comment: ""), preferredStyle: .alert) let cancel = UIAlertAction(title: NSLocalizedString("确定", comment: ""), style: .cancel, handler: nil) alertVC.addAction(cancel) present(alertVC, animated: true, completion: nil) break case (1, 1): let alertVC = UIAlertController(title: NSLocalizedString("感谢您的支持", comment: ""), message: NSLocalizedString("请直接联系作者, 进行问题反馈", comment: ""), preferredStyle: .alert) let cancel = UIAlertAction(title: NSLocalizedString("确定", comment: ""), style: .cancel, handler: nil) alertVC.addAction(cancel) present(alertVC, animated: true, completion: nil) break case (1, 2): let alertVC = UIAlertController(title: NSLocalizedString("QQ", comment: ""), message: NSLocalizedString("1054572107\n余强", comment: ""), preferredStyle: .alert) let cancel = UIAlertAction(title: NSLocalizedString("确定", comment: ""), style: .cancel, handler: nil) alertVC.addAction(cancel) present(alertVC, animated: true, completion: nil) break case (1, 3): navigationController?.pushViewController(LicenseViewController(), animated: true) break default: break } } } // MARK:- UITableViewDataSource extension ProfileViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return dataItems.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataItems[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID) cell?.textLabel?.text = dataItems[indexPath.section][indexPath.row] return cell! } }
mit
a42d0504667c96357467600b1a5a9b33
39.669231
202
0.643276
4.832724
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/VisualTriggerView.swift
1
12494
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Palettes_Palettes import third_party_objective_c_material_components_ios_components_Typography_Typography /// The view for the sensor card cell that displays visual triggers. class VisualTriggerView: UIView { // MARK: - Properties /// The height of the visual trigger view. static var height: CGFloat { return Metrics.height } private var indexOfTriggerToDisplay = 0 private var isShowingTriggerActivatedView = false private var sensor: Sensor? private var triggerFiredViewWidthConstraint: NSLayoutConstraint? private var triggers: [SensorTrigger]? // Timers private var multipleTriggersTimer: Timer? private var triggerFiredTimer: Timer? // Views private let checkmarkIconImageView = UIImageView(image: UIImage(named: "ic_check")) private let snapshotWrapper = UIView() private let triggerIconImageView = UIImageView(image: UIImage(named: "ic_trigger")) private let titleLabel = UILabel() private let triggerCountLabel = UILabel() private let triggerFiredView = TriggerFiredView() private enum Metrics { // View constants static let height: CGFloat = 50 static let imageSize = CGSize(width: 24, height: 24) static let innerHorizontalSpacing: CGFloat = 15 static let outerHorizontalMargin: CGFloat = 20 static let triggerCountHorizontalOffset: CGFloat = -2 // Rotation angles static let rotationAngleLeft = CGFloat(-Double.pi / 2) static let rotationAngleRight = CGFloat(Double.pi / 2) static let rotationAngleZero: CGFloat = 0 // Animation durations static let imageViewAlphaAnimationDuration: TimeInterval = 0.2 static let snapshotFadeAnimationDuration: TimeInterval = 0.3 static let triggerFiredAnimationDuration: TimeInterval = 0.2 static let rotationAnimationDuration: TimeInterval = 0.2 // Timer intervals static let multipleTriggersTimerInterval: TimeInterval = 4 static let triggerFiredTimerInterval: TimeInterval = 1 } // MARK: - Public override init(frame: CGRect) { super.init(frame: .zero) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } deinit { multipleTriggersTimer?.invalidate() triggerFiredTimer?.invalidate() } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: Metrics.height) } /// Sets the sensor and triggers for the visual trigger view. /// /// - Parameters: /// - triggers: The visual triggers. /// - sensor: The sensor the triggers are for. func setTriggers(_ triggers: [SensorTrigger], forSensor sensor: Sensor) { self.triggers = triggers self.sensor = sensor indexOfTriggerToDisplay = 0 updateTitleLabel() if triggers.count > 1 { triggerCountLabel.text = String(triggers.count) multipleTriggersTimer = Timer.scheduledTimer(timeInterval: Metrics.multipleTriggersTimerInterval, target: self, selector: #selector(multipleTriggersTimerFired), userInfo: nil, repeats: true) // Allows the timer to fire while scroll views are tracking. RunLoop.main.add(multipleTriggersTimer!, forMode: .common) } else { triggerCountLabel.text = nil multipleTriggersTimer?.invalidate() } } /// Shows the fired state for the trigger. @objc func triggerFired() { guard !isShowingTriggerActivatedView else { return } triggerFiredTimer?.invalidate() triggerFiredTimer = Timer.scheduledTimer(timeInterval: Metrics.triggerFiredTimerInterval, target: self, selector: #selector(endDisplayingTriggerActivatedViewTimerFired), userInfo: nil, repeats: false) // Allows the timer to fire while scroll views are tracking. RunLoop.main.add(triggerFiredTimer!, forMode: .common) UIView.animate(withDuration: Metrics.triggerFiredAnimationDuration) { self.triggerFiredViewWidthConstraint?.constant = self.bounds.size.width self.layoutIfNeeded() } updateImageViews(forFiredState: true) UIAccessibility.post(notification: .announcement, argument: triggerFiredView.titleLabel.text) isShowingTriggerActivatedView = true } // MARK: - Private private func configureView() { backgroundColor = MDCPalette.grey.tint900 // Image view wrapper. let imageViewWrapper = UIView() addSubview(imageViewWrapper) imageViewWrapper.translatesAutoresizingMaskIntoConstraints = false imageViewWrapper.leadingAnchor.constraint( equalTo: leadingAnchor, constant: Metrics.outerHorizontalMargin).isActive = true imageViewWrapper.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true imageViewWrapper.heightAnchor.constraint( equalToConstant: Metrics.imageSize.height).isActive = true imageViewWrapper.widthAnchor.constraint( equalToConstant: Metrics.imageSize.width).isActive = true // Checkmark image view. checkmarkIconImageView.alpha = 0 checkmarkIconImageView.tintColor = .white // Starts rotated left, so it can rotate to zero each time it shows. checkmarkIconImageView.transform = CGAffineTransform(rotationAngle: Metrics.rotationAngleLeft) checkmarkIconImageView.translatesAutoresizingMaskIntoConstraints = false imageViewWrapper.addSubview(checkmarkIconImageView) checkmarkIconImageView.pinToEdgesOfView(imageViewWrapper) // Trigger image view. triggerIconImageView.tintColor = .white triggerIconImageView.translatesAutoresizingMaskIntoConstraints = false imageViewWrapper.addSubview(triggerIconImageView) triggerIconImageView.pinToEdgesOfView(imageViewWrapper) // Trigger count label. triggerCountLabel.font = MDCTypography.captionFont() triggerCountLabel.textColor = MDCPalette.grey.tint900 triggerCountLabel.translatesAutoresizingMaskIntoConstraints = false imageViewWrapper.addSubview(triggerCountLabel) triggerCountLabel.centerXAnchor.constraint( equalTo: imageViewWrapper.centerXAnchor, constant: Metrics.triggerCountHorizontalOffset).isActive = true triggerCountLabel.centerYAnchor.constraint( equalTo: imageViewWrapper.centerYAnchor).isActive = true // Title label. titleLabel.font = MDCTypography.body2Font() titleLabel.textColor = .white titleLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(titleLabel) titleLabel.leadingAnchor.constraint(equalTo: imageViewWrapper.trailingAnchor, constant: Metrics.innerHorizontalSpacing).isActive = true titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Metrics.outerHorizontalMargin).isActive = true titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true // Snapshot wrapper. snapshotWrapper.translatesAutoresizingMaskIntoConstraints = false addSubview(snapshotWrapper) snapshotWrapper.pinToEdgesOfView(self) snapshotWrapper.alpha = 0 // Trigger fired view, width starts at 0. triggerFiredView.translatesAutoresizingMaskIntoConstraints = false addSubview(triggerFiredView) triggerFiredView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true triggerFiredView.topAnchor.constraint(equalTo: topAnchor).isActive = true triggerFiredView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true triggerFiredViewWidthConstraint = triggerFiredView.widthAnchor.constraint(equalToConstant: 0) triggerFiredViewWidthConstraint?.isActive = true triggerFiredView.titleLabel.translatesAutoresizingMaskIntoConstraints = false triggerFiredView.titleLabel.leadingAnchor.constraint( equalTo: titleLabel.leadingAnchor).isActive = true triggerFiredView.titleLabel.trailingAnchor.constraint( equalTo: titleLabel.trailingAnchor).isActive = true triggerFiredView.titleLabel.centerYAnchor.constraint( equalTo: titleLabel.centerYAnchor).isActive = true // Bring image view wrapper to the front so it is in front of the trigger fired view. bringSubviewToFront(imageViewWrapper) } private func updateImageViews(forFiredState firedState: Bool) { // Rotate the image views and count label. if firedState { triggerIconImageView.animateRotationTransform(to: Metrics.rotationAngleRight, from: Metrics.rotationAngleZero, duration: Metrics.rotationAnimationDuration) triggerCountLabel.animateRotationTransform(to: Metrics.rotationAngleRight, from: Metrics.rotationAngleZero, duration: 0.2) checkmarkIconImageView.animateRotationTransform(to: Metrics.rotationAngleZero, from: Metrics.rotationAngleLeft, duration: Metrics.rotationAnimationDuration) } else { triggerIconImageView.animateRotationTransform(to: Metrics.rotationAngleZero, from: Metrics.rotationAngleRight, duration: Metrics.rotationAnimationDuration) triggerCountLabel.animateRotationTransform(to: Metrics.rotationAngleZero, from: Metrics.rotationAngleRight, duration: Metrics.rotationAnimationDuration) checkmarkIconImageView.animateRotationTransform(to: Metrics.rotationAngleLeft, from: Metrics.rotationAngleZero, duration: Metrics.rotationAnimationDuration) } // Set the alphas of the image views. UIView.animate(withDuration: Metrics.imageViewAlphaAnimationDuration) { self.checkmarkIconImageView.alpha = firedState ? 1 : 0 self.triggerIconImageView.alpha = firedState ? 0 : 1 self.triggerCountLabel.alpha = self.triggerIconImageView.alpha } } private func updateTitleLabel() { guard let triggers = triggers, triggers.count > 0, let sensor = sensor else { titleLabel.text = nil return } titleLabel.text = triggers[indexOfTriggerToDisplay].textDescription(for: sensor) } // MARK: Timers @objc private func multipleTriggersTimerFired() { guard let triggers = triggers, triggers.count > 1 else { multipleTriggersTimer?.invalidate() indexOfTriggerToDisplay = 0 return } // Show a snapshot. guard let snapshotView = snapshotView(afterScreenUpdates: false) else { return } snapshotWrapper.addSubview(snapshotView) snapshotWrapper.alpha = 1 // Update the view indexOfTriggerToDisplay += 1 if indexOfTriggerToDisplay > triggers.endIndex - 1 { indexOfTriggerToDisplay = 0 } updateTitleLabel() // Fade away the snapshot. UIView.animate(withDuration: Metrics.snapshotFadeAnimationDuration, animations: { self.snapshotWrapper.alpha = 0 }) { (_) in snapshotView.removeFromSuperview() } } @objc private func endDisplayingTriggerActivatedViewTimerFired() { UIView.animate(withDuration: Metrics.triggerFiredAnimationDuration) { self.triggerFiredViewWidthConstraint?.constant = 0 self.layoutIfNeeded() } updateImageViews(forFiredState: false) isShowingTriggerActivatedView = false } }
apache-2.0
e4d880176c78a917f0e84720721a00ff
39.433657
98
0.702257
5.399309
false
false
false
false
yufenglv/AsyncDisplayKit
examples_extra/BackgroundPropertySetting/Sample/DemoCellNode.swift
6
2809
// // DemoCellNode.swift // Sample // // Created by Adlai Holler on 2/17/16. // // Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // 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 // FACEBOOK 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 AsyncDisplayKit final class DemoCellNode: ASCellNode { let childA = ASDisplayNode() let childB = ASDisplayNode() var state = State.Right override init() { super.init() usesImplicitHierarchyManagement = true } override func layoutSpecThatFits(constrainedSize: ASSizeRange) -> ASLayoutSpec { let specA = ASRatioLayoutSpec(ratio: 1, child: childA) specA.flexBasis = ASRelativeDimensionMakeWithPoints(1) specA.flexGrow = true let specB = ASRatioLayoutSpec(ratio: 1, child: childB) specB.flexBasis = ASRelativeDimensionMakeWithPoints(1) specB.flexGrow = true let children = state.isReverse ? [ specB, specA ] : [ specA, specB ] let direction: ASStackLayoutDirection = state.isVertical ? .Vertical : .Horizontal return ASStackLayoutSpec(direction: direction, spacing: 20, justifyContent: .SpaceAround, alignItems: .Center, children: children) } override func animateLayoutTransition(context: ASContextTransitioning!) { childA.frame = context.initialFrameForNode(childA) childB.frame = context.initialFrameForNode(childB) let tinyDelay = drand48() / 10 UIView.animateWithDuration(0.5, delay: tinyDelay, usingSpringWithDamping: 0.9, initialSpringVelocity: 1.5, options: .BeginFromCurrentState, animations: { () -> Void in self.childA.frame = context.finalFrameForNode(self.childA) self.childB.frame = context.finalFrameForNode(self.childB) }, completion: { context.completeTransition($0) }) } enum State { case Right case Up case Left case Down var isVertical: Bool { switch self { case .Up, .Down: return true default: return false } } var isReverse: Bool { switch self { case .Left, .Up: return true default: return false } } mutating func advance() { switch self { case .Right: self = .Up case .Up: self = .Left case .Left: self = .Down case .Down: self = .Right } } } }
bsd-3-clause
f0ce3f73049d83d9d8739d34401ea3bd
27.663265
169
0.714845
3.61054
false
false
false
false
CaueAlvesSilva/FeaturedGames
FeaturedGames/FeaturedGames/Extensions/UIImageView+Extensions.swift
1
1375
// // UIImageView+Extensions.swift // FeaturedGames // // Created by Cauê Silva on 04/08/17. // Copyright © 2017 Caue Alves. All rights reserved. // import Foundation import UIKit import PINCache import PINRemoteImage extension UIImageView { func downloadImage(with url: String) { addIndicatorView() pin_updateWithProgress = true pin_setImage(from: URL(string: url)) { result in if result.image != nil { self.removeIndicatorView() } } } func addIndicatorView() { if !subviews.contains(where: { $0.isKind(of: UIActivityIndicatorView.self) }) { let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) indicatorView.frame = CGRect(x: frame.size.width / 2, y: frame.size.height / 2, width: 15, height: 15) indicatorView.startAnimating() addSubview(indicatorView) bringSubview(toFront: indicatorView) backgroundColor = Colors.black.color.withAlphaComponent(0.05) } } func removeIndicatorView() { subviews.forEach { subview in if subview.isKind(of: UIActivityIndicatorView.self) { subview.removeFromSuperview() backgroundColor = Colors.black.color.withAlphaComponent(1) } } } }
mit
d3b27607747510451cdf220a421833b9
28.847826
114
0.616897
4.750865
false
false
false
false
asm-products/meowboard-ios
MeowboardKeyboard/KeyboardViewController.swift
1
5936
// // KeyboardViewController.swift // MeowboardKeyboard // // Created by Charles Pletcher on 9/22/14. // Copyright (c) 2014 Charles Pletcher. All rights reserved. // import UIKit class KeyboardViewController: UIInputViewController { let API_KEY = "dc6zaTOxFJmzC" var mainView: UIView! override func updateViewConstraints() { super.updateViewConstraints() } override func viewDidLoad() { super.viewDidLoad() var xibViews = NSBundle.mainBundle().loadNibNamed("Keyboard", owner: self, options: nil) self.mainView = xibViews[0] as UIView self.view.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addSubview(mainView) for subview in self.mainView.subviews as [AnyObject] { if let scrollView = subview as? UIScrollView { var contentRect: CGRect = CGRectZero for view in scrollView.subviews as [UIView] { contentRect = CGRectUnion(contentRect, view.frame) for button in view.subviews as [UIButton] { getDefaultGifAndSetAsButtonBackground(button) button.addTarget(self, action: "didTapButton:", forControlEvents: .TouchUpInside) } } scrollView.contentSize = contentRect.size; } else if let fixedView = subview as? UIView { for object in fixedView.subviews as [AnyObject] { if let button = object as? UIButton { button.addTarget(self, action: "didTapButton:", forControlEvents: .TouchUpInside) } } } } var keyboardHeightConstraint: NSLayoutConstraint = NSLayoutConstraint(item: self.view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0.0, constant: 500.0) self.view.addConstraint(keyboardHeightConstraint) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func cleanQuery(query: String) -> String { return query.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil).lowercaseString } func cleanTitle(title: String) -> String { return title.stringByReplacingOccurrencesOfString(" ", withString: "_", options: nil, range: nil).lowercaseString } func didTapButton(sender: AnyObject) { let button = sender as UIButton let title = button.titleForState(.Normal) as String! var proxy = textDocumentProxy as UITextDocumentProxy switch title { case "CHG" : self.advanceToNextInputMode() case "DEL" : while proxy.hasText() { proxy.deleteBackward() } default: getAndInsertRandomGifUrl(title, proxy: proxy) } } func getDefaultGifAndSetAsButtonBackground(button: UIButton) { var cleanedQuery = cleanQuery(button.titleForState(.Normal) as String!) var url = NSURL(string: "http://api.giphy.com/v1/gifs/search?q=\(cleanedQuery)&api_key=\(API_KEY)") var task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in if (error != nil) { return println(error) } // FIXME: We need to cut this down to one HTTP call, // and we need to cache the images for ~ 1 day var parsedData: NSArray = self.parseJson(data)["data"] as NSArray var imageObject: NSDictionary = parsedData[0] as NSDictionary var images: NSDictionary = imageObject["images"] as NSDictionary var fixedWidth: NSDictionary = images["fixed_width"] as NSDictionary var gifUrlString: String = fixedWidth["url"] as String var gifUrl: NSURL = NSURL.URLWithString(gifUrlString) var imageTask = NSURLSession.sharedSession().dataTaskWithURL(gifUrl) {(imageData, imageResponse, imageError) in if (imageError != nil) { return println(imageError) } var backgroundImage = UIImage.animatedImageWithData(imageData as NSData) button.setBackgroundImage(backgroundImage, forState: .Normal) } imageTask.resume() } task.resume() } func getAndInsertRandomGifUrl(query: String, proxy: UITextDocumentProxy) { var cleanedQuery = cleanQuery(query) var url = NSURL(string: "http://api.giphy.com/v1/gifs/search?q=\(cleanedQuery)&api_key=\(API_KEY)") var task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in if (error != nil) { return println(error) } var parsedData: NSArray = self.parseJson(data)["data"] as NSArray var imageObject: NSDictionary = parsedData[0] as NSDictionary var images: NSDictionary = imageObject["images"] as NSDictionary var fixedWidth: NSDictionary = images["fixed_width"] as NSDictionary var gifUrlString: String = fixedWidth["url"] as String // FIXME: Page through the list of available GIFs after the first click, // inserting a new one each click. proxy.insertText(gifUrlString) } task.resume() } func parseJson(data: NSData) -> NSDictionary { var error: NSError? var dictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary return dictionary } }
bsd-2-clause
b52857cf9bd98fcd39d75b6131265268
39.108108
225
0.601247
5.328546
false
false
false
false
dn-m/PathTools
PathTools/Path.swift
1
3538
// // Path.swift // PathTools // // Created by James Bean on 6/10/16. // // import Algebra import Collections import ArithmeticTools import GeometryTools public struct Path { // MARK: - Instance Properties public var isShape: Bool { return curves.all { curve in curve.order == .linear } } /// - Returns: `true` if there are no non-`.close` elements contained herein. Otherwise, /// `false`. public var isEmpty: Bool { return curves.isEmpty } /// - Returns: The axis-aligned bounding box for `Path`. /// /// - Warning: This uses a simplification technique for calculateing the bounding boxes of /// quadratic and cubic Bézier curves, which may result in some inaccuracy for whacky curves. /// public var axisAlignedBoundingBox: Rectangle { return curves.map { $0.axisAlignedBoundingBox }.nonEmptySum ?? .zero } internal let curves: [BezierCurve] // MARK: - Initializers /// Create a `Path` with the given `curves`. public init(_ curves: [BezierCurve]) { self.curves = curves } /// Create a `Path` with the given `pathElements`. public init(pathElements: [PathElement]) { guard let (head, tail) = pathElements.destructured, case let .move(start) = head else { self = Path([]) return } let builder = Path.builder.move(to: start) var last = start for element in tail { switch element { case .move(let point): builder.move(to: point) last = point case .line(let point): point == last ? builder.close() : builder.addLine(to: point) case .quadCurve(let point, let control): builder.addQuadCurve(to: point, control: control) case .curve(let point, let control1, let control2): builder.addCurve(to: point, control1: control1, control2: control2) case .close: builder.close() } } self = builder.build() } // MARK: - Instance Methods /// - Returns: Polygonal representation of the `Path`. public func simplified(segmentCount: Int) -> Polygon { let vertices = curves.map { $0.simplified(segmentCount: segmentCount) } let (most, last) = vertices.split(at: vertices.count - 1)! let merged = most.flatMap { $0.dropLast() } + last[0] if merged.count == 2 { return Polygon(vertices: merged + merged[0]) } return Polygon(vertices: merged) } } extension Path: CollectionWrapping { public var base: [BezierCurve] { return curves } } extension Path: Additive { /// Empty path. public static let zero = Path([]) /// - Returns: New `Path` with elements of two paths. public static func + (lhs: Path, rhs: Path) -> Path { return Path(lhs.curves + rhs.curves) } } extension Path: Equatable { // MARK: - Equatable public static func == (lhs: Path, rhs: Path) -> Bool { return lhs.curves == rhs.curves } } extension Path: CustomStringConvertible { // MARK: - CustomStringConvertible /// Printed description. public var description: String { var result = "Path:\n" result += curves.map { " - \($0)" }.joined(separator: "\n") return result } }
mit
433af190bd72cd0effea91754c6a11ca
25.795455
97
0.568561
4.372064
false
false
false
false
NocturneZX/TTT-Pre-Internship-Exercises
Swift/class 15/SwiftTabAppSample/SwiftTabAppSample/FirstViewController.swift
1
1525
// // FirstViewController.swift // SwiftTabAppSample // // Created by Oren Goldberg on 12/10/14. // Copyright (c) 2014 Turn To Tech. All rights reserved. // import UIKit class FirstViewController: UIViewController { @IBOutlet var txtCounter1: UITextField! @IBOutlet var txtCounter2: UITextField! var counter1:Int = 0 var counter2:Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveNotification:", name: "Test1", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveNotification:", name: "Test2", object: nil) } func receiveNotification(notification:NSNotification) { println("First View Notification Received: \(notification.name)") var extraInfo:Dictionary = notification.userInfo! if (notification.name == "Test1") { counter1++ var button_name:AnyObject = extraInfo["button_name"]! txtCounter1.text = "\(button_name) \(counter1)" } else { counter2++ var button_name:AnyObject = extraInfo["button_name"]! txtCounter2.text = "\(button_name) \(counter2)" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
9b4962fb5c85fe7e5c0ca85adb5fe784
32.173913
124
0.639344
4.721362
false
true
false
false
matoushybl/iKGK-ios
iKGK/LoadingController.swift
1
2640
// // LoadingController.swift // iKGK // // Created by Matouš Hýbl on 19/04/15. // Copyright (c) 2015 KGK. All rights reserved. // import UIKit import AFNetworking import Realm import SwiftyJSON import SwiftKit @objc(LoadingController) class LoadingController: UIViewController { private var activityIndicator: UIActivityIndicatorView! private var label: UILabel! override func loadView() { super.loadView() view = UIView() AFNetworkReachabilityManager.sharedManager().startMonitoring() activityIndicator => view label => view label.text = "Loading classes and teachers" label.textColor = UIColor.whiteColor() activityIndicator.snp_remakeConstraints { make in make.leading.trailing.centerY.equalTo(self.view) } label.snp_remakeConstraints { make in make.centerX.equalTo(self.view) make.top.equalTo(self.activityIndicator.snp_bottom).offset(10) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if(!isNetworkAvailable()) { showError("Network not available") } activityIndicator.startAnimating() DataDownloader.loadData({ let choosingController = ChoosingController() choosingController.onClassSelected += { [unowned self] data in Preferences.teacherMode = false Preferences.id = data.input.id self.showMainController() } choosingController.onTeacherSelected += { [unowned self] data in Preferences.teacherMode = true Preferences.id = data.input.id self.showMainController() } }, onError: { self.showError("Failed to load data, please try again later") }) } // FIXME let's hope this shit works private func isNetworkAvailable() -> Bool { return AFNetworkReachabilityManager.sharedManager().reachable } private func showError(message: String) { UIAlertView(title: "Error", message: message, delegate: nil, cancelButtonTitle: "Cancel").show() } private func showMainController() { let navigationController = UINavigationController(rootViewController: MainController()) navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.presentViewController(navigationController, animated: true, completion: nil) } }
mit
75c049756cc8cb4df23407bdec4081ae
31.975
119
0.63533
5.450413
false
false
false
false
AnarchyTools/atpkg
src/parsing/Parser.swift
1
5367
// Copyright (c) 2016 Anarchy Tools 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 atfoundation public enum ParseError: Error { case InvalidPackageFile case ExpectedTokenType(TokenType, Token?) case InvalidTokenForValueType(Token?) } public enum ParseValue { case StringLiteral(String) case IntegerLiteral(Int) case FloatLiteral(Double) case BoolLiteral(Bool) case Map([String:ParseValue]) case Vector([ParseValue]) } extension ParseValue { public var string: String? { if case let .StringLiteral(value) = self { return value } return nil } public var integer: Int? { if case let .IntegerLiteral(value) = self { return value } return nil } public var float: Double? { if case let .FloatLiteral(value) = self { return value } return nil } public var bool: Bool? { if case let .BoolLiteral(value) = self { return value } return nil } public var map: [String:ParseValue]? { if case let .Map(value) = self { return value } return nil } public var vector: [ParseValue]? { if case let .Vector(value) = self { return value } return nil } } final public class ParseType { public var name: String = "" public var properties: [String:ParseValue] = [:] } final public class Parser { let lexer: Lexer private func next() -> Token? { while true { guard let token = lexer.next() else { return nil } if token.type != .Comment && token.type != .Terminal { return lexer.peek() } } } public init?(filepath: Path) throws { guard let content = try String(loadFromFile: filepath) else { return nil } let scanner = Scanner(content: content) self.lexer = Lexer(scanner: scanner) } public func parse() throws -> ParseType { guard let token = next() else { throw ParseError.InvalidPackageFile } if token.type == .OpenParen { return try parseType() } else { throw ParseError.ExpectedTokenType(.OpenParen, token) } } private func parseType() throws -> ParseType { let type = ParseType() type.name = try parseIdentifier() type.properties = try parseKeyValuePairs() return type } private func parseKeyValuePairs() throws -> [String:ParseValue] { var pairs: [String:ParseValue] = [:] while let token = next(), token.type != .CloseParen && token.type != .CloseBrace { lexer.stall() let key = try parseKey() let value = try parseValue() pairs[key] = value } lexer.stall() return pairs } private func parseKey() throws -> String { let colon = next() if colon?.type != .Colon { throw ParseError.ExpectedTokenType(.Colon, lexer.peek()) } return try parseIdentifier() } private func parseIdentifier() throws -> String { guard let identifier = next() else { throw ParseError.ExpectedTokenType(.Identifier, lexer.peek()) } if identifier.type != .Identifier { throw ParseError.ExpectedTokenType(.Identifier, lexer.peek()) } return identifier.value } private func parseValue() throws -> ParseValue { guard let token = next() else { throw ParseError.InvalidTokenForValueType(nil) } switch token.type { case .OpenBrace: lexer.stall(); return try parseMap() case .OpenBracket: lexer.stall(); return try parseVector() case .StringLiteral: return .StringLiteral(token.value) case .Identifier where token.value == "true": return .BoolLiteral(true) case .Identifier where token.value == "false": return .BoolLiteral(false) default: throw ParseError.InvalidTokenForValueType(token) } } private func parseVector() throws -> ParseValue { if let token = next(),token.type != .OpenBracket { throw ParseError.ExpectedTokenType(.OpenBracket, token) } var items: [ParseValue] = [] while let token = next(), token.type != .CloseBracket { lexer.stall() items.append(try parseValue()) } lexer.stall() if let token = next(), token.type != .CloseBracket { throw ParseError.ExpectedTokenType(.CloseBracket, token) } return .Vector(items) } private func parseMap() throws -> ParseValue { if let token = next(), token.type != .OpenBrace { throw ParseError.ExpectedTokenType(.OpenBrace, token) } let items = try parseKeyValuePairs() if let token = next(), token.type != .CloseBrace { throw ParseError.ExpectedTokenType(.CloseBrace, token) } return .Map(items) } }
apache-2.0
ed3a08321f0643af6ef53190dfd2c6a3
29.494318
119
0.625116
4.4725
false
false
false
false
dzindra/toycar
iOS/auto/CircleViewController.swift
1
2302
// // CircleViewController.swift // auto // // Created by Džindra on 08.04.16. // Copyright © 2016 Dzindra. All rights reserved. // import UIKit class CircleViewController: UIViewController, Updatable { @IBOutlet weak var circleView: TouchView! @IBOutlet weak var lightSwitch: UISwitch! @IBOutlet weak var indicatorLeft: NSLayoutConstraint! @IBOutlet weak var indicatorTop: NSLayoutConstraint! @IBOutlet weak var indicator: TouchView! override func viewDidLoad() { super.viewDidLoad() circleView.circle = true circleView.touchBlock = { [weak self] loc, orig, active in self?.indicator.hidden = !active if active { self?.touched(loc, orig: orig) } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) update() } func update() { lightSwitch.on = CarService.instance.lights } func getM1(a: Double) -> Double { switch a { case 0.0..<90.0: return 1 case 90.0..<270.0: return 1.0-(a-90.0)/90.0 case 270..<360: return (a-270.0)/45.0-1.0 default: return -1 } } func getM2(a: Double) -> Double { switch a { case 0..<90: return a/90.0 case 180..<270: return 1-(a-180)/45 case 270..<360: return (a-270)/90-1 default: return 1 } } func touched(loc: CGPoint, orig: CGPoint) { indicatorTop.constant = orig.y-10 indicatorLeft.constant = orig.x-10 var a = Double(atan2(loc.y, -loc.x)) if a<0 { a+=M_PI*2 } a *= 180/M_PI var dist = Double(hypot(loc.x,loc.y)) if dist<0.2 { dist = 0 } CarService.instance.setSpeed(CarService.motorStop+Int(getM1(a)*dist*Double(CarService.motorStop)), CarService.motorStop+Int(getM2(a)*dist*Double(CarService.motorStop))) //print("\(CarService.instance.motor1-1023) \(CarService.instance.motor2-1023)") } @IBAction func lightsChanged(sender: UISwitch) { CarService.instance.lights = sender.on } }
bsd-2-clause
9dfadbe686f37f51cd8d259b9c38c7e0
25.436782
176
0.553043
3.852596
false
false
false
false
XeresRazor/SwiftRaytracer
src/pathtracer/Camera.swift
1
1873
// // Camera.swift // Raytracer // // Created by David Green on 4/14/16. // Copyright © 2016 David Green. All rights reserved. // import simd func randomInUnitDisc() -> double4 { var p = double4() repeat { p = 2.0 * double4(drand48(), drand48(), 0, 0) - double4(1,1,0, 0) } while dot(p, p) >= 1.0 return p } public struct Camera { private var origin: double4 private var lowerLeftCorner: double4 private var horizontal: double4 private var vertical: double4 private var u: double4 private var v: double4 private var w: double4 private var time0: Double private var time1: Double private var lensRadius: Double public init(lookFrom: double3, lookAt: double3, up: double3, verticalFOV: Double, aspect: Double, aperture: Double, focusDistance: Double, time0 t0: Double, time1 t1: Double) { time0 = t0 time1 = t1 lensRadius = aperture / 2 let theta = verticalFOV * M_PI / 180.0 let halfHeight = tan(theta / 2) let halfWidth = aspect * halfHeight let originTemp = lookFrom let wTemp = normalize(lookFrom - lookAt) let uTemp = normalize(cross(up, wTemp)) let vTemp = cross(wTemp, uTemp) origin = double4(originTemp.x, originTemp.y, originTemp.z, 0.0) w = double4(wTemp.x, wTemp.y, wTemp.z, 0.0) u = double4(uTemp.x, uTemp.y, uTemp.z, 0.0) v = double4(vTemp.x, vTemp.y, vTemp.z, 0.0) lowerLeftCorner = origin - halfWidth * focusDistance * u - halfHeight * focusDistance * v - focusDistance * w horizontal = 2 * halfWidth * focusDistance * u vertical = 2 * halfHeight * focusDistance * v } public func getRay(_ s: Double, _ t: Double) -> Ray { let rd = lensRadius * randomInUnitDisc() let offset = u * rd.x + v * rd.y let time = time0 + drand48() * (time1 - time0) return Ray(origin: origin + offset, direction: lowerLeftCorner + s * horizontal + t * vertical - origin - offset, time: time) } }
mit
a122f8120cf8be2965a5f48419a67438
29.688525
177
0.680021
2.948031
false
false
false
false
avito-tech/Marshroute
Marshroute/Sources/Transitions/PeekAndPopSupport/PeekAndPopData/WeakPeekAndPopData.swift
1
830
import UIKit final class WeakPeekAndPopData: PeekAndPopData { // MARK: - properties weak var peekViewController: UIViewController? weak var sourceViewController: UIViewController? weak var previewingContext: UIViewControllerPreviewing? let peekLocation: CGPoint let popAction: (() -> ()) // MARK: - Init init( peekViewController: UIViewController, sourceViewController: UIViewController, previewingContext: UIViewControllerPreviewing, peekLocation: CGPoint, popAction: @escaping (() -> ())) { self.peekViewController = peekViewController self.sourceViewController = sourceViewController self.previewingContext = previewingContext self.peekLocation = peekLocation self.popAction = popAction } }
mit
45c309b5ec9ec4b5a72501b0ae731715
29.740741
59
0.684337
5.971223
false
false
false
false
white-rabbit-apps/Fusuma
Sources/FusumaViewController.swift
1
13767
// // FusumaViewController.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/14. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit @objc public protocol FusumaDelegate: class { func fusumaImageSelected(image: UIImage, creationDate:NSDate?) optional func fusumaDismissedWithImage(image: UIImage) func fusumaVideoCompleted(withFileURL fileURL: NSURL) func fusumaCameraRollUnauthorized() optional func fusumaClosed() } public var fusumaBaseTintColor = UIColor.hex("#FFFFFF", alpha: 1.0) public var fusumaTintColor = UIColor.hex("#009688", alpha: 1.0) public var fusumaBackgroundColor = UIColor.hex("#212121", alpha: 1.0) public var fusumaAlbumImage : UIImage? = nil public var fusumaCameraImage : UIImage? = nil public var fusumaVideoImage : UIImage? = nil public var fusumaCheckImage : UIImage? = nil public var fusumaCloseImage : UIImage? = nil public var fusumaFlashOnImage : UIImage? = nil public var fusumaFlashOffImage : UIImage? = nil public var fusumaFlipImage : UIImage? = nil public var fusumaShotImage : UIImage? = nil public var fusumaVideoStartImage : UIImage? = nil public var fusumaVideoStopImage : UIImage? = nil public var fusumaCameraRollTitle = "CAMERA ROLL" public var fusumaCameraTitle = "PHOTO" public var fusumaVideoTitle = "VIDEO" public var fusumaTintIcons : Bool = true public enum FusumaModeOrder { case CameraFirst case LibraryFirst } //@objc public class FusumaViewController: UIViewController, FSCameraViewDelegate, FSAlbumViewDelegate { public final class FusumaViewController: UIViewController { enum Mode { case Camera case Library case Video } var mode: Mode = Mode.Camera public var modeOrder: FusumaModeOrder = .LibraryFirst var willFilter = true @IBOutlet weak var photoLibraryViewerContainer: UIView! @IBOutlet weak var cameraShotContainer: UIView! @IBOutlet weak var videoShotContainer: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var menuView: UIView! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var libraryButton: UIButton! @IBOutlet weak var cameraButton: UIButton! @IBOutlet weak var videoButton: UIButton! @IBOutlet weak var doneButton: UIButton! @IBOutlet var libraryFirstConstraints: [NSLayoutConstraint]! @IBOutlet var cameraFirstConstraints: [NSLayoutConstraint]! var albumView = FSAlbumView.instance() var cameraView = FSCameraView.instance() var videoView = FSVideoCameraView.instance() public weak var delegate: FusumaDelegate? = nil override public func loadView() { if let view = UINib(nibName: "FusumaViewController", bundle: NSBundle(forClass: self.classForCoder)).instantiateWithOwner(self, options: nil).first as? UIView { self.view = view } } override public func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = fusumaBackgroundColor cameraView.delegate = self albumView.delegate = self videoView.delegate = self menuView.backgroundColor = fusumaBackgroundColor menuView.addBottomBorder(UIColor.blackColor(), width: 1.0) let bundle = NSBundle(forClass: self.classForCoder) // Get the custom button images if they're set let albumImage = fusumaAlbumImage != nil ? fusumaAlbumImage : UIImage(named: "ic_insert_photo", inBundle: bundle, compatibleWithTraitCollection: nil) let cameraImage = fusumaCameraImage != nil ? fusumaCameraImage : UIImage(named: "ic_photo_camera", inBundle: bundle, compatibleWithTraitCollection: nil) let videoImage = fusumaVideoImage != nil ? fusumaVideoImage : UIImage(named: "ic_videocam", inBundle: bundle, compatibleWithTraitCollection: nil) let checkImage = fusumaCheckImage != nil ? fusumaCheckImage : UIImage(named: "ic_check", inBundle: bundle, compatibleWithTraitCollection: nil) let closeImage = fusumaCloseImage != nil ? fusumaCloseImage : UIImage(named: "ic_close", inBundle: bundle, compatibleWithTraitCollection: nil) if(fusumaTintIcons) { libraryButton.setImage(albumImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) libraryButton.setImage(albumImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Highlighted) libraryButton.setImage(albumImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Selected) libraryButton.tintColor = fusumaTintColor libraryButton.adjustsImageWhenHighlighted = false cameraButton.setImage(cameraImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) cameraButton.setImage(cameraImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Highlighted) cameraButton.setImage(cameraImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Selected) cameraButton.tintColor = fusumaTintColor cameraButton.adjustsImageWhenHighlighted = false closeButton.setImage(closeImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) closeButton.setImage(closeImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Highlighted) closeButton.setImage(closeImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Selected) closeButton.tintColor = fusumaBaseTintColor videoButton.setImage(videoImage, forState: .Normal) videoButton.setImage(videoImage, forState: .Highlighted) videoButton.setImage(videoImage, forState: .Selected) videoButton.tintColor = fusumaTintColor videoButton.adjustsImageWhenHighlighted = false doneButton.setImage(checkImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal) doneButton.tintColor = fusumaBaseTintColor } else { libraryButton.setImage(albumImage, forState: .Normal) libraryButton.setImage(albumImage, forState: .Highlighted) libraryButton.setImage(albumImage, forState: .Selected) libraryButton.tintColor = nil cameraButton.setImage(cameraImage, forState: .Normal) cameraButton.setImage(cameraImage, forState: .Highlighted) cameraButton.setImage(cameraImage, forState: .Selected) cameraButton.tintColor = nil videoButton.setImage(videoImage, forState: .Normal) videoButton.setImage(videoImage, forState: .Highlighted) videoButton.setImage(videoImage, forState: .Selected) videoButton.tintColor = nil closeButton.setImage(closeImage, forState: .Normal) doneButton.setImage(checkImage, forState: .Normal) } cameraButton.clipsToBounds = true libraryButton.clipsToBounds = true videoButton.clipsToBounds = true changeMode(Mode.Library) photoLibraryViewerContainer.addSubview(albumView) cameraShotContainer.addSubview(cameraView) videoShotContainer.addSubview(videoView) titleLabel.textColor = fusumaBaseTintColor // if modeOrder != .LibraryFirst { // libraryFirstConstraints.forEach { $0.priority = 250 } // cameraFirstConstraints.forEach { $0.priority = 1000 } // } } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override public func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) albumView.frame = CGRect(origin: CGPointZero, size: photoLibraryViewerContainer.frame.size) albumView.layoutIfNeeded() cameraView.frame = CGRect(origin: CGPointZero, size: cameraShotContainer.frame.size) cameraView.layoutIfNeeded() videoView.frame = CGRect(origin: CGPointZero, size: videoShotContainer.frame.size) videoView.layoutIfNeeded() albumView.initialize() cameraView.initialize() videoView.initialize() } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.stopAll() } override public func prefersStatusBarHidden() -> Bool { return true } @IBAction func closeButtonPressed(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: { self.delegate?.fusumaClosed?() }) } @IBAction func libraryButtonPressed(sender: UIButton) { changeMode(Mode.Library) } @IBAction func photoButtonPressed(sender: UIButton) { changeMode(Mode.Camera) } @IBAction func videoButtonPressed(sender: UIButton) { changeMode(Mode.Video) } @IBAction func doneButtonPressed(sender: UIButton) { let view = albumView.imageCropView UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0) let context = UIGraphicsGetCurrentContext() CGContextTranslateCTM(context, -albumView.imageCropView.contentOffset.x, -albumView.imageCropView.contentOffset.y) view.layer.renderInContext(context!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let date = albumView.selectedImageCreationDate delegate?.fusumaImageSelected(image, creationDate: date) self.dismissViewControllerAnimated(true, completion: { self.delegate?.fusumaDismissedWithImage?(image) }) } } extension FusumaViewController: FSAlbumViewDelegate, FSCameraViewDelegate, FSVideoCameraViewDelegate { // MARK: FSCameraViewDelegate func cameraShotFinished(image: UIImage) { let date = albumView.selectedImageCreationDate delegate?.fusumaImageSelected(image, creationDate: date) self.dismissViewControllerAnimated(true, completion: { self.delegate?.fusumaDismissedWithImage?(image) }) } // MARK: FSAlbumViewDelegate public func albumViewCameraRollUnauthorized() { delegate?.fusumaCameraRollUnauthorized() } func videoFinished(withFileURL fileURL: NSURL) { delegate?.fusumaVideoCompleted(withFileURL: fileURL) self.dismissViewControllerAnimated(true, completion: nil) } } private extension FusumaViewController { func stopAll() { self.videoView.stopCamera() self.cameraView.stopCamera() } func changeMode(mode: Mode) { if self.mode == mode { return } //operate this switch before changing mode to stop cameras switch self.mode { case .Library: break case .Camera: self.cameraView.stopCamera() case .Video: self.videoView.stopCamera() } self.mode = mode dishighlightButtons() switch mode { case .Library: titleLabel.text = NSLocalizedString(fusumaCameraRollTitle, comment: fusumaCameraRollTitle) doneButton.hidden = false highlightButton(libraryButton) self.view.bringSubviewToFront(photoLibraryViewerContainer) case .Camera: titleLabel.text = NSLocalizedString(fusumaCameraTitle, comment: fusumaCameraTitle) doneButton.hidden = true highlightButton(cameraButton) self.view.bringSubviewToFront(cameraShotContainer) cameraView.startCamera() case .Video: titleLabel.text = fusumaVideoTitle doneButton.hidden = true highlightButton(videoButton) self.view.bringSubviewToFront(videoShotContainer) videoView.startCamera() } self.view.bringSubviewToFront(menuView) } func dishighlightButtons() { cameraButton.tintColor = fusumaBaseTintColor libraryButton.tintColor = fusumaBaseTintColor videoButton.tintColor = fusumaBaseTintColor if cameraButton.layer.sublayers?.count > 1 { for layer in cameraButton.layer.sublayers! { if let borderColor = layer.borderColor where UIColor(CGColor: borderColor) == fusumaTintColor { layer.removeFromSuperlayer() } } } if libraryButton.layer.sublayers?.count > 1 { for layer in libraryButton.layer.sublayers! { if let borderColor = layer.borderColor where UIColor(CGColor: borderColor) == fusumaTintColor { layer.removeFromSuperlayer() } } } if videoButton.layer.sublayers?.count > 1 { for layer in videoButton.layer.sublayers! { if let borderColor = layer.borderColor where UIColor(CGColor: borderColor) == fusumaTintColor { layer.removeFromSuperlayer() } } } } func highlightButton(button: UIButton) { button.tintColor = fusumaTintColor button.addBottomBorder(fusumaTintColor, width: 3) } }
mit
437f058357154adf197fe178857aa9e5
34.937337
168
0.652063
5.647928
false
false
false
false
simonorlovsky/Carl-Energy
Energy/BarGraphView.swift
2
7043
// // DetailConsumptionViewController.swift // Carleton Energy App // 6/8/2015 // // By Hami Abdi, Caleb Braun, and Simon Orlovsky // // A view for representing multiple building's energy data on a bar graph // import UIKit @IBDesignable class BarGraphView: UIView { var buildingNames = [String]() var buildingData = [Double]() override func drawRect(rect: CGRect) { // Graph variables let graphWidth = Double(rect.width) let graphHeight = Double(rect.height) var maxUnit:Double = 0 // Get the current context let context = UIGraphicsGetCurrentContext() // Draw the grid lines UIColor.grayColor().setFill() UIColor.grayColor().setStroke() var gridLinesPath = UIBezierPath() gridLinesPath.moveToPoint(CGPoint(x:50, y:20)) //Add 5 lines for i in 1...5 { let nextPoint = CGPoint(x:(50*i), y:300) gridLinesPath.addLineToPoint(nextPoint) gridLinesPath.moveToPoint(CGPoint(x:50*(i+1), y:20)) } gridLinesPath.stroke() // Add the gridline labels for i in 1...5 { if let labelView = self.viewWithTag(i) as? UILabel { if self.buildingNames.count != 0 { maxUnit = self.buildingData[0] if maxUnit > 0 { var labelNum = Int(maxUnit / 5) * i // floor(self.buildingData[0]/50)*50 labelView.text = "\(labelNum)" } } } } // Draw the graph boundaries UIColor.blackColor().setStroke() var boundaryPath = UIBezierPath() boundaryPath.moveToPoint(CGPoint(x:1, y:graphHeight)) boundaryPath.addLineToPoint(CGPoint(x:1, y:2)) boundaryPath.addLineToPoint(CGPoint(x:graphWidth-1, y:2)) boundaryPath.addLineToPoint(CGPoint(x:graphWidth-1, y:24)) boundaryPath.addLineToPoint(CGPoint(x:1, y:24)) boundaryPath.lineWidth = 2.0 boundaryPath.stroke() // Draw the bars var numBars = 0 for buildingIndex in 0..<self.buildingNames.count { // println("Building: \(buildingName) \n Value: \(value)") let rectanglePath = CGPathCreateMutable() // Set up bar variables let barWidth = 25 var barLength:Double = 0 let top = Double(barWidth+(barWidth*numBars)) let bot = Double((barWidth*2)+(barWidth*numBars)) if maxUnit > 0 { barLength = (graphWidth/maxUnit * self.buildingData[buildingIndex]) * (5/6) } let points = [CGPoint(x:2, y:top), CGPoint(x:2, y:bot), CGPoint(x:barLength, y:bot), CGPoint(x:barLength, y:top)] // Draw the bar var startingPoint = points[0] CGPathMoveToPoint(rectanglePath, nil, startingPoint.x, startingPoint.y) for p in points { CGPathAddLineToPoint(rectanglePath, nil, p.x, p.y) } let barColor = UIColor(red: 0.8353, green: 0.4325, blue: 0.3608, alpha: 1) //rgb = (213,108,92) CGPathCloseSubpath(rectanglePath) CGContextAddPath(context, rectanglePath) CGContextSetFillColorWithColor(context, barColor.CGColor) CGContextFillPath(context) // Make the bar labels – tags start at 6 because the scale values are 1 through 5 let nameTag = 6 + (2*numBars) let valueTag = 7 + (2*numBars) var needNewLabels = true for view in self.subviews as! [UIView] { if let buildingLabel = view as? UILabel { if buildingLabel.tag == 6 + (2*numBars) { buildingLabel.text = "\(self.buildingNames[buildingIndex])" } if buildingLabel.tag == 7 + (2*numBars) { buildingLabel.text = "\(self.buildingData[buildingIndex])" buildingLabel.frame.origin.x = CGFloat(barLength-205) needNewLabels = false } } } if needNewLabels == true { let fontSize:CGFloat = 20 var nameLabel = UILabel(frame: CGRect(x: 5, y: top, width: 200.0, height: 25.0)) nameLabel.tag = nameTag nameLabel.text = "\(self.buildingNames[buildingIndex])" nameLabel.font = UIFont(name: "Avenir Next Condensed", size: fontSize) nameLabel.sizeToFit() var xpos = barLength-205 var textAlign = NSTextAlignment.Right if barLength < graphWidth * 2/3 { xpos = Double(nameLabel.frame.width+20) println(xpos) textAlign = NSTextAlignment.Left } var valueLabel = UILabel(frame: CGRect(x: xpos, y: top, width: 200.0, height: 25.0)) valueLabel.tag = valueTag valueLabel.textAlignment = textAlign valueLabel.text = "\(self.buildingData[buildingIndex])" valueLabel.textColor = UIColor(red: 0.235, green: 0.455, blue: 0.518, alpha: 1) valueLabel.font = UIFont(name: "Avenir Next Condensed-Bold", size: fontSize) self.addSubview(nameLabel) self.addSubview(valueLabel) } // Draw a white line to separate the bars UIColor.whiteColor().setStroke() var boundaryPath = UIBezierPath() boundaryPath.moveToPoint(CGPoint(x:2, y:bot)) boundaryPath.addLineToPoint(CGPoint(x:barLength, y:bot)) boundaryPath.lineWidth = 2.0 boundaryPath.stroke() numBars+=1 } self.setNeedsDisplay() } func loadData(buildingData: [String:[Double]]) { // Sort the dictionary var newDictionary = [String:Double]() for (building, energyValue) in buildingData { newDictionary[building] = round(100 * (energyValue.reduce(0, combine: +))) / 100 } var energyValues = Array(newDictionary.values) energyValues.sort {$0 > $1} self.buildingNames.removeAll(keepCapacity: true) self.buildingData.removeAll(keepCapacity: true) for number in energyValues { for (building, value) in newDictionary { if value == number { self.buildingNames.append(building) self.buildingData.append(value) newDictionary[building] = nil break } } } } }
mit
16cd9ee6ad30b4785cbd2333b7c7ed81
37.681319
125
0.531392
4.718499
false
false
false
false
SlimGinz/HomeworkHelper
Homework Helper/TeachersViewController.swift
1
3031
// // TeachersViewController.swift // Homework Helper // // Created by Cory Ginsberg on 2/7/15. // Copyright (c) 2015 Boiling Point Development. All rights reserved. // import UIKit import CoreData class TeachersViewController: UIViewController, UITableViewDelegate, PathMenuDelegate, MenuDelegate { let menu = Menu() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() menu.delegate = self menu.createPathMenu() navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) navigationController?.navigationBar.shadowImage = UIImage(named: "purple-shadow") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getCurrentViewController() -> UIViewController { return self } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 1; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } // Override to support editing the table view. func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // 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. } */ }
gpl-2.0
d451d8d8406579a5402a01602259eb3f
34.244186
148
0.669086
5.828846
false
false
false
false
zoeyzhong520/InformationTechnology
InformationTechnology/InformationTechnology/Classes/HomePage首页/DetailView.swift
1
1787
// // DetailView.swift // InformationTechnology // // Created by qianfeng on 16/10/31. // Copyright © 2016年 zzj. All rights reserved. // import UIKit class DetailView: UIViewController,navigationBarProtocol { //点击跳转页面 var webView:UIWebView? var url:NSURL? override func viewDidLoad() { super.viewDidLoad() configUI() } func configUI() { addTitle("科技之窗") //响应用户操作 self.view.userInteractionEnabled = true //点击跳转页面 self.automaticallyAdjustsScrollViewInsets = false webView = UIWebView(frame: CGRect(x: 0, y: 64, width: screenW, height: screenH-64)) let request = NSURLRequest(URL: url!) webView?.loadRequest(request) view.addSubview(webView!) self.navigationController?.navigationBar.tintColor = UIColor(red: 209/255.0, green: 49/255.0, blue: 92/255.0, alpha: 1.0) //添加button //addButton(nil, imageName: "userdetails_back_unselected_night", position: .left, selector: #selector(leftBtnClick)) } func leftBtnClick() { navigationController?.popViewControllerAnimated(true) } 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. } */ }
mit
a096acd219ce625ae5bfc6bed34f2ed1
27
129
0.638249
4.717391
false
false
false
false
brunomorgado/ScrollableAnimation
ScrollableAnimation/Tests/InterpolatorTests.swift
1
13732
// // InterpolatorTests.swift // ScrollableAnimationExample // // Created by Bruno Morgado on 01/01/15. // Copyright (c) 2015 kocomputer. All rights reserved. // import UIKit import XCTest class InterpolatorTests: XCTestCase { let animationController: ScrollableAnimationController = ScrollableAnimationController() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testInterpolatorFactory() { var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100)) let animationDistance = Float(300) var fromValue1 = mockAnimatable.layer.position var toValue1 = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance)) let animatableExpectedPosition = fromValue1 var basicAnimation = self.getMockBasicTranslationFromValue(fromValue1, toValue: toValue1, offsetFunction: TweenBlockEaseOutBounce, withDistance: animationDistance) /***** BasicInterpolator *****/ // BasicValueInterpolator var interpolatorFactory = InterpolatorAbstractFactory.interpolatorFactoryForType(.BasicInterpolatorFactory) var interpolator = interpolatorFactory?.interpolatorForAnimation(basicAnimation, animatable: mockAnimatable.layer) if let interpolator = interpolator { XCTAssertTrue(interpolator is BasicValueInterpolator) } else { XCTAssertTrue(false) } // BasicNumberInterpolator let fromValue2 = Float(1.0) let toValue2 = Float(0.0) basicAnimation = self.getMockBasicOpacityAnimationFromValue(fromValue2, toValue: toValue2, offsetFunction: TweenBlockEaseInQuad, withDistance: animationDistance) interpolator = interpolatorFactory?.interpolatorForAnimation(basicAnimation, animatable: mockAnimatable.layer) if let interpolator = interpolator { XCTAssertTrue(interpolator is BasicNumberInterpolator) } else { XCTAssertTrue(false) } /***** KeyframeInterpolator *****/ // KeyframeValueInterpolator let values1: [AnyObject] = [NSValue(CGPoint: CGPointZero),NSValue(CGPoint: CGPointZero)] let keyOffsets1 = [Float(0.0),Float(1.0)] var keyFrameAnimation = self.getMockKeyframeTranslationWithValues(values1, keyOffsets: keyOffsets1, functions: nil, withDistance: animationDistance) interpolatorFactory = InterpolatorAbstractFactory.interpolatorFactoryForType(.KeyframeInterpolatorFactory) interpolator = interpolatorFactory?.interpolatorForAnimation(keyFrameAnimation, animatable: mockAnimatable.layer) if let interpolator = interpolator { XCTAssertTrue(interpolator is KeyframeValueInterpolator) } else { XCTAssertTrue(false) } // KeyframeNumberInterpolator let values2 = [Float(0.0), Float(1.0)] let keyOffsets2 = [Float(0.0), Float(1.0)] keyFrameAnimation = self.getMockKeyframeOpacityAnimationWithValues(values2, keyOffsets: keyOffsets2, functions: nil, withDistance: animationDistance) interpolator = interpolatorFactory?.interpolatorForAnimation(keyFrameAnimation, animatable: mockAnimatable.layer) if let interpolator = interpolator { XCTAssertTrue(interpolator is KeyframeNumberInterpolator) } else { XCTAssertTrue(false) } } func testBasicNumberInterpolator () { let animation = self.getMockBasicOpacityAnimationFromValue(1.0, toValue: 0.0, offsetFunction: TweenBlockEaseInQuad, withDistance: 800) let animatable = UIView(frame: CGRectMake(0, 0, 100, 100)) animatable.layer.addScrollableAnimation(animation, forKey: "opacityAnimation", withController: animationController) let completionExpectation1 = expectationWithDescription("finished1") let completionExpectation2 = expectationWithDescription("finished2") let completionExpectation3 = expectationWithDescription("finished3") let completionExpectation4 = expectationWithDescription("finished4") animationController.updateAnimatablesForOffset(animation.beginOffset - 100) { XCTAssertEqual(animatable.layer.opacity, animation.fromValue as Float) completionExpectation1.fulfill() } animationController.updateAnimatablesForOffset(animation.beginOffset) { XCTAssertEqual(animatable.layer.opacity, animation.fromValue as Float) completionExpectation2.fulfill() } animationController.updateAnimatablesForOffset(animation.distance) { XCTAssertEqual(animatable.layer.opacity, animation.toValue as Float) completionExpectation3.fulfill() } animationController.updateAnimatablesForOffset(animation.distance + 100) { XCTAssertEqual(animatable.layer.opacity, animation.toValue as Float) completionExpectation4.fulfill() } waitForExpectationsWithTimeout(2, { error in XCTAssertNil(error, "Error") }) } func testBasicValueInterpolator () { let animatable = UIView(frame: CGRectMake(0, 0, 100, 100)) let animation = self.getMockBasicTranslationFromValue(animatable.layer.position, toValue: CGPointMake(animatable.layer.position.x, animatable.layer.position.y + 100), offsetFunction: TweenBlockEaseOutElastic, withDistance: 800) animatable.layer.addScrollableAnimation(animation, forKey: "translationAnimation", withController: animationController) let completionExpectation1 = expectationWithDescription("finished1") let completionExpectation2 = expectationWithDescription("finished2") let completionExpectation3 = expectationWithDescription("finished3") let completionExpectation4 = expectationWithDescription("finished4") animationController.updateAnimatablesForOffset(animation.beginOffset - 100) { XCTAssertEqual(animatable.layer.position, animation.fromValue!.CGPointValue()) completionExpectation1.fulfill() } animationController.updateAnimatablesForOffset(animation.beginOffset) { XCTAssertEqual(animatable.layer.position, animation.fromValue!.CGPointValue()) completionExpectation2.fulfill() } animationController.updateAnimatablesForOffset(animation.distance) { XCTAssertEqual(animatable.layer.position, animation.toValue!.CGPointValue()) completionExpectation3.fulfill() } animationController.updateAnimatablesForOffset(animation.distance + 100) { XCTAssertEqual(animatable.layer.position, animation.toValue!.CGPointValue()) completionExpectation4.fulfill() } waitForExpectationsWithTimeout(2, { error in XCTAssertNil(error, "Error") }) } func testKeyframeNumberInterpolator () { let animatable = UIView(frame: CGRectMake(0, 0, 100, 100)) let animation = self.getMockKeyframeOpacityAnimationWithValues([Float(0.0), Float(1.0)], keyOffsets: [Float(0.0), Float(1.0)], functions: [TweenBlockEaseOutExpo], withDistance: 800) animatable.layer.addScrollableAnimation(animation, forKey: "opacity", withController: animationController) let completionExpectation1 = expectationWithDescription("finished1") let completionExpectation2 = expectationWithDescription("finished2") let completionExpectation3 = expectationWithDescription("finished3") let completionExpectation4 = expectationWithDescription("finished4") animationController.updateAnimatablesForOffset(animation.beginOffset - 100) { XCTAssertEqual(animatable.layer.opacity, animation.values![0] as Float) completionExpectation1.fulfill() } animationController.updateAnimatablesForOffset(animation.beginOffset) { XCTAssertEqual(animatable.layer.opacity, animation.values![0] as Float) completionExpectation2.fulfill() } animationController.updateAnimatablesForOffset(animation.distance) { XCTAssertEqual(animatable.layer.opacity, animation.values![animation.values!.count - 1] as Float) completionExpectation3.fulfill() } animationController.updateAnimatablesForOffset(animation.distance + 100) { XCTAssertEqual(animatable.layer.opacity, animation.values![animation.values!.count - 1] as Float) completionExpectation4.fulfill() } waitForExpectationsWithTimeout(2, { error in XCTAssertNil(error, "Error") }) } func testKeyframeValueInterpolator () { let animatable = UIView(frame: CGRectMake(0, 0, 100, 100)) let animation = self.getMockKeyframeTranslationWithValues([NSValue(CGPoint: animatable.layer.position),NSValue(CGPoint: CGPointMake(animatable.layer.position.x, animatable.layer.position.y + 200))], keyOffsets: [Float(0.0),Float(1.0)], functions: [TweenBlockEaseOutExpo], withDistance: 800) animatable.layer.addScrollableAnimation(animation, forKey: "position", withController: animationController) let completionExpectation1 = expectationWithDescription("finished1") let completionExpectation2 = expectationWithDescription("finished2") let completionExpectation3 = expectationWithDescription("finished3") let completionExpectation4 = expectationWithDescription("finished4") animationController.updateAnimatablesForOffset(animation.beginOffset - 100) { XCTAssertEqual(animatable.layer.position, animation.values![0].CGPointValue()) completionExpectation1.fulfill() } animationController.updateAnimatablesForOffset(animation.beginOffset) { XCTAssertEqual(animatable.layer.position, animation.values![0].CGPointValue()) completionExpectation2.fulfill() } animationController.updateAnimatablesForOffset(animation.distance) { XCTAssertEqual(animatable.layer.position, animation.values![animation.values!.count - 1].CGPointValue()) completionExpectation3.fulfill() } animationController.updateAnimatablesForOffset(animation.distance + 100) { XCTAssertEqual(animatable.layer.position, animation.values![animation.values!.count - 1].CGPointValue()) completionExpectation4.fulfill() } waitForExpectationsWithTimeout(2, { error in XCTAssertNil(error, "Error") }) } // MARK: - Helper methods private func getMockBasicTranslationFromValue(fromValue: CGPoint, toValue: CGPoint, offsetFunction: TweenBlock, withDistance distance: Float) -> ScrollableBasicAnimation { let animation = ScrollableBasicAnimation(keyPath: "position") animation.beginOffset = 0 animation.distance = distance animation.fromValue = NSValue(CGPoint: fromValue) animation.toValue = NSValue(CGPoint: toValue) animation.offsetFunction = offsetFunction return animation } private func getMockBasicOpacityAnimationFromValue(fromValue: Float, toValue: Float, offsetFunction: TweenBlock, withDistance distance: Float) -> ScrollableBasicAnimation { let animation = ScrollableBasicAnimation(keyPath: "opacity") animation.beginOffset = 0 animation.distance = distance animation.fromValue = fromValue animation.toValue = toValue animation.offsetFunction = offsetFunction return animation } private func getMockKeyframeTranslationWithValues(values: [AnyObject]?, keyOffsets: [Float]?, functions: [TweenBlock]?, withDistance distance: Float) -> ScrollableKeyframeAnimation { let animation = ScrollableKeyframeAnimation(keyPath: "position") animation.beginOffset = 0 animation.distance = distance animation.values = values animation.keyOffsets = keyOffsets animation.functions = functions return animation } private func getMockKeyframeRotationWithValues(values: [AnyObject]?, keyOffsets: [Float]?, functions: [TweenBlock]?, withDistance distance: Float) -> ScrollableKeyframeAnimation { let animation = ScrollableKeyframeAnimation(keyPath: "transform.rotation.x") animation.beginOffset = 0 animation.distance = distance animation.values = values animation.keyOffsets = keyOffsets animation.functions = functions return animation } private func getMockKeyframeOpacityAnimationWithValues(values: [AnyObject]?, keyOffsets: [Float]?, functions: [TweenBlock]?, withDistance distance: Float) -> ScrollableKeyframeAnimation { let animation = ScrollableKeyframeAnimation(keyPath: "opacity") animation.beginOffset = 0 animation.distance = distance animation.values = values animation.keyOffsets = keyOffsets animation.functions = functions return animation } }
mit
ec65fc70815a9d6dba22923cfbaeda5a
46.351724
298
0.695165
5.577579
false
false
false
false
onevcat/Kingfisher
Sources/General/KingfisherError.swift
7
22596
// // KingfisherError.swift // Kingfisher // // Created by onevcat on 2018/09/26. // // Copyright (c) 2019 Wei Wang <[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 Foundation extension Never {} /// Represents all the errors which can happen in Kingfisher framework. /// Kingfisher related methods always throw a `KingfisherError` or invoke the callback with `KingfisherError` /// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog, /// then switch over the reason to know error detail. public enum KingfisherError: Error { // MARK: Error Reason Types /// Represents the error reason during networking request phase. /// /// - emptyRequest: The request is empty. Code 1001. /// - invalidURL: The URL of request is invalid. Code 1002. /// - taskCancelled: The downloading task is cancelled by user. Code 1003. public enum RequestErrorReason { /// The request is empty. Code 1001. case emptyRequest /// The URL of request is invalid. Code 1002. /// - request: The request is tend to be sent but its URL is invalid. case invalidURL(request: URLRequest) /// The downloading task is cancelled by user. Code 1003. /// - task: The session data task which is cancelled. /// - token: The cancel token which is used for cancelling the task. case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken) } /// Represents the error reason during networking response phase. /// /// - invalidURLResponse: The response is not a valid URL response. Code 2001. /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002. /// - URLSessionError: An error happens in the system URL session. Code 2003. /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004. /// - noURLResponse: The task is done but no URL response found. Code 2005. public enum ResponseErrorReason { /// The response is not a valid URL response. Code 2001. /// - response: The received invalid URL response. /// The response is expected to be an HTTP response, but it is not. case invalidURLResponse(response: URLResponse) /// The response contains an invalid HTTP status code. Code 2002. /// - Note: /// By default, status code 200..<400 is recognized as valid. You can override /// this behavior by conforming to the `ImageDownloaderDelegate`. /// - response: The received response. case invalidHTTPStatusCode(response: HTTPURLResponse) /// An error happens in the system URL session. Code 2003. /// - error: The underlying URLSession error object. case URLSessionError(error: Error) /// Data modifying fails on returning a valid data. Code 2004. /// - task: The failed task. case dataModifyingFailed(task: SessionDataTask) /// The task is done but no URL response found. Code 2005. /// - task: The failed task. case noURLResponse(task: SessionDataTask) } /// Represents the error reason during Kingfisher caching system. /// /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001. /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002. /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003. /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004. /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005. /// - imageNotExisting: The requested image does not exist in cache. Code 3006. /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007. /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008. /// - cannotCreateCacheFile: Cannot create the cache file at a certain fileURL under a key. Code 3009. /// - cannotSetCacheFileAttribute: Cannot set file attributes to a cached file. Code 3010. public enum CacheErrorReason { /// Cannot create a file enumerator for a certain disk URL. Code 3001. /// - url: The target disk URL from which the file enumerator should be created. case fileEnumeratorCreationFailed(url: URL) /// Cannot get correct file contents from a file enumerator. Code 3002. /// - url: The target disk URL from which the content of a file enumerator should be got. case invalidFileEnumeratorContent(url: URL) /// The file at target URL exists, but its URL resource is unavailable. Code 3003. /// - error: The underlying error thrown by file manager. /// - key: The key used to getting the resource from cache. /// - url: The disk URL where the target cached file exists. case invalidURLResource(error: Error, key: String, url: URL) /// The file at target URL exists, but the data cannot be loaded from it. Code 3004. /// - url: The disk URL where the target cached file exists. /// - error: The underlying error which describes why this error happens. case cannotLoadDataFromDisk(url: URL, error: Error) /// Cannot create a folder at a given path. Code 3005. /// - path: The disk path where the directory creating operation fails. /// - error: The underlying error which describes why this error happens. case cannotCreateDirectory(path: String, error: Error) /// The requested image does not exist in cache. Code 3006. /// - key: Key of the requested image in cache. case imageNotExisting(key: String) /// Cannot convert an object to data for storing. Code 3007. /// - object: The object which needs be convert to data. case cannotConvertToData(object: Any, error: Error) /// Cannot serialize an image to data for storing. Code 3008. /// - image: The input image needs to be serialized to cache. /// - original: The original image data, if exists. /// - serializer: The `CacheSerializer` used for the image serializing. case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: CacheSerializer) /// Cannot create the cache file at a certain fileURL under a key. Code 3009. /// - fileURL: The url where the cache file should be created. /// - key: The cache key used for the cache. When caching a file through `KingfisherManager` and Kingfisher's /// extension method, it is the resolved cache key based on your input `Source` and the image processors. /// - data: The data to be cached. /// - error: The underlying error originally thrown by Foundation when writing the `data` to the disk file at /// `fileURL`. case cannotCreateCacheFile(fileURL: URL, key: String, data: Data, error: Error) /// Cannot set file attributes to a cached file. Code 3010. /// - filePath: The path of target cache file. /// - attributes: The file attribute to be set to the target file. /// - error: The underlying error originally thrown by Foundation when setting the `attributes` to the disk /// file at `filePath`. case cannotSetCacheFileAttribute(filePath: String, attributes: [FileAttributeKey : Any], error: Error) /// The disk storage of cache is not ready. Code 3011. /// /// This is usually due to extremely lack of space on disk storage, and /// Kingfisher failed even when creating the cache folder. The disk storage will be in unusable state. Normally, /// ask user to free some spaces and restart the app to make the disk storage work again. /// - cacheURL: The intended URL which should be the storage folder. case diskStorageIsNotReady(cacheURL: URL) } /// Represents the error reason during image processing phase. /// /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001. public enum ProcessorErrorReason { /// Image processing fails. There is no valid output image from the processor. Code 4001. /// - processor: The `ImageProcessor` used to process the image or its data in `item`. /// - item: The image or its data content. case processingFailed(processor: ImageProcessor, item: ImageProcessItem) } /// Represents the error reason during image setting in a view related class. /// /// - emptySource: The input resource is empty or `nil`. Code 5001. /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002. /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003. public enum ImageSettingErrorReason { /// The input resource is empty or `nil`. Code 5001. case emptySource /// The resource task is finished, but it is not the one expected now. This usually happens when you set another /// resource on the view without cancelling the current on-going one. The previous setting task will fail with /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task. /// The result of this original task is contained in the associated value. /// Code 5002. /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error /// happens. /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without /// problem. /// - source: The original source value of the task. case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source) /// An error happens during getting data from an `ImageDataProvider`. Code 5003. case dataProviderError(provider: ImageDataProvider, error: Error) /// No more alternative `Source` can be used in current loading process. It means that the /// `.alternativeSources` are used and Kingfisher tried to recovery from the original error, but still /// fails for all the given alternative sources. The associated value holds all the errors encountered during /// the load process, including the original source loading error and all the alternative sources errors. /// Code 5004. case alternativeSourcesExhausted([PropagationError]) } // MARK: Member Cases /// Represents the error reason during networking request phase. case requestError(reason: RequestErrorReason) /// Represents the error reason during networking response phase. case responseError(reason: ResponseErrorReason) /// Represents the error reason during Kingfisher caching system. case cacheError(reason: CacheErrorReason) /// Represents the error reason during image processing phase. case processorError(reason: ProcessorErrorReason) /// Represents the error reason during image setting in a view related class. case imageSettingError(reason: ImageSettingErrorReason) // MARK: Helper Properties & Methods /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not. public var isTaskCancelled: Bool { if case .requestError(reason: .taskCancelled) = self { return true } return false } /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the /// associated value is a given status code. /// /// - Parameter code: The given status code. /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error /// and its status code equals to `code`, `true` is returned. Otherwise, `false`. public func isInvalidResponseStatusCode(_ code: Int) -> Bool { if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self { return response.statusCode == code } return false } public var isInvalidResponseStatusCode: Bool { if case .responseError(reason: .invalidHTTPStatusCode) = self { return true } return false } /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not. /// When a new image setting task starts while the old one is still running, the new task identifier will be /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes /// to let you know the setting process finishes with a certain result, but the image view or button is not set. public var isNotCurrentTask: Bool { if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self { return true } return false } var isLowDataModeConstrained: Bool { if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), case .responseError(reason: .URLSessionError(let sessionError)) = self, let urlError = sessionError as? URLError, urlError.networkUnavailableReason == .constrained { return true } return false } } // MARK: - LocalizedError Conforming extension KingfisherError: LocalizedError { /// A localized message describing what error occurred. public var errorDescription: String? { switch self { case .requestError(let reason): return reason.errorDescription case .responseError(let reason): return reason.errorDescription case .cacheError(let reason): return reason.errorDescription case .processorError(let reason): return reason.errorDescription case .imageSettingError(let reason): return reason.errorDescription } } } // MARK: - CustomNSError Conforming extension KingfisherError: CustomNSError { /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain. public static let domain = "com.onevcat.Kingfisher.Error" /// The error code within the given domain. public var errorCode: Int { switch self { case .requestError(let reason): return reason.errorCode case .responseError(let reason): return reason.errorCode case .cacheError(let reason): return reason.errorCode case .processorError(let reason): return reason.errorCode case .imageSettingError(let reason): return reason.errorCode } } } extension KingfisherError.RequestErrorReason { var errorDescription: String? { switch self { case .emptyRequest: return "The request is empty or `nil`." case .invalidURL(let request): return "The request contains an invalid or empty URL. Request: \(request)." case .taskCancelled(let task, let token): return "The session task was cancelled. Task: \(task), cancel token: \(token)." } } var errorCode: Int { switch self { case .emptyRequest: return 1001 case .invalidURL: return 1002 case .taskCancelled: return 1003 } } } extension KingfisherError.ResponseErrorReason { var errorDescription: String? { switch self { case .invalidURLResponse(let response): return "The URL response is invalid: \(response)" case .invalidHTTPStatusCode(let response): return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)." case .URLSessionError(let error): return "A URL session error happened. The underlying error: \(error)" case .dataModifyingFailed(let task): return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)." case .noURLResponse(let task): return "No URL response received. Task: \(task)," } } var errorCode: Int { switch self { case .invalidURLResponse: return 2001 case .invalidHTTPStatusCode: return 2002 case .URLSessionError: return 2003 case .dataModifyingFailed: return 2004 case .noURLResponse: return 2005 } } } extension KingfisherError.CacheErrorReason { var errorDescription: String? { switch self { case .fileEnumeratorCreationFailed(let url): return "Cannot create file enumerator for URL: \(url)." case .invalidFileEnumeratorContent(let url): return "Cannot get contents from the file enumerator at URL: \(url)." case .invalidURLResource(let error, let key, let url): return "Cannot get URL resource values or data for the given URL: \(url). " + "Cache key: \(key). Underlying error: \(error)" case .cannotLoadDataFromDisk(let url, let error): return "Cannot load data from disk at URL: \(url). Underlying error: \(error)" case .cannotCreateDirectory(let path, let error): return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)" case .imageNotExisting(let key): return "The image is not in cache, but you requires it should only be " + "from cache by enabling the `.onlyFromCache` option. Key: \(key)." case .cannotConvertToData(let object, let error): return "Cannot convert the input object to a `Data` object when storing it to disk cache. " + "Object: \(object). Underlying error: \(error)" case .cannotSerializeImage(let image, let originalData, let serializer): return "Cannot serialize an image due to the cache serializer returning `nil`. " + "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " + "serializer: \(serializer)." case .cannotCreateCacheFile(let fileURL, let key, let data, let error): return "Cannot create cache file at url: \(fileURL), key: \(key), data length: \(data.count). " + "Underlying foundation error: \(error)." case .cannotSetCacheFileAttribute(let filePath, let attributes, let error): return "Cannot set file attribute for the cache file at path: \(filePath), attributes: \(attributes)." + "Underlying foundation error: \(error)." case .diskStorageIsNotReady(let cacheURL): return "The disk storage is not ready to use yet at URL: '\(cacheURL)'. " + "This is usually caused by extremely lack of disk space. Ask users to free up some space and restart the app." } } var errorCode: Int { switch self { case .fileEnumeratorCreationFailed: return 3001 case .invalidFileEnumeratorContent: return 3002 case .invalidURLResource: return 3003 case .cannotLoadDataFromDisk: return 3004 case .cannotCreateDirectory: return 3005 case .imageNotExisting: return 3006 case .cannotConvertToData: return 3007 case .cannotSerializeImage: return 3008 case .cannotCreateCacheFile: return 3009 case .cannotSetCacheFileAttribute: return 3010 case .diskStorageIsNotReady: return 3011 } } } extension KingfisherError.ProcessorErrorReason { var errorDescription: String? { switch self { case .processingFailed(let processor, let item): return "Processing image failed. Processor: \(processor). Processing item: \(item)." } } var errorCode: Int { switch self { case .processingFailed: return 4001 } } } extension KingfisherError.ImageSettingErrorReason { var errorDescription: String? { switch self { case .emptySource: return "The input resource is empty." case .notCurrentSourceTask(let result, let error, let resource): if let result = result { return "Retrieving resource succeeded, but this source is " + "not the one currently expected. Result: \(result). Resource: \(resource)." } else if let error = error { return "Retrieving resource failed, and this resource is " + "not the one currently expected. Error: \(error). Resource: \(resource)." } else { return nil } case .dataProviderError(let provider, let error): return "Image data provider fails to provide data. Provider: \(provider), error: \(error)" case .alternativeSourcesExhausted(let errors): return "Image setting from alternaive sources failed: \(errors)" } } var errorCode: Int { switch self { case .emptySource: return 5001 case .notCurrentSourceTask: return 5002 case .dataProviderError: return 5003 case .alternativeSourcesExhausted: return 5004 } } }
mit
7d7a09bac298e56aef7bd1af499591f0
48.015184
126
0.662241
4.928244
false
false
false
false
ovh/swift-ovh
Examples/OVHAPIWrapper-Example-watchOS/OVHAPIWrapper-Example-watchOS/OVHVPSTask+CoreDataClass.swift
2
1035
// // OVHVPSTask+CoreDataClass.swift // // // Created by Cyril on 06/12/2016. // // This file was automatically generated and should not be edited. // import Foundation import CoreData public class OVHVPSTask: NSManagedObject { func isFinished() -> Bool { return state != OVHVPSTaskState.todo.rawValue && state != OVHVPSTaskState.doing.rawValue && state != OVHVPSTaskState.waitingAck.rawValue && state != OVHVPSTaskState.paused.rawValue } func isPaused() -> Bool { return state == OVHVPSTaskState.paused.rawValue } } public enum OVHVPSTaskState : String { case blocked, cancelled, doing, done, error, paused, todo, waitingAck } public enum OVHVPSTaskType : String { case addVeeamBackupJob, changeRootPassword, createSnapshot, deleteSnapshot, deliverVm, internalTask, openConsoleAccess, provisioningAdditionalIp, reOpenVm, rebootVm, reinstallVm, removeVeeamBackup, restoreFullVeeamBackup, restoreVeeamBackup, revertSnapshot, setMonitoring, setNetboot, startVm, stopVm, upgradeVm }
bsd-3-clause
4ee8482c0565960842b44a982cbc649e
33.5
315
0.748792
3.819188
false
false
false
false
kaunteya/Linex
Line/SourceEditorCommand.swift
1
5928
// // SourceEditorCommand.swift // Line // // Created by Kaunteya Suryawanshi on 29/08/17. // Copyright © 2017 Kaunteya Suryawanshi. All rights reserved. // import Foundation import XcodeKit enum Options: String { case duplicate, openNewLineBelow, openNewLineAbove, commentedDuplicate, deleteLine, join case lineBeginning } class SourceEditorCommand: NSObject, XCSourceEditorCommand { public func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Swift.Void) { let buffer = invocation.buffer switch Options(command: invocation.commandIdentifier)! { case .duplicate: buffer.selectionRanges.forEach { range in let end = range.end//Required for updating selection let copyOfLines = buffer.lines.objects(at: range.selectedLines) buffer.lines.insert(copyOfLines, at: range.selectedLines) switch range.selection { case .none(_, let column): if column == 0 { range.start.line += 1 range.end.line += 1 } case .words: break case .lines: range.start = end } } case .commentedDuplicate: buffer.selectionRanges.forEach { range in let end = range.end//Required for updating selection let copyOfLines = buffer.lines.objects(at: range.selectedLines) let commentedLines = copyOfLines.map { "//" + ($0 as! String) } buffer.lines.insert(commentedLines, at: range.selectedLines) switch range.selection { case .none(_, let column): if column == 0 { range.start.line += 1 range.end.line += 1 } case .words: break case .lines: range.start = end } } case .openNewLineBelow: buffer.selectionRanges.forEach { range in if range.isSelectionEmpty { let indentationOffset = buffer[range.start.line].indentationOffset let offsetWhiteSpaces = String(repeating: " ", count: indentationOffset) buffer.lines.insert(offsetWhiteSpaces, at: range.start.line + 1) //Selection let position = TextPosition(line: range.start.line + 1, column: indentationOffset) let lineSelection = XCSourceTextRange(start: position, end: position) buffer.selections.setArray([lineSelection]) } } case .openNewLineAbove: buffer.selectionRanges.forEach { range in if range.isSelectionEmpty { let indentationOffset = buffer[range.start.line].indentationOffset let offsetWhiteSpaces = String(repeating: " ", count: indentationOffset) buffer.lines.insert(offsetWhiteSpaces, at: range.start.line) //Selection let position = TextPosition(line: range.start.line, column: indentationOffset) let lineSelection = XCSourceTextRange(start: position, end: position) buffer.selections.setArray([lineSelection]) } } case .deleteLine: buffer.selectionRanges.forEach { range in switch range.selection { case .none, .words: buffer.lines.removeObject(at: range.start.line) case .lines: break } } case .join: buffer.selectionRanges.forEach { range in switch range.selection { case .none(let line, _): if line == buffer.lines.count { return } let caretOffset = buffer[line].count + 1 let lineIndexSet = IndexSet(arrayLiteral: line, line + 1) let lines = buffer[lineIndexSet] var joinedLine = lines.joined(separator: " ", trimming: .whitespacesAndNewlines) joinedLine.indent(by: lines.first!.indentationOffset) buffer.lines.replaceObject(at: line, with: joinedLine) buffer.lines.removeObject(at: line + 1) //Selection/CaretPosition range.start.column = caretOffset range.end.column = caretOffset case .words: break case .lines: let lines = buffer[range.selectedLines] var joinedLine = lines.joined(separator: " ", trimming: .whitespacesAndNewlines) joinedLine.indent(by: lines.first!.indentationOffset) buffer.lines.removeObjects(at: range.selectedLines) buffer.lines.insert(joinedLine, at: range.start.line) //Selection/CaretPosition range.end.line = range.start.line range.end.column = joinedLine.count } } case .lineBeginning: buffer.selectionRanges.forEach { range in switch range.selection { case .none(let line, let column): let indentationOffset = buffer[line].indentationOffset if column == indentationOffset { range.start.column = 0; range.end.column = 0; } else { range.start.column = indentationOffset; range.end.column = indentationOffset; } case .words, .lines: break } } } defer { completionHandler(nil) } } }
mit
5fc57ebe90e3e0182dc31a23f069f4a4
37.23871
102
0.537878
5.21743
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Helpers/UIFont+Weight.swift
1
1551
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit public extension UIFont { /// Returns a font object that is the same as the receiver but which has the specified weight func withWeight(_ weight: Weight) -> UIFont { // Remove bold trait since we will modify the weight var symbolicTraits = fontDescriptor.symbolicTraits symbolicTraits.remove(.traitBold) var traits = fontDescriptor.fontAttributes[.traits] as? [String: Any] ?? [:] traits[kCTFontWeightTrait as String] = weight traits[kCTFontSymbolicTrait as String] = symbolicTraits.rawValue var fontAttributes: [UIFontDescriptor.AttributeName: Any] = [:] fontAttributes[.family] = familyName fontAttributes[.traits] = traits return UIFont(descriptor: UIFontDescriptor(fontAttributes: fontAttributes), size: pointSize) } }
gpl-3.0
d86421cfef3e683411a70c1cd6d55c44
35.928571
100
0.720181
4.772308
false
false
false
false
Snail93/iOSDemos
SnailSwiftDemos/SnailSwiftDemos/ThirdFrameworks/ViewControllers/SQliteSwiftViewController.swift
2
6331
// // SQliteSwiftViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2016/11/29. // Copyright © 2016年 Snail. All rights reserved. // import UIKit class SQliteSwiftViewController: CustomViewController,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate { @IBOutlet weak var aTableView: UITableView! var updateAlertView : UIAlertView! var addAlertView : UIAlertView! var peoples = [People]() var updatedIndexPath : NSIndexPath! var updatedPeople : People! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initView() getData() } func initView() { rightBtn.isHidden = false navTitleLabel.text = "SQLite.swift" aTableView.register(UITableViewCell.self, forCellReuseIdentifier: "SQLiteCell") } func getData() { peoples = SQLiteSwiftManager.shared.allPeoples() aTableView.reloadData() } override func rightAction() { super.rightAction() addAlertView = UIAlertView(title: "新建资料", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定") //两个输入框 addAlertView.alertViewStyle = .loginAndPasswordInput addAlertView.textField(at: 1)?.isSecureTextEntry = false addAlertView.textField(at: 0)?.placeholder = "请输入姓名" addAlertView.textField(at: 1)?.placeholder = "请输入年龄" addAlertView.textField(at: 1)?.keyboardType = .numberPad addAlertView.show() } //MARK: - UIAlertViewDelegate methods func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { if addAlertView != nil && alertView == addAlertView { if buttonIndex == 1{ let name = alertView.textField(at: 0)?.text let age = Int((alertView.textField(at: 1)?.text)!) let people = People(n: name!, a: age!) let rowId = SQLiteSwiftManager.shared.insertWithPeople(people: people) if rowId > 0{ people.id = rowId peoples.append(people) aTableView.reloadData() }else{ return } } }else{ if buttonIndex == 1 { if SQLiteSwiftManager.shared.updatePeople(people: updatedPeople) { }else{ print("修改失败") } } } } func initUpdateAlertView() { updateAlertView = UIAlertView(title: "新建资料", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定") updatedPeople = peoples[updatedIndexPath.row] //两个输入框 updateAlertView.alertViewStyle = .loginAndPasswordInput updateAlertView.textField(at: 1)?.isSecureTextEntry = false updateAlertView.textField(at: 0)?.placeholder = "请输入姓名" updateAlertView.textField(at: 1)?.placeholder = "请输入年龄" updateAlertView.textField(at: 0)?.text = updatedPeople.name updateAlertView.textField(at: 1)?.text = "\(updatedPeople.age)" updateAlertView.textField(at: 1)?.keyboardType = .numberPad updateAlertView.show() } func alertView(_ alertView: UIAlertView, willDismissWithButtonIndex buttonIndex: Int) { print("willDismissWithButtonIndex") } func alertViewCancel(_ alertView: UIAlertView) { print("alertViewCancel") } func alertView(_ alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if updateAlertView != nil { if buttonIndex == 1 && alertView == updateAlertView{ updatedPeople.name = (alertView.textField(at: 0)?.text)! updatedPeople.age = Int((alertView.textField(at: 1)?.text)!)! peoples.remove(at: updatedIndexPath.row) peoples.insert(updatedPeople, at: updatedIndexPath.row) aTableView.reloadData() } } print("didDismissWithButtonIndex") } //MARK: - UITableViewDelegate methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return peoples.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SQLiteCell", for: indexPath) let people = peoples[indexPath.row] cell.textLabel?.text = people.name return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } //MARK: - 添加Cell的侧滑相关方法 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { var actions = [UITableViewRowAction]() let deleteAction = UITableViewRowAction(style: .default, title: "删除"){ (action : UITableViewRowAction, indexP : IndexPath) -> Void in let people = self.peoples[indexPath.row] if SQLiteSwiftManager.shared.deletePeopleWithId(pId: people.id) { print("删除成功") self.peoples.remove(at: indexPath.row) } //TODO:刷新指定组 tableView.reloadSections([indexPath.section], with: .none) } deleteAction.backgroundColor = UIColor.red actions.append(deleteAction) let updateAction = UITableViewRowAction(style: .default, title: "修改"){ (action : UITableViewRowAction, indexP : IndexPath) -> Void in self.updatedIndexPath = indexPath as NSIndexPath! self.initUpdateAlertView() } updateAction.backgroundColor = UIColor.green actions.append(updateAction) return actions } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
7216b94d7d075d63cd4a8732c28d848f
35.163743
131
0.614812
5.106524
false
false
false
false
knutigro/AppReviews
AppReviews/AppDelegate.swift
1
4096
// // AppDelegate.swift // App Reviews // // Created by Knut Inge Grosland on 2015-04-08. // Copyright (c) 2015 Cocmoc. All rights reserved. // import Cocoa import AppKit import SimpleCocoaAnalytics import Fabric import Crashlytics import Sparkle @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { lazy var applicationWindowController: NSWindowController = self.initialApplicationWindowController() lazy var aboutWindowController: NSWindowController = self.initialAboutWindowController() lazy var reviewsWindowController: ReviewWindowController = self.initialReviewWindowController() lazy var launchWindowController: NSWindowController = self.initialLaunchWindowController() var statusMenuController: StatusMenuController! // MARK: Application Process func applicationDidFinishLaunching(aNotification: NSNotification) { // Fabric CrashAlytics Fabric.with([Crashlytics()]) NSUserDefaults.standardUserDefaults().registerDefaults(["NSApplicationCrashOnExceptions": true]) // Google Analytics let analyticsHelper = AnalyticsHelper.sharedInstance() analyticsHelper.recordScreenWithName("Launch") analyticsHelper.beginPeriodicReportingWithAccount("UA-62792522-3", name: "App Reviews OSX", version: NSApplication.v_versionBuild()) // Create ReviewManager shared object _ = ReviewManager.start() if NSUserDefaults.review_isFirstLaunch() { NSUserDefaults.review_setDidLaunch() // As default set launch at startup NSApplication.setShouldLaunchAtStartup(true) } // Create StatusMenu statusMenuController = StatusMenuController() // Show Launchscreen if NSUserDefaults.review_shouldShowLaunchScreen() { self.launchWindowController.showWindow(self) NSApp.activateIgnoringOtherApps(true) } // Initialize Sparkle and do a first check // Since App Reviews is meant to run in background I want // to force the updater to start allready at first App Launch SUUpdater.sharedUpdater().checkForUpdatesInBackground() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application AnalyticsHelper.sharedInstance().handleApplicationWillClose() NSUserDefaults.standardUserDefaults().synchronize() } func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { // Saves changes in the application's managed object context before the application terminates. ReviewManager.saveContext() return .TerminateNow } } // MARK: WindowControllers extension AppDelegate { func initialLaunchWindowController() -> NSWindowController { let storyboard = NSStoryboard(name: "Main", bundle: nil) let windowController = storyboard.instantiateControllerWithIdentifier("LaunchWindowController") as! NSWindowController return windowController } func initialApplicationWindowController() -> NSWindowController { let storyboard = NSStoryboard(name: "Main", bundle: nil) let windowController = storyboard.instantiateControllerWithIdentifier("ApplicationWindowController") as! NSWindowController return windowController } func initialReviewWindowController() -> ReviewWindowController { let storyboard = NSStoryboard(name: "Main", bundle: nil) let windowController = storyboard.instantiateControllerWithIdentifier("ReviewWindowsController") as! ReviewWindowController return windowController } func initialAboutWindowController() -> NSWindowController { let storyboard = NSStoryboard(name: "Main", bundle: nil) let windowController = storyboard.instantiateControllerWithIdentifier("AboutWindowController") as! NSWindowController return windowController } }
gpl-3.0
2d273691490283c1fec0836a5e739e3e
36.236364
140
0.714111
6.14093
false
false
false
false
hzy87email/actor-platform
actor-apps/app-ios/ActorApp/Controllers/User/UserViewController.swift
3
10097
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class UserViewController: AATableViewController { private let UserInfoCellIdentifier = "UserInfoCellIdentifier" private let TitledCellIdentifier = "TitledCellIdentifier" let uid: Int var user: ACUserVM? var phones: JavaUtilArrayList? var binder = Binder() var tableData: UATableData! init(uid: Int) { self.uid = uid super.init(style: UITableViewStyle.Plain) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func viewDidLoad() { super.viewDidLoad() user = Actor.getUserWithUid(jint(uid)) self.edgesForExtendedLayout = UIRectEdge.Top self.automaticallyAdjustsScrollViewInsets = false tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.backgroundColor = MainAppTheme.list.backyardColor tableView.clipsToBounds = false tableView.tableFooterView = UIView() tableData = UATableData(tableView: tableView) tableData.registerClass(UserPhotoCell.self, forCellReuseIdentifier: UserInfoCellIdentifier) tableData.registerClass(TitledCell.self, forCellReuseIdentifier: TitledCellIdentifier) tableData.tableScrollClosure = { (tableView: UITableView) -> () in self.applyScrollUi(tableView) } // Avatar tableData.addSection().addCustomCell { (tableView, indexPath) -> UITableViewCell in let cell: UserPhotoCell = tableView.dequeueReusableCellWithIdentifier(self.UserInfoCellIdentifier, forIndexPath: indexPath) as! UserPhotoCell cell.contentView.superview?.clipsToBounds = false if self.user != nil { cell.setUsername(self.user!.getNameModel().get()) } self.applyScrollUi(tableView, cell: cell) return cell }.setHeight(avatarHeight) // Top section let contactsSection = tableData .addSection(true) .setFooterHeight(15) // Send Message if (!user!.isBot().boolValue) { contactsSection .addActionCell("ProfileSendMessage", actionClosure: { () -> () in self.navigateDetail(ConversationViewController(peer: ACPeer.userWithInt(jint(self.uid)))) self.popover?.dismissPopoverAnimated(true) }) } let nick = user!.getNickModel().get() if nick != nil { contactsSection .addTitledCell(localized("ProfileUsername"), text: "@\(nick)") } let about = user!.getAboutModel().get() if about != nil { contactsSection .addTextCell(localized("ProfileAbout"), text: about) } // Phones contactsSection .addCustomCells(55, countClosure: { () -> Int in if (self.phones != nil) { return Int(self.phones!.size()) } return 0 }) { (tableView, index, indexPath) -> UITableViewCell in let cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell if let phone = self.phones!.getWithInt(jint(index)) as? ACUserPhone { cell.setTitle(phone.getTitle(), content: "+\(phone.getPhone())") } return cell }.setAction { (index) -> () in let phoneNumber = (self.phones?.getWithInt(jint(index)).getPhone())! let hasPhone = UIApplication.sharedApplication().canOpenURL(NSURL(string: "tel://")!) if (!hasPhone) { UIPasteboard.generalPasteboard().string = "+\(phoneNumber)" self.alertUser("NumberCopied") } else { self.showActionSheet(["CallNumber", "CopyNumber"], cancelButton: "AlertCancel", destructButton: nil, sourceView: self.view, sourceRect: self.view.bounds, tapClosure: { (index) -> () in if (index == 0) { UIApplication.sharedApplication().openURL(NSURL(string: "tel://+\(phoneNumber)")!) } else if index == 1 { UIPasteboard.generalPasteboard().string = "+\(phoneNumber)" self.alertUser("NumberCopied") } }) } } tableData.addSection() .setHeaderHeight(15) .setFooterHeight(15) .addCommonCell { (cell) -> () in let peer = ACPeer.userWithInt(jint(self.uid)) cell.setSwitcherOn(Actor.isNotificationsEnabledWithPeer(peer)) cell.switchBlock = { (on: Bool) -> () in if !on && !self.user!.isBot().boolValue { self.confirmAlertUser("ProfileNotificationsWarring", action: "ProfileNotificationsWarringAction", tapYes: { () -> () in Actor.changeNotificationsEnabledWithPeer(peer, withValue: false) }, tapNo: { () -> () in cell.setSwitcherOn(true, animated: true) }) return } Actor.changeNotificationsEnabledWithPeer(peer, withValue: on) } } .setContent("ProfileNotifications") .setStyle(.Switch) let contactSection = tableData.addSection(true) .setHeaderHeight(15) .setFooterHeight(15) contactSection .addCommonCell { (cell) -> () in if (self.user!.isContactModel().get().booleanValue()) { cell.setContent(NSLocalizedString("ProfileRemoveFromContacts", comment: "Remove From Contacts")) cell.style = .Destructive } else { cell.setContent(NSLocalizedString("ProfileAddToContacts", comment: "Add To Contacts")) cell.style = .Action } } .setAction { () -> () in if (self.user!.isContactModel().get().booleanValue()) { self.execute(Actor.removeContactCommandWithUid(jint(self.uid))) } else { self.execute(Actor.addContactCommandWithUid(jint(self.uid))) } } // Rename contactSection .addActionCell("ProfileRename", actionClosure: { () -> () in if (!Actor.isRenameHintShown()) { self.confirmAlertUser("ProfileRenameMessage", action: "ProfileRenameAction", tapYes: { () -> () in self.renameUser() }) } else { self.renameUser() } }) // Binding data tableView.reloadData() binder.bind(user!.getAvatarModel(), closure: { (value: ACAvatar?) -> () in if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell { cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), avatar: value) } }) binder.bind(user!.getNameModel(), closure: { ( name: String?) -> () in if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell { cell.setUsername(name!) } self.title = name! }) binder.bind(user!.getPresenceModel(), closure: { (presence: ACUserPresence?) -> () in let presenceText = Actor.getFormatter().formatPresence(presence, withSex: self.user!.getSex()) if presenceText != nil { if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell { cell.setPresence(presenceText) } } }) binder.bind(user!.getPhonesModel(), closure: { (phones: JavaUtilArrayList?) -> () in if phones != nil { self.phones = phones self.tableView.reloadData() } }) binder.bind(user!.isContactModel(), closure: { (contect: ARValueModel?) -> () in self.tableView.reloadSections(NSIndexSet(index: contactSection.index), withRowAnimation: UITableViewRowAnimation.None) }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) applyScrollUi(tableView) navigationController?.navigationBar.shadowImage = UIImage() Actor.onProfileOpenWithUid(jint(uid)) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) Actor.onProfileClosedWithUid(jint(uid)) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.lt_reset() } func renameUser() { textInputAlert("ProfileEditHeader", content: self.user!.getNameModel().get(), action: "AlertSave", tapYes: { (nval) -> () in if nval.length > 0 { self.execute(Actor.editNameCommandWithUid(jint(self.uid), withName: nval)) } }) } }
mit
55654b5af5b4f5a7855f1b790f935d50
39.388
153
0.533426
5.472629
false
false
false
false
CJGitH/QQMusic
QQMusic/Classes/QQList/Controller/QQListTVC.swift
1
3486
// // QQListTVC.swift // QQMusic // // Created by chen on 16/5/16. // Copyright © 2016年 chen. All rights reserved. // import UIKit class QQListTVC: UITableViewController { var musicMs: [QQMusicModel] = [QQMusicModel]() { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // 界面操作 setUpInit() // 需要数据 -> 展示 // 数据怎么获取, 抽成一个工具类 // 好处: 重用性高, QQMusicDataTool.getMusicList { (musicMs) in // 展示数据 self.musicMs = musicMs //给播放工具类进行复制播放列表 QQMusicOperationTool.shareInstance.musicMList = musicMs } } } // 数据展示 extension QQListTVC { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return musicMs.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = QQMusicListCell.cellWithTableView(tableView) // 取出模型 let musicM = musicMs[indexPath.row] cell.musicM = musicM return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { //开始做动画 let currentcell = cell as! QQMusicListCell currentcell.beginAnimation(AnimatonType.Rotation) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //拿到数据模型 let musicM = musicMs[indexPath.row] //根据数据模型,播放音乐 QQMusicOperationTool.shareInstance.playMusic(musicM) //跳转到下一个控制器 performSegueWithIdentifier("listToDetail", sender: nil) } override func scrollViewDidScroll(scrollView: UIScrollView) { guard let indexPaths = tableView.indexPathsForVisibleRows else { return } //计算中间一行对应的索引 let first = indexPaths.first?.row ?? 0 let last = indexPaths.last?.row ?? 0 let middle = Int(Float(first + last) * 0.5) for indexPath in indexPaths { let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.x = CGFloat(abs(indexPath.row - middle) * 20) } } } // 界面搭建 extension QQListTVC { // 提供一个统一界面设置的方法, 供外界调用 private func setUpInit() { setUpTableView() setUpNavigationBar() } private func setUpTableView() -> () { let backView = UIImageView(image: UIImage(named: "QQListBack.jpg")) tableView.backgroundView = backView tableView.rowHeight = 60 tableView.separatorStyle = .None } private func setUpNavigationBar() -> () { navigationController?.navigationBarHidden = true } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
mit
4e2c46185d62c335c660a350f9b7b7c4
21.706294
134
0.562057
5.065523
false
false
false
false
digice/ios-dvm-boilerplate
Location/LocationViewController.swift
1
1612
// // LocationViewController.swift // DVM-Boilerplate // // Created by Digices LLC on 3/31/17. // Copyright © 2017 Digices LLC. All rights reserved. // import UIKit class LocationViewController: UIViewController, LocationManagerDelegate { // MARK: - Properties let manager : LocationManager = LocationManager() // MARK: - Outlets @IBOutlet weak var latitudeLabel: UILabel! @IBOutlet weak var longitudeLabel: UILabel! @IBOutlet weak var toggleButton: UIButton! // MARK: - UIViewController Methods override func viewDidLoad() { super.viewDidLoad() self.manager.delegate = self self.updateView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Custom Methods func updateView() { if let x = self.manager.data.latitude { self.latitudeLabel.text = "\(x)" } if let y = self.manager.data.longitude { self.longitudeLabel.text = "\(y)" } if self.manager.isUpdating == true { self.toggleButton.setTitle("Stop Updating", for: .normal) } else { self.toggleButton.setTitle("Start Updating", for: .normal) self.latitudeLabel.text = "" self.longitudeLabel.text = "" } } // MARK: - Actions @IBAction func toggleStatus(_ sender: Any) { self.manager.toggleStatus() self.updateView() } // MARK: - LocationManagerDelegate Methods func didUpdateLocation() { self.updateView() } func didChangeAuthorizationStatus() { // show alert? } func didSaveLocationData() { // set a message label? // update remote API? } }
mit
cedf05bdbda66a7fd20b977c129d2e73
18.888889
73
0.661701
4.25066
false
false
false
false
LYM-mg/DemoTest
其他功能/MGImagePickerControllerTest/MGImagePickerControllerTest/ImagePickerController/MGPhotosBrowseCell.swift
1
5715
// // MGPhotosBrowseCell.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/8. // Copyright © 2019 MG. All rights reserved. // import UIKit class MGPhotosBrowseCell: UICollectionViewCell { // MARK: public /// 显示图片的imageView lazy var mg_imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() /// 单击执行的闭包 var mg_photoBrowerSimpleTapHandle: ((Any) -> Void)? // MARK: private /// 是否已经缩放 fileprivate var isScale = false /// 底部负责缩放的滚动视图 lazy fileprivate var mg_scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.backgroundColor = .black scrollView.minimumZoomScale = CGFloat(self.minScaleZoome) scrollView.maximumZoomScale = CGFloat(self.maxScaleZoome) scrollView.delegate = self return scrollView }() /// 单击手势 lazy fileprivate var mg_simpleTap: UITapGestureRecognizer = { let simpleTap = UITapGestureRecognizer() simpleTap.numberOfTapsRequired = 1 simpleTap.require(toFail: self.mg_doubleTap) //设置响应 simpleTap.action({[weak self] (_) in if let strongSelf = self { if strongSelf.mg_photoBrowerSimpleTapHandle != nil { //执行闭包 strongSelf.mg_photoBrowerSimpleTapHandle?(strongSelf) } } /********** 此处不再返回原始比例,如需此功能,请清除此处注释 2019/7/8 ***********/ /* if strongSelf!.mg_scrollView.zoomScale != 1.0 { strongSelf!.mg_scrollView.setZoomScale(1.0, animated: true) } */ /*************************************************************************/ }) return simpleTap }() /// 双击手势 lazy fileprivate var mg_doubleTap: UITapGestureRecognizer = { let doubleTap = UITapGestureRecognizer() doubleTap.numberOfTapsRequired = 2 doubleTap.action({ [weak self](sender) in let strongSelf = self //表示需要缩放成1.0 guard strongSelf!.mg_scrollView.zoomScale == 1.0 else { strongSelf!.mg_scrollView.setZoomScale(1.0, animated: true); return } //进行放大 let width = strongSelf!.frame.width let scale = width / CGFloat(strongSelf!.maxScaleZoome) let point = sender.location(in: strongSelf!.mg_imageView) //对点进行处理 let originX = max(0, point.x - width / scale) let originY = max(0, point.y - width / scale) //进行位置的计算 let rect = CGRect(x: originX, y: originY, width: width / scale, height: width / scale) //进行缩放 strongSelf!.mg_scrollView.zoom(to: rect, animated: true) }) return doubleTap }() /// 最小缩放比例 fileprivate let minScaleZoome = 1.0 /// 最大缩放比例 fileprivate let maxScaleZoome = 2.0 override init(frame: CGRect) { super.init(frame: frame) addAndLayoutSubViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() addAndLayoutSubViews() } fileprivate func addAndLayoutSubViews() { contentView.addSubview(mg_scrollView) mg_scrollView.addSubview(mg_imageView) mg_scrollView.addGestureRecognizer(mg_simpleTap) mg_scrollView.addGestureRecognizer(mg_doubleTap) mg_scrollView.translatesAutoresizingMaskIntoConstraints = false mg_scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true mg_scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true mg_scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true mg_scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true mg_imageView.translatesAutoresizingMaskIntoConstraints = false mg_imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true mg_imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true mg_imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true mg_imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true mg_imageView.widthAnchor.constraint(equalTo: mg_scrollView.widthAnchor).isActive = true mg_imageView.heightAnchor.constraint(equalTo: mg_scrollView.heightAnchor).isActive = true //layout // mg_scrollView.snp.makeConstraints { (make) in // make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)) // } // // mg_imageView.snp.makeConstraints { [weak self](make) in // let strongSelf = self // make.edges.equalToSuperview() // make.width.equalTo(strongSelf!.mg_scrollView.snp.width) // make.height.equalTo(strongSelf!.mg_scrollView.snp.height) // } } } extension MGPhotosBrowseCell: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return mg_imageView } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { scrollView.setZoomScale(scale, animated: true) } }
mit
0664c7bb2fe8f4f6ab9133e1a6e9d35e
29.703911
106
0.621543
4.709512
false
false
false
false
magnetsystems/message-samples-ios
QuickStart/QuickStart/UserSearchViewController.swift
1
3326
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import MagnetMax class UserSearchViewController: UIViewController { // MARK: Outlets @IBOutlet weak var criteriaSegmentedControl: UISegmentedControl! @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var usersTableView: UITableView! // MARK: public properties var users : [MMUser] = [] // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() searchParametr = .BeginsWith } // MARK: private implementations private enum SearchParametr { case BeginsWith case EndsWith } private var searchParametr: SearchParametr = .BeginsWith { didSet { guard let currentUser = MMUser.currentUser() else { return } let userName = currentUser.userName switch searchParametr { case .BeginsWith: let searchQuery = "userName:\(userName.characters.first!)*" searchTextField.placeholder = searchQuery searchTextField.text = searchQuery case .EndsWith: let searchQuery = "userName:*\(userName.characters.last!)" searchTextField.placeholder = searchQuery searchTextField.text = searchQuery } } } // MARK: Actions @IBAction func criteriaChanged() { if criteriaSegmentedControl.selectedSegmentIndex == 0 { searchParametr = .BeginsWith } else if criteriaSegmentedControl.selectedSegmentIndex == 1 { searchParametr = .EndsWith } } @IBAction func retrieveUsers(sender: UIBarButtonItem) { if let searchString = searchTextField.text { MMUser.searchUsers(searchString, limit: 10, offset: 0, sort: "userName:asc", success: { [weak self] users in self?.users = users self?.usersTableView.reloadData() }, failure: { error in print("[ERROR]: \(error.localizedDescription)") }) } } } extension UserSearchViewController : UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UserCellIdentifier", forIndexPath: indexPath) let user = users[indexPath.row] cell.textLabel?.text = user.userName return cell } }
apache-2.0
e8f5641cedcd3ff261364189f35ac7da
28.696429
120
0.625676
5.3906
false
false
false
false
LYM-mg/DemoTest
indexView/Extesion/Category(扩展)/UIImage+Extension.swift
1
8001
// // UIImage+Extension.swift // chart2 // // Created by i-Techsys.com on 16/12/3. // Copyright © 2016年 i-Techsys. All rights reserved. // import UIKit import Accelerate import CoreImage // MARK: - 模糊的图片 extension UIImage { /** 返回一张处理过的模糊图片 - parameter value: 模糊程度 0 ~ 无限大 (一开始误认为0~1) */ public func blurImage(value: NSNumber) -> UIImage? { let context = CIContext(options: [CIContextOption.useSoftwareRenderer: true]) let ciImage = CoreImage.CIImage(image: self) guard let blurFilter = CIFilter(name: "CIGaussianBlur") else { return nil } blurFilter.setValue(ciImage, forKey: kCIInputImageKey) blurFilter.setValue(value, forKey: "inputRadius") guard let imageRef = context.createCGImage(blurFilter.outputImage!, from: (ciImage?.extent)!) else { return nil } return UIImage(cgImage: imageRef) } public func boxBlurImage(withBlurNumber blur: CGFloat) -> UIImage { var blur = blur if blur < 0.0 || blur > 1.0 { blur = 0.5 } var boxSize = Int(blur * 40) boxSize = boxSize - (boxSize % 2) + 1 let img = self.cgImage var inBuffer = vImage_Buffer() var outBuffer = vImage_Buffer() var error: vImage_Error! var pixelBuffer: UnsafeMutableRawPointer // 从CGImage中获取数据 let inProvider = img!.dataProvider let inBitmapData = inProvider!.data // 设置从CGImage获取对象的属性 inBuffer.width = UInt(img!.width) inBuffer.height = UInt(img!.height) inBuffer.rowBytes = img!.bytesPerRow inBuffer.data = UnsafeMutableRawPointer(mutating: CFDataGetBytePtr(inBitmapData!)) pixelBuffer = malloc(img!.bytesPerRow * img!.height) // if pixelBuffer == nil { // NSLog("No pixel buffer!") // } outBuffer.data = pixelBuffer outBuffer.width = UInt(img!.width) outBuffer.height = UInt(img!.height) outBuffer.rowBytes = img!.bytesPerRow error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(boxSize), UInt32(boxSize), nil, UInt32(kvImageEdgeExtend)) if error != nil && error != 0 { NSLog("error from convolution %ld", error) } let colorSpace = CGColorSpaceCreateDeviceRGB() let ctx = CGContext(data: outBuffer.data, width: Int(outBuffer.width), height: Int(outBuffer.height), bitsPerComponent: 8, bytesPerRow: outBuffer.rowBytes, space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) let imageRef = ctx!.makeImage()! let returnImage = UIImage(cgImage: imageRef) free(pixelBuffer) return returnImage } /** * 压缩图片,并返回压缩后的图片 */ public func imageCompress(targetWidth: CGFloat) -> UIImage? { let targetHeight = (targetWidth/self.size.width)*self.size.height let targetSize = CGSize(width: targetWidth, height: targetHeight) UIGraphicsBeginImageContext(size) self.draw(in: CGRect(origin: CGPoint.zero, size: targetSize)) guard let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil } UIGraphicsEndImageContext() return newImage } } // MARK: - 设置图片圆角和边框 以及 根据颜色返回一张图片 extension UIImage { /** 根据颜色返回一张图片 类方法 - parameter color: 颜色 - parameter size: 大小 */ public static func imageWithColor(color: UIColor?, size: CGSize = CGSize.zero) -> UIImage?{ var size = size if size == CGSize.zero { size = CGSize(width: MGScreenW, height: 64) } var color = color if (color == nil) { color = UIColor.orange } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(rect.size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor((color?.cgColor)!) context.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } /** 返回一张带边框的圆角图片 - parameter originImage: 原始图片,去到这个参数 改用对象方法 - parameter borderColor: 边框颜色 - parameter borderWidth: 边框大小 */ public func circleImage(borderColor: UIColor, borderWidth: CGFloat) -> UIImage? { //设置边框宽度 let imageWH: CGFloat = self.size.width //计算外圆的尺寸 let ovalWH:CGFloat = imageWH + 2 * borderWidth //开启上下文 UIGraphicsBeginImageContextWithOptions(self.size, false, 0) //画一个大的圆形 let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: ovalWH, height: ovalWH)) borderColor.set() path.fill() //设置裁剪区域 let clipPath = UIBezierPath(ovalIn: CGRect(x: borderWidth, y: borderWidth, width: ovalWH, height: ovalWH)) clipPath.addClip() //绘制图片 self.draw(at: CGPoint(x: borderWidth, y: borderWidth)) //从上下文中获取图片 guard let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil } //关闭上下文 UIGraphicsEndImageContext() return resultImage } // 返回一张原始图片 public static func mg_RenderModeOriginal(imageName: String) -> UIImage { let image = UIImage(named: imageName) return (image?.withRenderingMode(.alwaysOriginal))! } } // MARK: - 图片上绘制文字,返回一张带文字的图片 extension UIImage { /** 图片上绘制文字,返回一张带文字的图片 - parameter title: 要绘画到图片上的文字 - parameter drawAtPoint: 绘画的点(位置) - parameter fontSize: 要绘画到图片上的文字的大小 */ func imageWithTitle(title: String, drawAtPoint: CGPoint, fontSize: CGFloat) -> UIImage? { //画布大小 let size = CGSize(width: self.size.width, height: self.size.height) //创建一个基于位图的上下文 UIGraphicsBeginImageContextWithOptions(size,false,0.0) //opaque:NO scale:0.0 self.draw(at: drawAtPoint) //文字居中显示在画布上 let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.lineBreakMode = .byCharWrapping //NSLineBreakByCharWrapping paragraphStyle.alignment = NSTextAlignment.center//文字居中 //计算文字所占的size,文字居中显示在画布上 let sizeText = title.boundingRect(with: self.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize)] , context: nil); let width = self.size.width let height = self.size.height let rect = CGRect(x: (width-sizeText.width)/2, y: (height-sizeText.height)/2, width: sizeText.width, height: sizeText.height) //绘制文字 title.draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize),NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.paragraphStyle:paragraphStyle]) //返回绘制的新图形 guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil } UIGraphicsEndImageContext() return newImage } }
mit
467757347b9c89be332ab42719ecb325
35.246305
234
0.62816
4.462098
false
false
false
false
joerocca/GitHawk
Classes/Issues/Issue+IssueType.swift
1
13678
// // Issue+IssueType.swift // Freetime // // Created by Ryan Nystrom on 6/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit extension IssueOrPullRequestQuery.Data.Repository.IssueOrPullRequest.AsIssue: IssueType { var pullRequest: Bool { return false } var labelableFields: LabelableFields { return fragments.labelableFields } var commentFields: CommentFields { return fragments.commentFields } var reactionFields: ReactionFields { return fragments.reactionFields } var closableFields: ClosableFields { return fragments.closableFields } var merged: Bool { return false } var assigneeFields: AssigneeFields { return fragments.assigneeFields } var reviewRequestModel: IssueAssigneesModel? { return nil } var headPaging: HeadPaging { return timeline.pageInfo.fragments.headPaging } var milestoneFields: MilestoneFields? { return milestone?.fragments.milestoneFields } var fileChanges: FileChanges? { return nil } func timelineViewModels( owner: String, repo: String, width: CGFloat ) -> (models: [ListDiffable], mentionedUsers: [AutocompleteUser]) { guard let nodes = timeline.nodes else { return ([], []) } let cleanNodes = nodes.flatMap { $0 } var results = [ListDiffable]() var mentionedUsers = [AutocompleteUser]() for node in cleanNodes { if let comment = node.asIssueComment { if let model = createCommentModel( id: comment.fragments.nodeFields.id, commentFields: comment.fragments.commentFields, reactionFields: comment.fragments.reactionFields, width: width, owner: owner, repo: repo, threadState: .single, viewerCanUpdate: comment.fragments.updatableFields.viewerCanUpdate, viewerCanDelete: comment.fragments.deletableFields.viewerCanDelete, isRoot: false ) { results.append(model) mentionedUsers.append(AutocompleteUser( avatarURL: model.details.avatarURL, login: model.details.login )) } } else if let unlabeled = node.asUnlabeledEvent, let date = GithubAPIDateFormatter().date(from: unlabeled.createdAt) { let model = IssueLabeledModel( id: unlabeled.fragments.nodeFields.id, actor: unlabeled.actor?.login ?? Constants.Strings.unknown, title: unlabeled.label.name, color: unlabeled.label.color, date: date, type: .removed, repoOwner: owner, repoName: repo, width: width ) results.append(model) } else if let labeled = node.asLabeledEvent, let date = GithubAPIDateFormatter().date(from: labeled.createdAt) { let model = IssueLabeledModel( id: labeled.fragments.nodeFields.id, actor: labeled.actor?.login ?? Constants.Strings.unknown, title: labeled.label.name, color: labeled.label.color, date: date, type: .added, repoOwner: owner, repoName: repo, width: width ) results.append(model) } else if let closed = node.asClosedEvent, let date = GithubAPIDateFormatter().date(from: closed.createdAt) { let model = IssueStatusEventModel( id: closed.fragments.nodeFields.id, actor: closed.actor?.login ?? Constants.Strings.unknown, commitHash: closed.closedCommit?.oid, date: date, status: .closed, pullRequest: false ) results.append(model) } else if let reopened = node.asReopenedEvent, let date = GithubAPIDateFormatter().date(from: reopened.createdAt) { let model = IssueStatusEventModel( id: reopened.fragments.nodeFields.id, actor: reopened.actor?.login ?? Constants.Strings.unknown, commitHash: nil, date: date, status: .reopened, pullRequest: false ) results.append(model) } else if let locked = node.asLockedEvent, let date = GithubAPIDateFormatter().date(from: locked.createdAt) { let model = IssueStatusEventModel( id: locked.fragments.nodeFields.id, actor: locked.actor?.login ?? Constants.Strings.unknown, commitHash: nil, date: date, status: .locked, pullRequest: false ) results.append(model) } else if let unlocked = node.asUnlockedEvent, let date = GithubAPIDateFormatter().date(from: unlocked.createdAt) { let model = IssueStatusEventModel( id: unlocked.fragments.nodeFields.id, actor: unlocked.actor?.login ?? Constants.Strings.unknown, commitHash: nil, date: date, status: .unlocked, pullRequest: false ) results.append(model) } else if let referenced = node.asCrossReferencedEvent, let date = GithubAPIDateFormatter().date(from: referenced.createdAt) { let id = referenced.fragments.nodeFields.id let actor = referenced.actor?.login ?? Constants.Strings.unknown if let issueReference = referenced.source.asIssue, // do not ref the current issue issueReference.number != number { let model = IssueReferencedModel( id: id, owner: issueReference.repository.owner.login, repo: issueReference.repository.name, number: issueReference.number, pullRequest: false, state: issueReference.closed ? .closed : .open, date: date, title: issueReference.title, actor: actor, width: width ) results.append(model) } else if let prReference = referenced.source.asPullRequest { let model = IssueReferencedModel( id: id, owner: prReference.repository.owner.login, repo: prReference.repository.name, number: prReference.number, pullRequest: false, state: prReference.merged ? .merged : prReference.closed ? .closed : .open, date: date, title: prReference.title, actor: actor, width: width ) results.append(model) } } else if let referenced = node.asReferencedEvent, let date = GithubAPIDateFormatter().date(from: referenced.createdAt) { let repo = referenced.commitRepository.fragments.referencedRepositoryFields let id = referenced.fragments.nodeFields.id let actor = referenced.actor?.login ?? Constants.Strings.unknown if let commitRef = referenced.refCommit { let model = IssueReferencedCommitModel( id: id, owner: repo.owner.login, repo: repo.name, hash: commitRef.oid, actor: referenced.actor?.login ?? Constants.Strings.unknown, date: date, width: width ) results.append(model) } else if let issueReference = referenced.subject.asIssue, // do not ref the current issue issueReference.number != number { let model = IssueReferencedModel( id: id, owner: repo.owner.login, repo: repo.name, number: issueReference.number, pullRequest: false, state: issueReference.closed ? .closed : .open, date: date, title: issueReference.title, actor: actor, width: width ) results.append(model) } else if let prReference = referenced.subject.asPullRequest { let model = IssueReferencedModel( id: id, owner: repo.owner.login, repo: repo.name, number: prReference.number, pullRequest: false, state: prReference.merged ? .merged : prReference.closed ? .closed : .open, date: date, title: prReference.title, actor: actor, width: width ) results.append(model) } } else if let rename = node.asRenamedTitleEvent, let date = GithubAPIDateFormatter().date(from: rename.createdAt) { let text = IssueRenamedString( previous: rename.previousTitle, current: rename.currentTitle, width: width ) let model = IssueRenamedModel( id: rename.fragments.nodeFields.id, actor: rename.actor?.login ?? Constants.Strings.unknown, date: date, titleChangeString: text ) results.append(model) } else if let assigned = node.asAssignedEvent, let date = GithubAPIDateFormatter().date(from: assigned.createdAt) { let model = IssueRequestModel( id: assigned.fragments.nodeFields.id, actor: assigned.actor?.login ?? Constants.Strings.unknown, user: assigned.user?.login ?? Constants.Strings.unknown, date: date, event: .assigned, width: width ) results.append(model) } else if let unassigned = node.asUnassignedEvent, let date = GithubAPIDateFormatter().date(from: unassigned.createdAt) { let model = IssueRequestModel( id: unassigned.fragments.nodeFields.id, actor: unassigned.actor?.login ?? Constants.Strings.unknown, user: unassigned.user?.login ?? Constants.Strings.unknown, date: date, event: .unassigned, width: width ) results.append(model) } else if let milestone = node.asMilestonedEvent, let date = GithubAPIDateFormatter().date(from: milestone.createdAt) { let model = IssueMilestoneEventModel( id: milestone.fragments.nodeFields.id, actor: milestone.actor?.login ?? Constants.Strings.unknown, milestone: milestone.milestoneTitle, date: date, type: .milestoned, width: width ) results.append(model) } else if let demilestone = node.asDemilestonedEvent, let date = GithubAPIDateFormatter().date(from: demilestone.createdAt) { let model = IssueMilestoneEventModel( id: demilestone.fragments.nodeFields.id, actor: demilestone.actor?.login ?? Constants.Strings.unknown, milestone: demilestone.milestoneTitle, date: date, type: .demilestoned, width: width ) results.append(model) } else if let commit = node.asCommit, let urlString = commit.author?.user?.avatarUrl, let avatarURL = URL(string: urlString) { let model = IssueCommitModel( id: commit.fragments.nodeFields.id, login: commit.author?.user?.login ?? Constants.Strings.unknown, avatarURL: avatarURL, message: commit.messageHeadline, hash: commit.oid ) results.append(model) } } return (results, mentionedUsers) } }
mit
f072f9415170d079e89410d5859f8bc1
41.874608
99
0.497843
5.58701
false
false
false
false
huangboju/Moots
Examples/边缘侧滑/MedalCount Completed/MedalCount/Controllers/MedalCountViewController.swift
1
2818
/** * Copyright (c) 2016 Razeware LLC * * 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 MedalCountViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var medalCountStackView: UIStackView! @IBOutlet var countryFlags: [UIImageView]! @IBOutlet var countryNames: [UILabel]! @IBOutlet var countryGolds: [UILabel]! @IBOutlet var countrySilvers: [UILabel]! @IBOutlet var countryBronzes: [UILabel]! // MARK: - Properties var medalCount: MedalCount! // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Adding these constraints in code becuase storyboard froze when I tried adding the there medalCountStackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ medalCountStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor), medalCountStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) for (index, winner) in medalCount.winners.enumerated() { countryFlags[index].image = winner.flagImage countryNames[index].text = winner.country countryGolds[index].text = winner.goldString countrySilvers[index].text = winner.silverString countryBronzes[index].text = winner.bronzeString } setupGestureRecognizers() } } // MARK: - Private private extension MedalCountViewController { func setupGestureRecognizers() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:))) view.addGestureRecognizer(tapRecognizer) } } // MARK: - GestureRecognizerSelectors private extension MedalCountViewController { @objc dynamic func handleTap(gestureRecognizer: UITapGestureRecognizer) { dismiss(animated: true) } }
mit
3fb33b22fab2efdf3c9c9c70231f7e5e
36.078947
110
0.7555
4.627258
false
false
false
false
idikic/mac-address-resolver-mvvm-swift
00_HELPERS/Constants.swift
1
966
// // Constants.swift // M.A.C. // // Created by Ivan Dikic on 22/02/15. // Copyright (c) 2015 Iki. All rights reserved. // import Foundation struct Constants { struct UIGeometry { static let borderWidth = NSNumber(integer: 1) static let cornerRadius = NSNumber(integer: 5) } struct UIString { static let buttonTitleLookUp = "LOOK UP" static let buttonTitleResolveIPAddress = "RESOLVE IP ADDRESS" static let messageInvalidIPAddress = "Invalid IP address" static let messageNoLocalWiFiConnection = "No local WiFi connection" static let messageDestinationHostUnreachable = "Destination host unreachable" static let messageInvalidMACAddress = "Invalid MAC address" static let messageGenericError = "Ooops, please try again :)" static let textFieldTapToStart = "tap to start" static let macAddressEmptySuffix = "00:00:00" } struct UISegue { static let barcodeScannerSegue = "BarcodeScannerSegue" } }
mit
4c1ba917a50ab0a06d9500f2ae9f1942
26.628571
81
0.724638
4.128205
false
false
false
false
davidprochazka/HappyDay
HappyDaysCollectionVersion/HappyDaysCollectionVersion/PersonStatistics.swift
1
2259
// // TeamStatistics.swift // HappyDaysCollectionVersion // // Created by Ivo Pisarovic on 14/07/16. // Copyright © 2016 David Prochazka. All rights reserved. // import Foundation import CoreData class PersonStatistics: Statistics { var person: Person? init(person: Person, moc: NSManagedObjectContext){ self.person = person super.init(moc: moc) } internal override func performFetchRequest()->NSFetchedResultsController{ let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.moc!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // nadefinuji predikat // limit results to last 30 days and a concrete person let cal = NSCalendar.currentCalendar() let startDate = cal.dateByAddingUnit(.Day, value: -30, toDate: NSDate(), options: []) let teamPredicate = NSPredicate(format: "person.name like %@ AND timeStamp >= %@", person!.name!, startDate!) fetchRequest.predicate = teamPredicate // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.moc!, sectionNameKeyPath: nil, cacheName: nil) do { try fetchedResultsController.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } return fetchedResultsController } }
gpl-3.0
ff1f40eda7fc6ebe7ca9344722f6c33c
37.931034
190
0.659433
5.427885
false
false
false
false
turingcorp/gattaca
UnitTests/Model/Gif/Strategy/TMGifStrategyDownloadRequest.swift
1
2831
import XCTest @testable import gattaca class TMGifStrategyDownloadRequest:XCTestCase { private var urlResponseOk:URLResponse? private var urlResponseFail:URLResponse? private var gif:MGif? private var strategy:MGifStrategyDownload? private var fileUrl:URL? private let kIdentifier:String = "xUNd9Cr6NMXPBO1t7y" private let kFileName:String = "giphyTrending" private let kFileExtension:String = "json" private let kStatusCodeOk:Int = 200 private let kStatusCodeFail:Int = 0 override func setUp() { super.setUp() let gif:MGif = MGif() self.gif = gif strategy = MGifStrategyDownload( model:gif) let bundle:Bundle = Bundle(for:TMHomeRequest.self) guard let fileUrl:URL = bundle.url( forResource:kFileName, withExtension:kFileExtension) else { return } self.fileUrl = fileUrl urlResponseOk = HTTPURLResponse( url:fileUrl, statusCode:kStatusCodeOk, httpVersion:nil, headerFields:nil) urlResponseFail = HTTPURLResponse( url:fileUrl, statusCode:kStatusCodeFail, httpVersion:nil, headerFields:nil) } //MARK: internal func testSetup() { XCTAssertNotNil( fileUrl, "failed creating url") XCTAssertNotNil( urlResponseOk, "failed creating response") } func testFactoryUrl() { let url:URL? = strategy?.factoryUrl( identifier:kIdentifier) XCTAssertNotNil( url, "failed factorying url") } func testDownloadedData() { let data:Data? = strategy?.downloadedData( fileUrl:fileUrl, urlResponse:urlResponseOk, error:nil) XCTAssertNotNil( data, "failed creating data") } func testDownloadedDataResponseFailed() { let data:Data? = strategy?.downloadedData( fileUrl:fileUrl, urlResponse:urlResponseFail, error:nil) XCTAssertNil( data, "data should not be created") } func testDownloadedDataError() { let error:Error = NSError( domain:kIdentifier, code:0, userInfo:nil) let data:Data? = strategy?.downloadedData( fileUrl:fileUrl, urlResponse:urlResponseOk, error:error) XCTAssertNil( data, "data should not be created") } }
mit
3c5cf76f6e4c4e48a357d809116585c0
23.196581
58
0.53656
5.232902
false
true
false
false