repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
cornerAnt/Digger
refs/heads/master
Sources/DiggerManager.swift
mit
1
// // DiggerManager.swift // Digger // // Created by ant on 2017/10/25. // Copyright © 2017年 github.cornerant. All rights reserved. // import Foundation public protocol DiggerManagerProtocol{ /// logLevel hing,low,none var logLevel : LogLevel { set get } /// Apple limit is per session,The default value is 6 in macOS, or 4 in iOS. var maxConcurrentTasksCount : Int {set get} var allowsCellularAccess : Bool { set get } var timeout: TimeInterval { set get } /// Start the task at once,default is true var startDownloadImmediately : Bool { set get } func startTask(for diggerURL: DiggerURL) func stopTask(for diggerURL: DiggerURL) /// If the task is cancelled, the temporary file will be deleted func cancelTask(for diggerURL: DiggerURL) func startAllTasks() func stopAllTasks() func cancelAllTasks() } open class DiggerManager:DiggerManagerProtocol { // MARK:- property public static var shared = DiggerManager(name: digger) public var logLevel: LogLevel = .high open var startDownloadImmediately = true open var timeout: TimeInterval = 100 fileprivate var diggerSeeds = [URL: DiggerSeed]() fileprivate var session: URLSession fileprivate var diggerDelegate: DiggerDelegate? fileprivate let barrierQueue = DispatchQueue.barrier fileprivate let delegateQueue = OperationQueue.downloadDelegateOperationQueue public var maxConcurrentTasksCount: Int = 3 { didSet{ let count = maxConcurrentTasksCount == 0 ? 1 : maxConcurrentTasksCount session.invalidateAndCancel() session = setupSession(allowsCellularAccess, count) } } public var allowsCellularAccess: Bool = true { didSet{ session.invalidateAndCancel() session = setupSession(allowsCellularAccess, maxConcurrentTasksCount) } } // MARK:- lifeCycle private init(name: String) { DiggerCache.cachesDirectory = digger if name.isEmpty { fatalError("DiggerManager must hava a name") } diggerDelegate = DiggerDelegate() let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.allowsCellularAccess = allowsCellularAccess sessionConfiguration.httpMaximumConnectionsPerHost = maxConcurrentTasksCount session = URLSession(configuration: sessionConfiguration, delegate: diggerDelegate, delegateQueue: delegateQueue) } deinit { session.invalidateAndCancel() } private func setupSession(_ allowsCellularAccess:Bool ,_ maxDownloadTasksCount:Int ) -> URLSession{ diggerDelegate = DiggerDelegate() let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.allowsCellularAccess = allowsCellularAccess sessionConfiguration.httpMaximumConnectionsPerHost = maxDownloadTasksCount let session = URLSession(configuration: sessionConfiguration, delegate: diggerDelegate, delegateQueue: delegateQueue) return session } /// download file /// DiggerSeed contains information about the file /// - Parameter diggerURL: url /// - Returns: the diggerSeed of file @discardableResult public func download(with diggerURL: DiggerURL) -> DiggerSeed{ switch isDiggerURLCorrect(diggerURL) { case .success(let url): return createDiggerSeed(with: url) case .failure(_): fatalError("Please make sure the url or urlString is correct") } } } // MARK:- diggerSeed control extension DiggerManager{ func createDiggerSeed(with url: URL) -> DiggerSeed{ if let DiggerSeed = findDiggerSeed(with: url) { return DiggerSeed }else{ barrierQueue.sync(flags: .barrier){ let timeout = self.timeout == 0.0 ? 100 : self.timeout let diggerSeed = DiggerSeed(session: session, url: url, timeout: timeout) diggerSeeds[url] = diggerSeed } let diggerSeed = findDiggerSeed(with: url)! diggerDelegate?.manager = self if self.startDownloadImmediately{ diggerSeed.downloadTask.resume() } return diggerSeed } } public func removeDigeerSeed(for url : URL){ barrierQueue.sync(flags: .barrier) { diggerSeeds.removeValue(forKey: url) if diggerSeeds.isEmpty{ diggerDelegate = nil } } } func isDiggerURLCorrect(_ diggerURL: DiggerURL) -> Result<URL> { var correctURL: URL do { correctURL = try diggerURL.asURL() return Result.success(correctURL) } catch { diggerLog(error) return Result.failure(error) } } func findDiggerSeed(with diggerURL: DiggerURL) -> DiggerSeed? { var diggerSeed: DiggerSeed? switch isDiggerURLCorrect(diggerURL) { case .success(let url): barrierQueue.sync(flags: .barrier) { diggerSeed = diggerSeeds[url] } return diggerSeed case .failure(_): return diggerSeed } } } // MARK:- downloadTask control extension DiggerManager{ public func cancelTask(for diggerURL: DiggerURL) { switch isDiggerURLCorrect(diggerURL) { case .failure(_): return case .success(let url): barrierQueue.sync(flags: .barrier){ guard let diggerSeed = diggerSeeds[url] else { return } diggerSeed.downloadTask.cancel() } } } public func stopTask(for diggerURL: DiggerURL) { switch isDiggerURLCorrect(diggerURL) { case .failure(_): return case .success(let url): barrierQueue.sync(flags: .barrier){ guard let diggerSeed = diggerSeeds[url] else { return } if diggerSeed.downloadTask.state == .running{ diggerSeed.downloadTask.suspend() diggerDelegate?.notifySpeedZeroCallback(diggerSeed) } } } } public func startTask(for diggerURL: DiggerURL) { switch isDiggerURLCorrect(diggerURL) { case .failure(_): return case .success(let url): barrierQueue.sync(flags: .barrier){ guard let diggerSeed = diggerSeeds[url] else { return } if diggerSeed.downloadTask.state != .running{ diggerSeed.downloadTask.resume() self.diggerDelegate?.notifySpeedCallback(diggerSeed) } } } } public func startAllTasks() { _ = diggerSeeds.keys.map{ (url) in startTask(for: url) } } public func stopAllTasks() { _ = diggerSeeds.keys.map{ (url) in stopTask(for : url) } } public func cancelAllTasks() { _ = diggerSeeds.keys.map{ (url) in cancelTask(for: url) } } } // MARK:- URLSessionExtension extension URLSession { public func dataTask(with url : URL,timeout:TimeInterval) -> URLSessionDataTask{ let range = DiggerCache.fileSize(filePath: DiggerCache.tempPath(url: url)) var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) let headRange = "bytes=" + String(range) + "-" request.setValue(headRange, forHTTPHeaderField: "Range") let task = dataTask(with: request) task.priority = URLSessionTask.defaultPriority return task } }
43c22c500b58b71bf2604f480d851e87
24.428161
125
0.547746
false
false
false
false
rechsteiner/Parchment
refs/heads/main
Example/Examples/Icons/IconPagingCell.swift
mit
1
import Parchment import UIKit struct IconPagingCellViewModel { let image: UIImage? let selected: Bool let tintColor: UIColor let selectedTintColor: UIColor init(image: UIImage?, selected: Bool, options: PagingOptions) { self.image = image self.selected = selected tintColor = options.textColor selectedTintColor = options.selectedTextColor } } class IconPagingCell: PagingCell { fileprivate var viewModel: IconPagingCellViewModel? fileprivate lazy var imageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.contentMode = .scaleAspectFit return imageView }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(imageView) setupConstraints() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setPagingItem(_ pagingItem: PagingItem, selected: Bool, options: PagingOptions) { if let item = pagingItem as? IconItem { let viewModel = IconPagingCellViewModel( image: item.image, selected: selected, options: options ) imageView.image = viewModel.image if viewModel.selected { imageView.transform = CGAffineTransform(scaleX: 1, y: 1) imageView.tintColor = viewModel.selectedTintColor } else { imageView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) imageView.tintColor = viewModel.tintColor } self.viewModel = viewModel } } open override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { guard let viewModel = viewModel else { return } if let attributes = layoutAttributes as? PagingCellLayoutAttributes { let scale = (0.4 * attributes.progress) + 0.6 imageView.transform = CGAffineTransform(scaleX: scale, y: scale) imageView.tintColor = UIColor.interpolate( from: viewModel.tintColor, to: viewModel.selectedTintColor, with: attributes.progress ) } } private func setupConstraints() { imageView.translatesAutoresizingMaskIntoConstraints = false let topContraint = NSLayoutConstraint( item: imageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1.0, constant: 15 ) let bottomConstraint = NSLayoutConstraint( item: imageView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1.0, constant: -15 ) let leadingContraint = NSLayoutConstraint( item: imageView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1.0, constant: 0 ) let trailingContraint = NSLayoutConstraint( item: imageView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1.0, constant: 0 ) contentView.addConstraints([ topContraint, bottomConstraint, leadingContraint, trailingContraint, ]) } }
7be68cdc38e47b3a590dbeb3d234b5c8
28.836066
99
0.577473
false
false
false
false
iachievedit/swiftychatter
refs/heads/master
chatterserver/Sources/ChatterServer.swift
mit
1
// ChatterServer.swift // // The MIT License (MIT) // // Copyright (c) 2016 iAchieved.it 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 swiftysockets import Foundation class ChatterServer { private let ip:IP? private let server:TCPServerSocket? init?() { do { self.ip = try IP(port:5555) self.server = try TCPServerSocket(ip:self.ip!) } catch let error { print(error) return nil } } func start() { while true { do { let client = try server!.accept() self.addClient(client) } catch let error { print(error) } } } private var connectedClients:[TCPClientSocket] = [] private var connectionCount = 0 private func addClient(client:TCPClientSocket) { self.connectionCount += 1 let handlerThread = NSThread(){ let clientId = self.connectionCount print("Client \(clientId) connected") while true { do { if let s = try client.receiveString(untilDelimiter: "\n") { print("Received from client \(clientId): \(s)", terminator:"") self.broadcastMessage(s, except:client) } } catch let error { print ("Client \(clientId) disconnected: \(error)") self.removeClient(client) return } } } handlerThread.start() connectedClients.append(client) } private func removeClient(client:TCPClientSocket) { connectedClients = connectedClients.filter(){$0 !== client} } private func broadcastMessage(message:String, except:TCPClientSocket) { for client in connectedClients where client !== except { do { try client.sendString(message) try client.flush() } catch { // } } } }
4a3893ea8f2f22e3363a2ca119c44e61
28.736842
80
0.661239
false
false
false
false
Drakken-Engine/GameEngine
refs/heads/master
DrakkenEngine/dDebug.swift
gpl-3.0
1
// // dDebug.swift // DrakkenEngine // // Created by Allison Lindner on 25/10/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import Foundation import JavaScriptCore @objc public protocol dDebugExport: JSExport { func log(_ content: String) } public class dLog { public var transformName: String public var date: Date public var content: String public init(_ transformName: String, _ date: Date, _ content: String) { self.transformName = transformName self.date = date self.content = content } public func toString() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy.MM.dd - HH:mm:ss:SSSS" let dateString = dateFormatter.string(from: date) return "\(dateString) - \(transformName) - \(content)" } } public class dDebug: NSObject, dDebugExport { private var logs: [dLog] = [] internal var transform: dTransform public init(_ transform: dTransform) { self.transform = transform } public func log(_ content: String) { if transform._scene.DEBUG_MODE { let l = dLog(self.transform.name, Date(), String(content)) self.logs.append(l) dCore.instance.allDebugLogs.append(l) } } }
11a1bc590ec5d001e2fd551e100b38bc
25.098039
75
0.623591
false
false
false
false
qimuyunduan/ido_ios
refs/heads/master
ido_ios/SetPwdController.swift
mit
1
// // SetPwdController.swift // ido_ios // // Created by qimuyunduan on 16/6/8. // Copyright © 2016年 qimuyunduan. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class SetPwdController: UIViewController,UITextFieldDelegate { @IBOutlet weak var setPwd: UITextField! @IBOutlet weak var confirmPwd: UITextField! @IBOutlet weak var confirmButton: UIButton! var personName :String? override func viewDidLoad() { super.viewDidLoad() confirmPwd.delegate = self confirmButton.addTarget(self, action: #selector(SetPwdController.login), forControlEvents: UIControlEvents.TouchUpInside) } func textFieldDidBeginEditing(textField: UITextField) { confirmButton.setBackgroundImage(UIImage(named: "loginEnabled"), forState: UIControlState.Normal) } func login() -> Void { if setPwd.text == confirmPwd.text && setPwd.text?.characters.count >= 6 { let destinationController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("myTableViewController") as! MyTableViewController newUser() // if newUser()["result"] == "200" { // let userDefaults = NSUserDefaults.standardUserDefaults() // userDefaults.setBool(true, forKey: "registered") // userDefaults.setObject(personName, forKey: "userName") // destinationController.personalInfo["name"] = personName // destinationController.personalInfo["insureCompany"] = "ido cor" // destinationController.personalInfo["moneyLeft"] = "0" // self.presentViewController(destinationController, animated: false, completion: nil) // } } } func newUser() -> Void { let paras = ["userName":personName!,"password":String(setPwd.text),"salt":String(setPwd.text),"phone":personName!] Alamofire.request(.POST, HOST+"user",parameters:paras).responseJSON{ response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) } case .Failure(let error): print(error) } } } }
cefb96ace5a6e9839e9a3b834a6c50df
32.821918
170
0.593358
false
false
false
false
whyefa/RCSwitch
refs/heads/master
RCSwitch/RCSwitch.swift
mit
1
// // RCSwitch.swift // RCSwitch // // Created by Developer on 2016/11/7. // Copyright © 2016年 Beijing Haitao International Travel Service Co., Ltd. All rights reserved. // a swich for password security enter import UIKit let rcSwitchFontSize: CGFloat = 12 public class RCSwitch: UIControl, CAAnimationDelegate { // the text showing when isOn == true public var onText: String = "" { didSet { setNeedsLayout() } } // the text showing when isOn == false, default show ... public var offText: String = "" { didSet { setNeedsLayout() } } // shadowLayer show on superview or not, default is false public var isShadowShowing: Bool = false // onText background color public var onColor: UIColor = UIColor(red:243/255.0, green: 68/255.0, blue:107/255.0, alpha: 1) { didSet { onLayer.fillColor = onColor.cgColor setNeedsLayout() } } // offText background color public var offColor: UIColor = UIColor.white { didSet { offLayer.fillColor = offColor.cgColor setNeedsLayout() } } // textlayer show onText string private var onTextLayer: CATextLayer! // textlayer show offText string private var offTextLayer: CATextLayer? // switch max length private let maxLength: CGFloat = 60 // thumb offset the border private let margin: CGFloat = 2 // leftcorner / right corner radius private let minRadius:CGFloat = 3 // thumb radius # private var thumbRadius: CGFloat = 0 // animation duration private let rcswitchAnimationDuration: CFTimeInterval = 0.2 // on backgound layer fill with onColor private var onLayer: CAShapeLayer! // off background layer fill with offColor private var offLayer: CAShapeLayer! // round thumb layer private var thumbLayer: CAShapeLayer! // switch shadow color private var shadowLayer: CAShapeLayer! // if offText is not nil, offLayer show three dot private var dots = [CAShapeLayer]() // path of whole bounds private var fullPath: CGPath! // left thumb center when isOn == true private var leftArcCenter: CGPoint! // right thumb center when isOn == false private var rightArcCenter: CGPoint! public var isOn: Bool = false { didSet { self.isUserInteractionEnabled = false let leftPath = UIBezierPath(arcCenter: leftArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath let rightPath = UIBezierPath(arcCenter: rightArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath let lightMinPath = UIBezierPath(arcCenter: leftArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath let rightMinPath = UIBezierPath(arcCenter: rightArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath if self.isOn { let thumbAnimation = pathAnimation(from: leftPath, to: rightPath) thumbAnimation.delegate = self thumbLayer.add(thumbAnimation, forKey: "thumb") let onAnimation = pathAnimation(from: lightMinPath, to: fullPath) onLayer.add(onAnimation, forKey: "light") let offAnimation = pathAnimation(from: fullPath, to: rightMinPath) offLayer.add(offAnimation, forKey: "white") onTextLayer.isHidden = false offTextLayer?.isHidden = true } else { let thumbAnimation = pathAnimation(from: rightPath, to: leftPath) thumbAnimation.delegate = self thumbLayer.add(thumbAnimation, forKey: "thumb") let onAnimation = pathAnimation(from: fullPath, to: lightMinPath) onLayer.add(onAnimation, forKey: "light") let offAnimation = pathAnimation(from: rightMinPath, to: fullPath) offLayer.add(offAnimation, forKey: "white") onTextLayer.isHidden = true offTextLayer?.isHidden = false } } } override public func layoutSubviews() { super.layoutSubviews() let height: CGFloat = self.frame.height let width: CGFloat = self.frame.width leftArcCenter = CGPoint(x: height/2, y: height/2) rightArcCenter = CGPoint(x: width-height/2, y: height/2) thumbRadius = frame.height/2-margin onTextLayer.frame = onTextFrame() onTextLayer.string = onText fullPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: frame.height/2).cgPath thumbLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath onLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: minRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath offLayer.path = UIBezierPath(arcCenter: rightArcCenter, radius: minRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath if offText != "" { if offTextLayer == nil { offTextLayer = textLayer() offTextLayer!.foregroundColor = UIColor.lightGray.cgColor offTextLayer!.isHidden = isOn offLayer.addSublayer(offTextLayer!) } offTextLayer?.frame = offTextFrame() offTextLayer?.string = offText removeDots() } else { offTextLayer?.removeFromSuperlayer() setDots() } shadowLayer.frame = self.frame shadowLayer.path = fullPath self.superview!.layer.insertSublayer(shadowLayer, below: layer) } // MARK: - init override public init(frame: CGRect) { var rect = frame rect.size.width = min(frame.width, maxLength) super.init(frame: rect) self.frame = rect self.backgroundColor = .white layer.masksToBounds = true layer.cornerRadius = frame.height/2 thumbLayer = CAShapeLayer() thumbLayer.fillColor = UIColor.white.cgColor thumbLayer.shadowOffset = .zero thumbLayer.shadowRadius = 1 thumbLayer.shadowColor = UIColor.lightGray.cgColor thumbLayer.shadowOpacity = 0.9 layer.addSublayer(thumbLayer) onLayer = CAShapeLayer() onLayer.fillColor = onColor.cgColor layer.insertSublayer(onLayer, below: thumbLayer) onTextLayer = textLayer() onTextLayer.isHidden = true layer.insertSublayer(onTextLayer, above: offLayer) offLayer = CAShapeLayer() offLayer.fillColor = UIColor.white.cgColor self.layer.insertSublayer(offLayer, below: thumbLayer) shadowLayer = CAShapeLayer() shadowLayer.fillColor = UIColor.lightGray.cgColor shadowLayer.frame = self.frame shadowLayer.shadowRadius = 1.5 shadowLayer.shadowColor = UIColor.lightGray.cgColor shadowLayer.shadowOffset = .zero shadowLayer.shadowOpacity = 1 // tap gesture let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap)) self.addGestureRecognizer(tapGesture) } private func setDots() { let width = self.frame.width let height = self.frame.height var dotStartX = width/2 + width/2/3 let radius: CGFloat = 2 let dot1 = CAShapeLayer() dot1.fillColor = UIColor.lightGray.cgColor let dot1Path = UIBezierPath(arcCenter: CGPoint(x: dotStartX, y: height/2), radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) dot1.path = dot1Path.cgPath offLayer.addSublayer(dot1) dotStartX += radius*2 + 1 let dot2 = CAShapeLayer() dot2.fillColor = UIColor.lightGray.cgColor let dot2Path = UIBezierPath(arcCenter: CGPoint(x: dotStartX, y: height/2), radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) dot2.path = dot2Path.cgPath offLayer.addSublayer(dot2) dotStartX += radius*2 + 1 let dot3 = CAShapeLayer() dot3.fillColor = UIColor.lightGray.cgColor let dot3Path = UIBezierPath(arcCenter: CGPoint(x: dotStartX, y: height/2), radius: radius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) dot3.path = dot3Path.cgPath offLayer.addSublayer(dot3) dots.append(dot1) dots.append(dot2) dots.append(dot3) } private func removeDots() { for dot in dots { dot.removeFromSuperlayer() } dots.removeAll() } // MARK: - animate private func pathAnimation(from: CGPath, to: CGPath) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "path") animation.duration = rcswitchAnimationDuration animation.fromValue = from animation.toValue = to return animation } public func animationDidStart(_ anim: CAAnimation) { if self.isOn { thumbLayer.path = UIBezierPath(arcCenter: rightArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath onLayer.path = fullPath offLayer.path = UIBezierPath(arcCenter: rightArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath } else { thumbLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: thumbRadius, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath onLayer.path = UIBezierPath(arcCenter: leftArcCenter, radius: minRadius , startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true).cgPath offLayer.path = fullPath } } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { self.isUserInteractionEnabled = true } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - private @objc private func handleTap() { self.isOn = !isOn } // MARK: - text layer private func textLayer() -> CATextLayer { let textlayer = CATextLayer() textlayer.foregroundColor = UIColor.white.cgColor textlayer.fontSize = rcSwitchFontSize textlayer.font = "PingFangSC-Light" as CFTypeRef? textlayer.contentsScale = 2 return textlayer } private func onTextFrame() -> CGRect { let size = textSize(str: onText) return CGRect(origin: CGPoint(x: thumbRadius, y: (self.frame.height-size.height)/2), size: size) } private func offTextFrame() -> CGRect{ let size = textSize(str: offText) let x:CGFloat = self.frame.width - CGFloat(10) - size.width return CGRect(origin: CGPoint(x: x, y: (self.frame.height-size.height)/2), size: size) } private func textSize(str: String) -> CGSize { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let size = str.size(attributes: [NSFontAttributeName: UIFont(name: "PingFangSC-Light", size: rcSwitchFontSize)!, NSForegroundColorAttributeName: UIColor.black, NSParagraphStyleAttributeName: paragraphStyle]) return size } }
440392467270c848fb2d77a79591f860
37.093023
215
0.643032
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Vision/VisionFaceLandmarks/VisionFaceLandmarks/ViewController.swift
mit
1
// // ViewController.swift // VisionFaceLandmarks // // Created by Domenico Solazzo on 8/25/17. // Copyright © 2017 Domenico Solazzo. All rights reserved. // import UIKit import AVFoundation import Vision class ViewController: UIViewController { // AVCapture Session var session: AVCaptureSession? // Shape Layer let shapeLayer = CAShapeLayer() // Vision requests let faceDetection = VNDetectFaceRectanglesRequest() // Face Landmarks request let faceLandmarks = VNDetectFaceLandmarksRequest() // Face Detection request handler let faceDetectionRequest = VNSequenceRequestHandler() // Face Landmarks request handler let faceLandmarksRequest = VNSequenceRequestHandler() // Preview Layer lazy var previewLayer: AVCaptureVideoPreviewLayer? = { // Check if the AVCapture session is initialized, otherwise return nil guard let session = self.session else { return nil } // Create the preview layer var previewLayer = AVCaptureVideoPreviewLayer(session: session) // Set the aspect of the preview video previewLayer.videoGravity = .resizeAspectFill return previewLayer }() // Camera to use var frontCamera: AVCaptureDevice? = { return AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: .video, position: AVCaptureDevice.Position.front) }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. sessionPrepare() session?.startRunning() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() previewLayer?.frame = view.frame shapeLayer.frame = view.frame } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard let previewLayer = previewLayer else { return } view.layer.addSublayer(previewLayer) shapeLayer.strokeColor = UIColor.red.cgColor shapeLayer.lineWidth = 2.0 //needs to filp coordinate system for Vision shapeLayer.setAffineTransform(CGAffineTransform(scaleX: -1, y: -1)) view.layer.addSublayer(shapeLayer) } // Prepare the session func sessionPrepare() { session = AVCaptureSession() guard let session = session, let captureDevice = frontCamera else { return } do { let deviceInput = try AVCaptureDeviceInput(device: captureDevice) session.beginConfiguration() if session.canAddInput(deviceInput) { session.addInput(deviceInput) } let output = AVCaptureVideoDataOutput() output.videoSettings = [ String(kCVPixelBufferPixelFormatTypeKey): Int(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) ] output.alwaysDiscardsLateVideoFrames = true if session.canAddOutput(output) { session.addOutput(output) } session.commitConfiguration() let queue = DispatchQueue(label: "output.queue") output.setSampleBufferDelegate(self, queue: queue) print("Setup delegate") } catch { print("Can't setup session") } } } extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate { func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) let attachments = CMCopyDictionaryOfAttachments(kCFAllocatorDefault, sampleBuffer, kCMAttachmentMode_ShouldPropagate) let ciImage = CIImage(cvImageBuffer: pixelBuffer!, options: attachments as! [String : Any]?) //leftMirrored for front camera let ciImageWithOrientation = ciImage.oriented(forExifOrientation: Int32(UIImageOrientation.leftMirrored.rawValue)) detectFace(on: ciImageWithOrientation) } } extension ViewController { func detectFace(on image: CIImage) { try? faceDetectionRequest.perform([faceDetection], on: image) if let results = faceDetection.results as? [VNFaceObservation] { if !results.isEmpty { faceLandmarks.inputFaceObservations = results DispatchQueue.main.async { self.shapeLayer.sublayers?.removeAll() } } } } func detectLandmarks(on image: CIImage) { try? faceLandmarksDetectionRequest.perform([faceLandmarks], on: image) if let landmarksResults = faceLandmarks.results as? [VNFaceObservation] { for observation in landmarksResults { DispatchQueue.main.async { if let boundingBox = self.faceLandmarks.inputFaceObservations?.first?.boundingBox { let faceBoundingBox = boundingBox.scaled(to: self.view.bounds.size) //different types of landmarks let faceContour = observation.landmarks?.faceContour self.convertPointsForFace(faceContour, faceBoundingBox) let leftEye = observation.landmarks?.leftEye self.convertPointsForFace(leftEye, faceBoundingBox) let rightEye = observation.landmarks?.rightEye self.convertPointsForFace(rightEye, faceBoundingBox) let nose = observation.landmarks?.nose self.convertPointsForFace(nose, faceBoundingBox) let lips = observation.landmarks?.innerLips self.convertPointsForFace(lips, faceBoundingBox) let leftEyebrow = observation.landmarks?.leftEyebrow self.convertPointsForFace(leftEyebrow, faceBoundingBox) let rightEyebrow = observation.landmarks?.rightEyebrow self.convertPointsForFace(rightEyebrow, faceBoundingBox) let noseCrest = observation.landmarks?.noseCrest self.convertPointsForFace(noseCrest, faceBoundingBox) let outerLips = observation.landmarks?.outerLips self.convertPointsForFace(outerLips, faceBoundingBox) } } } } } func convertPointsForFace(_ landmark: VNFaceLandmarkRegion2D?, _ boundingBox: CGRect) { if (landmark?.pointCount) != nil { let points = landmark?.normalizedPoints let convertedPoints = convert(points!) let faceLandmarkPoints = convertedPoints.map { (point: (x: CGFloat, y: CGFloat)) -> (x: CGFloat, y: CGFloat) in let pointX = point.x * boundingBox.width + boundingBox.origin.x let pointY = point.y * boundingBox.height + boundingBox.origin.y return (x: pointX, y: pointY) } DispatchQueue.main.async { self.draw(points: faceLandmarkPoints) } } } func draw(points: [(x: CGFloat, y: CGFloat)]) { let newLayer = CAShapeLayer() newLayer.strokeColor = UIColor.red.cgColor newLayer.lineWidth = 2.0 let path = UIBezierPath() path.move(to: CGPoint(x: points[0].x, y: points[0].y)) for i in 0..<points.count - 1 { let point = CGPoint(x: points[i].x, y: points[i].y) path.addLine(to: point) path.move(to: point) } path.addLine(to: CGPoint(x: points[0].x, y: points[0].y)) newLayer.path = path.cgPath shapeLayer.addSublayer(newLayer) } func convert(_ points: [CGPoint]) -> [(x: CGFloat, y: CGFloat)] { var convertedPoints = [(x: CGFloat, y: CGFloat)]() for point in points { convertedPoints.append((x: point.x, y: point.y)) } return convertedPoints } }
0dd24a9ef29864b2a08533ef2775dade
36.131356
144
0.589182
false
false
false
false
Reaction-Framework/react-native-canvas
refs/heads/master
ios/RCTIONImage2DContext.swift
mit
2
// // RCTIONImage2DContext.swift // RCTIONImage2D // // Created by Marko on 14/01/16. // // import Foundation import ImageIO import MobileCoreServices class RCTIONImage2DContext: NSObject { private var contextId = NSUUID().UUIDString private var image: CGImageRef? func getContextId() -> String { return self.contextId; } func createFromFileUrl(fileUrl: String, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void { let imageData = NSData.init(contentsOfURL: NSURL.init(fileURLWithPath: fileUrl))! self.createFromData(imageData, withMaxWidth: maxWidth, withMaxHeight: maxHeight) } func createFromBase64String(base64: String, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void { let imageData = NSData.init(base64EncodedString: base64, options: NSDataBase64DecodingOptions(rawValue: 0))! self.createFromData(imageData, withMaxWidth: maxWidth, withMaxHeight: maxHeight) } private func createFromData(imageData: NSData, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void { let imageSource = CGImageSourceCreateWithData(imageData, nil)! let newImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)! self.createFromImage(newImage, withMaxWidth: maxWidth, withMaxHeight: maxHeight) } private func createFromImage(image: CGImageRef, withMaxWidth maxWidth: Int, withMaxHeight maxHeight: Int) -> Void { let orgWidth = Double(CGImageGetWidth(image)) let orgHeight = Double(CGImageGetHeight(image)) var calcNewWidth = Double(maxWidth) var calcNewHeight = Double(maxHeight) if orgWidth <= calcNewWidth && orgHeight <= calcNewHeight { self.image = image return; } if orgWidth / calcNewWidth < orgHeight / calcNewHeight { calcNewWidth = (calcNewHeight / orgHeight) * orgWidth } else { calcNewHeight = (calcNewWidth / orgWidth) * orgHeight } let newWidth = Int(calcNewWidth) let newHeight = Int(calcNewHeight) let context = CGBitmapContextCreate( nil, newWidth, newHeight, CGImageGetBitsPerComponent(image), 32 * newWidth, CGImageGetColorSpace(image), CGImageGetAlphaInfo(image).rawValue ) CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(newWidth), CGFloat(newHeight)), image) self.image = CGBitmapContextCreateImage(context) } func save(fileName: String) -> String { let imageData = self.getAsData() let documentsDirectory: NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let fileManager = NSFileManager.defaultManager() let imagePath = (documentsDirectory.stringByAppendingPathComponent(fileName) as NSString).stringByAppendingPathExtension("jpg")! fileManager.createFileAtPath(imagePath, contents: imageData, attributes: nil) return imagePath } func getAsBase64String() -> String { return self.getAsData().base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) } private func getAsData() -> NSData { let imageData = CFDataCreateMutable(nil, 0) let type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, "image/png", kUTTypeImage)!.takeRetainedValue() let destination = CGImageDestinationCreateWithData(imageData, type, 1, nil)! CGImageDestinationAddImage(destination, self.image!, nil) CGImageDestinationFinalize(destination) return imageData } func getWidth() -> Int { return CGImageGetWidth(self.image); } func getHeight() -> Int { return CGImageGetHeight(self.image); } func crop(cropRectangle: CGRect) -> Void { self.image = CGImageCreateWithImageInRect(self.image, cropRectangle); } func drawBorder(color: String, withLeftTop leftTop: CGSize, withRightBottom rightBottom: CGSize) throws -> Void { let orgWidth = self.getWidth() let orgHeight = self.getHeight() let newWidth = orgWidth + Int(leftTop.width + rightBottom.width); let newHeight = orgHeight + Int(leftTop.height + rightBottom.height); let context = CGBitmapContextCreate( nil, newWidth, newHeight, CGImageGetBitsPerComponent(self.image), 32 * newWidth, CGImageGetColorSpace(self.image), CGImageGetAlphaInfo(self.image).rawValue ) CGContextBeginPath(context); CGContextSetFillColorWithColor(context, try UIColor.parseColor(color).CGColor); CGContextFillRect(context, CGRectMake(0, 0, CGFloat(newWidth), CGFloat(newHeight))); CGContextDrawImage(context, CGRectMake(leftTop.width, rightBottom.height, CGFloat(orgWidth), CGFloat(orgHeight)), self.image); self.image = CGBitmapContextCreateImage(context); } deinit { self.image = nil; } }
30b69af38fb3306cb879ac147112bfad
34.021898
132
0.722176
false
false
false
false
ploden/viral-bible-ios
refs/heads/master
Viral-Bible-Ios/Viral-Bible-Ios/Classes/Controllers/BooksVC.swift
mit
1
// // BooksVC.swift // Viral-Bible-Ios // // Created by Philip Loden on 10/4/15. // Copyright © 2015 Alan Young. All rights reserved. // import UIKit class BooksVC: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var bibleVersion : BibleVersion? var books : [BibleBook]? override func viewDidLoad() { super.viewDidLoad() self.tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "Cell") if let version = self.bibleVersion { MBProgressHUD.showHUDAddedTo(self.view, animated: true) APIController.getBooks(version) { (books, error) -> () in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in MBProgressHUD.hideHUDForView(self.view, animated: true) self.books = books self.tableView.reloadData() }) } } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let books = self.books { return books.count } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let aCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell if let books = self.books { let book = books[indexPath.row] aCell.titleLabel.text = book.bookName } return aCell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let books = self.books { let selectedBook = books[indexPath.row] let vc = ChaptersVC.VB_instantiateFromStoryboard() as! ChaptersVC vc.bibleBook = selectedBook self.navigationController?.pushViewController(vc, animated: true) } } }
5d0910b007886f3301515f69e84e67bb
30.573529
119
0.61714
false
false
false
false
codwam/NPB
refs/heads/master
Demos/NPBDemo/NPB/Private/NPBSwizzle.swift
mit
1
// // NPBSwizzle.swift // NPBDemo // // Created by 李辉 on 2017/4/12. // Copyright © 2017年 codwam. All rights reserved. // import Foundation // MARK: - Instance func npb_instanceMethodSwizzling(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector) { let originalMethod = class_getInstanceMethod(cls, originalSelector) let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector) npb_addMethodSwizzling(cls: cls, originalSelector: originalSelector, swizzledSelector: swizzledSelector, originalMethod: originalMethod, swizzledMethod: swizzledMethod) } func npb_instanceMethodReplaceSwizzling(cls: AnyClass, originalSelector: Selector, swizzledIMP: IMP) { let originalMethod = class_getInstanceMethod(cls, originalSelector) let didAddMethod = class_addMethod(cls, originalSelector, swizzledIMP, method_getTypeEncoding(originalMethod)) if !didAddMethod { method_setImplementation(originalMethod, swizzledIMP) } } // MARK: - Class func npb_classMethodSwizzling(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector) { let cls: AnyClass = object_getClass(cls) let originalMethod = class_getClassMethod(cls, originalSelector) let swizzledMethod = class_getClassMethod(cls, swizzledSelector) npb_addMethodSwizzling(cls: cls, originalSelector: originalSelector, swizzledSelector: swizzledSelector, originalMethod: originalMethod, swizzledMethod: swizzledMethod) } // MARK: - Basic func npb_addMethodSwizzling(cls: AnyClass, originalSelector: Selector, swizzledSelector: Selector, originalMethod: Method?, swizzledMethod: Method?) { let didAddMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) if didAddMethod { class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) } else { method_exchangeImplementations(originalMethod, swizzledMethod) } }
b19e1fd4cb0f26259f7fa9239f041caf
41.0625
172
0.78207
false
false
false
false
baottran/nSURE
refs/heads/master
nSURE/ESMonthDropOffViewController.swift
mit
1
// // ASScheduleDropOffViewController.swift // nSURE // // Created by Bao Tran on 7/20/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit class ESMonthDropOffViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var monthYearLabel: UILabel! @IBOutlet weak var calendarCollectionView: UICollectionView! var repairObj: PFObject? var repairArray: Array<PFObject>? var today = NSDate.today() var currentDate = NSDate.today() override func viewDidLoad() { super.viewDidLoad() // println("assessment Array: \(assessmentArray)") monthYearLabel.text = "\(today.monthName) \(today.year)" self.view.addSubview(calendarCollectionView) calendarCollectionView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func nextMonth(){ currentDate = (currentDate + 1.month).beginningOfMonth monthYearLabel.text = "\(currentDate.monthName) \(currentDate.year)" self.calendarCollectionView.reloadData() } @IBAction func previousMonth(){ let newDate = (currentDate - 1.month).beginningOfMonth if newDate >= today.beginningOfMonth { currentDate = newDate monthYearLabel.text = "\(currentDate.monthName) \(currentDate.year)" self.calendarCollectionView.reloadData() } } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let numOfDaysInMonth = currentDate.monthDays() let numOfCellsForMonth = numOfDaysInMonth + cellsForMonth(currentDate) return numOfCellsForMonth } func cellsForMonth(currentDate: NSDate) -> Int{ var numOfCellsToAdd: Int switch currentDate.beginningOfMonth.weekdayName { case "Monday": numOfCellsToAdd = 1 case "Tuesday": numOfCellsToAdd = 2 case "Wednesday": numOfCellsToAdd = 3 case "Thursday": numOfCellsToAdd = 4 case "Friday": numOfCellsToAdd = 5 case "Saturday": numOfCellsToAdd = 6 case "Sunday": numOfCellsToAdd = 0 default: numOfCellsToAdd = 0 } return numOfCellsToAdd } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("dayCell", forIndexPath: indexPath) as! MonthDayCollectionViewCell let cellDate = currentDate.beginningOfMonth + (indexPath.row - cellsForMonth(currentDate)).days var numOfDropOffs: Int = 0 if let repairs = repairArray { for repair in repairs { if let dropOffDate = repair["dropOffDate"] as? NSDate { if (dropOffDate >= cellDate.beginningOfDay) && (dropOffDate <= (cellDate.beginningOfDay + 1.day)){ numOfDropOffs = numOfDropOffs + 1 } } } } cell.dayNum.text = String(cellDate.day) cell.dayNum.userInteractionEnabled = false cell.dayNum.userInteractionEnabled = false if indexPath.row < cellsForMonth(currentDate){ cell.dayLabel.text = "" cell.backgroundColor = UIColor.grayColor() } else if (currentDate.month == today.month) && (currentDate.year == today.year) && (indexPath.row < (cellsForMonth(currentDate) + today.day - 1)){ cell.dayLabel.text = "" cell.backgroundColor = UIColor.grayColor() } else { cell.dayLabel.text = "\(10 - numOfDropOffs) open drop offs" cell.backgroundColor = UIColor.greenColor() } return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "Choose Drop Off Time" { let dayController = segue.destinationViewController as! ESDayDropOffViewController if let indexPath = calendarCollectionView.indexPathForCell(sender as! UICollectionViewCell){ let cellDate = currentDate.beginningOfMonth + (indexPath.row - cellsForMonth(currentDate)).days dayController.currentDate = cellDate dayController.repairObj = repairObj dayController.repairArray = repairArray } } } }
0d98ebadaa857370d9e58279f2e82fbe
35.569231
155
0.631679
false
false
false
false
BenjyAir/PDEXChart
refs/heads/master
PDEXChart/Lib/PDLineChart.swift
mit
2
// // AppDelegate.swift // PDEXChart // // Created by KokerWang on 15/3/17. // Copyright (c) 2015年 KokerWang. All rights reserved. // import UIKit import QuartzCore class PDLineChartDataItem { //optional var axesColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0) //坐标轴颜色 var axesTipColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0) //坐标轴刻度值颜色 // var chartLayerColor: UIColor = UIColor(red: 61.0 / 255, green: 189.0 / 255, blue: 100.0 / 255, alpha: 1.0) //折线的颜色 var showAxes: Bool = true var xAxesDegreeTexts: [String]? var yAxesDegreeTexts: [String]? //require var xMax: CGFloat! var xInterval: CGFloat! var yMax: CGFloat! var yInterval: CGFloat! //数据 var lines : Array<[CGPoint]>? init() { } } class PDLineChart: PDChart { var axesComponent: PDChartAxesComponent! var dataItem: PDLineChartDataItem! init(frame: CGRect, dataItem: PDLineChartDataItem) { super.init(frame: frame) self.dataItem = dataItem var axesDataItem: PDChartAxesComponentDataItem = PDChartAxesComponentDataItem() axesDataItem.targetView = self axesDataItem.featureH = self.getFeatureHeight() axesDataItem.featureW = self.getFeatureWidth() axesDataItem.xMax = dataItem.xMax axesDataItem.xInterval = dataItem.xInterval axesDataItem.yMax = dataItem.yMax axesDataItem.yInterval = dataItem.yInterval axesDataItem.xAxesDegreeTexts = dataItem.xAxesDegreeTexts axesDataItem.yAxesDegreeTexts = dataItem.yAxesDegreeTexts axesComponent = PDChartAxesComponent(dataItem: axesDataItem) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func getFeatureWidth() -> CGFloat { return CGFloat(self.frame.size.width) } func getFeatureHeight() -> CGFloat { return CGFloat(self.frame.size.height) } override func strokeChart() { if !(self.dataItem.lines != nil) { return } //动画 CATransaction.begin() var pathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = 1.0 pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pathAnimation.fromValue = 0.0 pathAnimation.toValue = 1.0 var size = self.dataItem.lines?.count var colors = getColors(size!) for var i = 0; i < size!; i++ { // chartLayer //func addAnimation(anim: CAAnimation!, forKey key: String!) drawLine(i, color: colors[i]).addAnimation(pathAnimation, forKey: "strokeEndAnimation") } //class func setCompletionBlock(block: (() -> Void)!) CATransaction.setCompletionBlock({ () -> Void in }) CATransaction.commit() UIGraphicsEndImageContext() } func drawLine (index : Int, color : UIColor) -> CAShapeLayer{ //绘图layer var chartLayer: CAShapeLayer = CAShapeLayer() chartLayer.lineCap = kCALineCapRound chartLayer.lineJoin = kCALineJoinRound chartLayer.fillColor = UIColor.clearColor().CGColor chartLayer.strokeColor = color.CGColor chartLayer.lineWidth = 2.0 chartLayer.strokeStart = 0.0 chartLayer.strokeEnd = 1.0 self.layer.addSublayer(chartLayer) //画线段 UIGraphicsBeginImageContext(self.frame.size) var progressLine: UIBezierPath = UIBezierPath() var basePoint: CGPoint = axesComponent.getBasePoint() var xAxesWidth: CGFloat = axesComponent.getXAxesWidth() var yAxesHeight: CGFloat = axesComponent.getYAxesHeight() var pointArray: [CGPoint] = self.dataItem.lines![index] for var i = 0; i < pointArray.count; i++ { var point: CGPoint = pointArray[i] var pixelPoint: CGPoint = CGPoint(x: basePoint.x + point.x / self.dataItem.xMax * xAxesWidth, y: basePoint.y - point.y / self.dataItem.yMax * yAxesHeight)//转换为可以绘制的,屏幕中的像素点 if i == 0 { progressLine.moveToPoint(pixelPoint) } else { progressLine.addLineToPoint(pixelPoint) } } progressLine.stroke() chartLayer.path = progressLine.CGPath return chartLayer } override func drawRect(rect: CGRect) { super.drawRect(rect) var context: CGContext = UIGraphicsGetCurrentContext() axesComponent.strokeAxes(context) } }
fc049eeaf5c3294cb6b89735858f330f
31.986755
219
0.600602
false
false
false
false
mathiasquintero/Sweeft
refs/heads/master
Example/Sweeft/Person.swift
mit
1
// // Person.swift // Sweeft // // Created by Mathias Quintero on 12/28/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import Sweeft final class Person: Observable { let id: Int let name: String var photo: UIImage? var listeners = [Listener]() init(id: Int, name: String, photo: UIImage? = nil) { self.id = id self.name = name self.photo = photo } func fetchImage(with path: String) { MovieImageAPI.fetchImage(with: path).onSuccess { image in self.photo = image self.hasChanged() } } } extension Person: Deserializable { convenience init?(from json: JSON) { guard let id = json["id"].int, let name = json["name"].string else { return nil } self.init(id: id, name: name) json["profile_path"].string | fetchImage } } extension Person { static func person(with id: Int, using api: MoviesAPI = .shared) -> Person.Result { return Person.get(using: api, at: .person, arguments: ["id": id]) } static func people(with ids: [Int], using api: MoviesAPI = .shared) -> Person.Results { return api.doBulkObjectRequest(to: .person, arguments: ids => { ["id": $0] }) } } extension Person { func getMovies(using api: MoviesAPI = .shared, limitedTo limit: Int = 25) -> Movie.Results { return api.doJSONRequest(to: .moviesForPerson, arguments: ["id": id]).flatMap(completionQueue: .main) { json -> Response<[Movie]> in let ids = json["cast"].array ==> { $0["id"].int } return Movie.movies(with: ids.array(withFirst: limit), using: api) } } }
36d241171fa9ed66775c758354c6fe50
24.985915
118
0.547967
false
false
false
false
himanshuy/MemeMe-v1.0
refs/heads/master
ImagePick/MemeMeViewController.swift
mit
1
// // MemeMeViewController.swift // ImagePick // // Created by Himanshu Yadav on 8/25/15. // Copyright (c) 2015 Himanshu Yadav. All rights reserved. // import UIKit class MemeMeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { @IBOutlet weak var pickedImage: UIImageView! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var topMemeText: UITextField! @IBOutlet weak var bottomMemeText: UITextField! @IBOutlet weak var topBar: UIToolbar! @IBOutlet weak var bottomToolbar: UIToolbar! @IBOutlet weak var shareButton: UIBarButtonItem! var currentKeyboardHeight: CGFloat = 0.0 let memeTextAttributes = [ NSStrokeColorAttributeName: UIColor.blackColor(), NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!, NSStrokeWidthAttributeName: -2 ] override func viewDidLoad() { super.viewDidLoad() topMemeText.text = "TOP" bottomMemeText.text = "BOTTOM" shareButton.enabled = false memeTextFieldLayout(topMemeText) memeTextFieldLayout(bottomMemeText) } func memeTextFieldLayout(textField: UITextField) { textField.delegate = self textField.textAlignment = NSTextAlignment.Center textField.defaultTextAttributes = memeTextAttributes } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) subscribeToKeyboardNotifications() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) unsubscribeFromKeyboardNotifications() } @IBAction func pickImageFromAlbum(sender: AnyObject) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary presentViewController(imagePicker, animated: true){ self.shareButton.enabled = true } } @IBAction func pickImageFromCamera(sender: AnyObject) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func shareMeme(sender: UIBarButtonItem) { let activityController = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil) presentViewController(activityController, animated: true, completion: nil) activityController.completionWithItemsHandler = { activity, success, items, error in if( activity == UIActivityTypeSaveToCameraRoll && success) { self.saveMeme() self.presentSentMeme() } } } @IBAction func cancelShare(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) presentSentMeme() } func saveMeme() { //create the Meme if(pickedImage.image != nil){ let meme = Meme(topText: topMemeText.text!, bottomText: bottomMemeText.text!, image: pickedImage.image!, memedImage: generateMemedImage()) let object = UIApplication.sharedApplication().delegate let appDelegate = object as! AppDelegate appDelegate.memes.append(meme) UIImageWriteToSavedPhotosAlbum(generateMemedImage(), self, Selector("image:didFinishSavingWithError:contextInfo:"), nil) } } func presentSentMeme() { let memeMeTabBarViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tabBarController") as! UITabBarController self.presentViewController(memeMeTabBarViewController, animated: true, completion: nil) } func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo: UnsafePointer<()>) { dispatch_async(dispatch_get_main_queue(), { UIAlertView(title: "Success", message: "This image has been saved to your Photo album successfully", delegate: nil, cancelButtonTitle: "Close").show() }) } func generateMemedImage() -> UIImage { topBar.hidden = true bottomToolbar.hidden = true //Generate Meme UIGraphicsBeginImageContext(view.frame.size) view.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true) let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() topBar.hidden = false bottomToolbar.hidden = false return memedImage } //Clear the text field func textFieldDidBeginEditing(textField: UITextField) { if textField.text == "TOP" || textField.text == "BOTTOM" { textField.text = "" } } //When user presses return, keyboard dismissed. func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { pickedImage.image = image } dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func subscribeToKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func unsubscribeFromKeyboardNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { if bottomMemeText.isFirstResponder() { let kbSize: CGFloat = getKeyboardHeight(notification) let deltaHeight: CGFloat = kbSize - currentKeyboardHeight view.frame.origin.y -= deltaHeight currentKeyboardHeight = kbSize } } func keyboardWillHide(notification: NSNotification) { //view.frame.origin.y += getKeyboardHeight(notification) currentKeyboardHeight = 0 view.frame.origin.y = 0 } func getKeyboardHeight(notification: NSNotification) -> CGFloat { let userInfo = notification.userInfo let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue //of CGRect return keyboardSize.CGRectValue().height } }
f8f824c4ddc994d1bbb0ef52a01eb7d5
38.016043
162
0.690789
false
false
false
false
minsOne/DigitClockInSwift
refs/heads/master
MainFeature/MainFeature/Dependencies/Settings/Settings/Sources/ViewController.swift
mit
1
// // ViewController.swift // Settings // // Created by minsone on 2019/10/19. // Copyright © 2019 minsone. All rights reserved. // import Foundation import RIBs import RxSwift import UIKit import Library public protocol PresentableListener: class { func update(color: UIColor) func done() } final public class ViewController: UITableViewController, SettingTableViewCellPresenterListener, Instantiable, Presentable, ViewControllable { public static var storyboardName: String { "SettingsViewController" } // MARK: Properties var btnDone: UIBarButtonItem? private let headerTitleList = ["Theme", "Maker", "Version"] private let makerTexts = ["Developer : Ahn Jung Min", "Designer : Joo Sung Hyun"] public weak var listener: PresentableListener? override public var prefersStatusBarHidden: Bool { true } override public func viewDidLoad() { super.viewDidLoad() setup() } func setup() { self.title = "Digit Clock" self.initBarButton() } func initBarButton() { guard responds(to: #selector(pressedDoneBtn)) else { return } btnDone = UIBarButtonItem( barButtonSystemItem: .done, target: self, action: #selector(pressedDoneBtn)) navigationItem.setRightBarButton(btnDone, animated: true) } override public func numberOfSections(in tableView: UITableView) -> Int { 3 } override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 1: return makerTexts.count default: return 1 } } override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: SettingTableViewCell switch indexPath.section { case 1: cell = tableView.dequeueReusableCell(withIdentifier: makerCellIdentifier, for: indexPath) as! SettingMakerTableViewCell let makerCell = cell as! SettingMakerTableViewCell makerCell.makerLabel.text = makerTexts[indexPath.row] case 2: cell = tableView.dequeueReusableCell( withIdentifier: versionCellIdentifier, for: indexPath) as! SettingVersionTableViewCell let versionCell = cell as! SettingVersionTableViewCell let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "" versionCell.versionLabel.text = "Version : " + version default: cell = tableView.dequeueReusableCell(withIdentifier: themeCellIdentifier, for: indexPath) as! SettingThemeTableViewCell } cell.selectionStyle = .none cell.delegate = self return cell } override public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { headerTitleList[section] } override public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80.0 } @objc func pressedDoneBtn(sender: UIBarButtonItem) { listener?.done() } func selectedBackground(theme: UIColor) { listener?.update(color: theme) if !UIDevice.isIPad { listener?.done() } } }
7fe000adc0fd8f2691a9f85275eb0313
29.956897
142
0.620162
false
false
false
false
CodaFi/swift
refs/heads/master
test/SILOptimizer/sil_combine_protocol_conf.swift
apache-2.0
8
// RUN: %target-swift-frontend %s -O -wmo -emit-sil -Xllvm -sil-disable-pass=DeadFunctionElimination | %FileCheck %s // case 1: class protocol -- should optimize internal protocol SomeProtocol : class { func foo(x:SomeProtocol) -> Int func foo_internal() -> Int } internal class SomeClass: SomeProtocol { func foo_internal() ->Int { return 10 } func foo(x:SomeProtocol) -> Int { return x.foo_internal() } } // case 2: non-class protocol -- should optimize internal protocol SomeNonClassProtocol { func bar(x:SomeNonClassProtocol) -> Int func bar_internal() -> Int } internal class SomeNonClass: SomeNonClassProtocol { func bar_internal() -> Int { return 20 } func bar(x:SomeNonClassProtocol) -> Int { return x.bar_internal() } } // case 3: class conforming to protocol has a derived class -- should not optimize internal protocol DerivedProtocol { func foo() -> Int } internal class SomeDerivedClass: DerivedProtocol { func foo() -> Int { return 20 } } internal class SomeDerivedClassDerived: SomeDerivedClass { } // case 3: public protocol -- should not optimize public protocol PublicProtocol { func foo() -> Int } internal class SomePublicClass: PublicProtocol { func foo() -> Int { return 20 } } // case 4: Chain of protocols P1->P2->C -- optimize internal protocol MultiProtocolChain { func foo() -> Int } internal protocol RefinedMultiProtocolChain : MultiProtocolChain { func bar() -> Int } internal class SomeMultiClass: RefinedMultiProtocolChain { func foo() -> Int { return 20 } func bar() -> Int { return 30 } } // case 5: Generic conforming type -- should not optimize internal protocol GenericProtocol { func foo() -> Int } internal class GenericClass<T> : GenericProtocol { var items = [T]() func foo() -> Int { return items.count } } // case 6: two classes conforming to protocol internal protocol MultipleConformanceProtocol { func foo() -> Int } internal class Klass1: MultipleConformanceProtocol { func foo() -> Int { return 20 } } internal class Klass2: MultipleConformanceProtocol { func foo() -> Int { return 30 } } internal class Other { let x:SomeProtocol let y:SomeNonClassProtocol let z:DerivedProtocol let p:PublicProtocol let q:MultiProtocolChain let r:GenericProtocol let s:MultipleConformanceProtocol init(x:SomeProtocol, y:SomeNonClassProtocol, z:DerivedProtocol, p:PublicProtocol, q:MultiProtocolChain, r:GenericProtocol, s:MultipleConformanceProtocol) { self.x = x; self.y = y; self.z = z; self.p = p; self.q = q; self.r = r; self.s = s; } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF : $@convention(method) (@guaranteed Other) -> Int { // CHECK: bb0 // CHECK: debug_value // CHECK: integer_literal // CHECK: [[R1:%.*]] = ref_element_addr %0 : $Other, #Other.z // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*DerivedProtocol to $*@opened("{{.*}}") DerivedProtocol // CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") DerivedProtocol, #DerivedProtocol.foo : <Self where Self : DerivedProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") DerivedProtocol : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W1]]<@opened("{{.*}}") DerivedProtocol>([[O1]]) : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R2:%.*]] = ref_element_addr %0 : $Other, #Other.p // CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*PublicProtocol to $*@opened("{{.*}}") PublicProtocol // CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") PublicProtocol, #PublicProtocol.foo : <Self where Self : PublicProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") PublicProtocol : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W2]]<@opened("{{.*}}") PublicProtocol>([[O2]]) : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R3:%.*]] = ref_element_addr %0 : $Other, #Other.r // CHECK: [[O3:%.*]] = open_existential_addr immutable_access [[R3]] : $*GenericProtocol to $*@opened("{{.*}}") GenericProtocol // CHECK: [[W3:%.*]] = witness_method $@opened("{{.*}}") GenericProtocol, #GenericProtocol.foo : <Self where Self : GenericProtocol> (Self) -> () -> Int, [[O3]] : $*@opened("{{.*}}") GenericProtocol : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W3]]<@opened("{{.*}}") GenericProtocol>([[O3]]) : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R4:%.*]] = ref_element_addr %0 : $Other, #Other.s // CHECK: [[O4:%.*]] = open_existential_addr immutable_access %36 : $*MultipleConformanceProtocol to $*@opened("{{.*}}") MultipleConformanceProtocol // CHECK: [[W4:%.*]] = witness_method $@opened("{{.*}}") MultipleConformanceProtocol, #MultipleConformanceProtocol.foo : <Self where Self : MultipleConformanceProtocol> (Self) -> () -> Int, %37 : $*@opened("{{.*}}") MultipleConformanceProtocol : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W4]]<@opened("{{.*}}") MultipleConformanceProtocol>(%37) : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF' @inline(never) func doWorkClass () ->Int { return self.x.foo(x:self.x) // optimize + self.y.bar(x:self.y) // optimize + self.z.foo() // do not optimize + self.p.foo() // do not optimize + self.q.foo() // optimize + self.r.foo() // do not optimize + self.s.foo() // do not optimize } } // case 1: struct -- optimize internal protocol PropProtocol { var val: Int { get set } } internal struct PropClass: PropProtocol { var val: Int init(val: Int) { self.val = val } } // case 2: generic struct -- do not optimize internal protocol GenericPropProtocol { var val: Int { get set } } internal struct GenericPropClass<T>: GenericPropProtocol { var val: Int init(val: Int) { self.val = val } } // case 3: nested struct -- optimize internal protocol NestedPropProtocol { var val: Int { get } } struct Outer { struct Inner : NestedPropProtocol { var val: Int init(val: Int) { self.val = val } } } // case 4: generic nested struct -- do not optimize internal protocol GenericNestedPropProtocol { var val: Int { get } } struct GenericOuter<T> { struct GenericInner : GenericNestedPropProtocol { var val: Int init(val: Int) { self.val = val } } } internal class OtherClass { var arg1: PropProtocol var arg2: GenericPropProtocol var arg3: NestedPropProtocol var arg4: GenericNestedPropProtocol init(arg1:PropProtocol, arg2:GenericPropProtocol, arg3: NestedPropProtocol, arg4: GenericNestedPropProtocol) { self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 self.arg4 = arg4 } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF : $@convention(method) (@guaranteed OtherClass) -> Int { // CHECK: bb0([[ARG:%.*]] : // CHECK: debug_value // CHECK: [[R1:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg1 // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*PropProtocol to $*@opened("{{.*}}") PropProtocol // CHECK: [[U1:%.*]] = unchecked_addr_cast [[O1]] : $*@opened("{{.*}}") PropProtocol to $*PropClass // CHECK: [[S1:%.*]] = struct_element_addr [[U1]] : $*PropClass, #PropClass.val // CHECK: [[S11:%.*]] = struct_element_addr [[S1]] : $*Int, #Int._value // CHECK: load [[S11]] // CHECK: [[R2:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg2 // CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*GenericPropProtocol to $*@opened("{{.*}}") GenericPropProtocol // CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") GenericPropProtocol, #GenericPropProtocol.val!getter : <Self where Self : GenericPropProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") GenericPropProtocol : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W2]]<@opened("{{.*}}") GenericPropProtocol>([[O2]]) : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R4:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg3 // CHECK: [[O4:%.*]] = open_existential_addr immutable_access [[R4]] : $*NestedPropProtocol to $*@opened("{{.*}}") NestedPropProtocol // CHECK: [[U4:%.*]] = unchecked_addr_cast [[O4]] : $*@opened("{{.*}}") NestedPropProtocol to $*Outer.Inner // CHECK: [[S4:%.*]] = struct_element_addr [[U4]] : $*Outer.Inner, #Outer.Inner.val // CHECK: [[S41:%.*]] = struct_element_addr [[S4]] : $*Int, #Int._value // CHECK: load [[S41]] // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: [[R5:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg4 // CHECK: [[O5:%.*]] = open_existential_addr immutable_access [[R5]] : $*GenericNestedPropProtocol to $*@opened("{{.*}}") GenericNestedPropProtocol // CHECK: [[W5:%.*]] = witness_method $@opened("{{.*}}") GenericNestedPropProtocol, #GenericNestedPropProtocol.val!getter : <Self where Self : GenericNestedPropProtocol> (Self) -> () -> Int, [[O5:%.*]] : $*@opened("{{.*}}") GenericNestedPropProtocol : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W5]]<@opened("{{.*}}") GenericNestedPropProtocol>([[O5]]) : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF' @inline(never) func doWorkStruct () -> Int{ return self.arg1.val // optimize + self.arg2.val // do not optimize + self.arg3.val // optimize + self.arg4.val // do not optimize } } // case 1: enum -- optimize internal protocol AProtocol { var val: Int { get } mutating func getVal() -> Int } internal enum AnEnum : AProtocol { case avalue var val: Int { switch self { case .avalue: return 10 } } mutating func getVal() -> Int { return self.val } } // case 2: generic enum -- do not optimize internal protocol AGenericProtocol { var val: Int { get } mutating func getVal() -> Int } internal enum AGenericEnum<T> : AGenericProtocol { case avalue var val: Int { switch self { case .avalue: return 10 } } mutating func getVal() -> Int { return self.val } } internal class OtherKlass { var arg1: AProtocol var arg2: AGenericProtocol init(arg1:AProtocol, arg2:AGenericProtocol) { self.arg1 = arg1 self.arg2 = arg2 } // CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF : $@convention(method) (@guaranteed OtherKlass) -> Int { // CHECK: bb0([[ARG:%.*]] : // CHECK: debug_value // CHECK: integer_literal // CHECK: [[R1:%.*]] = ref_element_addr [[ARG]] : $OtherKlass, #OtherKlass.arg2 // CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*AGenericProtocol to $*@opened("{{.*}}") AGenericProtocol // CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") AGenericProtocol, #AGenericProtocol.val!getter : <Self where Self : AGenericProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") AGenericProtocol : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: apply [[W1]]<@opened("{{.*}}") AGenericProtocol>([[O1]]) : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int // CHECK: struct_extract // CHECK: integer_literal // CHECK: builtin // CHECK: tuple_extract // CHECK: tuple_extract // CHECK: cond_fail // CHECK: struct // CHECK: return // CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF' @inline(never) func doWorkEnum() -> Int { return self.arg1.val // optimize + self.arg2.val // do not optimize } }
904572737a0291768f2c1def509d63c9
38.150568
386
0.654597
false
false
false
false
Isuru-Nanayakkara/Broadband-Usage-Meter-OSX
refs/heads/master
Broadband Usage Meter/Broadband Usage Meter/PreferencesWindow.swift
mit
1
// // PreferencesWindow.swift // SLT Usage Meter // // Created by Isuru Nanayakkara on 10/23/15. // Copyright © 2015 BitInvent. All rights reserved. // import Cocoa protocol PreferencesDelegate { func preferencesDidUpdate() } class PreferencesWindow: NSWindowController, NSWindowDelegate { @IBOutlet weak var userIDTextField: NSTextField! @IBOutlet weak var passwordTextField: NSSecureTextField! var delegate: PreferencesDelegate? override var windowNibName: String { return "PreferencesWindow" } override func windowDidLoad() { super.windowDidLoad() window?.center() window?.makeKeyAndOrderFront(nil) NSApp.activateIgnoringOtherApps(true) // TODO: Refector NSUserDefaults code duplication let userDefaults = NSUserDefaults.standardUserDefaults() let userID = userDefaults.stringForKey("userID") let password = userDefaults.stringForKey("password") if let userID = userID, let password = password { userIDTextField.stringValue = userID passwordTextField.stringValue = password } // TODO: Add this in the next version. Current placement of the label is ugly // registerLabel.allowsEditingTextAttributes = true // registerLabel.selectable = true // // let url = NSURL(string: "https://www.internetvas.slt.lk/SLTVasPortal-war/register/register.jsp")! // let str = NSMutableAttributedString(string: "If you don't have a portal account, create one ") // str.appendAttributedString(NSAttributedString.hyperlinkFromString("here", withURL: url)) // registerLabel.attributedStringValue = str // registerLabel.alignment = .Center } @IBAction func loginButtonClicked(sender: NSButton) { let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(userIDTextField.stringValue, forKey: "userID") userDefaults.setValue(passwordTextField.stringValue, forKey: "password") delegate?.preferencesDidUpdate() close() } }
b72cf6958e778a14832408b3fc3d8e6b
33.206349
107
0.676102
false
false
false
false
eofster/Telephone
refs/heads/master
UseCasesTestDoubles/RingtonePlaybackUseCaseSpy.swift
gpl-3.0
1
// // RingtonePlaybackUseCaseSpy.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone 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. // // Telephone 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. // import UseCases public final class RingtonePlaybackUseCaseSpy: NSObject { public private(set) var isPlaying = false public private(set) var didCallStart = false public private(set) var didCallStop = false } extension RingtonePlaybackUseCaseSpy: RingtonePlaybackUseCase { public func start() throws { didCallStart = true isPlaying = true } public func stop() { didCallStop = true isPlaying = false } }
a79787490deb8ee21b418473d9dc3ebe
29.108108
72
0.717235
false
false
false
false
swernimo/iOS
refs/heads/master
UI Kit Fundamentals 1/ClickCounter/ClickCounter/ViewController(old).swift
mit
1
// // ViewController.swift // ClickCounter // // Created by Sean Wernimont on 10/23/15. // Copyright © 2015 Just One Guy. All rights reserved. // import UIKit class ViewControllerOld: UIViewController { var count = 0; var label: UILabel! override func viewDidLoad() { super.viewDidLoad() let label = createLabel(); let button = createButton("Increase Count"); button.addTarget(self, action: "incrementCount", forControlEvents: UIControlEvents.TouchUpInside); let decrementButton = createButton("Decrease Count"); decrementButton.frame = CGRectMake(100, 200, 60, 60); decrementButton.addTarget(self, action: "decreaseCount", forControlEvents: UIControlEvents.TouchUpInside); self.view.addSubview(label); self.view.addSubview(button); self.view.addSubview(decrementButton); self.label = label; } func createLabel() -> UILabel{ let label = UILabel(); label.frame = CGRectMake(150, 150, 60, 60); label.text = "0"; return label; } func createButton(title: String) -> UIButton{ let button = UIButton(); button.frame = CGRectMake(150, 250, 60, 60); button.setTitle(title, forState: .Normal); button.setTitleColor(UIColor.blueColor(), forState: .Normal); return button; } func incrementCount() -> Void{ self.count++; self.label.text = "\(self.count)"; } func decreaseCount() -> Void{ self.count--; self.label.text = "\(self.count)"; } }
fb680b125658edb56b7fc99741e0bab1
27.224138
114
0.603301
false
false
false
false
Eonil/EditorLegacy
refs/heads/trial1
Modules/EditorFileTreeNavigationFeature/EditorFileTreeNavigationFeature/FileNavigating/FileSystemMonitor2.swift
mit
1
//// //// FileSystemMonitor2.swift //// Editor //// //// Created by Hoon H. on 11/14/14. //// Copyright (c) 2014 Eonil. All rights reserved. //// // //import Foundation //import EonilDispatch //import EonilFileSystemEvents //import Precompilation // //@availability(*,deprecated=0) //final class FileSystemMonitor2 { // // /// We don't need to know what happen because whatever it happen, // /// it might not be exist at point of receive due to nature of asynchronous notification. // let notifyEventForURL = Notifier<NSURL>() // // let queue:Queue // let stream:EonilFileSystemEventStream // // init(rootLocationToMonitor:NSURL) { // assert(NSThread.currentThread() == NSThread.mainThread()) // // unowned let notify = notifyEventForURL // queue = Queue(label: "FileSystemMonitor2/EventStreamQueue", attribute: Queue.Attribute.Serial) // stream = EonilFileSystemEventStream(callback: { (events:[AnyObject]!) -> Void in // async(Queue.main, { // for e1 in events as [EonilFileSystemEvent] { // let u1 = NSURL(fileURLWithPath: e1.path)!.absoluteURL! // notify.signal(u1) // // } // }) // }, pathsToWatch: [rootLocationToMonitor.path!], latency:1, watchRoot: false, queue: rawObjectOf(queue)) // } //} //
4ba09e04dc3788620f0893bfb0558b91
30
107
0.687097
false
false
false
false
google-books/swift-api-client
refs/heads/develop
GoogleBooksApiClient/HttpClient.swift
mit
1
import Foundation typealias RequestParameter = (key: String, value: String) typealias RequestHeader = (key: String, value: String) enum HttpMethod: String { case get = "GET" case post = "POST" } // A Simple wrapper of URLSession.dataTask final class HttpClient { private let session: URLSession init(session: URLSession) { self.session = session } func execute(request: URLRequest, completionHandler: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) -> URLSessionDataTask { let task = session.dataTask(with: request, completionHandler: { (data, response, error) in guard let response = response, let data = data else { completionHandler(nil, nil, HttpClientError.unknown) return } guard let httpResponse = response as? HTTPURLResponse else { completionHandler(data, nil, HttpClientError.nonHTTPResponse(response: response)) return } completionHandler(data, httpResponse, error) }) return task } } enum HttpClientError: Error { case unknown case nonHTTPResponse(response: URLResponse) }
60071b6ad760b44e407ff1616f3df986
27.952381
133
0.632401
false
false
false
false
LYM-mg/MGOFO
refs/heads/master
MGOFO/MGOFO/Class/Tools/SQLiteManager.swift
mit
1
// // SQLiteManager.swift // FMDB的基本使用 // // Created by ming on 16/4/18. // Copyright © 2016年 ming. All rights reserved. // import UIKit class SQLiteManager: NSObject { // 单例 static let shareInstance: SQLiteManager = SQLiteManager() override init() { super.init() openDB(name: "statues.db") } var dbQueue: FMDatabaseQueue? // 打开数据库/数据库的名称 func openDB(name: String) { // 1.拼接路径 let path = name.cache() // debugPrint(path) // 2.创建数据库对象 // 这哥们会自动打开。内部已经封装创建db dbQueue = FMDatabaseQueue(path: path) // 3.创建表 creatTable() } /// 创建表 private func creatTable(){ // 1.编写SQL语句 // let sql = "CREATE TABLE IF NOT EXISTS t_productmodels(" + // "id INTEGER PRIMARY KEY AUTOINCREMENT," + // "modelId decimal," + // "modelText TEXT," + // "userId INTEGER," + // "creatTime TEXT NOT NULL DEFAULT (datetime('now','localtime'))" + // ");" let sql = "CREATE TABLE IF NOT EXISTS t_productmodels (" + "modelId TEXT PRIMARY KEY, " + "modelText TEXT, " + "userId TEXT, " + "creatTime TEXT NOT NULL DEFAULT (datetime('now','localtime'))" + ");" // 2.执行SQL语句 /// 在FMDB中除了查询语句其他所有的操作都称为更新 /// 在这里执行的操作就是线程安全的?为什么呢?因为其内部是一个串行队列内部开启一条子线程 dbQueue?.inDatabase({ (db) -> Void in db?.executeUpdate(sql, withArgumentsIn: nil) }) } }
0289fe9262812edf93320179486b8d01
22.69697
79
0.530051
false
false
false
false
steven7/ParkingApp
refs/heads/master
MapboxNavigationTests/MapboxNavigationTests.swift
isc
1
import XCTest import FBSnapshotTestCase import MapboxDirections @testable import MapboxNavigation class MapboxNavigationTests: FBSnapshotTestCase { var shieldImage: UIImage { get { let bundle = Bundle(for: MapboxNavigationTests.self) return UIImage(named: "80px-I-280", in: bundle, compatibleWith: nil)! } } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. recordMode = false isDeviceAgnostic = true } func storyboard() -> UIStoryboard { return UIStoryboard(name: "Navigation", bundle: Bundle.navigationUI) } func testManeuverViewMultipleLines() { let controller = storyboard().instantiateViewController(withIdentifier: "RouteManeuverViewController") as! RouteManeuverViewController XCTAssert(controller.view != nil) controller.distance = nil controller.streetLabel.text = "This should be multiple lines" controller.turnArrowView.isEnd = true controller.shieldImage = shieldImage FBSnapshotVerifyView(controller.view) } func testManeuverViewSingleLine() { let controller = storyboard().instantiateViewController(withIdentifier: "RouteManeuverViewController") as! RouteManeuverViewController XCTAssert(controller.view != nil) controller.distance = 1000 controller.streetLabel.text = "This text should shrink" controller.turnArrowView.isEnd = true controller.shieldImage = shieldImage FBSnapshotVerifyView(controller.view) } }
37c9f085346e8e2cff64f3ebfd0b4972
33.897959
142
0.677193
false
true
false
false
venticake/RetricaImglyKit-iOS
refs/heads/master
RetricaImglyKit/Classes/Frontend/Editor/Tools/FocusToolController.swift
mit
1
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** * A `FocusToolController` is reponsible for displaying the UI to adjust the focus of an image. */ @available(iOS 8, *) @objc(IMGLYFocusToolController) public class FocusToolController: PhotoEditToolController { // MARK: - Statics private static let IconCaptionCollectionViewCellReuseIdentifier = "IconCaptionCollectionViewCellReuseIdentifier" private static let IconCaptionCollectionViewCellSize = CGSize(width: 64, height: 80) // MARK: - Properties private lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = FocusToolController.IconCaptionCollectionViewCellSize flowLayout.scrollDirection = .Horizontal flowLayout.minimumLineSpacing = 8 let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.registerClass(IconCaptionCollectionViewCell.self, forCellWithReuseIdentifier: FocusToolController.IconCaptionCollectionViewCellReuseIdentifier) collectionView.backgroundColor = UIColor.clearColor() collectionView.delegate = self collectionView.dataSource = self return collectionView }() private var activeFocusType: IMGLYFocusType = .Off { didSet { if oldValue != activeFocusType { switch activeFocusType { case .Off: UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: { self.circleGradientView?.alpha = 0 self.boxGradientView?.alpha = 0 self.sliderContainerView?.alpha = 0 }) { _ in self.circleGradientView?.hidden = true self.boxGradientView?.hidden = true } case .Linear: boxGradientView?.hidden = false UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: { self.circleGradientView?.alpha = 0 self.boxGradientView?.alpha = 1 self.sliderContainerView?.alpha = 1 }) { _ in self.circleGradientView?.hidden = true } case .Radial: circleGradientView?.hidden = false UIView.animateWithDuration(0.25, delay: 0, options: [.CurveEaseInOut], animations: { self.circleGradientView?.alpha = 1 self.boxGradientView?.alpha = 0 self.sliderContainerView?.alpha = 1 }) { _ in self.boxGradientView?.hidden = true } } } } } private var boxGradientView: BoxGradientView? private var circleGradientView: CircleGradientView? private var sliderContainerView: UIView? private var slider: Slider? private var sliderConstraints: [NSLayoutConstraint]? private var gradientViewConstraints: [NSLayoutConstraint]? private var didPerformInitialGradientViewLayout = false // MARK: - UIViewController /** :nodoc: */ public override func viewDidLoad() { super.viewDidLoad() toolStackItem.performChanges { toolStackItem.mainToolbarView = collectionView toolStackItem.titleLabel?.text = options.title if let applyButton = toolStackItem.applyButton { applyButton.addTarget(self, action: #selector(FocusToolController.apply(_:)), forControlEvents: .TouchUpInside) applyButton.accessibilityLabel = Localize("Apply changes") options.applyButtonConfigurationClosure?(applyButton) } if let discardButton = toolStackItem.discardButton { discardButton.addTarget(self, action: #selector(FocusToolController.discard(_:)), forControlEvents: .TouchUpInside) discardButton.accessibilityLabel = Localize("Discard changes") options.discardButtonConfigurationClosure?(discardButton) } } let boxGradientView = BoxGradientView() boxGradientView.gradientViewDelegate = self boxGradientView.hidden = true boxGradientView.alpha = 0 view.addSubview(boxGradientView) self.boxGradientView = boxGradientView options.boxGradientViewConfigurationClosure?(boxGradientView) let circleGradientView = CircleGradientView() circleGradientView.gradientViewDelegate = self circleGradientView.hidden = true circleGradientView.alpha = 0 view.addSubview(circleGradientView) self.circleGradientView = circleGradientView options.circleGradientViewConfigurationClosure?(circleGradientView) switch photoEditModel.focusType { case .Off: collectionView.selectItemAtIndexPath(NSIndexPath(forItem: IMGLYFocusType.Off.rawValue, inSection: 0), animated: false, scrollPosition: .None) case .Linear: collectionView.selectItemAtIndexPath(NSIndexPath(forItem: IMGLYFocusType.Linear.rawValue, inSection: 0), animated: false, scrollPosition: .None) boxGradientView.hidden = false boxGradientView.alpha = 1 activeFocusType = .Linear case .Radial: collectionView.selectItemAtIndexPath(NSIndexPath(forItem: IMGLYFocusType.Radial.rawValue, inSection: 0), animated: false, scrollPosition: .None) circleGradientView.hidden = false circleGradientView.alpha = 1 activeFocusType = .Radial } let sliderContainerView = UIView() sliderContainerView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8) sliderContainerView.translatesAutoresizingMaskIntoConstraints = false sliderContainerView.alpha = photoEditModel.focusType == .Off ? 0 : 1 view.addSubview(sliderContainerView) self.sliderContainerView = sliderContainerView options.sliderContainerConfigurationClosure?(sliderContainerView) let slider = Slider() slider.accessibilityLabel = Localize("Blur intensity") slider.translatesAutoresizingMaskIntoConstraints = false slider.maximumValue = 15 slider.neutralValue = 2 slider.minimumValue = 2 slider.neutralPointTintColor = UIColor(red: 0.24, green: 0.67, blue: 0.93, alpha: 1) slider.thumbTintColor = UIColor(red: 0.24, green: 0.67, blue: 0.93, alpha: 1) slider.filledTrackColor = UIColor(red: 0.24, green: 0.67, blue: 0.93, alpha: 1) slider.value = photoEditModel.focusBlurRadius sliderContainerView.addSubview(slider) slider.addTarget(self, action: #selector(FocusToolController.changeValue(_:)), forControlEvents: .ValueChanged) self.slider = slider options.sliderConfigurationClosure?(slider) view.setNeedsUpdateConstraints() } private var options: FocusToolControllerOptions { get { return configuration.focusToolControllerOptions } } /** :nodoc: */ public override func updateViewConstraints() { super.updateViewConstraints() if let boxGradientView = boxGradientView, circleGradientView = circleGradientView where gradientViewConstraints == nil { var constraints = [NSLayoutConstraint]() boxGradientView.translatesAutoresizingMaskIntoConstraints = false circleGradientView.translatesAutoresizingMaskIntoConstraints = false constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: boxGradientView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: circleGradientView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)) NSLayoutConstraint.activateConstraints(constraints) gradientViewConstraints = constraints } if let sliderContainerView = sliderContainerView, slider = slider where sliderConstraints == nil { var constraints = [NSLayoutConstraint]() constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: sliderContainerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 44)) constraints.append(NSLayoutConstraint(item: slider, attribute: .CenterY, relatedBy: .Equal, toItem: sliderContainerView, attribute: .CenterY, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: slider, attribute: .Left, relatedBy: .Equal, toItem: sliderContainerView, attribute: .Left, multiplier: 1, constant: 20)) constraints.append(NSLayoutConstraint(item: slider, attribute: .Right, relatedBy: .Equal, toItem: sliderContainerView, attribute: .Right, multiplier: 1, constant: -20)) NSLayoutConstraint.activateConstraints(constraints) sliderConstraints = constraints } } /** :nodoc: */ public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) guard let previewView = delegate?.photoEditToolControllerPreviewView(self), previewContainer = delegate?.photoEditToolControllerPreviewViewScrollingContainer(self) else { return } let flippedControlPoint1 = flipNormalizedPointVertically(photoEditModel.focusNormalizedControlPoint1) let flippedControlPoint2 = flipNormalizedPointVertically(photoEditModel.focusNormalizedControlPoint2) let leftMargin = (previewContainer.bounds.width - previewView.bounds.width) / 2 let topMargin = (previewContainer.bounds.height - previewView.bounds.height) / 2 let denormalizedControlPoint1 = CGPoint(x: flippedControlPoint1.x * previewView.bounds.width + leftMargin, y: flippedControlPoint1.y * previewView.bounds.height + topMargin) let denormalizedControlPoint2 = CGPoint(x: flippedControlPoint2.x * previewView.bounds.width + leftMargin, y: flippedControlPoint2.y * previewView.bounds.height + topMargin) boxGradientView?.controlPoint1 = denormalizedControlPoint1 boxGradientView?.controlPoint2 = denormalizedControlPoint2 circleGradientView?.controlPoint1 = denormalizedControlPoint1 circleGradientView?.controlPoint2 = denormalizedControlPoint2 } // MARK: - PhotoEditToolController /** :nodoc: */ public override func photoEditModelDidChange(notification: NSNotification) { super.photoEditModelDidChange(notification) activeFocusType = photoEditModel.focusType slider?.value = photoEditModel.focusBlurRadius collectionView.selectItemAtIndexPath(NSIndexPath(forItem: activeFocusType.rawValue, inSection: 0), animated: true, scrollPosition: .None) } /** :nodoc: */ public override func didBecomeActiveTool() { super.didBecomeActiveTool() options.didEnterToolClosure?() } /** :nodoc: */ public override func willResignActiveTool() { super.willResignActiveTool() options.willLeaveToolClosure?() } // MARK: - Actions @objc private func changeValue(sender: Slider) { photoEditModel.performChangesWithBlock { self.photoEditModel.focusBlurRadius = CGFloat(sender.value) } options.sliderChangedValueClosure?(sender, activeFocusType) } @objc private func apply(sender: UIButton) { delegate?.photoEditToolControllerDidFinish(self) } @objc private func discard(sender: UIButton) { delegate?.photoEditToolController(self, didDiscardChangesInFavorOfPhotoEditModel: uneditedPhotoEditModel) } // MARK: - Helpers private func normalizeControlPoint(point: CGPoint) -> CGPoint { guard let previewView = delegate?.photoEditToolControllerPreviewView(self) else { return point } if let boxGradientView = boxGradientView where activeFocusType == .Linear { let convertedPoint = previewView.convertPoint(point, fromView: boxGradientView) return CGPoint(x: convertedPoint.x / previewView.bounds.size.width, y: convertedPoint.y / previewView.bounds.size.height) } else if let circleGradientView = circleGradientView where activeFocusType == .Radial { let convertedPoint = previewView.convertPoint(point, fromView: circleGradientView) return CGPoint(x: convertedPoint.x / previewView.bounds.size.width, y: convertedPoint.y / previewView.bounds.size.height) } return point } private func denormalizeControlPoint(point: CGPoint) -> CGPoint { guard let previewView = delegate?.photoEditToolControllerPreviewView(self) else { return point } if let boxGradientView = boxGradientView where activeFocusType == .Linear { let denormalizedPoint = CGPoint(x: point.x * previewView.bounds.size.width, y: point.y * previewView.bounds.size.height) return previewView.convertPoint(denormalizedPoint, toView: boxGradientView) } else if let circleGradientView = circleGradientView where activeFocusType == .Radial { let denormalizedPoint = CGPoint(x: point.x * previewView.bounds.size.width, y: point.y * previewView.bounds.size.height) return previewView.convertPoint(denormalizedPoint, toView: circleGradientView) } return point } private func flipNormalizedPointVertically(point: CGPoint) -> CGPoint { return CGPoint(x: point.x, y: 1 - point.y) } } @available(iOS 8, *) extension FocusToolController: UICollectionViewDelegate { /** :nodoc: */ public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let actionType = options.allowedFocusTypes[indexPath.item] photoEditModel.focusType = actionType switch actionType { case .Off: UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) case .Linear: photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(boxGradientView?.controlPoint1 ?? CGPoint.zero)) photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(boxGradientView?.controlPoint2 ?? CGPoint.zero)) UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, boxGradientView) case.Radial: photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(circleGradientView?.controlPoint1 ?? CGPoint.zero)) photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(circleGradientView?.controlPoint2 ?? CGPoint.zero)) UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, circleGradientView) } options.focusTypeSelectedClosure?(activeFocusType) } } @available(iOS 8, *) extension FocusToolController: UICollectionViewDataSource { /** :nodoc: */ public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } /** :nodoc: */ public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return options.allowedFocusTypes.count } /** :nodoc: */ public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(FocusToolController.IconCaptionCollectionViewCellReuseIdentifier, forIndexPath: indexPath) let actionType = options.allowedFocusTypes[indexPath.item] if let iconCaptionCell = cell as? IconCaptionCollectionViewCell { if actionType == .Off { iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_option_focus_off", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("No Focus") iconCaptionCell.accessibilityLabel = Localize("No Focus") } else if actionType == .Linear { iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_option_focus_linear", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Linear") iconCaptionCell.accessibilityLabel = Localize("Linear focus") } else if actionType == .Radial { iconCaptionCell.imageView.image = UIImage(named: "imgly_icon_option_focus_radial", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection: nil)?.imageWithRenderingMode(.AlwaysTemplate) iconCaptionCell.captionLabel.text = Localize("Radial") iconCaptionCell.accessibilityLabel = Localize("Radial focus") } options.focusTypeButtonConfigurationClosure?(iconCaptionCell, actionType) } return cell } } @available(iOS 8, *) extension FocusToolController: UICollectionViewDelegateFlowLayout { /** :nodoc: */ public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return UIEdgeInsetsZero } let cellSpacing = flowLayout.minimumLineSpacing let cellWidth = flowLayout.itemSize.width let cellCount = collectionView.numberOfItemsInSection(section) let inset = max((collectionView.bounds.width - (CGFloat(cellCount) * (cellWidth + cellSpacing))) * 0.5, 0) return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: 0) } } @available(iOS 8, *) extension FocusToolController: GradientViewDelegate { /** :nodoc: */ public func gradientViewUserInteractionStarted(gradientView: UIView) { } /** :nodoc: */ public func gradientViewUserInteractionEnded(gradientView: UIView) { } /** :nodoc: */ public func gradientViewControlPointChanged(gradientView: UIView) { if let gradientView = gradientView as? CircleGradientView where gradientView == circleGradientView { photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint1)) photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint2)) } else if let gradientView = gradientView as? BoxGradientView where gradientView == boxGradientView { photoEditModel.focusNormalizedControlPoint1 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint1)) photoEditModel.focusNormalizedControlPoint2 = flipNormalizedPointVertically(normalizeControlPoint(gradientView.controlPoint2)) } } }
8ba15830f301cd7bc1bfa4d0989e1fab
46.837004
210
0.698269
false
false
false
false
APUtils/APExtensions
refs/heads/master
APExtensions/Classes/Core/_Extensions/_UIKit/UIImage+Utils.swift
mit
1
// // UIImage+Utils.swift // APExtensions // // Created by Anton Plebanovich on 9/20/17. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import UIKit public extension UIImage { /// Creates image from contents of local file /// - return: Returns nil if image can not be created or file can not be found. @available(iOS 9.0, *) convenience init?(contentsOfFile file: URL) { guard file.isFileURL && !file.hasDirectoryPath else { return nil } self.init(contentsOfFile: file.path) } /// Returns image with overlay image drawn the center on top. func image(withOverlayImageAtCenter overlayImage: UIImage) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) defer { UIGraphicsEndImageContext() } draw(at: CGPoint(x: 0, y: 0)) let centerRectOrigin = CGPoint(x: (size.width - overlayImage.size.width) / 2, y: (size.height - overlayImage.size.height) / 2) let centerRect = CGRect(origin: centerRectOrigin, size: overlayImage.size) overlayImage.draw(in: centerRect) if let image = UIGraphicsGetImageFromCurrentImageContext() { return image } else { return self } } /// Returns image with overlay image drawn in the `rect` on top. func image(withOverlayImage overlayImage: UIImage, inRect rect: CGRect) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) defer { UIGraphicsEndImageContext() } draw(at: CGPoint(x: 0, y: 0)) overlayImage.draw(in: rect) if let image = UIGraphicsGetImageFromCurrentImageContext() { return image } else { return self } } /// Resizes specified image to required size. It uses aspect fill approach and high interpolation quality. /// - parameters: /// - size: Required size. /// - returns: Resized image. func image(withSize size: CGSize) -> UIImage { guard self.size != size else { return self } let scale = max(size.width / self.size.width, size.height / self.size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) defer { UIGraphicsEndImageContext() } let context = UIGraphicsGetCurrentContext() context?.interpolationQuality = .high let scaledWidth = self.size.width * scale let scaledHeight = self.size.height * scale let originX = (size.width - scaledWidth) / 2 let originY = (size.height - scaledHeight) / 2 draw(in: CGRect(x: originX, y: originY, width: scaledWidth, height: scaledHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() return newImage ?? self } }
ff9c4fb7fa8968b4b5770c1fc6089635
35.384615
134
0.630374
false
false
false
false
SwiftGFX/SwiftMath
refs/heads/master
Sources/String+Math.swift
bsd-2-clause
1
// // String+Math.swift // SwiftMath // // Created by Andrey Volodin on 02.11.16. // // import Foundation internal extension String { var floatArray: [Float] { let ignoredCharacters = CharacterSet(charactersIn: "{} ,") let components = self.components(separatedBy: ignoredCharacters) return components.filter { $0.count > 0 } .map { return Float($0)! } } } public extension Vector2f { // String should be {p.x, p.y} init(_ string: String) { let components = string.floatArray if components.count == 2 { self.init(components[0], components[1]) } else { self.init() } } } public extension Rect { // String should be {o.x, o.y, s.w, s.h} init(_ string: String) { let components = string.floatArray if components.count == 2 { self.init(origin: Point(components[0], components[1]), size: Size(components[2], components[3])) } else { self.init() } } }
7e94cc614ad6eeb24118a4c9f6e62899
23.727273
72
0.539522
false
false
false
false
jverkoey/FigmaKit
refs/heads/main
Sources/FigmaKit/Node/SliceNode.swift
apache-2.0
1
extension Node { public final class SliceNode: Node { /// Bounding box of the node in absolute space coordinates. public let absoluteBoundingBox: FigmaKit.Rectangle /// An array of export settings representing images to export from the node. public let exportSettings: [ExportSetting] /// The top two rows of a matrix that represents the 2D transform of this node relative to its parent. /// /// The bottom row of the matrix is implicitly always (0, 0, 1). Use to transform coordinates in geometry. public let relativeTransform: Transform /// Width and height of element. /// /// This is different from the width and height of the bounding box in that the absolute bounding box /// represents the element after scaling and rotation. public let size: FigmaKit.Vector private enum CodingKeys: String, CodingKey { case absoluteBoundingBox case exportSettings case relativeTransform case size } public required init(from decoder: Decoder) throws { let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys) self.absoluteBoundingBox = try keyedDecoder.decode(FigmaKit.Rectangle.self, forKey: .absoluteBoundingBox) self.exportSettings = try keyedDecoder.decodeIfPresent([ExportSetting].self, forKey: .exportSettings) ?? [] self.relativeTransform = try keyedDecoder.decode(Transform.self, forKey: .relativeTransform) self.size = try keyedDecoder.decode(FigmaKit.Vector.self, forKey: .size) try super.init(from: decoder) } public override func encode(to encoder: Encoder) throws { fatalError("Not yet implemented") } override var contentDescription: String { return """ - absoluteBoundingBox: \(absoluteBoundingBox) - exportSettings: \(exportSettings.description.indented(by: 2)) - relativeTransform: \(relativeTransform) - size: \(size) """ } } }
784fb4d407d4baafddccec49146074a6
39.22
113
0.683739
false
false
false
false
BryanHoke/swift-corelibs-foundation
refs/heads/master
Foundation/NSDictionary.swift
apache-2.0
2
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation extension Dictionary : _ObjectTypeBridgeable { public func _bridgeToObject() -> NSDictionary { let keyBuffer = UnsafeMutablePointer<NSObject>.alloc(count) let valueBuffer = UnsafeMutablePointer<AnyObject>.alloc(count) var idx = 0 self.forEach { let key = _NSObjectRepresentableBridge($0.0) let value = _NSObjectRepresentableBridge($0.1) keyBuffer.advancedBy(idx).initialize(key) valueBuffer.advancedBy(idx).initialize(value) idx++ } let dict = NSDictionary(objects: valueBuffer, forKeys: keyBuffer, count: count) keyBuffer.destroy(count) valueBuffer.destroy(count) keyBuffer.dealloc(count) valueBuffer.dealloc(count) return dict } public static func _forceBridgeFromObject(x: NSDictionary, inout result: Dictionary?) { var dict = [Key: Value]() var failedConversion = false if x.dynamicType == NSDictionary.self || x.dynamicType == NSMutableDictionary.self { x.enumerateKeysAndObjectsUsingBlock { key, value, stop in if let k = key as? Key { if let v = value as? Value { dict[k] = v } else { failedConversion = true stop.memory = true } } else { failedConversion = true stop.memory = true } } } else if x.dynamicType == _NSCFDictionary.self { let cf = x._cfObject let cnt = CFDictionaryGetCount(cf) let keys = UnsafeMutablePointer<UnsafePointer<Void>>.alloc(cnt) let values = UnsafeMutablePointer<UnsafePointer<Void>>.alloc(cnt) CFDictionaryGetKeysAndValues(cf, keys, values) for idx in 0..<cnt { let key = unsafeBitCast(keys.advancedBy(idx).memory, AnyObject.self) let value = unsafeBitCast(values.advancedBy(idx).memory, AnyObject.self) if let k = key as? Key { if let v = value as? Value { dict[k] = v } else { failedConversion = true break } } else { failedConversion = true break } } keys.destroy(cnt) values.destroy(cnt) keys.dealloc(cnt) values.dealloc(cnt) } if !failedConversion { result = dict } } public static func _conditionallyBridgeFromObject(x: NSDictionary, inout result: Dictionary?) -> Bool { _forceBridgeFromObject(x, result: &result) return true } } public class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID()) internal var _storage = [NSObject: AnyObject]() public var count: Int { get { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage.count } else { NSRequiresConcreteImplementation() } } } public func objectForKey(aKey: AnyObject) -> AnyObject? { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage[aKey as! NSObject] } else { NSRequiresConcreteImplementation() } } public func keyEnumerator() -> NSEnumerator { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return NSGeneratorEnumerator(_storage.keys.generate()) } else { NSRequiresConcreteImplementation() } } public override convenience init() { self.init(objects: nil, forKeys: nil, count: 0) } public required init(objects: UnsafePointer<AnyObject>, forKeys keys: UnsafePointer<NSObject>, count cnt: Int) { for idx in 0..<cnt { let key = keys[idx].copy() let value = objects[idx] _storage[key as! NSObject] = value } } public required convenience init?(coder aDecoder: NSCoder) { self.init(objects: nil, forKeys: nil, count: 0) } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public convenience init(object: AnyObject, forKey key: NSCopying) { self.init(objects: [object], forKeys: [key as! NSObject]) } // public convenience init(dictionary otherDictionary: [NSObject : AnyObject]) { // self.init(dictionary: otherDictionary, copyItems: false) // } // public convenience init(dictionary otherDictionary: [NSObject : AnyObject], copyItems flag: Bool) { // var keys = Array<KeyType>() // var values = Array<AnyObject>() // for key in otherDictionary.keys { // keys.append(key) // var value = otherDictionary[key] // if flag { // if let val = value as? NSObject { // value = val.copy() // } // } // values.append(value!) // } // self.init(objects: values, forKeys: keys) // } public convenience init(objects: [AnyObject], forKeys keys: [NSObject]) { let keyBuffer = UnsafeMutablePointer<NSObject>.alloc(keys.count) for idx in 0..<keys.count { keyBuffer[idx] = keys[idx] } let valueBuffer = UnsafeMutablePointer<AnyObject>.alloc(objects.count) for idx in 0..<objects.count { valueBuffer[idx] = objects[idx] } self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count) keyBuffer.destroy(keys.count) valueBuffer.destroy(objects.count) keyBuffer.dealloc(keys.count) valueBuffer.dealloc(objects.count) } public var allKeys: [AnyObject] { get { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage.keys.map { $0 } } else { var keys = [AnyObject]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { keys.append(key) } return keys } } } public var allValues: [AnyObject] { get { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage.values.map { $0 } } else { var values = [AnyObject]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { values.append(objectForKey(key)!) } return values } } } /// Alternative pseudo funnel method for fastpath fetches from dictionaries /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: Since this API is under consideration it may be either removed or revised in the near future public func getObjects(inout objects: [AnyObject], inout andKeys keys: [AnyObject], count: Int) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { for (key, value) in _storage { keys.append(key) objects.append(value) } } else { let enumerator = keyEnumerator() while let key = enumerator.nextObject() { let value = objectForKey(key)! keys.append(key) objects.append(value) } } } public subscript (key: AnyObject) -> AnyObject? { get { return objectForKey(key) } } public func allKeysForObject(anObject: AnyObject) -> [AnyObject] { var matching = Array<AnyObject>() enumerateKeysAndObjectsWithOptions([]) { key, value, _ in if value === anObject { matching.append(key) } } return matching } public override var description: String { NSUnimplemented() } public var descriptionInStringsFileFormat: String { NSUnimplemented() } public func descriptionWithLocale(locale: AnyObject?) -> String { NSUnimplemented() } public func descriptionWithLocale(locale: AnyObject?, indent level: Int) -> String { NSUnimplemented() } public func isEqualToDictionary(otherDictionary: [NSObject : AnyObject]) -> Bool { if count != otherDictionary.count { return false } for key in keyEnumerator() { if let otherValue = otherDictionary[key as! NSObject] as? NSObject { let value = objectForKey(key as! NSObject)! as! NSObject if otherValue != value { return false } } else { return false } } return true } public struct Generator : GeneratorType { let dictionary : NSDictionary var keyGenerator : Array<AnyObject>.Generator public mutating func next() -> (key: AnyObject, value: AnyObject)? { if let key = keyGenerator.next() { return (key, dictionary.objectForKey(key)!) } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.generate() } } internal struct ObjectGenerator: GeneratorType { let dictionary : NSDictionary var keyGenerator : Array<AnyObject>.Generator mutating func next() -> AnyObject? { if let key = keyGenerator.next() { return dictionary.objectForKey(key)! } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.generate() } } public func objectEnumerator() -> NSEnumerator { return NSGeneratorEnumerator(ObjectGenerator(self)) } public func objectsForKeys(keys: [NSObject], notFoundMarker marker: AnyObject) -> [AnyObject] { var objects = [AnyObject]() for key in keys { if let object = objectForKey(key) { objects.append(object) } else { objects.append(marker) } } return objects } public func writeToFile(path: String, atomically useAuxiliaryFile: Bool) -> Bool { NSUnimplemented() } public func writeToURL(url: NSURL, atomically: Bool) -> Bool { NSUnimplemented() } // the atomically flag is ignored if url of a type that cannot be written atomically. public func enumerateKeysAndObjectsUsingBlock(block: (NSObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateKeysAndObjectsWithOptions([], usingBlock: block) } public func enumerateKeysAndObjectsWithOptions(opts: NSEnumerationOptions, usingBlock block: (NSObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Void) { let count = self.count var keys = [AnyObject]() var objects = [AnyObject]() getObjects(&objects, andKeys: &keys, count: count) var stop = ObjCBool(false) for idx in 0..<count { withUnsafeMutablePointer(&stop, { stop in block(keys[idx] as! NSObject, objects[idx], stop) }) if stop { break } } } public func keysSortedByValueUsingComparator(cmptr: NSComparator) -> [AnyObject] { return keysSortedByValueWithOptions([], usingComparator: cmptr) } public func keysSortedByValueWithOptions(opts: NSSortOptions, usingComparator cmptr: NSComparator) -> [AnyObject] { let sorted = allKeys.sort { lhs, rhs in return cmptr(lhs, rhs) == .OrderedSame } return sorted } public func keysOfEntriesPassingTest(predicate: (AnyObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<NSObject> { return keysOfEntriesWithOptions([], passingTest: predicate) } public func keysOfEntriesWithOptions(opts: NSEnumerationOptions, passingTest predicate: (AnyObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<NSObject> { var matching = Set<NSObject>() enumerateKeysAndObjectsWithOptions(opts) { key, value, stop in if predicate(key, value, stop) { matching.insert(key) } } return matching } override internal var _cfTypeID: CFTypeID { return CFDictionaryGetTypeID() } required public convenience init(dictionaryLiteral elements: (NSObject, AnyObject)...) { var keys = [NSObject]() var values = [AnyObject]() for (key, value) in elements { keys.append(key) values.append(value) } self.init(objects: values, forKeys: keys) } } extension NSDictionary : _CFBridgable, _SwiftBridgable { internal var _cfObject: CFDictionaryRef { return unsafeBitCast(self, CFDictionaryRef.self) } internal var _swiftObject: Dictionary<NSObject, AnyObject> { var dictionary: [NSObject: AnyObject]? Dictionary._forceBridgeFromObject(self, result: &dictionary) return dictionary! } } extension NSMutableDictionary { internal var _cfMutableObject: CFMutableDictionaryRef { return unsafeBitCast(self, CFMutableDictionaryRef.self) } } extension CFDictionaryRef : _NSBridgable, _SwiftBridgable { internal var _nsObject: NSDictionary { return unsafeBitCast(self, NSDictionary.self) } internal var _swiftObject: [NSObject: AnyObject] { return _nsObject._swiftObject } } extension Dictionary : _NSBridgable, _CFBridgable { internal var _nsObject: NSDictionary { return _bridgeToObject() } internal var _cfObject: CFDictionaryRef { return _nsObject._cfObject } } public class NSMutableDictionary : NSDictionary { public func removeObjectForKey(aKey: AnyObject) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { if let key = aKey as? NSObject { _storage.removeValueForKey(key) } // CFDictionaryRemoveValue(unsafeBitCast(self, CFMutableDictionaryRef.self), unsafeBitCast(aKey, UnsafePointer<Void>.self)) } else { NSRequiresConcreteImplementation() } } public func setObject(anObject: AnyObject, forKey aKey: NSObject) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { _storage[aKey] = anObject // CFDictionarySetValue(unsafeBitCast(self, CFMutableDictionaryRef.self), unsafeBitCast(aKey, UnsafePointer<Void>.self), unsafeBitCast(anObject, UnsafePointer<Void>.self)) } else { NSRequiresConcreteImplementation() } } public convenience required init() { self.init(capacity: 0) } public init(capacity numItems: Int) { super.init(objects: nil, forKeys: nil, count: 0) } public convenience required init?(coder aDecoder: NSCoder) { self.init() } public required init(objects: UnsafePointer<AnyObject>, forKeys keys: UnsafePointer<NSObject>, count cnt: Int) { super.init(objects: objects, forKeys: keys, count: cnt) } public convenience init?(contentsOfFile path: String) { NSUnimplemented() } public convenience init?(contentsOfURL url: NSURL) { NSUnimplemented() } } extension NSMutableDictionary { public func addEntriesFromDictionary(otherDictionary: [NSObject : AnyObject]) { for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } public func removeAllObjects() { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { _storage.removeAll() // CFDictionaryRemoveAllValues(unsafeBitCast(self, CFMutableDictionaryRef.self)) } else { for key in allKeys { removeObjectForKey(key) } } } public func removeObjectsForKeys(keyArray: [AnyObject]) { for key in keyArray { removeObjectForKey(key) } } public func setDictionary(otherDictionary: [NSObject : AnyObject]) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { _storage = otherDictionary } else { removeAllObjects() for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } } public subscript (key: NSObject) -> AnyObject? { get { return objectForKey(key) } set { if let val = newValue { setObject(val, forKey: key) } else { removeObjectForKey(key) } } } } extension NSDictionary : SequenceType { public func generate() -> Generator { return Generator(self) } } // MARK - Shared Key Sets extension NSDictionary { /* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:. The keys are copied from the array and must be copyable. If the array parameter is nil or not an NSArray, an exception is thrown. If the array of keys is empty, an empty key set is returned. The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used). As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant. Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage. */ public class func sharedKeySetForKeys(keys: [NSCopying]) -> AnyObject { NSUnimplemented() } } extension NSMutableDictionary { /* Create a mutable dictionary which is optimized for dealing with a known set of keys. Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal. As with any dictionary, the keys must be copyable. If keyset is nil, an exception is thrown. If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown. */ public convenience init(sharedKeySet keyset: AnyObject) { NSUnimplemented() } } extension NSDictionary : DictionaryLiteralConvertible { } extension Dictionary : Bridgeable { public func bridge() -> NSDictionary { return _nsObject } } extension NSDictionary : Bridgeable { public func bridge() -> [NSObject: AnyObject] { return _swiftObject } }
0cbc5f8aa5aca8284c919bb669f06c3c
34.846975
182
0.596446
false
false
false
false
CombineCommunity/CombineExt
refs/heads/main
Sources/Operators/Internal/Lock.swift
mit
1
// swiftlint:disable all //===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// import Darwin @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) typealias Lock = os_unfair_lock_t @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) extension UnsafeMutablePointer where Pointee == os_unfair_lock_s { internal init() { let l = UnsafeMutablePointer.allocate(capacity: 1) l.initialize(to: os_unfair_lock()) self = l } internal func cleanupLock() { deinitialize(count: 1) deallocate() } internal func lock() { os_unfair_lock_lock(self) } internal func tryLock() -> Bool { let result = os_unfair_lock_trylock(self) return result } internal func unlock() { os_unfair_lock_unlock(self) } }
6a7f2e43d857de8491ce2fbe614f9c60
26.288889
80
0.59772
false
false
false
false
ozbe/dwift
refs/heads/master
Dwift.playground/contents.swift
mit
1
import UIKit // Replace token & pin for uat let token = "" let pin = "" //: //: Constants //: class Paths { static let host = "https://uat.dwolla.com/oauth/rest" static let transactionsSubpath = "/transactions" static let sendSubpath = transactionsSubpath + "/send" } class ErrorMessages { static let InvalidAccessToken = "Invalid access token" static let InsufficientBalance = "Insufficient balance" static let InvalidAccountPin = "Invalid account PIN" } class RequestKeys { static let DestinationId = "destinationId" static let Pin = "pin" static let Amount = "amount" static let DestinationType = "destinationType" static let FundsSource = "fundsSource" static let Notes = "notes" static let AssumeCosts = "assumeCosts" static let AdditionalFees = "additionalFees" static let Metadata = "metadata" static let AssumeAdditionalFees = "assumeAdditionalFees" static let FacilitatorAmount = "facilitatorAmount" } class ResponseKeys { static let Success = "Success" static let Message = "Message" static let Response = "Response" } //: //: Enums //: enum TransactionStatus { case Pending case Processed case Failed case Cancelled case Reclaimed } enum TransactionType { case MoneySent case MoneyReceived case Deposit case Withdrawal case Fee } enum DestinationType { case Dwolla case Email case Phone case Twitter case Facebook case LinkedIn } enum Scopes { case Send } enum HttpMethod: String { case GET = "GET" case POST = "POST" } //: //: Structs //: struct JsonRequest { var url: String var method: HttpMethod var headers: [String: String?]? var params: [String: String]? var body: [String: AnyObject]? init(url: String, method: HttpMethod = .GET, headers: [String: String?]? = nil, params: [String: String]? = nil, body: [String: AnyObject]? = nil) { self.url = url self.method = method self.headers = headers self.params = params self.body = body } } struct JsonResponse { let status: Int let headers: [String: String]? = nil let body: [String: AnyObject]? = nil } struct Response<T> { let success: Bool let message: String let response: T? } struct Entity { let id: String let name: String } struct SendRequest { let destinationId: String let pin: String let amount: Double let destinationType: DestinationType? let fundsSource: String? let notes: String? let assumeCosts: Bool? let additionalFeeds: Bool? let metadata: [String: String]? let assumeAdditionalFees: Bool? let facilitatorAmount: Bool? init(destinationId: String, pin: String, amount: Double, destinationType: DestinationType? = nil, fundsSource: String? = nil, notes: String? = nil, assumeCosts: Bool? = nil, additionalFeeds: Bool? = nil, metadata: [String: String]? = nil, assumeAdditionalFees: Bool? = nil, facilitatorAmount: Bool? = nil) { self.destinationId = destinationId self.pin = pin self.amount = amount self.destinationType = destinationType self.fundsSource = fundsSource self.notes = notes self.assumeCosts = assumeCosts self.additionalFeeds = additionalFeeds self.metadata = metadata self.assumeAdditionalFees = assumeAdditionalFees self.facilitatorAmount = facilitatorAmount } } //: //: ## Protocols //: protocol ToJson { func toJson() -> [String: AnyObject] } protocol ToJsonValue { func toJsonValue() -> String } protocol JsonClient { func execute(request: JsonRequest) -> (JsonResponse?, NSError?) } protocol DwollaApi { func send(request: SendRequest) -> Response<Double> } //: //: ## Extensions //: // From good 'ol stackoverflow extension Dictionary { init(_ pairs: [Element]) { self.init() for (k, v) in pairs { self[k] = v } } func map<OutKey: Hashable, OutValue>(transform: Element -> (OutKey, OutValue)) -> [OutKey: OutValue] { return Dictionary<OutKey, OutValue>(Swift.map(self, transform)) } func filter(includeElement: Element -> Bool) -> [Key: Value] { return Dictionary(Swift.filter(self, includeElement)) } } extension TransactionStatus: ToJsonValue { func toJsonValue() -> String { switch self { case .Cancelled: return "cancelled" default: return "" } } } extension DestinationType: ToJsonValue { func toJsonValue() -> String { switch self { case .Dwolla: return "dwolla" default: return "" } } } extension SendRequest: ToJson { func toJson() -> [String : AnyObject] { return [ RequestKeys.DestinationId: self.destinationId, RequestKeys.Pin: self.pin, RequestKeys.Amount: self.amount, RequestKeys.DestinationType: getOptionalJson(self.destinationType) ] } private func getOptionalJson(value: Optional<ToJsonValue>) -> String { return value?.toJsonValue() ?? "" } } //: //: ## Classes //: class NSURLRequestBuilder { var urlRequest = NSMutableURLRequest() func setUrl(url: String?) -> NSURLRequestBuilder { if let url = url { urlRequest.URL = NSURL(string: url) } else { urlRequest.URL = nil } return self } func setMethod(method: HttpMethod) -> NSURLRequestBuilder { urlRequest.HTTPMethod = method.rawValue return self } func setHeaders(headers: [String: String?]?) -> NSURLRequestBuilder { if let headers = headers { for header in headers { urlRequest.setValue(header.1, forHTTPHeaderField: header.0) } } else { urlRequest.allHTTPHeaderFields = nil } return self } func setParams(params: [String: String]?, encode: Bool = true) -> NSURLRequestBuilder { // TODO // encode? // fun? // may have to set url in build with params return self } func setBody(body: [String: AnyObject]?, error: NSErrorPointer) -> NSURLRequestBuilder { if let body = body, let data = NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.allZeros, error: error) { setBody(data) urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } else { setBody(nil) } return self } func setBody(body: NSData?) -> NSURLRequestBuilder { urlRequest.HTTPBody = body urlRequest.setValue(body?.length.description, forHTTPHeaderField: "Content-Length") return self } func setJsonRequest(jsonRequest: JsonRequest, error: NSErrorPointer) -> NSURLRequestBuilder { return self .setUrl(jsonRequest.url) .setMethod(jsonRequest.method) .setHeaders(jsonRequest.headers) .setParams(jsonRequest.params) .setBody(jsonRequest.body, error: error) } func reset() { urlRequest = NSMutableURLRequest() } func build() -> NSURLRequest { return urlRequest.copy() as! NSURLRequest } } class NSJsonClient: JsonClient { let dummyError = NSError(domain: "", code: 1, userInfo: nil) let urlBuilder = NSURLRequestBuilder() func execute(request: JsonRequest) -> (JsonResponse?, NSError?) { switch createURLRequest(request) { case let (_, .Some(error)): return (nil, error) case let (.Some(urlRequest), _): return execute(urlRequest) default: return (nil, dummyError) } } private func createURLRequest(jsonRequest: JsonRequest) -> (NSURLRequest?, NSError?) { var error: NSError? if let url = NSURL(string: jsonRequest.url) { let urlRequest = urlBuilder .setJsonRequest(jsonRequest, error: &error) .build() return (urlRequest, error) } else { return (nil, dummyError) } } private func execute(urlRequest: NSURLRequest) -> (JsonResponse?, NSError?) { switch performRequest(urlRequest) { case let (_, _, error) where error != nil: return (nil, error) case let (.Some(data), .Some(urlResponse), _) where urlResponse is NSHTTPURLResponse: return createJsonResponse(data, response: urlResponse as! NSHTTPURLResponse) default: return (nil, dummyError) } } private func performRequest(urlRequest: NSURLRequest) -> (NSData?, NSURLResponse?, NSError?) { let semaphore = dispatch_semaphore_create(0); var data: NSData? = nil var response: NSURLResponse? = nil var error: NSError? = nil NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (taskData, taskResponse, taskError) -> Void in data = taskData response = taskResponse error = taskError dispatch_semaphore_signal(semaphore); }).resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); return (data, response, error) } private func createJsonResponse(data: NSData, response: NSHTTPURLResponse) -> (JsonResponse?, NSError?) { var error: NSError? let headers = response.allHeaderFields.map { (k, v) in (k as! String, v as! String) } let body = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as! Dictionary<String, AnyObject> return (JsonResponse(status: response.statusCode, headers: headers, body: body), error) } } class DwollaApiV2: DwollaApi { let headers: [String: String?] let client: JsonClient let host: String convenience init(token: String) { self.init(token: token, host: Paths.host, client: NSJsonClient()) } init(token: String, host: String, client: JsonClient) { headers = [ "Authorization": "Bearer \(token)" ] self.host = host self.client = client } func send(request: SendRequest) -> Response<Double> { return post(Paths.sendSubpath, body: request.toJson()) { response in if let response = response as? Double { return response } return nil } } private func get<T>(subPath: String, params: [String: String]?, responseTransform: (AnyObject?) -> T?) -> Response<T> { let jsonRequest = JsonRequest(url: host + subPath, method: .GET, headers: headers, params: params) return execute(jsonRequest, responseTransform: responseTransform) } private func post<T>(subPath: String, body: [String: AnyObject], responseTransform: (AnyObject?) -> T?) -> Response<T> { let jsonRequest = JsonRequest(url: host + subPath, method: .POST, headers: headers, body: body) return execute(jsonRequest, responseTransform: responseTransform) } private func execute<T>(jsonRequest: JsonRequest, responseTransform: (AnyObject?) -> T?) -> Response<T> { switch client.execute(jsonRequest) { case let (_, .Some(error)): return Response(success: false, message: error.description, response: nil) case let (.Some(jsonResponse), _): return parse(jsonResponse.body, transform: responseTransform) default: return Response(success: false, message: "Unexpected error", response: nil) } } private func parse<T>(body: [String: AnyObject]?, transform: (AnyObject?) -> T?) -> Response<T> { if let body = body, let success = body[ResponseKeys.Success] as? Bool, let message = body[ResponseKeys.Message] as? String, let response = transform(body[ResponseKeys.Response]) { return Response(success: success, message: message, response: response) } else { return Response(success: false, message: "Unknown error", response: nil) } } } //: //: ## Send //: // happy path let client = DwollaApiV2(token: token) let sendRequest = SendRequest(destinationId: "812-741-6790", pin: pin, amount: 0.01) let sendResponse = client.send(sendRequest) // invalid pin // invalid amount
2da3bc90a49e53ad0b50741e5fe8569f
27.050328
152
0.610344
false
false
false
false
tjw/swift
refs/heads/master
benchmark/utils/TestsUtils.swift
apache-2.0
1
//===--- TestsUtils.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 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 // //===----------------------------------------------------------------------===// #if os(Linux) import Glibc #else import Darwin #endif public enum BenchmarkCategory : String { // Validation "micro" benchmarks test a specific operation or critical path that // we know is important to measure. case validation // subsystems to validate and their subcategories. case api, Array, String, Dictionary, Codable, Set, Data case sdk case runtime, refcount, metadata // Other general areas of compiled code validation. case abstraction, safetychecks, exceptions, bridging, concurrency // Algorithms are "micro" that test some well-known algorithm in isolation: // sorting, searching, hashing, fibonaci, crypto, etc. case algorithm // Miniapplications are contrived to mimic some subset of application behavior // in a way that can be easily measured. They are larger than micro-benchmarks, // combining multiple APIs, data structures, or algorithms. This includes small // standardized benchmarks, pieces of real applications that have been extracted // into a benchmark, important functionality like JSON parsing, etc. case miniapplication // Regression benchmarks is a catch-all for less important "micro" // benchmarks. This could be a random piece of code that was attached to a bug // report. We want to make sure the optimizer as a whole continues to handle // this case, but don't know how applicable it is to general Swift performance // relative to the other micro-benchmarks. In particular, these aren't weighted // as highly as "validation" benchmarks and likely won't be the subject of // future investigation unless they significantly regress. case regression // Most benchmarks are assumed to be "stable" and will be regularly tracked at // each commit. A handful may be marked unstable if continually tracking them is // counterproductive. case unstable // CPU benchmarks represent instrinsic Swift performance. They are useful for // measuring a fully baked Swift implementation across different platforms and // hardware. The benchmark should also be reasonably applicable to real Swift // code--it should exercise a known performance critical area. Typically these // will be drawn from the validation benchmarks once the language and standard // library implementation of the benchmark meets a reasonable efficiency // baseline. A benchmark should only be tagged "cpubench" after a full // performance investigation of the benchmark has been completed to determine // that it is a good representation of future Swift performance. Benchmarks // should not be tagged if they make use of an API that we plan on // reimplementing or call into code paths that have known opportunities for // significant optimization. case cpubench // Explicit skip marker case skip } public struct BenchmarkInfo { /// The name of the benchmark that should be displayed by the harness. public var name: String /// A function that invokes the specific benchmark routine. public var runFunction: (Int) -> () /// A set of category tags that describe this benchmark. This is used by the /// harness to allow for easy slicing of the set of benchmarks along tag /// boundaries, e.x.: run all string benchmarks or ref count benchmarks, etc. public var tags: [BenchmarkCategory] /// An optional function that if non-null is run before benchmark samples /// are timed. public var setUpFunction: (() -> ())? /// An optional function that if non-null is run immediately after a sample is /// taken. public var tearDownFunction: (() -> ())? public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory], setUpFunction: (() -> ())? = nil, tearDownFunction: (() -> ())? = nil) { self.name = name self.runFunction = runFunction self.tags = tags self.setUpFunction = setUpFunction self.tearDownFunction = tearDownFunction } } extension BenchmarkInfo : Comparable { public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name < rhs.name } public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name == rhs.name } } extension BenchmarkInfo : Hashable { public var hashValue: Int { return name.hashValue } } // Linear function shift register. // // This is just to drive benchmarks. I don't make any claim about its // strength. According to Wikipedia, it has the maximal period for a // 32-bit register. struct LFSR { // Set the register to some seed that I pulled out of a hat. var lfsr : UInt32 = 0xb78978e7 mutating func shift() { lfsr = (lfsr >> 1) ^ (UInt32(bitPattern: -Int32((lfsr & 1))) & 0xD0000001) } mutating func randInt() -> Int64 { var result : UInt32 = 0 for _ in 0..<32 { result = (result << 1) | (lfsr & 1) shift() } return Int64(bitPattern: UInt64(result)) } } var lfsrRandomGenerator = LFSR() // Start the generator from the beginning public func SRand() { lfsrRandomGenerator = LFSR() } public func Random() -> Int64 { return lfsrRandomGenerator.randInt() } @inline(__always) public func CheckResults( _ resultsMatch: Bool, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) { guard _fastPath(resultsMatch) else { print("Incorrect result in \(function), \(file):\(line)") abort() } } public func False() -> Bool { return false } /// This is a dummy protocol to test the speed of our protocol dispatch. public protocol SomeProtocol { func getValue() -> Int } struct MyStruct : SomeProtocol { init() {} func getValue() -> Int { return 1 } } public func someProtocolFactory() -> SomeProtocol { return MyStruct() } // Just consume the argument. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func blackHole<T>(_ x: T) { } // Return the passed argument without letting the optimizer know that. @inline(never) public func identity<T>(_ x: T) -> T { return x } // Return the passed argument without letting the optimizer know that. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func getInt(_ x: Int) -> Int { return x } // The same for String. @inline(never) public func getString(_ s: String) -> String { return s }
4ed987575e730cb88a3b16d49e827ffe
34.367347
90
0.698067
false
false
false
false
MKGitHub/UIPheonix
refs/heads/master
Sources/UIPBaseViewController.swift
apache-2.0
1
/** UIPheonix Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved. https://github.com/MKGitHub/UIPheonix http://www.xybernic.com Copyright 2016/2017/2018/2019 Mohsan Khan 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. */ #if os(iOS) || os(tvOS) import UIKit #elseif os(macOS) import Cocoa #endif /** The base view controller protocol. */ protocol UIPBaseViewControllerProtocol:class { // We can't use "className" because that belongs to Objective-C NSObject. // /// Name of this class. var nameOfClass:String { get } /// Name of this class (static context). static var nameOfClass:String { get } } #if os(iOS) || os(tvOS) /** The base view controller. Subclass this to gain its features. Example code is provided in this file. */ class UIPBaseViewController:UIViewController, UIPBaseViewControllerProtocol { /** We have to implement this because we use `self` in the `makeViewController` function. */ override required public init(nibName nibNameOrNil:String?, bundle nibBundleOrNil:Bundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } /** We have to implement this because we use `self` in the `makeViewController` function. */ required public init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } // MARK: UIPBaseViewControllerProtocol /// Name of this class. var nameOfClass:String { get { return "\(type(of:self))" } } /// Name of this class (static context). static var nameOfClass:String { get { return "\(self)" } } // MARK: Public Member var newInstanceAttributes = Dictionary<String, Any>() // MARK: Public Weak Reference weak var parentVC:UIPBaseViewController? // MARK: Life Cycle /** Example implementation, copy & paste into your concrete class. Create a new instance of this view controller with attributes and a parent view controller for sending attributes back. */ class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T { // with nib guard let vc:T = self.init(nibName:"\(self)", bundle:nil) as? T else { fatalError("[UIPheonix] New instance of type '\(self)' failed to init!") } // init members vc.newInstanceAttributes = attributes vc.parentVC = parentVC return vc } /** This view controller is about to be dismissed. The child view controller should implement this to send data back to its parent view controller. - Returns: A dictionary for our parent view controller, default nil. */ func dismissInstance() -> Dictionary<String, Any>? { // by default we return nil return nil } override func willMove(toParent parent:UIViewController?) { super.willMove(toParent:parent) // `self` view controller is being removed // i.e. we are moving back to our parent if (parent == nil) { if let parentVC = parentVC, let dict = dismissInstance() { parentVC.childViewController(self, willDismissWithAttributes:dict) } } } /** Assuming that this view controller is a parent, then its child is about to be dismissed. The parent view controller should implement this to receive data back from its child view controller. */ func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>) { fatalError("[UIPheonix] You must override \(#function) in your subclass!") } } #elseif os(macOS) /** The base view controller. Subclass this to gain its features. Example code is provided in this file. */ class UIPBaseViewController:NSViewController, UIPBaseViewControllerProtocol { /** We have to implement this because we use `self` in the `makeViewController` function. */ override required public init(nibName nibNameOrNil:NSNib.Name?, bundle nibBundleOrNil:Bundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } /** We have to implement this because we use `self` in the `makeViewController` function. */ required public init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } // MARK: UIPBaseViewControllerProtocol /// Name of this class. var nameOfClass:String { get { return "\(type(of:self))" } } /// Name of this class (static context). static var nameOfClass:String { get { return "\(self)" } } // MARK: Public Member var newInstanceAttributes = Dictionary<String, Any>() // MARK: Public Weak Reference weak var parentVC:UIPBaseViewController? // MARK: Life Cycle /** Example implementation, copy & paste into your concrete class. Create a new instance of this view controller with attributes and a parent view controller for sending attributes back. */ class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T { // with nib guard let vc:T = self.init(nibName:NSNib.Name("\(self)"), bundle:nil) as? T else { fatalError("[UIPheonix] New instance of type '\(self)' failed to init!") } // init members vc.newInstanceAttributes = attributes vc.parentVC = parentVC return vc } /** This view controller is about to be dismissed. The child view controller should implement this to send data back to its parent view controller. - Returns: A dictionary for our parent view controller, default nil. */ func dismissInstance() -> Dictionary<String, Any>? { // by default we return nil return nil } /** Assuming that this view controller is a parent, then its child is about to be dismissed. The parent view controller should implement this to receive data back from its child view controller. */ func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>) { fatalError("[UIPheonix] You must override \(#function) in your subclass!") } } #endif
6e56b0a431c05d7ef451e2df71e40773
30.110204
139
0.610076
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/serialize-and-deserialize-bst.swift
mit
2
/** * https://leetcode.com/problems/serialize-and-deserialize-bst/ * * */ // Date: Sun Jun 28 11:39:57 PDT 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ /// Same as https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ class Codec { // Encodes a tree to a single string. func serialize(_ root: TreeNode?) -> String { var ret: [String] = [] var queue = [root] while queue.isEmpty == false { let node = queue.removeFirst() if let node = node { ret.append("\(node.val)") queue.insert(node.right, at: 0) queue.insert(node.left, at: 0) } else { ret.append("null") } } print("\(ret)") return ret.joined(separator: ",") } // Decodes your encoded data to tree. func deserialize(_ data: String) -> TreeNode? { func build(_ data: [String], at index: inout Int) -> TreeNode? { let content = data[index] index += 1 if content == "null" { return nil } let node = TreeNode(Int(content)!) node.left = build(data, at: &index) node.right = build(data, at: &index) return node } let data = data.split(separator: ",").map { String($0) } var index = 0 let node = build(data, at: &index) return node } } /** * Your Codec object will be instantiated and called as such: * let obj = Codec() * val s = obj.serialize(root) * let ans = obj.serialize(s) */
d9a7de9f5ecba5c72ea4cf1eeeb54745
27.384615
80
0.520867
false
false
false
false
bkmunar/firefox-ios
refs/heads/master
ClientTests/MockProfile.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Account import ReadingList import Shared import Storage import Sync import XCTest public class MockSyncManager: SyncManager { public func syncClients() -> SyncResult { return deferResult(.Completed) } public func syncClientsAndTabs() -> Success { return succeed() } public func syncHistory() -> SyncResult { return deferResult(.Completed) } public func onAddedAccount() -> Success { return succeed() } public func onRemovedAccount(account: FirefoxAccount?) -> Success { return succeed() } } public class MockProfile: Profile { private let name: String = "mockaccount" func localName() -> String { return name } lazy var db: BrowserDB = { return BrowserDB(files: self.files) }() /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. */ private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = { return SQLiteHistory(db: self.db) }() var favicons: Favicons { return self.places } var history: protocol<BrowserHistory, SyncableHistory> { return self.places } lazy var syncManager: SyncManager = { return MockSyncManager() }() lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = { return SQLiteBookmarks(db: self.db, favicons: self.places) }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs) }() lazy var prefs: Prefs = { return MockProfilePrefs() }() lazy var files: FileAccessor = { return ProfileFileAccessor(profile: self) }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath) }() private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var passwords: Passwords = { return MockPasswords(files: self.files) }() lazy var thumbnails: Thumbnails = { return SDWebThumbnails(files: self.files) }() let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration() var account: FirefoxAccount? = nil func getAccount() -> FirefoxAccount? { return account } func setAccount(account: FirefoxAccount) { self.account = account self.syncManager.onAddedAccount() } func removeAccount() { let old = self.account self.account = nil self.syncManager.onRemovedAccount(old) } func getClients() -> Deferred<Result<[RemoteClient]>> { return deferResult([]) } func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> { return deferResult([]) } }
b79a70c6a98cb039a66c66e3859d7719
26.106195
99
0.660353
false
false
false
false
thehung111/ViSearchSwiftSDK
refs/heads/master
ViSearchSDK/ViSearchSDK/Classes/Request/ViBaseSearchParams.swift
mit
1
import Foundation /// Protocol to generate dictionary for query parameters (in the URL) public protocol ViSearchParamsProtocol{ /// Generate dictionary of parameters for query string use in ViSearch APIs /// Reference: http://developers.visenze.com/api/?shell#advanced-parameters /// /// - returns: dictionary func toDict() -> [String: Any] } /// Base class for constructing Search API requests /// This was not meant to be used directly. /// See http://developers.visenze.com/api/?shell#advanced-parameters for more details on various parameters open class ViBaseSearchParams : ViSearchParamsProtocol { // MARK: properties /// The number of results returned per page. The maximum number of results returned from the API is 100 /// Default to 10 public var limit : Int = 10 /// The result page number. public var page : Int = 1 /// If the value is true, the score for each image result will be included in the response. public var score : Bool = false /// The metadata fields to filter the results. Only fields marked with ‘searchable’ in ViSearch Dashboard can be used as filters. /// If the filter field is not in data schema, it will be ignored. public var fq : [String:String] = [:] /// The metadata fields to be returned. If the query value is not in data schema, it will be ignored. public var fl : [String] = [] /// If true, query information will be returned. public var queryInfo : Bool = false /// Sets the minimum score threshold for the search. /// The value must be between 0.0 to 1.0 inclusively, or an error will be returned. Default value is 0.0. public var scoreMin : Float = 0 /// Sets the maximum score threshold for the search. /// The value must be between 0.0 to 1.0 inclusively, or an error will be returned. Default value is 1.0 public var scoreMax : Float = 1 /// To retrieve all metadata of your image results, specify get_all_fl parameter and set it to true. public var getAllFl : Bool = false /// See http://developers.visenze.com/api/?shell#automatic-object-recognition-beta /// Used for automatic object recognition public var detection : String? = nil // MARK: search protocol public func toDict() -> [String: Any] { var dict : [String:Any] = [:] if limit > 0 { dict["limit"] = String(limit) } if page > 0 { dict["page"] = String(page) } dict["score"] = score ? "true" : "false" dict["score_max"] = String(format: "%f", scoreMax); dict["score_min"] = String(format: "%f", scoreMin); dict["get_all_fl"] = (getAllFl ? "true" : "false" ) if (detection != nil) { dict["detection"] = detection! } if queryInfo { dict["qinfo"] = "true" } if fq.count > 0 { var arr : [String] = [] for ( key, val) in fq { let s = "\(key):\(val)" arr.append(s) } dict["fq"] = arr } if fl.count > 0 { dict["fl"] = fl } return dict ; } }
4a4ea0a92a61091737b4be9812a8fa80
31.038095
134
0.576992
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Chime/Chime_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Chime public struct ChimeErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case badRequestException = "BadRequestException" case conflictException = "ConflictException" case forbiddenException = "ForbiddenException" case notFoundException = "NotFoundException" case resourceLimitExceededException = "ResourceLimitExceededException" case serviceFailureException = "ServiceFailureException" case serviceUnavailableException = "ServiceUnavailableException" case throttledClientException = "ThrottledClientException" case unauthorizedClientException = "UnauthorizedClientException" case unprocessableEntityException = "UnprocessableEntityException" } private let error: Code public let context: AWSErrorContext? /// initialize Chime public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// You don't have permissions to perform the requested operation. public static var accessDeniedException: Self { .init(.accessDeniedException) } /// The input parameters don't match the service's restrictions. public static var badRequestException: Self { .init(.badRequestException) } /// The request could not be processed because of conflict in the current state of the resource. public static var conflictException: Self { .init(.conflictException) } /// The client is permanently forbidden from making the request. For example, when a user tries to create an account from an unsupported Region. public static var forbiddenException: Self { .init(.forbiddenException) } /// One or more of the resources in the request does not exist in the system. public static var notFoundException: Self { .init(.notFoundException) } /// The request exceeds the resource limit. public static var resourceLimitExceededException: Self { .init(.resourceLimitExceededException) } /// The service encountered an unexpected error. public static var serviceFailureException: Self { .init(.serviceFailureException) } /// The service is currently unavailable. public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } /// The client exceeded its request rate limit. public static var throttledClientException: Self { .init(.throttledClientException) } /// The client is not currently authorized to make the request. public static var unauthorizedClientException: Self { .init(.unauthorizedClientException) } /// The request was well-formed but was unable to be followed due to semantic errors. public static var unprocessableEntityException: Self { .init(.unprocessableEntityException) } } extension ChimeErrorType: Equatable { public static func == (lhs: ChimeErrorType, rhs: ChimeErrorType) -> Bool { lhs.error == rhs.error } } extension ChimeErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
d10faa85556e217ba28ad13335b65e14
45.241379
148
0.701715
false
false
false
false
kperryua/swift
refs/heads/master
test/SILGen/types.swift
apache-2.0
2
// RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | %FileCheck %s class C { var member: Int = 0 // Methods have method calling convention. // CHECK-LABEL: sil hidden @_TFC5types1C3foo{{.*}} : $@convention(method) (Int, @guaranteed C) -> () { func foo(x x: Int) { // CHECK: bb0([[X:%[0-9]+]] : $Int, [[THIS:%[0-9]+]] : $C): member = x // CHECK-NOT: strong_retain // CHECK: [[FN:%[0-9]+]] = class_method %1 : $C, #C.member!setter.1 // CHECK: apply [[FN]](%0, %1) : $@convention(method) (Int, @guaranteed C) -> () // CHECK-NOT: strong_release } } struct S { var member: Int // CHECK-LABEL: sil hidden @{{.*}}1S3foo{{.*}} : $@convention(method) (Int, @inout S) -> () mutating func foo(x x: Int) { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int, [[THIS:%[0-9]+]] : $*S): member = x // CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[X:%[0-9]+]] = project_box [[XADDR]] // CHECK: [[MEMBER:%[0-9]+]] = struct_element_addr [[THIS]] : $*S, #S.member // CHECK: copy_addr [[X]] to [[MEMBER]] } class SC { // CHECK-LABEL: sil hidden @_TFCV5types1S2SC3bar{{.*}} func bar() {} } } func f() { class FC { // CHECK-LABEL: sil shared @_TFCF5types1fFT_T_L_2FC3zim{{.*}} func zim() {} } } func g(b b : Bool) { if (b) { class FC { // CHECK-LABEL: sil shared @_TFCF5types1gFT1bSb_T_L_2FC3zim{{.*}} func zim() {} } } else { class FC { // CHECK-LABEL: sil shared @_TFCF5types1gFT1bSb_T_L0_2FC3zim{{.*}} func zim() {} } } } struct ReferencedFromFunctionStruct { let f: (ReferencedFromFunctionStruct) -> () = {x in ()} let g: (ReferencedFromFunctionEnum) -> () = {x in ()} } enum ReferencedFromFunctionEnum { case f((ReferencedFromFunctionEnum) -> ()) case g((ReferencedFromFunctionStruct) -> ()) } // CHECK-LABEL: sil hidden @_TF5types34referencedFromFunctionStructFieldsFVS_28ReferencedFromFunctionStructTFS0_T_FOS_26ReferencedFromFunctionEnumT__ // CHECK: [[F:%.*]] = struct_extract [[X:%.*]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.f // CHECK: [[F]] : $@callee_owned (@owned ReferencedFromFunctionStruct) -> () // CHECK: [[G:%.*]] = struct_extract [[X]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.g // CHECK: [[G]] : $@callee_owned (@owned ReferencedFromFunctionEnum) -> () func referencedFromFunctionStructFields(_ x: ReferencedFromFunctionStruct) -> ((ReferencedFromFunctionStruct) -> (), (ReferencedFromFunctionEnum) -> ()) { return (x.f, x.g) } // CHECK-LABEL: sil hidden @_TF5types32referencedFromFunctionEnumFieldsFOS_26ReferencedFromFunctionEnumTGSqFS0_T__GSqFVS_28ReferencedFromFunctionStructT___ // CHECK: bb{{[0-9]+}}([[F:%.*]] : $@callee_owned (@owned ReferencedFromFunctionEnum) -> ()): // CHECK: bb{{[0-9]+}}([[G:%.*]] : $@callee_owned (@owned ReferencedFromFunctionStruct) -> ()): func referencedFromFunctionEnumFields(_ x: ReferencedFromFunctionEnum) -> ( ((ReferencedFromFunctionEnum) -> ())?, ((ReferencedFromFunctionStruct) -> ())? ) { switch x { case .f(let f): return (f, nil) case .g(let g): return (nil, g) } }
7e7c4c5ca7f02f388042b53653736df1
32.247423
155
0.60031
false
false
false
false
spritekitbook/flappybird-swift
refs/heads/master
Chapter 10/Finish/FloppyBird/FloppyBird/Settings.swift
apache-2.0
7
// // Settings.swift // FloppyBird // // Created by Jeremy Novak on 9/27/16. // Copyright © 2016 SpriteKit Book. All rights reserved. // import Foundation class Settings { static let sharedInstance = Settings() // MARK: - Private class constants private let defaults = UserDefaults.standard private let keyFirstRun = "First Run" private let keyBestScore = "Best Score" // MARK: - Init init() { if defaults.object(forKey: keyFirstRun) == nil { firstLaunch() } } private func firstLaunch() { defaults.set(0, forKey: keyBestScore) defaults.set(false, forKey: keyFirstRun) defaults.synchronize() } // MARK: - Public saving methods func saveBest(score: Int) { defaults.set(score, forKey: keyBestScore) defaults.synchronize() } // MARK: - Public retrieving methods func getBestScore() -> Int { return defaults.integer(forKey: keyBestScore) } }
acff42b37a8dee5326815a31815289ee
21.933333
57
0.600775
false
false
false
false
futomtom/DynoOrder
refs/heads/branch
Dyno/Pods/Segmentio/Segmentio/Source/Cells/SegmentioCellWithImageAfterLabel.swift
mit
3
// // SegmentioCellWithImageAfterLabel.swift // Segmentio // // Created by Dmitriy Demchenko // Copyright © 2016 Yalantis Mobile. All rights reserved. // import UIKit final class SegmentioCellWithImageAfterLabel: SegmentioCell { override func setupConstraintsForSubviews() { super.setupConstraintsForSubviews() guard let imageContainerView = imageContainerView else { return } guard let containerView = containerView else { return } let metrics = ["labelHeight": segmentTitleLabelHeight] let views = [ "imageContainerView": imageContainerView, "containerView": containerView ] // main constraints let segmentImageViewVerticalConstraint = NSLayoutConstraint.constraints( withVisualFormat: "V:[imageContainerView(labelHeight)]", options: [.alignAllCenterY], metrics: metrics, views: views) NSLayoutConstraint.activate(segmentImageViewVerticalConstraint) let contentViewHorizontalConstraints = NSLayoutConstraint.constraints( withVisualFormat: "|-[containerView]-[imageContainerView(labelHeight)]-|", options: [.alignAllCenterY], metrics: metrics, views: views) NSLayoutConstraint.activate(contentViewHorizontalConstraints) // custom constraints topConstraint = NSLayoutConstraint( item: containerView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: padding ) topConstraint?.isActive = true bottomConstraint = NSLayoutConstraint( item: contentView, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: padding ) bottomConstraint?.isActive = true } }
34218393ee886506d6f8dd83acd0e644
29.926471
86
0.599144
false
false
false
false
anto0522/AdMate
refs/heads/AppStore_Version
Pods/SQLite.swift/SQLite/Extensions/FTS5.swift
mit
3
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // extension Module { @warn_unused_result public static func FTS5(config: FTS5Config) -> Module { return Module(name: "fts5", arguments: config.arguments()) } } /// Configuration for the [FTS5](https://www.sqlite.org/fts5.html) extension. /// /// **Note:** this is currently only applicable when using SQLite.swift together with a FTS5-enabled version /// of SQLite. public class FTS5Config : FTSConfig { public enum Detail : CustomStringConvertible { /// store rowid, column number, term offset case Full /// store rowid, column number case Column /// store rowid case None public var description: String { switch self { case Full: return "full" case Column: return "column" case None: return "none" } } } var detail: Detail? var contentRowId: Expressible? var columnSize: Int? override public init() { } /// [External Content Tables](https://www.sqlite.org/fts5.html#section_4_4_2) public func contentRowId(column: Expressible) -> Self { self.contentRowId = column return self } /// [The Columnsize Option](https://www.sqlite.org/fts5.html#section_4_5) public func columnSize(size: Int) -> Self { self.columnSize = size return self } /// [The Detail Option](https://www.sqlite.org/fts5.html#section_4_6) public func detail(detail: Detail) -> Self { self.detail = detail return self } override func options() -> Options { var options = super.options() options.append("content_rowid", value: contentRowId) if let columnSize = columnSize { options.append("columnsize", value: Expression<Int>(value: columnSize)) } options.append("detail", value: detail) return options } override func formatColumnDefinitions() -> [Expressible] { return columnDefinitions.map { definition in if definition.options.contains(.unindexed) { return " ".join([definition.0, Expression<Void>(literal: "UNINDEXED")]) } else { return definition.0 } } } }
da047447ada7174e8c37d97a17638d00
34.381443
108
0.656469
false
true
false
false
josve05a/wikipedia-ios
refs/heads/develop
Wikipedia/Code/EditPreviewViewController.swift
mit
2
import UIKit import WMF protocol EditPreviewViewControllerDelegate: NSObjectProtocol { func editPreviewViewControllerDidTapNext(_ editPreviewViewController: EditPreviewViewController) } class EditPreviewViewController: UIViewController, Themeable, WMFPreviewSectionLanguageInfoDelegate, WMFPreviewAnchorTapAlertDelegate { var section: MWKSection? var wikitext = "" var editFunnel: EditFunnel? var loggedEditActions: NSMutableSet? var editFunnelSource: EditFunnelSource = .unknown var savedPagesFunnel: SavedPagesFunnel? var theme: Theme = .standard weak var delegate: EditPreviewViewControllerDelegate? @IBOutlet private var previewWebViewContainer: PreviewWebViewContainer! private let fetcher = PreviewHtmlFetcher() func previewWebViewContainer(_ previewWebViewContainer: PreviewWebViewContainer, didTapLink url: URL, exists: Bool, isExternal: Bool) { if !exists { let title = WMFLocalizedString("wikitext-preview-link-not-found-preview-title", value: "No internal link found", comment: "Title for nonexistent link preview popup") let message = WMFLocalizedString("wikitext-preview-link-not-found-preview-description", value: "Wikipedia does not have an article with this exact name", comment: "Description for nonexistent link preview popup") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: CommonStrings.okTitle, style: .default)) present(alertController, animated: true) } else if isExternal { let title = WMFLocalizedString("wikitext-preview-link-external-preview-title", value: "External link", comment: "Title for external link preview popup") let message = String(format: WMFLocalizedString("wikitext-preview-link-external-preview-description", value: "This link leads to an external website: %1$@", comment: "Description for external link preview popup. $1$@ is the external url."), url.absoluteString) let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: CommonStrings.okTitle, style: .default, handler: nil)) present(alertController, animated: true) } else { guard let dataStore = SessionSingleton.sharedInstance()?.dataStore, let language = section?.articleLanguage, var components = URLComponents(url: url, resolvingAgainstBaseURL: false), let host = components.host else { showInternalLinkInAlert(link: url.absoluteString) return } components.host = "\(language).\(host)" guard let articleURL = components.url else { showInternalLinkInAlert(link: url.absoluteString) return } let internalLinkViewController = EditPreviewInternalLinkViewController(articleURL: articleURL, dataStore: dataStore) internalLinkViewController.modalPresentationStyle = .overCurrentContext internalLinkViewController.modalTransitionStyle = .crossDissolve internalLinkViewController.apply(theme: theme) present(internalLinkViewController, animated: true, completion: nil) } } private func showInternalLinkInAlert(link: String) { let title = WMFLocalizedString("wikitext-preview-link-preview-title", value: "Link preview", comment: "Title for link preview popup") let message = String(format: WMFLocalizedString("wikitext-preview-link-preview-description", value: "This link leads to '%1$@'", comment: "Description of the link URL. %1$@ is the URL."), link) let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: CommonStrings.okTitle, style: .default, handler: nil)) present(alertController, animated: true) } @objc func goBack() { navigationController?.popViewController(animated: true) } @objc func goForward() { delegate?.editPreviewViewControllerDidTapNext(self) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = WMFLocalizedString("navbar-title-mode-edit-wikitext-preview", value: "Preview", comment: "Header text shown when wikitext changes are being previewed. {{Identical|Preview}}") navigationItem.leftBarButtonItem = UIBarButtonItem.wmf_buttonType(.caretLeft, target: self, action: #selector(self.goBack)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: CommonStrings.nextTitle, style: .done, target: self, action: #selector(self.goForward)) navigationItem.rightBarButtonItem?.tintColor = theme.colors.link if let loggedEditActions = loggedEditActions, !loggedEditActions.contains(EditFunnel.Action.preview) { editFunnel?.logEditPreviewForArticle(from: editFunnelSource, language: section?.articleLanguage) loggedEditActions.add(EditFunnel.Action.preview) } preview() apply(theme: theme) } override func viewWillDisappear(_ animated: Bool) { WMFAlertManager.sharedInstance.dismissAlert() super.viewWillDisappear(animated) } func wmf_editedSectionLanguageInfo() -> MWLanguageInfo? { guard let lang = section?.url?.wmf_language else { return nil } return MWLanguageInfo(forCode: lang) } private func preview() { WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("wikitext-preview-changes", value: "Retrieving preview of your changes...", comment: "Alert text shown when getting preview of user changes to wikitext"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) fetcher.fetchHTML(forWikiText: wikitext, articleURL: section?.url) { (previewHTML, error) in DispatchQueue.main.async { if let error = error { WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) return } WMFAlertManager.sharedInstance.dismissAlert() self.previewWebViewContainer.webView.loadHTML(previewHTML, baseURL: URL(string: "https://wikipedia.org"), withAssetsFile: "preview.html", scrolledToFragment: nil, padding: UIEdgeInsets.zero, theme: self.theme) } } } func apply(theme: Theme) { self.theme = theme if viewIfLoaded == nil { return } previewWebViewContainer.apply(theme: theme) } }
a10ca63dfea351a1813fcd7c12d95891
52.527132
283
0.689066
false
false
false
false
28stephlim/Heartbeat-Analyser
refs/heads/master
Music/VoiceMemos/VoiceMemos/Model/CoreDataStack.swift
mit
5
// // CoreDataStack.swift // VoiceMemos // // Created by Zhouqi Mo on 2/20/15. // Copyright (c) 2015 Zhouqi Mo. All rights reserved. // import Foundation import CoreData class CoreDataStack { var context:NSManagedObjectContext var psc:NSPersistentStoreCoordinator var model:NSManagedObjectModel var store:NSPersistentStore? init() { let bundle = NSBundle.mainBundle() let modelURL = bundle.URLForResource("VoiceMemos", withExtension:"momd") model = NSManagedObjectModel(contentsOfURL: modelURL!)! psc = NSPersistentStoreCoordinator(managedObjectModel:model) context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) context.persistentStoreCoordinator = psc let documentsURL = applicationDocumentsDirectory() let storeURL = documentsURL.URLByAppendingPathComponent("VoiceMemos.sqlite") let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] do { try store = psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options) } catch { debugPrint("Error adding persistent store: \(error)") abort() } } func saveContext() { if context.hasChanges { do { try context.save() } catch { debugPrint("Could not save: \(error)") } } } func applicationDocumentsDirectory() -> NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] } }
c107104140c9ced10461a77f1ed950ad
28
120
0.613685
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Gutenberg/Collapsable Header/CollapsableHeaderViewController.swift
gpl-2.0
1
import UIKit import WordPressUI class CollapsableHeaderViewController: UIViewController, NoResultsViewHost { enum SeperatorStyle { case visibile case automatic case hidden } let scrollableView: UIScrollView let accessoryView: UIView? let mainTitle: String let prompt: String let primaryActionTitle: String let secondaryActionTitle: String? let defaultActionTitle: String? open var accessoryBarHeight: CGFloat { return 44 } open var seperatorStyle: SeperatorStyle { return self.hasAccessoryBar ? .visibile : .automatic } private let hasDefaultAction: Bool private var notificationObservers: [NSObjectProtocol] = [] @IBOutlet weak var containerView: UIView! @IBOutlet weak var headerView: CollapsableHeaderView! let titleView: UILabel = { let title = UILabel(frame: .zero) title.adjustsFontForContentSizeCategory = true title.font = WPStyleGuide.serifFontForTextStyle(UIFont.TextStyle.largeTitle, fontWeight: .semibold).withSize(17) title.isHidden = true title.adjustsFontSizeToFitWidth = true title.minimumScaleFactor = 2/3 return title }() @IBOutlet weak var largeTitleTopSpacingConstraint: NSLayoutConstraint! @IBOutlet weak var largeTitleView: UILabel! @IBOutlet weak var promptView: UILabel! @IBOutlet weak var accessoryBar: UIView! @IBOutlet weak var accessoryBarHeightConstraint: NSLayoutConstraint! @IBOutlet weak var footerView: UIView! @IBOutlet weak var footerHeightContraint: NSLayoutConstraint! @IBOutlet weak var defaultActionButton: UIButton! @IBOutlet weak var secondaryActionButton: UIButton! @IBOutlet weak var primaryActionButton: UIButton! @IBOutlet weak var selectedStateButtonsContainer: UIStackView! @IBOutlet weak var seperator: UIView! /// This is used as a means to adapt to different text sizes to force the desired layout and then active `headerHeightConstraint` /// when scrolling begins to allow pushing the non static items out of the scrollable area. @IBOutlet weak var initialHeaderTopConstraint: NSLayoutConstraint! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var titleToSubtitleSpacing: NSLayoutConstraint! @IBOutlet weak var subtitleToCategoryBarSpacing: NSLayoutConstraint! /// As the Header expands it allows a little bit of extra room between the bottom of the filter bar and the bottom of the header view. These next two constaints help account for that slight adustment. @IBOutlet weak var minHeaderBottomSpacing: NSLayoutConstraint! @IBOutlet weak var maxHeaderBottomSpacing: NSLayoutConstraint! @IBOutlet weak var scrollableContainerBottomConstraint: NSLayoutConstraint! @IBOutlet var visualEffects: [UIVisualEffectView]! { didSet { visualEffects.forEach { (visualEffect) in visualEffect.effect = UIBlurEffect.init(style: .systemChromeMaterial) // Allow touches to pass through to the scroll view behind the header. visualEffect.contentView.isUserInteractionEnabled = false } } } private var footerHeight: CGFloat { let verticalMargins: CGFloat = 16 let buttonHeight: CGFloat = 44 let safeArea = (UIApplication.shared.mainWindow?.safeAreaInsets.bottom ?? 0) return verticalMargins + buttonHeight + verticalMargins + safeArea } private var isShowingNoResults: Bool = false { didSet { if oldValue != isShowingNoResults { updateHeaderDisplay() } } } private let hasAccessoryBar: Bool private var shouldHideAccessoryBar: Bool { return isShowingNoResults || !hasAccessoryBar } private var shouldUseCompactLayout: Bool { return traitCollection.verticalSizeClass == .compact } private var topInset: CGFloat = 0 private var _maxHeaderHeight: CGFloat = 0 private var maxHeaderHeight: CGFloat { if shouldUseCompactLayout { return minHeaderHeight } else { return _maxHeaderHeight } } private var _midHeaderHeight: CGFloat = 0 private var midHeaderHeight: CGFloat { if shouldUseCompactLayout { return minHeaderHeight } else { return _midHeaderHeight } } private var minHeaderHeight: CGFloat = 0 private var accentColor: UIColor { return UIColor { (traitCollection: UITraitCollection) -> UIColor in if traitCollection.userInterfaceStyle == .dark { return UIColor.muriel(color: .primary, .shade40) } else { return UIColor.muriel(color: .primary, .shade50) } } } // MARK: - Static Helpers public static func closeButton(target: Any?, action: Selector) -> UIBarButtonItem { let closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) closeButton.layer.cornerRadius = 15 closeButton.accessibilityLabel = NSLocalizedString("Close", comment: "Dismisses the current screen") closeButton.setImage(UIImage.gridicon(.crossSmall), for: .normal) closeButton.addTarget(target, action: action, for: .touchUpInside) closeButton.tintColor = .secondaryLabel closeButton.backgroundColor = UIColor { (traitCollection: UITraitCollection) -> UIColor in if traitCollection.userInterfaceStyle == .dark { return UIColor.systemFill } else { return UIColor.quaternarySystemFill } } return UIBarButtonItem(customView: closeButton) } // MARK: - Initializers /// Configure and display the no results view controller /// /// - Parameters: /// - scrollableView: Populates the scrollable area of this container. Required. /// - title: The Large title and small title in the header. Required. /// - prompt: The subtitle/prompt in the header. Required. /// - primaryActionTitle: The button title for the right most button when an item is selected. Required. /// - secondaryActionTitle: The button title for the left most button when an item is selected. Optional - nil results in the left most button being hidden when an item is selected. /// - defaultActionTitle: The button title for the button that is displayed when no item is selected. Optional - nil results in the footer being hidden when no item is selected. /// - accessoryView: The view to be placed in the placeholder of the accessory bar. Optional - The default is nil. /// init(scrollableView: UIScrollView, mainTitle: String, prompt: String, primaryActionTitle: String, secondaryActionTitle: String? = nil, defaultActionTitle: String? = nil, accessoryView: UIView? = nil) { self.scrollableView = scrollableView self.mainTitle = mainTitle self.prompt = prompt self.primaryActionTitle = primaryActionTitle self.secondaryActionTitle = secondaryActionTitle self.defaultActionTitle = defaultActionTitle self.hasAccessoryBar = (accessoryView != nil) self.hasDefaultAction = (defaultActionTitle != nil) self.accessoryView = accessoryView super.init(nibName: "\(CollapsableHeaderViewController.self)", bundle: .main) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() insertChildView() insertAccessoryView() navigationItem.titleView = titleView largeTitleView.font = WPStyleGuide.serifFontForTextStyle(UIFont.TextStyle.largeTitle, fontWeight: .semibold) toggleFilterBarConstraints() styleButtons() setStaticText() scrollableView.delegate = self formatNavigationController() extendedLayoutIncludesOpaqueBars = true edgesForExtendedLayout = .top updateSeperatorStyle() } /// The estimated content size of the scroll view. This is used to adjust the content insests to allow the header to be scrollable to be collapsable still when /// it's not populated with enough data. This is desirable to help maintain the header's state when the filtered options change and reduce the content size. open func estimatedContentSize() -> CGSize { return scrollableView.contentSize } override func viewWillAppear(_ animated: Bool) { if !isViewOnScreen() { layoutHeader() } startObservingKeyboardChanges() super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { stopObservingKeyboardChanges() super.viewWillDisappear(animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) guard isShowingNoResults else { return } coordinator.animate(alongsideTransition: nil) { (_) in self.updateHeaderDisplay() if self.shouldHideAccessoryBar { self.disableInitialLayoutHelpers() self.snapToHeight(self.scrollableView, height: self.minHeaderHeight, animated: false) } } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { styleButtons() } if let previousTraitCollection = previousTraitCollection, traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass { isUserInitiatedScroll = false layoutHeaderInsets() // This helps reset the header changes after a rotation. scrollViewDidScroll(scrollableView) scrollViewDidEndDecelerating(scrollableView) } } // MARK: - Footer Actions @IBAction open func defaultActionSelected(_ sender: Any) { /* This should be overriden in a child class in order to enable support. */ } @IBAction open func primaryActionSelected(_ sender: Any) { /* This should be overriden in a child class in order to enable support. */ } @IBAction open func secondaryActionSelected(_ sender: Any) { /* This should be overriden in a child class in order to enable support. */ } // MARK: - Format Nav Bar /* * To allow more flexibility in the navigation bar's header items, we keep the navigation bar available. * However, that space is also essential to a uniform design of the header. This function updates the design of the * navigation bar. We set the design to the `navigationItem`, which is ViewController specific. */ private func formatNavigationController() { let newAppearance = UINavigationBarAppearance() newAppearance.configureWithTransparentBackground() newAppearance.backgroundColor = .clear newAppearance.shadowColor = .clear newAppearance.shadowImage = UIImage() navigationItem.standardAppearance = newAppearance navigationItem.scrollEdgeAppearance = newAppearance navigationItem.compactAppearance = newAppearance setNeedsStatusBarAppearanceUpdate() } // MARK: - View Styling private func setStaticText() { titleView.text = mainTitle titleView.sizeToFit() largeTitleView.text = mainTitle promptView.text = prompt primaryActionButton.setTitle(primaryActionTitle, for: .normal) if let defaultActionTitle = defaultActionTitle { defaultActionButton.setTitle(defaultActionTitle, for: .normal) } else { footerHeightContraint.constant = 0 footerView.layoutIfNeeded() defaultActionButton.isHidden = true selectedStateButtonsContainer.isHidden = false } if let secondaryActionTitle = secondaryActionTitle { secondaryActionButton.setTitle(secondaryActionTitle, for: .normal) } else { secondaryActionButton.isHidden = true } } private func insertChildView() { scrollableView.translatesAutoresizingMaskIntoConstraints = false scrollableView.clipsToBounds = false let top = NSLayoutConstraint(item: scrollableView, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: scrollableView, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: 0) let leading = NSLayoutConstraint(item: scrollableView, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: scrollableView, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1, constant: 0) containerView.addSubview(scrollableView) containerView.addConstraints([top, bottom, leading, trailing]) } private func insertAccessoryView() { guard let accessoryView = accessoryView else { return } accessoryView.translatesAutoresizingMaskIntoConstraints = false let top = NSLayoutConstraint(item: accessoryView, attribute: .top, relatedBy: .equal, toItem: accessoryBar, attribute: .top, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: accessoryView, attribute: .bottom, relatedBy: .equal, toItem: accessoryBar, attribute: .bottom, multiplier: 1, constant: 0) let leading = NSLayoutConstraint(item: accessoryView, attribute: .leading, relatedBy: .equal, toItem: accessoryBar, attribute: .leading, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: accessoryView, attribute: .trailing, relatedBy: .equal, toItem: accessoryBar, attribute: .trailing, multiplier: 1, constant: 0) accessoryBar.addSubview(accessoryView) accessoryBar.addConstraints([top, bottom, leading, trailing]) } private func styleButtons() { let seperator = UIColor.separator [defaultActionButton, secondaryActionButton].forEach { (button) in button?.titleLabel?.font = WPStyleGuide.fontForTextStyle(.body, fontWeight: .medium) button?.layer.borderColor = seperator.cgColor button?.layer.borderWidth = 1 button?.layer.cornerRadius = 8 } primaryActionButton.titleLabel?.font = WPStyleGuide.fontForTextStyle(.body, fontWeight: .medium) primaryActionButton.backgroundColor = accentColor primaryActionButton.layer.cornerRadius = 8 } // MARK: - Header and Footer Sizing private func toggleFilterBarConstraints() { accessoryBarHeightConstraint.constant = shouldHideAccessoryBar ? 0 : accessoryBarHeight let collapseBottomSpacing = shouldHideAccessoryBar || (seperatorStyle == .hidden) maxHeaderBottomSpacing.constant = collapseBottomSpacing ? 1 : 24 minHeaderBottomSpacing.constant = collapseBottomSpacing ? 1 : 9 } private func updateHeaderDisplay() { headerHeightConstraint.isActive = false initialHeaderTopConstraint.isActive = true toggleFilterBarConstraints() accessoryBar.layoutIfNeeded() headerView.layoutIfNeeded() calculateHeaderSnapPoints() layoutHeaderInsets() } private func calculateHeaderSnapPoints() { let accessoryBarSpacing: CGFloat if shouldHideAccessoryBar { minHeaderHeight = 1 accessoryBarSpacing = minHeaderHeight } else { minHeaderHeight = accessoryBarHeightConstraint.constant + minHeaderBottomSpacing.constant accessoryBarSpacing = accessoryBarHeightConstraint.constant + maxHeaderBottomSpacing.constant } _midHeaderHeight = titleToSubtitleSpacing.constant + promptView.frame.height + subtitleToCategoryBarSpacing.constant + accessoryBarSpacing _maxHeaderHeight = largeTitleTopSpacingConstraint.constant + largeTitleView.frame.height + _midHeaderHeight } private func layoutHeaderInsets() { let topInset: CGFloat = maxHeaderHeight if let tableView = scrollableView as? UITableView { tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: topInset)) tableView.tableHeaderView?.backgroundColor = .clear } else { self.topInset = topInset scrollableView.contentInset.top = topInset } updateFooterInsets() } /* * Calculates the needed space for the footer to allow the header to still collapse but also to prevent unneeded space * at the bottome of the tableView when multiple cells are rendered. */ private func updateFooterInsets() { /// Update the footer height if it's being displayed. if footerHeightContraint.constant > 0 { footerHeightContraint.constant = footerHeight } /// The needed distance to fill the rest of the screen to allow the header to still collapse when scrolling (or to maintain a collapsed header if it was already collapsed when selecting a filter) let distanceToBottom = scrollableView.frame.height - minHeaderHeight - estimatedContentSize().height let newHeight: CGFloat = max(footerHeight, distanceToBottom) if let tableView = scrollableView as? UITableView { tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: newHeight)) tableView.tableFooterView?.isGhostableDisabled = true tableView.tableFooterView?.backgroundColor = .clear } else { scrollableView.contentInset.bottom = newHeight } } private func layoutHeader() { [headerView, footerView].forEach({ $0?.setNeedsLayout() $0?.layoutIfNeeded() }) calculateHeaderSnapPoints() layoutHeaderInsets() updateTitleViewVisibility(false) } // MARK: - Subclass callbacks /// A public interface to notify the container that the content has loaded data or is attempting too. public func displayNoResultsController(title: String, subtitle: String?, resultsDelegate: NoResultsViewControllerDelegate?) { guard !isShowingNoResults else { return } isShowingNoResults = true disableInitialLayoutHelpers() snapToHeight(scrollableView, height: minHeaderHeight) configureAndDisplayNoResults(on: containerView, title: title, subtitle: subtitle, noConnectionSubtitle: subtitle, buttonTitle: NSLocalizedString("Retry", comment: "A prompt to attempt the failed network request again"), customizationBlock: { (noResultsController) in noResultsController.delegate = resultsDelegate }) } public func dismissNoResultsController() { guard isShowingNoResults else { return } isShowingNoResults = false snapToHeight(scrollableView, height: maxHeaderHeight) hideNoResults() } /// In scenarios where the content offset before content changes doesn't align with the available space after the content changes then the offset can be lost. In /// order to preserve the header's collpased state we cache the offset and attempt to reapply it if needed. private var stashedOffset: CGPoint? = nil /// Tracks if the current scroll behavior was intiated by a user drag event private var isUserInitiatedScroll = false /// A public interface to notify the container that the content size of the scroll view is about to change. This is useful in adjusting the bottom insets to allow the /// view to still be scrollable with the content size is less than the total space of the expanded screen. public func contentSizeWillChange() { stashedOffset = scrollableView.contentOffset updateFooterInsets() } /// A public interface to notify the container that the selected state for an items has changed. public func itemSelectionChanged(_ hasSelectedItem: Bool) { let animationSpeed = CollapsableHeaderCollectionViewCell.selectionAnimationSpeed guard hasDefaultAction else { UIView.animate(withDuration: animationSpeed, delay: 0, options: .curveEaseInOut, animations: { self.footerHeightContraint.constant = hasSelectedItem ? self.footerHeight : 0 self.footerView.setNeedsLayout() self.footerView.layoutIfNeeded() }) return } guard hasSelectedItem == selectedStateButtonsContainer.isHidden else { return } defaultActionButton.isHidden = false selectedStateButtonsContainer.isHidden = false defaultActionButton.alpha = hasSelectedItem ? 1 : 0 selectedStateButtonsContainer.alpha = hasSelectedItem ? 0 : 1 let alpha: CGFloat = hasSelectedItem ? 0 : 1 let selectedStateContainerAlpha: CGFloat = hasSelectedItem ? 1 : 0 UIView.animate(withDuration: animationSpeed, delay: 0, options: .transitionCrossDissolve, animations: { self.defaultActionButton.alpha = alpha self.selectedStateButtonsContainer.alpha = selectedStateContainerAlpha }) { (_) in self.defaultActionButton.isHidden = hasSelectedItem self.selectedStateButtonsContainer.isHidden = !hasSelectedItem } } // MARK: - Seperator styling private func updateSeperatorStyle(animated: Bool = true) { let shouldBeHidden: Bool switch seperatorStyle { case .automatic: shouldBeHidden = headerHeightConstraint.constant > minHeaderHeight && !shouldUseCompactLayout case .visibile: shouldBeHidden = false case .hidden: shouldBeHidden = true } seperator.animatableSetIsHidden(shouldBeHidden, animated: animated) } } // MARK: - UIScrollViewDelegate extension CollapsableHeaderViewController: UIScrollViewDelegate { private func disableInitialLayoutHelpers() { if !headerHeightConstraint.isActive { initialHeaderTopConstraint.isActive = false headerHeightConstraint.isActive = true } } /// Restores the stashed content offset if it appears as if it's been reset. private func restoreContentOffsetIfNeeded(_ scrollView: UIScrollView) { guard var stashedOffset = stashedOffset else { return } stashedOffset = resolveContentOffsetCollisions(scrollView, cachedOffset: stashedOffset) scrollView.contentOffset = stashedOffset } private func resolveContentOffsetCollisions(_ scrollView: UIScrollView, cachedOffset: CGPoint) -> CGPoint { var adjustedOffset = cachedOffset /// If the content size has changed enough to where the cached offset would scroll beyond the allowable bounds then we reset to the minum scroll height to /// maintain the header's size. if scrollView.contentSize.height - cachedOffset.y < scrollView.frame.height { adjustedOffset.y = maxHeaderHeight - headerHeightConstraint.constant stashedOffset = adjustedOffset } return adjustedOffset } private func resizeHeaderIfNeeded(_ scrollView: UIScrollView) { let scrollOffset = scrollView.contentOffset.y + topInset let newHeaderViewHeight = maxHeaderHeight - scrollOffset if newHeaderViewHeight < minHeaderHeight { headerHeightConstraint.constant = minHeaderHeight } else { headerHeightConstraint.constant = newHeaderViewHeight } } internal func updateTitleViewVisibility(_ animated: Bool = true) { var shouldHide = shouldUseCompactLayout ? false : (headerHeightConstraint.constant > midHeaderHeight) shouldHide = headerHeightConstraint.isActive ? shouldHide : true titleView.animatableSetIsHidden(shouldHide, animated: animated) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { /// Clear the stashed offset because the user has initiated a change stashedOffset = nil isUserInitiatedScroll = true } func scrollViewDidScroll(_ scrollView: UIScrollView) { guard stashedOffset == nil || stashedOffset == CGPoint.zero else { restoreContentOffsetIfNeeded(scrollView) return } guard !shouldUseCompactLayout, !isShowingNoResults else { updateTitleViewVisibility(true) updateSeperatorStyle() return } disableInitialLayoutHelpers() resizeHeaderIfNeeded(scrollView) updateTitleViewVisibility(isUserInitiatedScroll) updateSeperatorStyle() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { snapToHeight(scrollView) isUserInitiatedScroll = false } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { snapToHeight(scrollView) } } private func snapToHeight(_ scrollView: UIScrollView) { guard !shouldUseCompactLayout else { return } if largeTitleView.frame.midY > 0 { snapToHeight(scrollView, height: maxHeaderHeight) } else if promptView.frame.midY > 0 { snapToHeight(scrollView, height: midHeaderHeight) } else if headerHeightConstraint.constant != minHeaderHeight { snapToHeight(scrollView, height: minHeaderHeight) } } public func expandHeader() { guard !shouldUseCompactLayout else { return } snapToHeight(scrollableView, height: maxHeaderHeight) } private func snapToHeight(_ scrollView: UIScrollView, height: CGFloat, animated: Bool = true) { scrollView.contentOffset.y = maxHeaderHeight - height - topInset headerHeightConstraint.constant = height updateTitleViewVisibility(animated) updateSeperatorStyle(animated: animated) guard animated else { headerView.setNeedsLayout() headerView.layoutIfNeeded() return } UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: { self.headerView.setNeedsLayout() self.headerView.layoutIfNeeded() }, completion: nil) } } // MARK: - Keyboard Adjustments extension CollapsableHeaderViewController { private func startObservingKeyboardChanges() { let willShowObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { (notification) in UIView.animate(withKeyboard: notification) { (_, endFrame) in self.scrollableContainerBottomConstraint.constant = endFrame.height - self.footerHeight } } let willHideObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { (notification) in UIView.animate(withKeyboard: notification) { (_, _) in self.scrollableContainerBottomConstraint.constant = 0 } } let willChangeFrameObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: .main) { (notification) in UIView.animate(withKeyboard: notification) { (_, endFrame) in self.scrollableContainerBottomConstraint.constant = endFrame.height - self.footerHeight } } notificationObservers.append(willShowObserver) notificationObservers.append(willHideObserver) notificationObservers.append(willChangeFrameObserver) } private func stopObservingKeyboardChanges() { notificationObservers.forEach { (observer) in NotificationCenter.default.removeObserver(observer) } notificationObservers = [] } }
c8ad199d6c114997d51a7f79689877ac
43.053435
204
0.686779
false
false
false
false
charles-oder/Project-Euler-Swift
refs/heads/master
ProjectEulerSwift/Palindrome.swift
apache-2.0
1
// // Palindrome.swift // ProjectEulerSwift // // Created by Charles Oder on 4/5/15. // Copyright (c) 2015 Charles Oder. All rights reserved. // import Foundation class Palindrome { class func CreateDigitList(value: Int) -> NSMutableArray { var n = value var list: NSMutableArray = NSMutableArray() while n > 0 { var digit = n % 10 list.insertObject(digit, atIndex: 0) n /= 10 } return list } class func isPalindrome(value: Int) -> Bool { let list = CreateDigitList(value) var reversedList = NSMutableArray() for n in list { reversedList.insertObject(n, atIndex: 0) } return list == reversedList } class func findLargestPalindromeOfProducts(numberLength: Int) -> Int { let max = Int(pow(10, Double(numberLength))) var largestPalidrome = 0 for var x = 1; x < max; x++ { for var y = 1; y < max; y++ { let product = x * y if isPalindrome(product) && (product > largestPalidrome) { largestPalidrome = product } } } return largestPalidrome } }
5b98f50de1525829fa2c71d4f223f4ea
25.574468
74
0.538462
false
false
false
false
appsandwich/ppt2rk
refs/heads/master
ppt2rk/RunkeeperGPXUploadParser.swift
mit
1
// // RunkeeperGPXUploadParser.swift // ppt2rk // // Created by Vinny Coyne on 18/05/2017. // Copyright © 2017 App Sandwich Limited. All rights reserved. // import Foundation class RunkeeperGPXUploadParser { var data: Data? = nil init(_ data: Data) { self.data = data } public func parseWithHandler(_ handler: @escaping (RunkeeperActivity?) -> Void) { guard let data = self.data else { handler(nil) return } guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else { handler(nil) return } guard let dictionary = json as? Dictionary<String, Any> else { handler(nil) return } if let error = dictionary["error"] as? String, error.characters.count > 0 { handler(nil) return } guard let trackImportData = dictionary["trackImportData"] as? Dictionary<String, Any> else { handler(nil) return } guard let duration = trackImportData["duration"] as? Double, let startTime = trackImportData["startTime"] as? Int, let trackPoints = trackImportData["trackPoints"] as? Array< Dictionary<String, Any> >, trackPoints.count > 0 else { handler(nil) return } // Thanks to https://medium.com/@ndcrandall/automating-gpx-file-imports-in-runkeeper-f446917f8a19 //str << "#{point['type']},#{point['latitude']},#{point['longitude']},#{point['deltaTime']},0,#{point['deltaDistance']};" var totalDistance = 0.0 let runkeeperString = trackPoints.reduce("") { (string, trackPoint) -> String in guard let type = trackPoint["type"] as? String, let latitude = trackPoint["latitude"] as? Double, let longitude = trackPoint["longitude"] as? Double, let deltaTime = trackPoint["deltaTime"] as? Double, let deltaDistance = trackPoint["deltaDistance"] as? Double else { return string } let trackPointString = "\(type),\(latitude),\(longitude),\(Int(deltaTime)),0,\(deltaDistance);" totalDistance += deltaDistance return string + trackPointString } let date = Date(timeIntervalSince1970: Double(startTime) / 1000.0) let runkeeperActivity = RunkeeperActivity(id: -1, timestamp: date, distance: "\(totalDistance)", duration: "\(duration / 1000.0)", day: "") runkeeperActivity.convertedFromGPXString = runkeeperString handler(runkeeperActivity) } }
9c99105a12c040f14986c02e991b3756
34.217949
279
0.573353
false
false
false
false
cristianames92/PortalView
refs/heads/master
Sources/Components/Progress.swift
mit
2
// // Progress.swift // PortalView // // Created by Cristian Ames on 4/11/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // public func progress<MessageType>( progress: ProgressCounter = ProgressCounter.initial, style: StyleSheet<ProgressStyleSheet> = ProgressStyleSheet.defaultStyleSheet, layout: Layout = layout()) -> Component<MessageType> { return .progress(progress, style, layout) } // MARK:- Style sheet public enum ProgressContentType { case color(Color) case image(Image) } public struct ProgressStyleSheet { public static let defaultStyleSheet = StyleSheet<ProgressStyleSheet>(component: ProgressStyleSheet()) public var progressStyle: ProgressContentType public var trackStyle: ProgressContentType public init( progressStyle: ProgressContentType = .color(defaultProgressColor), trackStyle: ProgressContentType = .color(defaultTrackColor)) { self.progressStyle = progressStyle self.trackStyle = trackStyle } } public func progressStyleSheet(configure: (inout BaseStyleSheet, inout ProgressStyleSheet) -> ()) -> StyleSheet<ProgressStyleSheet> { var base = BaseStyleSheet() var custom = ProgressStyleSheet() configure(&base, &custom) return StyleSheet(component: custom, base: base) }
502f5f998c329111ee3ac9f3bbb7ef4f
28.173913
133
0.716841
false
false
false
false
gkaimakas/SwiftValidatorsReactiveExtensions
refs/heads/master
Example/SwiftValidatorsReactiveExtensions/ViewController.swift
mit
1
// // ViewController.swift // SwiftValidatorsReactiveExtensions // // Created by gkaimakas on 03/31/2017. // Copyright (c) 2017 gkaimakas. All rights reserved. // import ReactiveCocoa import ReactiveSwift import Result import SwiftValidators import SwiftValidatorsReactiveExtensions import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let viewModel = FormViewModel() var inputs: [FieldViewModel] = [] var submitView: SumbitView! var headerView: HeaderView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. inputs = [ viewModel.emailField, viewModel.passwordField ] inputs.enumerated().forEach { (offset: Int, element: FieldViewModel) in element.hasErrors .producer .startWithValues({ (value: Bool) in if value == true && self.tableView.numberOfRows(inSection: offset) == 2 { self.tableView.beginUpdates() self.tableView.insertRows(at: [IndexPath(item: 2, section: offset)], with: .automatic) self.tableView.endUpdates() } if value == false && self.tableView.numberOfRows(inSection: offset) == 3 { self.tableView.beginUpdates() self.tableView.deleteRows(at: [IndexPath(item: 2, section: offset)], with: .automatic) self.tableView.endUpdates() } }) } headerView = HeaderView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 256)) headerView.viewModel = viewModel submitView = SumbitView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 80)) submitView.credentialsAction = viewModel.submit tableView.dataSource = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 20 tableView.tableHeaderView = headerView tableView.tableFooterView = submitView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return inputs.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 2 + ( inputs[section].hasErrors.value == true ? 1 : 0) } if section == 1 { return 2 + ( inputs[section].hasErrors.value == true ? 1 : 0) } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.item == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: HintTableViewCell.identifier) as! HintTableViewCell cell.hint = inputs[indexPath.section].hint.producer return cell } if indexPath.item == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: TextInputTableViewCell.identifier) as! TextInputTableViewCell cell.validatingProperty = inputs[indexPath.section].validatingProperty if indexPath.section == 0 { cell.textField.keyboardType = .emailAddress } else { cell.textField.keyboardType = .default } cell.textField.isSecureTextEntry = (indexPath.section == 1) return cell } if indexPath.item == 2 { let cell = tableView.dequeueReusableCell(withIdentifier: ErrorTableViewCell.identifier) as! ErrorTableViewCell cell.validatingProperty = inputs[indexPath.section].validatingProperty return cell } return UITableViewCell() } }
732853b1b5a7ae0066439a930673d2f0
34.550847
130
0.599762
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/Utilites/3rdParty/InputBar/SAIToolboxItem.swift
mit
1
// // SAIToolboxItem.swift // SAC // // Created by SAGESSE on 9/15/16. // Copyright © 2016-2017 SAGESSE. All rights reserved. // import UIKit @objc open class SAIToolboxItem: NSObject { open var name: String open var identifier: String open var image: UIImage? open var highlightedImage: UIImage? public init(_ identifier: String, _ name: String, _ image: UIImage?, _ highlightedImage: UIImage? = nil) { self.identifier = identifier self.name = name self.image = image self.highlightedImage = highlightedImage } }
6493945e9b0fe36100709d0fd39d0ca5
22.64
110
0.64467
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/ConversationList/ListContent/ConversationListContentController/ConversationListHeaderView.swift
gpl-3.0
1
// Wire // Copyright (C) 2019 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 import WireCommonComponents extension UIView { func rotate(to angleInDegrees: CGFloat) { transform = transform.rotated(by: angleInDegrees / 180 * CGFloat.pi) } } typealias TapHandler = (_ collapsed: Bool) -> Void final class ConversationListHeaderView: UICollectionReusableView { private let spacing: CGFloat = 8 var folderBadge: Int = 0 { didSet { let isHidden = folderBadge <= 0 badgeView.updateCollapseConstraints(isCollapsed: isHidden) badgeView.isHidden = isHidden badgeMarginConstraint?.constant = isHidden ? 0 : -spacing badgeWidthConstraint?.constant = isHidden ? 0 : 28 let text: String? switch folderBadge { case 1...99: text = String(folderBadge) case 100...: text = "99+" default: text = nil } badgeView.textLabel.text = text } } var collapsed = false { didSet { guard collapsed != oldValue else { return } // update rotation if collapsed { arrowIconImageView.rotate(to: -90) } else { arrowIconImageView.transform = .identity } } } var tapHandler: TapHandler? private var badgeMarginConstraint: NSLayoutConstraint? private var badgeWidthConstraint: NSLayoutConstraint? private let titleLabel: UILabel = { let label = DynamicFontLabel( fontSpec: .smallRegularFont, color: .white) label.textColor = SemanticColors.Label.textConversationListCell label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) return label }() let badgeView: RoundedTextBadge = { let margin: CGFloat = 12 let roundedTextBadge = RoundedTextBadge(contentInset: UIEdgeInsets(top: 2, left: margin, bottom: 2, right: margin), font: FontSpec(.medium, .semibold).font!) roundedTextBadge.textLabel.textColor = SemanticColors.Label.conversationListTableViewCellBadge roundedTextBadge.backgroundColor = SemanticColors.View.backgroundConversationListTableViewCellBadge roundedTextBadge.isHidden = true return roundedTextBadge }() /// display title of the header var title: String? { get { return titleLabel.text } set { titleLabel.text = newValue } } override var accessibilityLabel: String? { get { return title } set { super.accessibilityLabel = newValue } } override var accessibilityValue: String? { get { typealias ConversationListHeader = L10n.Accessibility.ConversationsListHeader let state = collapsed ? ConversationListHeader.CollapsedButton.description : ConversationListHeader.ExpandedButton.description return state + " \(folderBadge)" } set { super.accessibilityValue = newValue } } private let arrowIconImageView: UIImageView = { let imageView = UIImageView() imageView.tintColor = SemanticColors.Label.textConversationListCell imageView.setTemplateIcon(.downArrow, size: .tiny) return imageView }() required override init(frame: CGRect) { super.init(frame: frame) [titleLabel, arrowIconImageView, badgeView].forEach(addSubview) createConstraints() addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggledCollapsed))) isAccessibilityElement = true shouldGroupAccessibilityChildren = true backgroundColor = SemanticColors.View.backgroundConversationList addBorder(for: .bottom) } @objc private func toggledCollapsed() { let newCollaped = !collapsed UIView.animate(withDuration: 0.2, animations: { self.collapsed = newCollaped }) tapHandler?(newCollaped) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createConstraints() { [arrowIconImageView, titleLabel].prepareForLayout() arrowIconImageView.setContentCompressionResistancePriority(.required, for: .horizontal) badgeMarginConstraint = titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: badgeView.leadingAnchor, constant: 0) badgeWidthConstraint = badgeView.widthAnchor.constraint(greaterThanOrEqualToConstant: 0) NSLayoutConstraint.activate([ arrowIconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: CGFloat.ConversationList.horizontalMargin), arrowIconImageView.centerYAnchor.constraint(equalTo: centerYAnchor), titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor), titleLabel.leadingAnchor.constraint(equalTo: arrowIconImageView.trailingAnchor, constant: spacing), badgeMarginConstraint!, badgeView.heightAnchor.constraint(equalToConstant: 20), badgeWidthConstraint!, badgeView.centerYAnchor.constraint(equalTo: centerYAnchor), badgeView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -CGFloat.ConversationList.horizontalMargin) ] ) } }
091e4a5554a75833cbabb3c0e234ca96
32.05291
165
0.656315
false
false
false
false
DrabWeb/Sudachi
refs/heads/master
Sudachi/Sudachi/SCPreferencesViewController.swift
gpl-3.0
1
// // SCPreferencesViewController.swift // Sudachi // // Created by Seth on 2016-04-17. // import Cocoa class SCPreferencesViewController: NSViewController { /// The main window of this view controller var preferencesWindow : NSWindow = NSWindow(); /// The label for the theme popup button @IBOutlet var themeLabel: NSTextField! /// The popup button for setting the theme @IBOutlet var themePopupButton: NSPopUpButton! /// When we click themePopupButton... @IBAction func themePopupButtonInteracted(sender: AnyObject) { // If we clicked the "Add from folder..." item... if(themePopupButton.selectedItem?.title == "Add from folder...") { // Prompt to install a theme SCThemingEngine().defaultEngine().promptToInstallTheme(); // Reload the menu items addThemePopupButtonItems(); } } /// When we click the "Apply" button... @IBAction func applyButtonPressed(sender: AnyObject) { // Save the preferences savePreferences(); // Close the window preferencesWindow.close(); } /// The label to tell the user they have to restart Sudachi for visual changes to take effect @IBOutlet var restartLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Style the window styleWindow(); // Load the theme loadTheme(); // Add the theme popup button menu items addThemePopupButtonItems(); } /// Puts the entered preferences values into the global preferences object func savePreferences() { // Set the values // If the chosen theme was Default... if(themePopupButton.selectedItem!.title == "Default") { // Set the theme path to "" (NSApplication.sharedApplication().delegate as! AppDelegate).preferences.themePath = ""; } // If we chose any other theme... else { // Set the theme path to the chosen item's path (NSApplication.sharedApplication().delegate as! AppDelegate).preferences.themePath = NSHomeDirectory() + "/Library/Application Support/Sudachi/themes/" + themePopupButton.selectedItem!.title + ".sctheme"; } } /// Selects the current theme for themePopupButton func selectCurrentTheme() { // For every item in themePopupButton's item titles... for(currentItemIndex, currentItemTitle) in themePopupButton.itemTitles.enumerate() { // If the current item's title matches the title of the current theme... if(currentItemTitle == NSString(string: SCThemingEngine().defaultEngine().currentThemePath).lastPathComponent.stringByReplacingOccurrencesOfString("." + NSString(string: SCThemingEngine().defaultEngine().currentThemePath).pathExtension, withString: "")) { // Select this item themePopupButton.selectItemAtIndex(currentItemIndex); // Stop the loop return; } // If the current item's title is Default and the theme folder path is blank... if(currentItemTitle == "Default" && SCThemingEngine().defaultEngine().currentThemePath == "") { // Select this item themePopupButton.selectItemAtIndex(currentItemIndex); // Stop the loop return; } } } /// Sets up the menu items in themePopupButton, and then selects the current theme func addThemePopupButtonItems() { // Remove all the current menu items themePopupButton.menu?.removeAllItems(); // Add the "Default" menu item themePopupButton.addItemWithTitle("Default"); do { // For every file in the themes folder of the Sudachi application support folder... for(_, currentFile) in try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSHomeDirectory() + "/Library/Application Support/Sudachi/themes").enumerate() { // If the current file's extension is .sctheme and its a folder... if(NSString(string: currentFile).pathExtension == "sctheme" && SCFileUtilities().isFolder(NSHomeDirectory() + "/Library/Application Support/Sudachi/themes/" + currentFile)) { // Add the current theme folder to them menu, without the extension themePopupButton.addItemWithTitle(currentFile.stringByReplacingOccurrencesOfString("." + NSString(string: currentFile).pathExtension, withString: "")); } } } catch let error as NSError { // Print the error description print("SCPreferencesViewController: Error reading themes directory, \(error.description)"); } // Add the "Add from folder..." menu item themePopupButton.addItemWithTitle("Add from folder..."); // Refresh the popup button's style (themePopupButton as! SCPopUpButton).setMenuItemsTitleColorsAndFonts(); // Select the current theme selectCurrentTheme(); } /// Loads in the theme variables from SCThemingEngine func loadTheme() { // Set the titlebar color preferencesWindow.standardWindowButton(.CloseButton)?.superview?.superview?.superview?.wantsLayer = true; preferencesWindow.standardWindowButton(.CloseButton)?.superview?.layer?.backgroundColor = SCThemingEngine().defaultEngine().titlebarColor.CGColor; preferencesWindow.standardWindowButton(.CloseButton)?.superview?.superview?.superview?.layer?.backgroundColor = SCThemingEngine().defaultEngine().titlebarColor.CGColor; // Allow the window to be transparent and set the background color preferencesWindow.opaque = false; preferencesWindow.backgroundColor = SCThemingEngine().defaultEngine().backgroundColor; // If we said to hide window titlebars... if(SCThemingEngine().defaultEngine().titlebarsHidden) { // Hide the titlebar of the window preferencesWindow.standardWindowButton(.CloseButton)?.superview?.superview?.removeFromSuperview(); // Set the content view to be full size preferencesWindow.styleMask |= NSFullSizeContentViewWindowMask; } // Set the label colors themeLabel.textColor = SCThemingEngine().defaultEngine().preferencesLabelColor; restartLabel.textColor = SCThemingEngine().defaultEngine().preferencesLabelColor; // Set the label fonts themeLabel.font = SCThemingEngine().defaultEngine().setFontFamily(themeLabel.font!, size: SCThemingEngine().defaultEngine().preferencesLabelFontSize); restartLabel.font = SCThemingEngine().defaultEngine().setFontFamily(themeLabel.font!, size: SCThemingEngine().defaultEngine().preferencesLabelFontSize); } /// Styles the window func styleWindow() { // Get the window preferencesWindow = NSApplication.sharedApplication().windows.last!; // Style the titlebar preferencesWindow.titleVisibility = .Hidden; preferencesWindow.titlebarAppearsTransparent = true; // Get the windows center position on the X let windowX = ((NSScreen.mainScreen()?.frame.width)! / 2) - (480 / 2); // Get the windows center position on the Y let windowY = (((NSScreen.mainScreen()?.frame.height)! / 2) - (270 / 2)) + 50; // Center the window preferencesWindow.setFrame(NSRect(x: windowX, y: windowY, width: 480, height: 270), display: false); } }
bf2b9659421a3df45b81d2aad76c0e43
43.704545
267
0.63849
false
false
false
false
KrishMunot/swift
refs/heads/master
test/decl/func/keyword-argument-labels.swift
apache-2.0
6
// RUN: %target-parse-verify-swift struct SomeRange { } // Function declarations. func paramName(_ func: Int, in: SomeRange) { } func firstArgumentLabelWithParamName(in range: SomeRange) { } func firstArgumentLabelWithParamName2(range in: SomeRange) { } func escapedInout(`inout` value: SomeRange) { } struct SomeType { // Initializers init(func: () -> ()) { } init(init func: () -> ()) { } // Subscripts subscript (class index: AnyClass) -> Int { return 0 } subscript (class: AnyClass) -> Int { return 0 } subscript (struct: Any.Type) -> Int { return 0 } } class SomeClass { } // Function types. typealias functionType = (in: SomeRange) -> Bool // Calls func testCalls(_ range: SomeRange) { paramName(0, in: range) firstArgumentLabelWithParamName(in: range) firstArgumentLabelWithParamName2(range: range) var st = SomeType(func: {}) st = SomeType(init: {}) _ = st[class: SomeClass.self] _ = st[SomeClass.self] _ = st[SomeType.self] escapedInout(`inout`: range) // Fix-Its paramName(0, `in`: range) // expected-warning{{keyword 'in' does not need to be escaped in argument list}}{{16-17=}}{{19-20=}} }
95e667437a3b84ae9c835714d7f7438d
21.960784
128
0.658412
false
false
false
false
gaoleegin/DamaiPlayBusinessnormal
refs/heads/master
DamaiPlayBusinessPhone/DamaiPlayBusinessPhone/Classes/ActiveList/DMActiveListViewController.swift
apache-2.0
1
// // DMActiveListViewController.swift // DamaiPlayBusinessPhone // // Created by 高李军 on 15/11/4. // Copyright © 2015年 DamaiPlayBusinessPhone. All rights reserved. // import UIKit import SVProgressHUD class DMActiveListViewController: UITableViewController { ///设置 @IBAction func settingBtnClicked(sender: AnyObject) { let settingVC = DMSettingViewController() navigationController?.pushViewController(settingVC, animated: true) } private var avtivityList:[DMActiveModel]? private var introduction:String? override func viewDidLoad() { super.viewDidLoad() ///加载数据 self.loadData() } ///加载列表数据 func loadData(){ SVProgressHUD.show() DMActiveModel.loadActiveList(1, pageSize: 10) { (acitiviList, being) -> () in self.avtivityList = acitiviList self.introduction = "\(being.abeing)个进行中的活动" + " | " + "\(being.allDone)个已结束的活动" SVProgressHUD.dismiss() self.tableView.reloadData() } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 100 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = NSBundle.mainBundle().loadNibNamed("ActiveHeader", owner: self, options: nil).last as! DMActiveHeaderView let user = DMUser.getUser() headerView.userName.text = user.name headerView.userImage.sd_setImageWithURL(NSURL(string: user.avatar)) headerView.introductionLabel.text = introduction return headerView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.avtivityList?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ActiveListcell", forIndexPath: indexPath) as! DMActiveListTableViewCell let model = self.avtivityList![indexPath.row] cell.activitModel = model return cell } }
0f0235b4e635c8ded5e0836bdba96ae1
28.178947
135
0.646825
false
false
false
false
SquidKit/SquidKit
refs/heads/master
deprecated/JSONResponseEndpoint.swift
mit
1
// // JSONEndpoint.swift // SquidKit // // Created by Mike Leavy on 8/24/14. // Copyright (c) 2014 SquidKit. All rights reserved. // import UIKit import Alamofire open class JSONResponseEndpoint: Endpoint { var manager:SessionManager? open func connect(_ completionHandler: @escaping (AnyObject?, ResponseStatus) -> Void) { let (params, method) = self.params() var encoding:ParameterEncoding = .URL if let specifiedEncoding = self.encoding() { encoding = specifiedEncoding } else { switch method { case .POST: encoding = .JSON default: break } } var defaultHeaders = Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] if let additionalHeaders = self.additionalHeaders() { for (headerName, headerValue) in additionalHeaders { defaultHeaders[headerName] = headerValue } } let configuration = URLSessionConfiguration.default configuration.HTTPAdditionalHeaders = defaultHeaders var serverTrustPolicyManager:ServerTrustPolicyManager? if self.serverTrustPolicy.count > 0 { serverTrustPolicyManager = ServerTrustPolicyManager(policies: self.serverTrustPolicy) } self.manager = SessionManager(configuration: configuration, serverTrustPolicyManager: serverTrustPolicyManager) let (user, password) = self.basicAuthPair() self.request = self.manager!.request(method, self.url(), parameters: params, encoding: encoding) .shouldAuthenticate(user: user, password: password) .validate() .responseJSON(options: self.jsonReadingOptions, completionHandler:{ [weak self] response in if let strongSelf = self { switch (response.result) { case .Success(let value): if let jsonDictionary = value as? [String: AnyObject] { strongSelf.connectResponse(jsonDictionary, responseStatus: .OK, completionHandler: completionHandler) } else if let jsonArray = value as? [AnyObject] { strongSelf.connectResponse(jsonArray, responseStatus: .OK, completionHandler:completionHandler) } else { strongSelf.connectResponse(nil, responseStatus: .ResponseFormatError, completionHandler:completionHandler) } case .Failure(let error): strongSelf.connectResponse(nil, responseStatus: strongSelf.formatError(response.response, error:error), completionHandler:completionHandler) } } }) self.logRequest(encoding, headers: defaultHeaders) } func connectResponse(_ responseData:AnyObject?, responseStatus:ResponseStatus, completionHandler: (AnyObject?, ResponseStatus) -> Void) { self.logResponse(responseData, responseStatus: responseStatus) completionHandler(responseData, responseStatus) } //OVERRIDE open var jsonReadingOptions:JSONSerialization.ReadingOptions { get { return .allowFragments } } } // MARK: Logging extension JSONResponseEndpoint { func logRequest(_ encoding:ParameterEncoding, headers:[NSObject : AnyObject]?) { if let logger = self as? EndpointLoggable { switch logger.requestLogging { case .verbose: logger.log( "===============================\n" + "SquidKit Network Request\n" + "===============================\n" + "Request = " + "\(self.request?.description)" + "\n" + "Encoding = " + "\(encoding)" + "\n" + "HTTP headers: " + "\(headers)" + "\n" + "===============================\n") case .minimal: logger.log(self.request?.description) default: break } } } func logResponse(_ responseData:AnyObject?, responseStatus:ResponseStatus) { if let logger = self as? EndpointLoggable { switch logger.responseLogging { case .verbose: logger.log( "===============================\n" + "SquidKit Network Response for " + "\(self.request?.description)" + "\n" + "===============================\n" + "Response Status = " + "\(responseStatus)" + "\n" + "JSON:" + "\n" + "\(responseData)" + "\n" + "===============================\n") case .minimal: logger.log("Response Status = " + "\(responseStatus)") default: break } } } } extension Request { func shouldAuthenticate(user: String?, password: String?) -> Self { if let haveUser = user, let havePassword = password { return self.authenticate(user: haveUser, password: havePassword) } return self } }
663568786301bdf0502b4588e53bebe1
37.570423
168
0.525105
false
false
false
false
jaiversin/AppsCatalog
refs/heads/master
AppsCatalog/Modules/CategoryList/CategoryListViewController.swift
mit
1
// // CategoryListViewController.swift // AppsCatalog // // Created by Jhon López on 5/22/16. // Copyright © 2016 jaiversin. All rights reserved. // import UIKit var CellIdentifier = "CategoryCell" class CategoryListViewController: UITableViewController, CategoryListViewInterface { var categoryListPresenter:CategoryListPresenter? var tableDataSource : [CategoryListModel]? @IBOutlet weak var noResultsButton: UIButton! @IBOutlet var noResultsView: UIView! @IBOutlet weak var categoriesTable: UITableView! override func viewDidLoad() { super.viewDidLoad() self.categoriesTable = tableView // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { self.categoryListPresenter?.loadCategories() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func reloadResults(sender: UIButton) { NSLog("Se van a recargar, ay ay ay") self.categoryListPresenter?.reloadCategories() } // MARK: - Implementación de CategoryListWireframe func showNoResults() { self.view = noResultsView // self.noResultsButton.hidden = false; // self.categoriesTable.hidden = true; } func showResults(categories: [CategoryListModel]) { if categories.count == 0 { self.showNoResults() } else { self.view = tableView self.tableDataSource = categories self.tableView.reloadData() } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.tableDataSource?.count)! } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Categorías" } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let currentCategory = self.tableDataSource?[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = currentCategory?.label return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let currentCategory = self.tableDataSource?[indexPath.row] self.categoryListPresenter?.showAppListForCategory((currentCategory?.identifier)!) } }
66edb8fc69bb5eef890f6bc971728866
29.326087
122
0.666308
false
false
false
false
antonio081014/LeetCode-CodeBase
refs/heads/main
Swift/string-to-integer-atoi.swift
mit
1
// This is a take away code. // Original post: https://leetcode.com/problems/string-to-integer-atoi/discuss/1698567/Swift class Solution { func myAtoi(_ s: String) -> Int { var result = 0 var sign = 1 var isStarted = false for char in s { if char == " " { if isStarted { break } } else if (char == "-" || char == "+") { if isStarted { break } isStarted = true if char == "-" { sign = -1 } } else if char >= "0" && char <= "9" { isStarted = true if let val = char.wholeNumberValue { result = result*10+val } if result > Int32.max { return sign == 1 ? Int(Int32.max) : Int(Int32.min) } } else { break } } return result*sign } }
60ba7fd3486be2a9df4615aaab03dc8c
29
92
0.37619
false
false
false
false
CoderXiaoming/Ronaldo
refs/heads/master
SaleManager/SaleManager/ComOperation/Model/SAMOwedInfoModel.swift
apache-2.0
1
// // SAMOwedInfoModel.swift // SaleManager // // Created by apple on 16/12/23. // Copyright © 2016年 YZH. All rights reserved. // import UIKit var SAMOwedStockNode = 0.0 class SAMOwedInfoModel: NSObject { ///缺货记录的id var id = "" { didSet{ id = ((id == "") ? "---" : id) } } ///起始日期 var startDate = "" { didSet{ startDate = ((startDate == "") ? "---" : startDate) } } ///交货日期 var endDate = "" { didSet{ endDate = ((endDate == "") ? "---" : endDate) } } ///客户ID var CGUnitID = "" { didSet{ CGUnitID = ((CGUnitID == "") ? "---" : CGUnitID) } } ///客户名称 var CGUnitName = "" { didSet{ CGUnitName = ((CGUnitName == "") ? "---" : CGUnitName) } } ///产品编号ID var productID = "" { didSet{ productID = ((productID == "") ? "---" : productID) } } ///产品编号名称 var productIDName = "" { didSet{ productIDName = ((productIDName == "") ? "---" : productIDName) } } ///缺货数量 var countM = 0.0 ///缺货匹数 var countP = 0 ///备注 var memoInfo = "" { didSet{ memoInfo = ((memoInfo == "") ? "---" : memoInfo) } } ///状态:欠货中,已完成,已删除 var iState = "" { didSet{ //设置状态指示图片 switch iState { case "欠货中": orderStateImageName = "oweding" case "已完成": orderStateImageName = "owedCompletion" case "已删除": orderStateImageName = "owedDelete" case "统计": orderStateImageName = "owedCount" default: break } } } //MARK: - 附加属性 ///用户数据模型 var orderCustomerModel: SAMCustomerModel? { //简单创建用户数据模型 let model = SAMCustomerModel() model.CGUnitName = CGUnitName model.id = CGUnitID return model } ///当前欠货的产品数据模型 var stockModel: SAMStockProductModel? { //简单创建当前欠货的产品数据模型 let model = SAMStockProductModel() model.productIDName = productIDName model.id = productID return model } ///状态图片 var orderStateImageName = "" ///库存米数 var stockCountM: Double = 0.0 }
d0bf1f31429bc5a240d2ad3762ef772d
20.846847
75
0.447423
false
false
false
false
3DprintFIT/octoprint-ios-client
refs/heads/dev
Carthage/Checkouts/Nimble/Tests/NimbleTests/AsynchronousTest.swift
mit
12
import Dispatch import Foundation import XCTest import Nimble final class AsyncTest: XCTestCase, XCTestCaseProvider { static var allTests: [(String, (AsyncTest) -> () throws -> Void)] { return [ ("testToEventuallyPositiveMatches", testToEventuallyPositiveMatches), ("testToEventuallyNegativeMatches", testToEventuallyNegativeMatches), ("testWaitUntilPositiveMatches", testWaitUntilPositiveMatches), ("testToEventuallyWithCustomDefaultTimeout", testToEventuallyWithCustomDefaultTimeout), ("testWaitUntilTimesOutIfNotCalled", testWaitUntilTimesOutIfNotCalled), ("testWaitUntilTimesOutWhenExceedingItsTime", testWaitUntilTimesOutWhenExceedingItsTime), ("testWaitUntilNegativeMatches", testWaitUntilNegativeMatches), ("testWaitUntilDetectsStalledMainThreadActivity", testWaitUntilDetectsStalledMainThreadActivity), ("testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed", testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed), ("testWaitUntilErrorsIfDoneIsCalledMultipleTimes", testWaitUntilErrorsIfDoneIsCalledMultipleTimes), ("testWaitUntilMustBeInMainThread", testWaitUntilMustBeInMainThread), ("testToEventuallyMustBeInMainThread", testToEventuallyMustBeInMainThread), ] } class Error: Swift.Error {} let errorToThrow = Error() private func doThrowError() throws -> Int { throw errorToThrow } func testToEventuallyPositiveMatches() { var value = 0 deferToMainQueue { value = 1 } expect { value }.toEventually(equal(1)) deferToMainQueue { value = 0 } expect { value }.toEventuallyNot(equal(1)) } func testToEventuallyNegativeMatches() { let value = 0 failsWithErrorMessage("expected to eventually not equal <0>, got <0>") { expect { value }.toEventuallyNot(equal(0)) } failsWithErrorMessage("expected to eventually equal <1>, got <0>") { expect { value }.toEventually(equal(1)) } failsWithErrorMessage("expected to eventually equal <1>, got an unexpected error thrown: <\(errorToThrow)>") { expect { try self.doThrowError() }.toEventually(equal(1)) } failsWithErrorMessage("expected to eventually not equal <0>, got an unexpected error thrown: <\(errorToThrow)>") { expect { try self.doThrowError() }.toEventuallyNot(equal(0)) } } func testToEventuallyWithCustomDefaultTimeout() { AsyncDefaults.Timeout = 2 defer { AsyncDefaults.Timeout = 1 } var value = 0 let sleepThenSetValueTo: (Int) -> Void = { newValue in Thread.sleep(forTimeInterval: 1.1) value = newValue } var asyncOperation: () -> Void = { sleepThenSetValueTo(1) } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect { value }.toEventually(equal(1)) asyncOperation = { sleepThenSetValueTo(0) } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect { value }.toEventuallyNot(equal(1)) } func testWaitUntilPositiveMatches() { waitUntil { done in done() } waitUntil { done in deferToMainQueue { done() } } } func testWaitUntilTimesOutIfNotCalled() { failsWithErrorMessage("Waited more than 1.0 second") { waitUntil(timeout: 1) { _ in return } } } func testWaitUntilTimesOutWhenExceedingItsTime() { var waiting = true failsWithErrorMessage("Waited more than 0.01 seconds") { waitUntil(timeout: 0.01) { done in let asyncOperation: () -> Void = { Thread.sleep(forTimeInterval: 0.1) done() waiting = false } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } } } // "clear" runloop to ensure this test doesn't poison other tests repeat { RunLoop.main.run(until: Date().addingTimeInterval(0.2)) } while(waiting) } func testWaitUntilNegativeMatches() { failsWithErrorMessage("expected to equal <2>, got <1>") { waitUntil { done in Thread.sleep(forTimeInterval: 0.1) expect(1).to(equal(2)) done() } } } func testWaitUntilDetectsStalledMainThreadActivity() { let msg = "-waitUntil() timed out but was unable to run the timeout handler because the main thread is unresponsive (0.5 seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run." failsWithErrorMessage(msg) { waitUntil(timeout: 1) { done in Thread.sleep(forTimeInterval: 5.0) done() } } } func testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed() { // Currently we are unable to catch Objective-C exceptions when built by the Swift Package Manager #if !SWIFT_PACKAGE let referenceLine = #line + 9 var msg = "Unexpected exception raised: Nested async expectations are not allowed " msg += "to avoid creating flaky tests." msg += "\n\n" msg += "The call to\n\t" msg += "expect(...).toEventually(...) at \(#file):\(referenceLine + 7)\n" msg += "triggered this exception because\n\t" msg += "waitUntil(...) at \(#file):\(referenceLine + 1)\n" msg += "is currently managing the main run loop." failsWithErrorMessage(msg) { // reference line waitUntil(timeout: 2.0) { done in var protected: Int = 0 DispatchQueue.main.async { protected = 1 } expect(protected).toEventually(equal(1)) done() } } #endif } func testWaitUntilErrorsIfDoneIsCalledMultipleTimes() { #if !SWIFT_PACKAGE waitUntil { done in deferToMainQueue { done() expect { done() }.to(raiseException(named: "InvalidNimbleAPIUsage")) } } #endif } func testWaitUntilMustBeInMainThread() { #if !SWIFT_PACKAGE var executedAsyncBlock: Bool = false let asyncOperation: () -> Void = { expect { waitUntil { done in done() } }.to(raiseException(named: "InvalidNimbleAPIUsage")) executedAsyncBlock = true } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect(executedAsyncBlock).toEventually(beTruthy()) #endif } func testToEventuallyMustBeInMainThread() { #if !SWIFT_PACKAGE var executedAsyncBlock: Bool = false let asyncOperation: () -> Void = { expect { expect(1).toEventually(equal(2)) }.to(raiseException(named: "InvalidNimbleAPIUsage")) executedAsyncBlock = true } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect(executedAsyncBlock).toEventually(beTruthy()) #endif } }
3624a810cdff7c3268273fbf8e09e68f
36.202703
385
0.602131
false
true
false
false
kcome/SwiftIB
refs/heads/master
SwiftIB/EClientSocket.swift
mit
1
// // EClientSocket.swift // SwiftIB // // Created by Harry Li on 2/01/2015. // Copyright (c) 2014-2019 Hanfei Li. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to // do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation // Client version history // // 6 = Added parentId to orderStatus // 7 = The new execDetails event returned for an order filled status and reqExecDetails // Also market depth is available. // 8 = Added lastFillPrice to orderStatus() event and permId to execution details // 9 = Added 'averageCost', 'unrealizedPNL', and 'unrealizedPNL' to updatePortfolio event // 10 = Added 'serverId' to the 'open order' & 'order status' events. // We send back all the API open orders upon connection. // Added new methods reqAllOpenOrders, reqAutoOpenOrders() // Added FA support - reqExecution has filter. // - reqAccountUpdates takes acct code. // 11 = Added permId to openOrder event. // 12 = requsting open order attributes ignoreRth, hidden, and discretionary // 13 = added goodAfterTime // 14 = always send size on bid/ask/last tick // 15 = send allocation description string on openOrder // 16 = can receive account name in account and portfolio updates, and fa params in openOrder // 17 = can receive liquidation field in exec reports, and notAutoAvailable field in mkt data // 18 = can receive good till date field in open order messages, and request intraday backfill // 19 = can receive rthOnly flag in ORDER_STATUS // 20 = expects TWS time string on connection after server version >= 20. // 21 = can receive bond contract details. // 22 = can receive price magnifier in version 2 contract details message // 23 = support for scanner // 24 = can receive volatility order parameters in open order messages // 25 = can receive HMDS query start and end times // 26 = can receive option vols in option market data messages // 27 = can receive delta neutral order type and delta neutral aux price in place order version 20: API 8.85 // 28 = can receive option model computation ticks: API 8.9 // 29 = can receive trail stop limit price in open order and can place them: API 8.91 // 30 = can receive extended bond contract def, new ticks, and trade count in bars // 31 = can receive EFP extensions to scanner and market data, and combo legs on open orders // ; can receive RT bars // 32 = can receive TickType.LAST_TIMESTAMP // ; can receive "whyHeld" in order status messages // 33 = can receive ScaleNumComponents and ScaleComponentSize is open order messages // 34 = can receive whatIf orders / order state // 35 = can receive contId field for Contract objects // 36 = can receive outsideRth field for Order objects // 37 = can receive clearingAccount and clearingIntent for Order objects // 38 = can receive multiplier and primaryExchange in portfolio updates // ; can receive cumQty and avgPrice in execution // ; can receive fundamental data // ; can receive underComp for Contract objects // ; can receive reqId and end marker in contractDetails/bondContractDetails // ; can receive ScaleInitComponentSize and ScaleSubsComponentSize for Order objects // 39 = can receive underConId in contractDetails // 40 = can receive algoStrategy/algoParams in openOrder // 41 = can receive end marker for openOrder // ; can receive end marker for account download // ; can receive end marker for executions download // 42 = can receive deltaNeutralValidation // 43 = can receive longName(companyName) // ; can receive listingExchange // ; can receive RTVolume tick // 44 = can receive end market for ticker snapshot // 45 = can receive notHeld field in openOrder // 46 = can receive contractMonth, industry, category, subcategory fields in contractDetails // ; can receive timeZoneId, tradingHours, liquidHours fields in contractDetails // 47 = can receive gamma, vega, theta, undPrice fields in TICK_OPTION_COMPUTATION // 48 = can receive exemptCode in openOrder // 49 = can receive hedgeType and hedgeParam in openOrder // 50 = can receive optOutSmartRouting field in openOrder // 51 = can receive smartComboRoutingParams in openOrder // 52 = can receive deltaNeutralConId, deltaNeutralSettlingFirm, deltaNeutralClearingAccount and deltaNeutralClearingIntent in openOrder // 53 = can receive orderRef in execution // 54 = can receive scale order fields (PriceAdjustValue, PriceAdjustInterval, ProfitOffset, AutoReset, // InitPosition, InitFillQty and RandomPercent) in openOrder // 55 = can receive orderComboLegs (price) in openOrder // 56 = can receive trailingPercent in openOrder // 57 = can receive commissionReport message // 58 = can receive CUSIP/ISIN/etc. in contractDescription/bondContractDescription // 59 = can receive evRule, evMultiplier in contractDescription/bondContractDescription/executionDetails // can receive multiplier in executionDetails // 60 = can receive deltaNeutralOpenClose, deltaNeutralShortSale, deltaNeutralShortSaleSlot and deltaNeutralDesignatedLocation in openOrder // 61 = can receive multiplier in openOrder // can receive tradingClass in openOrder, updatePortfolio, execDetails and position // 62 = can receive avgCost in position message // 63 = can receive verifyMessageAPI, verifyCompleted, displayGroupList and displayGroupUpdated messages let CLIENT_VERSION: Int = 63 let SERVER_VERSION: Int = 38 let EOL: [UInt8] = [0] let BAG_SEC_TYPE: String = "BAG" let GROUPS: Int = 1 let PROFILES: Int = 2 let ALIASES: Int = 3 open class EClientSocket { class func faMsgTypeName(_ faDataType: Int) -> String { switch (faDataType) { case 1: return "GROUPS" case 2: return "PROFILES" case 3: return "ALIASES" default: return "" } } // outgoing msg id's let REQ_MKT_DATA = 1 let CANCEL_MKT_DATA = 2 let PLACE_ORDER = 3 let CANCEL_ORDER = 4 let REQ_OPEN_ORDERS = 5 let REQ_ACCOUNT_DATA = 6 let REQ_EXECUTIONS = 7 let REQ_IDS = 8 let REQ_CONTRACT_DATA = 9 let REQ_MKT_DEPTH = 10 let CANCEL_MKT_DEPTH = 11 let REQ_NEWS_BULLETINS = 12 let CANCEL_NEWS_BULLETINS = 13 let SET_SERVER_LOGLEVEL = 14 let REQ_AUTO_OPEN_ORDERS = 15 let REQ_ALL_OPEN_ORDERS = 16 let REQ_MANAGED_ACCTS = 17 let REQ_FA = 18 let REPLACE_FA = 19 let REQ_HISTORICAL_DATA = 20 let EXERCISE_OPTIONS = 21 let REQ_SCANNER_SUBSCRIPTION = 22 let CANCEL_SCANNER_SUBSCRIPTION = 23 let REQ_SCANNER_PARAMETERS = 24 let CANCEL_HISTORICAL_DATA = 25 let REQ_CURRENT_TIME = 49 let REQ_REAL_TIME_BARS = 50 let CANCEL_REAL_TIME_BARS = 51 let REQ_FUNDAMENTAL_DATA = 52 let CANCEL_FUNDAMENTAL_DATA = 53 let REQ_CALC_IMPLIED_VOLAT = 54 let REQ_CALC_OPTION_PRICE = 55 let CANCEL_CALC_IMPLIED_VOLAT = 56 let CANCEL_CALC_OPTION_PRICE = 57 let REQ_GLOBAL_CANCEL = 58 let REQ_MARKET_DATA_TYPE = 59 let REQ_POSITIONS = 61 let REQ_ACCOUNT_SUMMARY = 62 let CANCEL_ACCOUNT_SUMMARY = 63 let CANCEL_POSITIONS = 64 let VERIFY_REQUEST = 65 let VERIFY_MESSAGE = 66 let QUERY_DISPLAY_GROUPS = 67 let SUBSCRIBE_TO_GROUP_EVENTS = 68 let UPDATE_DISPLAY_GROUP = 69 let UNSUBSCRIBE_FROM_GROUP_EVENTS = 70 let START_API = 71 let MIN_SERVER_VER_REAL_TIME_BARS = 34 let MIN_SERVER_VER_SCALE_ORDERS = 35 let MIN_SERVER_VER_SNAPSHOT_MKT_DATA = 35 let MIN_SERVER_VER_SSHORT_COMBO_LEGS = 35 let MIN_SERVER_VER_WHAT_IF_ORDERS = 36 let MIN_SERVER_VER_CONTRACT_CONID = 37 let MIN_SERVER_VER_PTA_ORDERS = 39 let MIN_SERVER_VER_FUNDAMENTAL_DATA = 40 let MIN_SERVER_VER_UNDER_COMP = 40 let MIN_SERVER_VER_CONTRACT_DATA_CHAIN = 40 let MIN_SERVER_VER_SCALE_ORDERS2 = 40 let MIN_SERVER_VER_ALGO_ORDERS = 41 let MIN_SERVER_VER_EXECUTION_DATA_CHAIN = 42 let MIN_SERVER_VER_NOT_HELD = 44 let MIN_SERVER_VER_SEC_ID_TYPE = 45 let MIN_SERVER_VER_PLACE_ORDER_CONID = 46 let MIN_SERVER_VER_REQ_MKT_DATA_CONID = 47 let MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT = 49 let MIN_SERVER_VER_REQ_CALC_OPTION_PRICE = 50 let MIN_SERVER_VER_CANCEL_CALC_IMPLIED_VOLAT = 50 let MIN_SERVER_VER_CANCEL_CALC_OPTION_PRICE = 50 let MIN_SERVER_VER_SSHORTX_OLD = 51 let MIN_SERVER_VER_SSHORTX = 52 let MIN_SERVER_VER_REQ_GLOBAL_CANCEL = 53 let MIN_SERVER_VER_HEDGE_ORDERS = 54 let MIN_SERVER_VER_REQ_MARKET_DATA_TYPE = 55 let MIN_SERVER_VER_OPT_OUT_SMART_ROUTING = 56 let MIN_SERVER_VER_SMART_COMBO_ROUTING_PARAMS = 57 let MIN_SERVER_VER_DELTA_NEUTRAL_CONID = 58 let MIN_SERVER_VER_SCALE_ORDERS3 = 60 let MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE = 61 let MIN_SERVER_VER_TRAILING_PERCENT = 62 let MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE = 66 let MIN_SERVER_VER_ACCT_SUMMARY = 67 let MIN_SERVER_VER_TRADING_CLASS = 68 let MIN_SERVER_VER_SCALE_TABLE = 69 let MIN_SERVER_VER_LINKING = 70 fileprivate var _eWrapper : EWrapper // msg handler fileprivate var _anyWrapper : AnyWrapper // msg handler fileprivate var dos : OutputStream? = nil // the socket output stream fileprivate var connected : Bool = false // true if we are connected fileprivate var _reader : EReader? = nil // thread which reads msgs from socket fileprivate var _serverVersion : Int = 0 fileprivate var TwsTime : String = "" fileprivate var clientId : Int = 0 fileprivate var extraAuth : Bool = false func serverVersion() -> Int { return _serverVersion } func TwsConnectionTime() -> String { return TwsTime } func anyWrapper() -> AnyWrapper { return _anyWrapper } func eWrapper() -> EWrapper { return _eWrapper } func reader() -> EReader? { return _reader } func isConnected() -> Bool { return connected } func outputStream() -> OutputStream? { return dos } public init(p_eWrapper: EWrapper, p_anyWrapper: AnyWrapper) { _anyWrapper = p_anyWrapper _eWrapper = p_eWrapper } open func setExtraAuth(_ p_extraAuth: Bool) { extraAuth = p_extraAuth } open func eConnect(_ host: String, port: Int, clientId: Int) { // synchronized self.eConnect(host, p_port: port, p_clientId: clientId, p_extraAuth: false) } open func eConnect(_ p_host: String, p_port: Int, p_clientId: Int, p_extraAuth: Bool) { // synchronized // already connected? let host = checkConnected(p_host) var port : UInt32 = 0 if p_port > 0 { port = UInt32(p_port) } clientId = p_clientId extraAuth = p_extraAuth if host.isEmpty { return } self.eConnect(p_host, p_port: port) // TODO: Handle errors here // catch( Exception e) { // eDisconnect() // connectionError() // } } func connectionError() { _anyWrapper.error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_CONNECT_FAIL.code, errorMsg: EClientErrors_CONNECT_FAIL.msg) _reader = nil } func checkConnected(_ host: String) -> String { if connected { _anyWrapper.error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_ALREADY_CONNECTED.code, errorMsg: EClientErrors_ALREADY_CONNECTED.msg) return "" } if host.isEmpty { return "127.0.0.1" } return host } func createReader(_ socket: EClientSocket, dis: InputStream) -> EReader { return EReader(parent: socket, dis: dis) } open func eConnect(_ p_host: String, p_port: UInt32) { // synchronized // create io streams var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let host: CFString = p_host as CFString CFStreamCreatePairWithSocketToHost(nil, host, p_port, &readStream, &writeStream) let dis : InputStream = readStream!.takeRetainedValue() self.dos = writeStream!.takeRetainedValue() // TODO: add delegates here // self.inputStream.delegate = self // self.outputStream.delegate = self dis.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default) dos?.schedule(in: RunLoop.current, forMode: RunLoop.Mode.default) dis.open() dos?.open() // set client version send(CLIENT_VERSION) // start reader thread _reader = createReader(self, dis: dis) // check server version _serverVersion = (_reader?.readInt())! print("Server Version: \(_serverVersion)") if _serverVersion >= 20 { if let ttime = _reader?.readStr() { TwsTime = ttime } print("TWS Time at connection: \(TwsTime)") } if (_serverVersion < SERVER_VERSION) { eDisconnect() _anyWrapper.error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code, errorMsg: EClientErrors_UPDATE_TWS.msg) return } // set connected flag connected = true; // Send the client id if _serverVersion >= 3 { if _serverVersion < MIN_SERVER_VER_LINKING { send(clientId) } else if (!extraAuth){ startAPI() } } _reader?.start() } open func eDisconnect() { // synchronized // not connected? if dos == nil { return } connected = false extraAuth = false clientId = -1 _serverVersion = 0 TwsTime = "" let pdos = dos dos = nil let preader = _reader _reader = nil // stop reader thread; reader thread will close input stream if preader != nil { preader?.cancel() } // close output stream if preader != nil { pdos?.close() } } func startAPI() { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 send(START_API) send(VERSION) send(clientId) // TODO: Handle errors here // catch( Exception e) { // error( EClientErrors_NO_VALID_ID, // EClientErrors_FAIL_SEND_STARTAPI, "" + e) // close() // } } open func cancelScannerSubscription(_ tickerId: Int) { // synchronized // not connected? if !connected { notConnected() return } if _serverVersion < 24 { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support API scanner subscription.") return } let VERSION = 1 // send cancel mkt data msg send(CANCEL_SCANNER_SUBSCRIPTION) send(VERSION) send(tickerId) // TODO: Handle errors here // catch( Exception e) { // error( tickerId, EClientErrors_FAIL_SEND_CANSCANNER, "" + e) // close() // } } open func reqScannerParameters() { // synchronized // not connected? if !connected { notConnected() return } if (_serverVersion < 24) { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support API scanner subscription.") return } let VERSION = 1 send(REQ_SCANNER_PARAMETERS) send(VERSION) // TODO: Handle errors here // catch( Exception e) { // error( EClientErrors_NO_VALID_ID, // EClientErrors_FAIL_SEND_REQSCANNERPARAMETERS, "" + e) // close() // } } open func reqScannerSubscription(_ tickerId: Int, subscription: ScannerSubscription, scannerSubscriptionOptions: [TagValue]?) { // synchronized // not connected? if !connected { notConnected() return } if _serverVersion < 24 { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support API scanner subscription.") return } let VERSION = 4 send(REQ_SCANNER_SUBSCRIPTION) send(VERSION) send(tickerId) sendMax(subscription.numberOfRows) send(subscription.instrument) send(subscription.locationCode) send(subscription.scanCode) sendMax(subscription.abovePrice) sendMax(subscription.belowPrice) sendMax(subscription.aboveVolume) sendMax(subscription.marketCapAbove) sendMax(subscription.marketCapBelow) send(subscription.moodyRatingAbove) send(subscription.moodyRatingBelow) send(subscription.spRatingAbove) send(subscription.spRatingBelow) send(subscription.maturityDateAbove) send(subscription.maturityDateBelow) sendMax(subscription.couponRateAbove) sendMax(subscription.couponRateBelow) send(subscription.excludeConvertible) if _serverVersion >= 25 { sendMax(subscription.averageOptionVolumeAbove) send(subscription.scannerSettingPairs) } if _serverVersion >= 27 { send(subscription.stockTypeFilter) } // send scannerSubscriptionOptions parameter if _serverVersion >= MIN_SERVER_VER_LINKING { var scannerSubscriptionOptionsStr = "" if scannerSubscriptionOptions != nil { let scannerSubscriptionOptionsCount = scannerSubscriptionOptions!.count if scannerSubscriptionOptionsCount > 0 { for i in 1...scannerSubscriptionOptionsCount { let tagValue = scannerSubscriptionOptions![i-1] scannerSubscriptionOptionsStr += tagValue.tag scannerSubscriptionOptionsStr += "=" scannerSubscriptionOptionsStr += tagValue.value scannerSubscriptionOptionsStr += ";" } } } send( scannerSubscriptionOptionsStr ) } // TODO: Handle errors here // catch( Exception e) { // error( tickerId, EClientErrors_FAIL_SEND_REQSCANNER, "" + e) // close() // } } open func reqMktData(_ tickerId: Int, contract: Contract, genericTickList: String, snapshot: Bool, mktDataOptions: [TagValue]?) { // synchronized if !connected { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_NOT_CONNECTED, tail: "") return } if _serverVersion < MIN_SERVER_VER_SNAPSHOT_MKT_DATA && snapshot { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support snapshot market data requests.") return } if _serverVersion < MIN_SERVER_VER_UNDER_COMP { if contract.underComp != nil { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support delta-neutral orders.") return } } if _serverVersion < MIN_SERVER_VER_REQ_MKT_DATA_CONID { if contract.conId > 0 { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support conId parameter.") return } } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if !contract.tradingClass.isEmpty { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It ot support tradingClass parameter in reqMarketData.") return } } let VERSION = 11 // send req mkt data msg send(REQ_MKT_DATA) send(VERSION) send(tickerId) // send contract fields if _serverVersion >= MIN_SERVER_VER_REQ_MKT_DATA_CONID { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) if _serverVersion >= 15 { send(contract.multiplier) } send(contract.exchange) if _serverVersion >= 14 { send(contract.primaryExch) } send(contract.currency) if _serverVersion >= 2 { send(contract.localSymbol) } if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.tradingClass) } if _serverVersion >= 8 && caseInsensitiveEqual(contract.secType, BAG_SEC_TYPE) { send(contract.comboLegs.count) for i in 1...contract.comboLegs.count { let comboLeg = contract.comboLegs[i] send(comboLeg.conId) send(comboLeg.ratio) send(comboLeg.action) send(comboLeg.exchange) } } if _serverVersion >= MIN_SERVER_VER_UNDER_COMP { if let underComp = contract.underComp { send(true) send(underComp.conId) send(underComp.delta) send(underComp.price) } else { send( false) } } if _serverVersion >= 31 { /* * Note: Even though SHORTABLE tick type supported only * starting server version 33 it would be relatively * expensive to expose this restriction here. * * Therefore we are relying on TWS doing validation. */ send( genericTickList) } if _serverVersion >= MIN_SERVER_VER_SNAPSHOT_MKT_DATA { send (snapshot) } // send mktDataOptions parameter if _serverVersion >= MIN_SERVER_VER_LINKING { var mktDataOptionsStr = "" if mktDataOptions != nil { let mktDataOptionsCount = mktDataOptions!.count for i in 1...mktDataOptionsCount { let tagValue = mktDataOptions![i] mktDataOptionsStr += tagValue.tag mktDataOptionsStr += "=" mktDataOptionsStr += tagValue.value mktDataOptionsStr += ";" } } send( mktDataOptionsStr ) } // TODO: Handle errors here // catch( Exception e) { // error( tickerId, EClientErrors_FAIL_SEND_REQMKT, "" + e) // close() // } } open func cancelHistoricalData(_ tickerId :Int) { // synchronized // not connected? if !connected { notConnected() return } if _serverVersion < 24 { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support historical data query cancellation.") return } let VERSION = 1 // send cancel mkt data msg send(CANCEL_HISTORICAL_DATA) send(VERSION) send(tickerId) // TODO: Handle errors here // catch( Exception e) { // error( tickerId, EClientErrors_FAIL_SEND_CANHISTDATA, "" + e) // close() // } } open func cancelRealTimeBars(_ tickerId: Int) { // synchronized // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_REAL_TIME_BARS { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support realtime bar data query cancellation.") return } let VERSION = 1 // send cancel mkt data msg send( CANCEL_REAL_TIME_BARS) send( VERSION) send( tickerId) // Handle errors here // catch( Exception e) { // error( tickerId, EClientErrors_FAIL_SEND_CANRTBARS, "" + e) // close() // } } /** Note that formatData parameter affects intra-day bars only; 1-day bars always return with date in YYYYMMDD format. */ open func reqHistoricalData(_ tickerId: Int, contract: Contract, endDateTime: String, durationStr: String, barSizeSetting: String, whatToShow: String, useRTH: Int, formatDate: Int, chartOptions: [TagValue]?) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 6 if _serverVersion < 16 { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support historical data backfill.") return } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support conId and tradingClass parameters in reqHistroricalData.") return } } send(REQ_HISTORICAL_DATA) send(VERSION) send(tickerId) // send contract fields if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) send(contract.multiplier) send(contract.exchange) send(contract.primaryExch) send(contract.currency) send(contract.localSymbol) if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.tradingClass) } if _serverVersion >= 31 { send(contract.includeExpired ? 1 : 0) } if _serverVersion >= 20 { send(endDateTime) send(barSizeSetting) } send(durationStr) send(useRTH) send(whatToShow) if _serverVersion > 16 { send(formatDate) } if (caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType)) { send(contract.comboLegs.count) for i in 1...contract.comboLegs.count { let comboLeg = contract.comboLegs[i - 1] send(comboLeg.conId) send(comboLeg.ratio) send(comboLeg.action) send(comboLeg.exchange) } } // send chartOptions parameter if _serverVersion >= MIN_SERVER_VER_LINKING { var chartOptionsStr = "" if chartOptions != nil { let chartOptionsCount = chartOptions!.count for i in 1...chartOptionsCount { let tagValue = chartOptions![i] chartOptionsStr += tagValue.tag chartOptionsStr += "=" chartOptionsStr += tagValue.value chartOptionsStr += ";" } } send(chartOptionsStr) } // TODO: Handle errors here // catch (Exception e) { // error(tickerId, EClientErrors_FAIL_SEND_REQHISTDATA, "" + e) // close() // } } open func reqRealTimeBars(_ tickerId: Int, contract: Contract, barSize: Int, whatToShow: String, useRTH: Bool, realTimeBarsOptions: [TagValue]?) { // synchronized // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_REAL_TIME_BARS { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support real time bars.") return } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support conId and tradingClass parameters in reqRealTimeBars.") return } } let VERSION = 3 // send req mkt data msg send(REQ_REAL_TIME_BARS) send(VERSION) send(tickerId) // send contract fields if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) send(contract.multiplier) send(contract.exchange) send(contract.primaryExch) send(contract.currency) send(contract.localSymbol) if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.tradingClass) } send(barSize) // this parameter is not currently used send(whatToShow) send(useRTH) // send realTimeBarsOptions parameter if _serverVersion >= MIN_SERVER_VER_LINKING { var realTimeBarsOptionsStr = "" if realTimeBarsOptions != nil { let realTimeBarsOptionsCount = realTimeBarsOptions!.count for i in 1...realTimeBarsOptionsCount { let tagValue = realTimeBarsOptions![i] realTimeBarsOptionsStr += tagValue.tag realTimeBarsOptionsStr += "=" realTimeBarsOptionsStr += tagValue.value realTimeBarsOptionsStr += ";" } } send(realTimeBarsOptionsStr) } // TODO: Handle errors here //catch( Exception e) { //error( tickerId, EClientErrors_FAIL_SEND_REQRTBARS, "" + e) //close() //} } open func reqContractDetails(_ reqId: Int, contract: Contract) { // synchronized // not connected? if !connected { notConnected() return } // This feature is only available for versions of TWS >=4 if (_serverVersion < 4) { error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code, errorMsg: EClientErrors_UPDATE_TWS.msg) return } if (_serverVersion < MIN_SERVER_VER_SEC_ID_TYPE) { if ((contract.secIdType.isEmpty == false) || (contract.secId.isEmpty == false)) { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support secIdType and secId parameters.") return } } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if (contract.tradingClass.isEmpty == false) { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support tradingClass parameter in reqContractDetails.") return } } let VERSION = 7 // send req mkt data msg send(REQ_CONTRACT_DATA) send(VERSION) if _serverVersion >= MIN_SERVER_VER_CONTRACT_DATA_CHAIN { send(reqId) } // send contract fields if _serverVersion >= MIN_SERVER_VER_CONTRACT_CONID { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) if _serverVersion >= 15 { send(contract.multiplier) } send(contract.exchange) send(contract.currency) send(contract.localSymbol) if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.tradingClass) } if _serverVersion >= 31 { send(contract.includeExpired) } if _serverVersion >= MIN_SERVER_VER_SEC_ID_TYPE { send(contract.secIdType) send(contract.secId) } // TODO: Handle errors here //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQCONTRACT, "" + e) //close() //} } open func reqMktDepth(_ tickerId: Int, contract: Contract, numRows: Int, mktDepthOptions: [TagValue]?) { // synchronized // not connected? if !connected { notConnected() return } // This feature is only available for versions of TWS >=6 if (_serverVersion < 6) { error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code, errorMsg: EClientErrors_UPDATE_TWS.msg) return } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support conId and tradingClass parameters in reqMktDepth.") return } } let VERSION = 5 // send req mkt data msg send(REQ_MKT_DEPTH) send(VERSION) send(tickerId) // send contract fields if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) if _serverVersion >= 15 { send(contract.multiplier) } send(contract.exchange) send(contract.currency) send(contract.localSymbol) if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.tradingClass) } if _serverVersion >= 19 { send(numRows) } // send mktDepthOptions parameter if _serverVersion >= MIN_SERVER_VER_LINKING { var mktDepthOptionsStr = "" if mktDepthOptions != nil { let mktDepthOptionsCount = mktDepthOptions!.count for i in 1...mktDepthOptionsCount { let tagValue = mktDepthOptions![i] mktDepthOptionsStr += tagValue.tag mktDepthOptionsStr += "=" mktDepthOptionsStr += tagValue.value mktDepthOptionsStr += ";" } } send(mktDepthOptionsStr) } // TODO: Handle errors here //catch( Exception e) { //error( tickerId, EClientErrors_FAIL_SEND_REQMKTDEPTH, "" + e) //close() //} } open func cancelMktData(_ tickerId: Int) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send cancel mkt data msg send(CANCEL_MKT_DATA) send(VERSION) send(tickerId) // TODO: Handle errors here //catch( Exception e) { //error( tickerId, EClientErrors_FAIL_SEND_CANMKT, "" + e) //close() //} } open func cancelMktDepth(_ tickerId: Int) { // synchronized // not connected? if !connected { notConnected() return } // This feature is only available for versions of TWS >=6 if (_serverVersion < 6) { error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code, errorMsg: EClientErrors_UPDATE_TWS.msg) return } let VERSION = 1 // send cancel mkt data msg send(CANCEL_MKT_DEPTH) send(VERSION) send(tickerId) // TODO: Handle errors here //catch( Exception e) { //error( tickerId, EClientErrors_FAIL_SEND_CANMKTDEPTH, "" + e) //close() //} } func exerciseOptions(_ tickerId: Int, contract: Contract, exerciseAction: Int, exerciseQuantity: Int, account: String, override: Int) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 2 if _serverVersion < 21 { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support options exercise from the API.") return } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if ((contract.tradingClass.isEmpty == false) || (contract.conId > 0)) { error(tickerId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support conId and tradingClass parameters in exerciseOptions.") return } } send(EXERCISE_OPTIONS) send(VERSION) send(tickerId) // send contract fields if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) send(contract.multiplier) send(contract.exchange) send(contract.currency) send(contract.localSymbol) if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.tradingClass) } send(exerciseAction) send(exerciseQuantity) send(account) send(override) // TODO: Handle errors here //catch (Exception e) { //error(tickerId, EClientErrors_FAIL_SEND_REQMKT, "" + e) //close() //} } func placeOrder(_ id: Int, contract: Contract, order: Order) { // synchronized // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_SCALE_ORDERS { if (order.scaleInitLevelSize != Int.max || order.scalePriceIncrement != Double.nan) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support Scale orders.") return } } if _serverVersion < MIN_SERVER_VER_SSHORT_COMBO_LEGS { if contract.comboLegs.count > 0 { for i in 1...contract.comboLegs.count { let comboLeg = contract.comboLegs[i] if (comboLeg.shortSaleSlot != 0 || (comboLeg.designatedLocation.isEmpty == false)) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support SSHORT flag for combo legs.") return } } } } if _serverVersion < MIN_SERVER_VER_WHAT_IF_ORDERS { if (order.whatIf) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support what-if orders.") return } } if _serverVersion < MIN_SERVER_VER_UNDER_COMP { if (contract.underComp != nil) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support delta-neutral orders.") return } } if _serverVersion < MIN_SERVER_VER_SCALE_ORDERS2 { if (order.scaleSubsLevelSize != Int.max) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support Subsequent Level Size for Scale orders.") return } } if _serverVersion < MIN_SERVER_VER_ALGO_ORDERS { if order.algoStrategy.isEmpty == false { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support algo orders.") return } } if _serverVersion < MIN_SERVER_VER_NOT_HELD { if (order.notHeld) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support notHeld parameter.") return } } if _serverVersion < MIN_SERVER_VER_SEC_ID_TYPE { if (contract.secIdType.isEmpty == false) || (contract.secId.isEmpty == false) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support secIdType and secId parameters.") return } } if _serverVersion < MIN_SERVER_VER_PLACE_ORDER_CONID { if (contract.conId > 0) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support conId parameter.") return } } if _serverVersion < MIN_SERVER_VER_SSHORTX { if (order.exemptCode != -1) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support exemptCode parameter.") return } } if _serverVersion < MIN_SERVER_VER_SSHORTX { if contract.comboLegs.count > 0 { for i in 1...contract.comboLegs.count { let comboLeg = contract.comboLegs[i] if (comboLeg.exemptCode != -1) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support exemptCode parameter.") return } } } } if _serverVersion < MIN_SERVER_VER_HEDGE_ORDERS { if order.hedgeType.isEmpty == false { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support hedge orders.") return } } if _serverVersion < MIN_SERVER_VER_OPT_OUT_SMART_ROUTING { if (order.optOutSmartRouting) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support optOutSmartRouting parameter.") return } } if _serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL_CONID { if (order.deltaNeutralConId > 0 || !order.deltaNeutralSettlingFirm.isEmpty || !order.deltaNeutralClearingAccount.isEmpty || !order.deltaNeutralClearingIntent.isEmpty ) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support deltaNeutral parameters: ConId, SettlingFirm, ClearingAccount, ClearingIntent") return } } if _serverVersion < MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE { if (!order.deltaNeutralOpenClose.isEmpty || !order.deltaNeutralShortSale || order.deltaNeutralShortSaleSlot > 0 || !order.deltaNeutralDesignatedLocation.isEmpty ) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support deltaNeutral parameters: OpenClose, ShortSale, ShortSaleSlot, DesignatedLocation") return } } if _serverVersion < MIN_SERVER_VER_SCALE_ORDERS3 { if (order.scalePriceIncrement > 0 && order.scalePriceIncrement != Double.nan) { if (order.scalePriceAdjustValue != Double.nan || order.scalePriceAdjustInterval != Int.max || order.scaleProfitOffset != Double.nan || order.scaleAutoReset || order.scaleInitPosition != Int.max || order.scaleInitFillQty != Int.max || order.scaleRandomPercent) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support Scale order parameters: PriceAdjustValue, PriceAdjustInterval, " + "ProfitOffset, AutoReset, InitPosition, InitFillQty and RandomPercent") return } } } if _serverVersion < MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) { if order.orderComboLegs.count > 0 { for i in 1...order.orderComboLegs.count { let orderComboLeg = order.orderComboLegs[i] if (orderComboLeg.price != Double.nan) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support per-leg prices for order combo legs.") return } } } } if _serverVersion < MIN_SERVER_VER_TRAILING_PERCENT { if (order.trailingPercent != Double.nan) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support trailing percent parameter") return } } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if (contract.tradingClass.isEmpty == false) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support tradingClass parameters in placeOrder.") return } } if _serverVersion < MIN_SERVER_VER_SCALE_TABLE { if (order.scaleTable.isEmpty == false || order.activeStartTime.isEmpty == false || order.activeStopTime.isEmpty == false) { error(id, pair: EClientErrors_UPDATE_TWS, tail: " It does not support scaleTable, activeStartTime and activeStopTime parameters.") return } } let VERSION = (_serverVersion < MIN_SERVER_VER_NOT_HELD) ? 27 : 42 // send place order msg send(PLACE_ORDER) send(VERSION) send(id) // send contract fields if (_serverVersion >= MIN_SERVER_VER_PLACE_ORDER_CONID) { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) if _serverVersion >= 15 { send(contract.multiplier) } send(contract.exchange) if (_serverVersion >= 14) { send(contract.primaryExch) } send(contract.currency) if (_serverVersion >= 2) { send (contract.localSymbol) } if _serverVersion >= MIN_SERVER_VER_TRADING_CLASS { send(contract.tradingClass) } if (_serverVersion >= MIN_SERVER_VER_SEC_ID_TYPE){ send(contract.secIdType) send(contract.secId) } // send main order fields send(order.action) send(order.totalQuantity) send(order.orderType) if _serverVersion < MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE { send(order.lmtPrice == Double.nan ? 0 : order.lmtPrice) } else { sendMax(order.lmtPrice) } if _serverVersion < MIN_SERVER_VER_TRAILING_PERCENT { send(order.auxPrice == Double.nan ? 0 : order.auxPrice) } else { sendMax(order.auxPrice) } // send extended order fields send(order.tif) send(order.ocaGroup) send(order.account) send(order.openClose) send(order.origin) send(order.orderRef) send(order.transmit) if (_serverVersion >= 4 ) { send (order.parentId) } if (_serverVersion >= 5 ) { send (order.blockOrder) send (order.sweepToFill) send (order.displaySize) send (order.triggerMethod) if _serverVersion < 38 { // will never happen send(/* order.ignoreRth */ false) } else { send (order.outsideRth) } } if _serverVersion >= 7 { send(order.hidden) } // Send combo legs for BAG requests if _serverVersion >= 8 && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) { send(contract.comboLegs.count) for i in 1...contract.comboLegs.count { let comboLeg = contract.comboLegs[i] send(comboLeg.conId) send(comboLeg.ratio) send(comboLeg.action) send(comboLeg.exchange) send(comboLeg.openClose) if _serverVersion >= MIN_SERVER_VER_SSHORT_COMBO_LEGS { send(comboLeg.shortSaleSlot) send(comboLeg.designatedLocation) } if _serverVersion >= MIN_SERVER_VER_SSHORTX_OLD { send(comboLeg.exemptCode) } } } // Send order combo legs for BAG requests if _serverVersion >= MIN_SERVER_VER_ORDER_COMBO_LEGS_PRICE && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) { send(order.orderComboLegs.count) for i in 1...order.orderComboLegs.count { let orderComboLeg = order.orderComboLegs[i] sendMax(orderComboLeg.price) } } if _serverVersion >= MIN_SERVER_VER_SMART_COMBO_ROUTING_PARAMS && caseInsensitiveEqual(BAG_SEC_TYPE, contract.secType) { let smartComboRoutingParams = order.smartComboRoutingParams let smartComboRoutingParamsCount = smartComboRoutingParams.count send(smartComboRoutingParamsCount) for i in 1...smartComboRoutingParamsCount { let tagValue = smartComboRoutingParams[i] send(tagValue.tag) send(tagValue.value) } } if ( _serverVersion >= 9 ) { // send deprecated sharesAllocation field send("") } if ( _serverVersion >= 10 ) { send(order.discretionaryAmt) } if ( _serverVersion >= 11 ) { send(order.goodAfterTime) } if ( _serverVersion >= 12 ) { send(order.goodTillDate) } if ( _serverVersion >= 13 ) { send(order.faGroup) send(order.faMethod) send(order.faPercentage) send(order.faProfile) } if _serverVersion >= 18 { // institutional short sale slot fields. send(order.shortSaleSlot) // 0 only for retail, 1 or 2 only for institution. send(order.designatedLocation) // only populate when order.shortSaleSlot = 2. } if _serverVersion >= MIN_SERVER_VER_SSHORTX_OLD { send(order.exemptCode) } if _serverVersion >= 19 { send(order.ocaType) if _serverVersion < 38 { // will never happen send(/* order.rthOnly */ false) } send(order.rule80A) send(order.settlingFirm) send(order.allOrNone) sendMax(order.minQty) sendMax(order.percentOffset) send(order.eTradeOnly) send(order.firmQuoteOnly) sendMax(order.nbboPriceCap) sendMax(order.auctionStrategy) sendMax(order.startingPrice) sendMax(order.stockRefPrice) sendMax(order.delta) // Volatility orders had specific watermark price attribs in server version 26 let lower = (_serverVersion == 26 && order.orderType == "VOL") ? Double.nan : order.stockRangeLower let upper = (_serverVersion == 26 && order.orderType == "VOL") ? Double.nan : order.stockRangeUpper sendMax(lower) sendMax(upper) } if _serverVersion >= 22 { send(order.overridePercentageConstraints) } if _serverVersion >= 26 { // Volatility orders sendMax(order.volatility) sendMax(order.volatilityType) if _serverVersion < 28 { send(caseInsensitiveEqual(order.deltaNeutralOrderType, "MKT")) } else { send(order.deltaNeutralOrderType) sendMax(order.deltaNeutralAuxPrice) if _serverVersion >= MIN_SERVER_VER_DELTA_NEUTRAL_CONID && order.deltaNeutralOrderType.isEmpty == false { send(order.deltaNeutralConId) send(order.deltaNeutralSettlingFirm) send(order.deltaNeutralClearingAccount) send(order.deltaNeutralClearingIntent) } if _serverVersion >= MIN_SERVER_VER_DELTA_NEUTRAL_OPEN_CLOSE && order.deltaNeutralOrderType.isEmpty == false { send(order.deltaNeutralOpenClose) send(order.deltaNeutralShortSale) send(order.deltaNeutralShortSaleSlot) send(order.deltaNeutralDesignatedLocation) } } send(order.continuousUpdate) if _serverVersion == 26 { // Volatility orders had specific watermark price attribs in server version 26 let lower = order.orderType == "VOL" ? order.stockRangeLower : Double.nan let upper = order.orderType == "VOL" ? order.stockRangeUpper : Double.nan sendMax(lower) sendMax(upper) } sendMax(order.referencePriceType) } if _serverVersion >= 30 { // TRAIL_STOP_LIMIT stop price sendMax(order.trailStopPrice) } if (_serverVersion >= MIN_SERVER_VER_TRAILING_PERCENT){ sendMax(order.trailingPercent) } if _serverVersion >= MIN_SERVER_VER_SCALE_ORDERS { if _serverVersion >= MIN_SERVER_VER_SCALE_ORDERS2 { sendMax (order.scaleInitLevelSize) sendMax (order.scaleSubsLevelSize) } else { send ("") sendMax (order.scaleInitLevelSize) } sendMax (order.scalePriceIncrement) } if _serverVersion >= MIN_SERVER_VER_SCALE_ORDERS3 && order.scalePriceIncrement > 0.0 && order.scalePriceIncrement == Double.nan { sendMax (order.scalePriceAdjustValue) sendMax (order.scalePriceAdjustInterval) sendMax (order.scaleProfitOffset) send (order.scaleAutoReset) sendMax (order.scaleInitPosition) sendMax (order.scaleInitFillQty) send (order.scaleRandomPercent) } if _serverVersion >= MIN_SERVER_VER_SCALE_TABLE { send (order.scaleTable) send (order.activeStartTime) send (order.activeStopTime) } if _serverVersion >= MIN_SERVER_VER_HEDGE_ORDERS { send (order.hedgeType) if (order.hedgeType.isEmpty == false) { send (order.hedgeParam) } } if _serverVersion >= MIN_SERVER_VER_OPT_OUT_SMART_ROUTING { send (order.optOutSmartRouting) } if _serverVersion >= MIN_SERVER_VER_PTA_ORDERS { send (order.clearingAccount) send (order.clearingIntent) } if _serverVersion >= MIN_SERVER_VER_NOT_HELD { send (order.notHeld) } if _serverVersion >= MIN_SERVER_VER_UNDER_COMP { if let underComp = contract.underComp { send(true) send(underComp.conId) send(underComp.delta) send(underComp.price) } else { send(false) } } if _serverVersion >= MIN_SERVER_VER_ALGO_ORDERS { send(order.algoStrategy) if (order.algoStrategy.isEmpty == false) { let algoParams = order.algoParams let algoParamsCount = algoParams.count send(algoParamsCount) for i in 1...algoParamsCount { let tagValue = algoParams[i] send(tagValue.tag) send(tagValue.value) } } } if _serverVersion >= MIN_SERVER_VER_WHAT_IF_ORDERS { send (order.whatIf) } // send orderMiscOptions parameter if _serverVersion >= MIN_SERVER_VER_LINKING { var orderMiscOptionsStr = "" let orderMiscOptions = order.orderMiscOptions let orderMiscOptionsCount = orderMiscOptions.count for i in 1...orderMiscOptionsCount { let tagValue = orderMiscOptions[i] orderMiscOptionsStr += tagValue.tag orderMiscOptionsStr += "=" orderMiscOptionsStr += tagValue.value orderMiscOptionsStr += ";" } send(orderMiscOptionsStr) } // TODO: Handle errors here //catch( Exception e) { //error( id, EClientErrors_FAIL_SEND_ORDER, "" + e) //close() //} } open func reqAccountUpdates(_ subscribe: Bool, acctCode: String) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 2 // send cancel order msg send(REQ_ACCOUNT_DATA ) send(VERSION) send(subscribe) // Send the account code. This will only be used for FA clients if ( _serverVersion >= 9 ) { send(acctCode) } //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_ACCT, "" + e) //close() //} } open func reqExecutions(_ reqId: Int, filter: ExecutionFilter) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 3 // send cancel order msg send(REQ_EXECUTIONS) send(VERSION) if _serverVersion >= MIN_SERVER_VER_EXECUTION_DATA_CHAIN { send(reqId) } // Send the execution rpt filter data if ( _serverVersion >= 9 ) { send(filter.clientId) send(filter.acctCode) // Note that the valid format for m_time is "yyyymmdd-hh:mm:ss" send(filter.time) send(filter.symbol) send(filter.secType) send(filter.exchange) send(filter.side) } //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_EXEC, "" + e) //close() //} } open func cancelOrder(_ id: Int) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send cancel order msg send(CANCEL_ORDER) send(VERSION) send(id) //catch( Exception e) { //error( id, EClientErrors_FAIL_SEND_CORDER, "" + e) //close() //} } open func reqOpenOrders() { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send cancel order msg send(REQ_OPEN_ORDERS) send(VERSION) //catch( Exception e) { //error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e) //tail: close() //} } open func reqIds(_ numIds: Int) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 send(REQ_IDS) send(VERSION) send(numIds) //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CORDER, "" + e) //close() //} } open func reqNewsBulletins(_ allMsgs: Bool) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 send(REQ_NEWS_BULLETINS) send(VERSION) send(allMsgs) //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CORDER, "" + e) //close() //} } open func cancelNewsBulletins() { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send cancel order msg send(CANCEL_NEWS_BULLETINS) send(VERSION) //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CORDER, "" + e) //close() //} } func setServerLogLevel(_ logLevel: Int) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send the set server logging level message send(SET_SERVER_LOGLEVEL) send(VERSION) send(logLevel) //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_SERVER_LOG_LEVEL, "" + e) //close() //} } open func reqAutoOpenOrders(_ bAutoBind: Bool) { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send req open orders msg send(REQ_AUTO_OPEN_ORDERS) send(VERSION) send(bAutoBind) //catch( Exception e) { //error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e) //tail: close() //} } open func reqAllOpenOrders() { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send req all open orders msg send(REQ_ALL_OPEN_ORDERS) send(VERSION) //catch( Exception e) { //error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e) //tail: close() //} } open func reqManagedAccts() { // synchronized // not connected? if !connected { notConnected() return } let VERSION = 1 // send req FA managed accounts msg send(REQ_MANAGED_ACCTS) send(VERSION) //catch( Exception e) { //error(EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_OORDER, "" + e) //tail: close() //} } open func requestFA(_ faDataType: Int) { // synchronized // not connected? if !connected { notConnected() return } // This feature is only available for versions of TWS >= 13 if (_serverVersion < 13) { error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code, errorMsg: EClientErrors_UPDATE_TWS.msg) return } let VERSION = 1 send(REQ_FA ) send(VERSION) send(faDataType) //catch( Exception e) { //error( faDataType, EClientErrors_FAIL_SEND_FA_REQUEST, "" + e) //close() //} } func replaceFA(_ faDataType: Int, xml: String) { // synchronized // not connected? if !connected { notConnected() return } // This feature is only available for versions of TWS >= 13 if (_serverVersion < 13) { error(EClientErrors_NO_VALID_ID, errorCode: EClientErrors_UPDATE_TWS.code, errorMsg: EClientErrors_UPDATE_TWS.msg) return } let VERSION = 1 send(REPLACE_FA ) send(VERSION) send(faDataType) send(xml) //catch( Exception e) { //error( faDataType, EClientErrors_FAIL_SEND_FA_REPLACE, "" + e) //close() //} } open func reqCurrentTime() { // synchronized // not connected? if !connected { notConnected() return } // This feature is only available for versions of TWS >= 33 if (_serverVersion < 33) { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support current time requests.") return } let VERSION = 1 send(REQ_CURRENT_TIME ) send(VERSION) //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQCURRTIME, "" + e) //close() //} } open func reqFundamentalData(_ reqId: Int, contract: Contract, reportType: String) { // synchronized // not connected? if !connected { notConnected() return } if (_serverVersion < MIN_SERVER_VER_FUNDAMENTAL_DATA) { error( reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support fundamental data requests.") return } if (_serverVersion < MIN_SERVER_VER_TRADING_CLASS) { if( contract.conId > 0) { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support conId parameter in reqFundamentalData.") return } } let VERSION = 2 // send req fund data msg send(REQ_FUNDAMENTAL_DATA) send(VERSION) send(reqId) // send contract fields if (_serverVersion >= MIN_SERVER_VER_TRADING_CLASS) { send(contract.conId) } send(contract.symbol) send(contract.secType) send(contract.exchange) send(contract.primaryExch) send(contract.currency) send(contract.localSymbol) send(reportType) //catch( Exception e) { //error( reqId, EClientErrors_FAIL_SEND_REQFUNDDATA, "" + e) //close() //} } open func cancelFundamentalData(_ reqId: Int) { // synchronized // not connected? if !connected { notConnected() return } if (_serverVersion < MIN_SERVER_VER_FUNDAMENTAL_DATA) { error( reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support fundamental data requests.") return } let VERSION = 1 // send req mkt data msg send(CANCEL_FUNDAMENTAL_DATA) send(VERSION) send(reqId) //catch( Exception e) { //error( reqId, EClientErrors_FAIL_SEND_CANFUNDDATA, "" + e) //close() //} } // synchronized func calculateImpliedVolatility(_ reqId: Int, contract: Contract, optionPrice: Double, underPrice: Double) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support calculate implied volatility requests.") return } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if contract.tradingClass.isEmpty == false { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support tradingClass parameter in calculateImpliedVolatility.") return } } let VERSION = 2 // send calculate implied volatility msg send(REQ_CALC_IMPLIED_VOLAT) send(VERSION) send(reqId) // send contract fields send(contract.conId) send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) send(contract.multiplier) send(contract.exchange) send(contract.primaryExch) send(contract.currency) send(contract.localSymbol) if (_serverVersion >= MIN_SERVER_VER_TRADING_CLASS) { send(contract.tradingClass) } send(optionPrice) send(underPrice) //catch( Exception e) { //error( reqId, EClientErrors_FAIL_SEND_REQCALCIMPLIEDVOLAT, "" + e) //close() //} } // synchronized open func cancelCalculateImpliedVolatility(_ reqId: Int) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_CANCEL_CALC_IMPLIED_VOLAT { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support calculate implied volatility cancellation.") return } let VERSION = 1 // send cancel calculate implied volatility msg send(CANCEL_CALC_IMPLIED_VOLAT) send(VERSION) send(reqId) //catch( Exception e) { //error( reqId, EClientErrors_FAIL_SEND_CANCALCIMPLIEDVOLAT, "" + e) //close() //} } // synchronized func calculateOptionPrice(_ reqId: Int, contract: Contract, volatility: Double, underPrice: Double) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_REQ_CALC_OPTION_PRICE { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support calculate option price requests.") return } if _serverVersion < MIN_SERVER_VER_TRADING_CLASS { if contract.tradingClass.isEmpty == false { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support tradingClass parameter in calculateOptionPrice.") return } } let VERSION = 2 // send calculate option price msg send(REQ_CALC_OPTION_PRICE) send(VERSION) send(reqId) // send contract fields send(contract.conId) send(contract.symbol) send(contract.secType) send(contract.expiry) send(contract.strike) send(contract.right) send(contract.multiplier) send(contract.exchange) send(contract.primaryExch) send(contract.currency) send(contract.localSymbol) if (_serverVersion >= MIN_SERVER_VER_TRADING_CLASS) { send(contract.tradingClass) } send(volatility) send(underPrice) //catch( Exception e) { //error( reqId, EClientErrors_FAIL_SEND_REQCALCOPTIONPRICE, "" + e) //close() //} } // synchronized open func cancelCalculateOptionPrice(_ reqId: Int) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_CANCEL_CALC_OPTION_PRICE { error(reqId, pair: EClientErrors_UPDATE_TWS, tail: " It does not support calculate option price cancellation.") return } let VERSION = 1 // send cancel calculate option price msg send(CANCEL_CALC_OPTION_PRICE) send(VERSION) send(reqId) //catch( Exception e) { //error( reqId, EClientErrors_FAIL_SEND_CANCALCOPTIONPRICE, "" + e) //close() //} } // synchronized open func reqGlobalCancel() { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_REQ_GLOBAL_CANCEL { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support globalCancel requests.") return } let VERSION = 1 // send request global cancel msg send(REQ_GLOBAL_CANCEL) send(VERSION) //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQGLOBALCANCEL, "" + e) //close() //} } // synchronized open func reqMarketDataType(_ marketDataType: Int) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_REQ_MARKET_DATA_TYPE { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support marketDataType requests.") return } let VERSION = 1 // send the reqMarketDataType message send(REQ_MARKET_DATA_TYPE) send(VERSION) send(marketDataType) //catch( Exception e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQMARKETDATATYPE, "" + e) //close() //} } // synchronized open func reqPositions() { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support position requests.") return } let VERSION = 1 let b = Builder() b.send(REQ_POSITIONS) b.send(VERSION) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQPOSITIONS, "" + e) //} } // synchronized open func cancelPositions() { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support position cancellation.") return } let VERSION = 1 let b = Builder() b.send(CANCEL_POSITIONS) b.send(VERSION) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CANPOSITIONS, "" + e) //} } // synchronized open func reqAccountSummary(_ reqId: Int, group: String, tags: String) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support account summary requests.") return } let VERSION = 1 let b = Builder() b.send(REQ_ACCOUNT_SUMMARY) b.send(VERSION) b.send(reqId) b.send(group) b.send(tags) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_REQACCOUNTDATA, "" + e) //} } // synchronized open func cancelAccountSummary(_ reqId: Int) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_ACCT_SUMMARY { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support account summary cancellation.") return } let VERSION = 1 let b = Builder() b.send(CANCEL_ACCOUNT_SUMMARY) b.send(VERSION) b.send(reqId) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_CANACCOUNTDATA, "" + e) //} } // synchronized func verifyRequest(_ apiName: String, apiVersion: String) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_LINKING { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support verification request.") return } if (!extraAuth) { error( EClientErrors_NO_VALID_ID, pair: EClientErrors_FAIL_SEND_VERIFYMESSAGE, tail: " Intent to authenticate needs to be expressed during initial connect request.") return } let VERSION = 1 let b = Builder() b.send(VERIFY_REQUEST) b.send(VERSION) b.send(apiName) b.send(apiVersion) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_VERIFYREQUEST, "" + e) //} } // synchronized func verifyMessage(_ apiData: String) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_LINKING { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support verification message sending.") return } let VERSION = 1 let b = Builder() b.send(VERIFY_MESSAGE) b.send(VERSION) b.send(apiData) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_VERIFYMESSAGE, "" + e) //} } // synchronized func queryDisplayGroups(_ reqId: Int) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_LINKING { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support queryDisplayGroups request.") return } let VERSION = 1 let b = Builder() b.send(QUERY_DISPLAY_GROUPS) b.send(VERSION) b.send(reqId) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_QUERYDISPLAYGROUPS, "" + e) //} } // synchronized func subscribeToGroupEvents(_ reqId: Int, groupId: Int) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_LINKING { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support subscribeToGroupEvents request.") return } let VERSION = 1 let b = Builder() b.send(SUBSCRIBE_TO_GROUP_EVENTS) b.send(VERSION) b.send(reqId) b.send(groupId) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_SUBSCRIBETOGROUPEVENTS, "" + e) //} } // synchronized func updateDisplayGroup(_ reqId: Int, contractInfo: String) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_LINKING { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support updateDisplayGroup request.") return } let VERSION = 1 let b = Builder() b.send(UPDATE_DISPLAY_GROUP) b.send(VERSION) b.send(reqId) b.send(contractInfo) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_UPDATEDISPLAYGROUP, "" + e) //} } // synchronized func unsubscribeFromGroupEvents(_ reqId: Int) { // not connected? if !connected { notConnected() return } if _serverVersion < MIN_SERVER_VER_LINKING { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_UPDATE_TWS, tail: " It does not support unsubscribeFromGroupEvents request.") return } let VERSION = 1 let b = Builder() b.send(UNSUBSCRIBE_FROM_GROUP_EVENTS) b.send(VERSION) b.send(reqId) let bgb = b.bytes dos?.write(bgb, maxLength: bgb.count) //catch (IOException e) { //error( EClientErrors_NO_VALID_ID, EClientErrors_FAIL_SEND_UNSUBSCRIBEFROMGROUPEVENTS, "" + e) //} } func error(_ id: Int, errorCode: Int, errorMsg: String) { // synchronized _anyWrapper.error(id, errorCode: errorCode, errorMsg: errorMsg) } open func close() { eDisconnect() eWrapper().connectionClosed() } func error(_ id: Int, pair: CodeMsgPair, tail: String) { error(id, errorCode: pair.code, errorMsg: pair.msg + tail) } func send(_ str: String) { // write string to data buffer; writer thread will // write it to socket if !str.isEmpty { // TODO: Add comprehensive error handling here if let dataBytes = str.data(using: String.Encoding.utf8, allowLossyConversion: false) { var bytes = [UInt8](repeating: 0, count: dataBytes.count) (dataBytes as NSData).getBytes(&bytes, length: dataBytes.count) dos?.write(bytes, maxLength: dataBytes.count) } } sendEOL() } func sendEOL() { dos?.write(EOL, maxLength: 1) } func send(_ val: Int) { send(itos(val)) } func send(_ val: Character) { let s = String(val) send(s) } func send(_ val: Double) { send(dtos(val)) } func send(_ val: Int64) { send(ltos(val)) } func sendMax(_ val: Double) { if (val == Double.nan) { sendEOL() } else { send(dtos(val)) } } func sendMax(_ val: Int) { if (val == Int.max) { sendEOL() } else { send(itos(val)) } } func send(_ val: Bool) { send( val ? 1 : 0) } func notConnected() { error(EClientErrors_NO_VALID_ID, pair: EClientErrors_NOT_CONNECTED, tail: "") } } // REMOVED METHOD // public synchronized void eConnect(Socket socket, int clientId) throws IOException { // m_clientId = clientId // eConnect(socket) // } // // private static boolean IsEmpty(String str) { // return Util.StringIsEmpty(str) // } // // private static boolean is( String str) { // // return true if the string is not empty // return str != null && str.length() > 0; // } // // private static boolean isNull( String str) { // // return true if the string is null or empty // return !is( str) // } // // /** @deprecated, never called. */ // protected synchronized void error( String err) { // _anyWrapper.error( err) // }
8a112162a37dd1e3ff415ffd93c3a84c
32.37281
166
0.54194
false
false
false
false
phillips07/StudyCast
refs/heads/master
StudyCast/CustomTabBarController.swift
mit
1
// // CustomTabBarController.swift // StudyCast // // Created by Dennis Huebert on 2016-11-11. // Copyright © 2016 Austin Phillips. All rights reserved. // import UIKit class CustomTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let groupsTableViewContoller = GroupsTableViewController() let groupsNavigationController = UINavigationController(rootViewController: groupsTableViewContoller) groupsNavigationController.title = "Groups" groupsNavigationController.tabBarItem.image = UIImage(named: "GroupsIcon") let castController = CastMapController() let castNavigationController = UINavigationController(rootViewController: castController) castNavigationController.title = "Cast" castNavigationController.tabBarItem.image = UIImage(named: "CastIcon") let homeController = MainScreenController() let homeNavigationController = UINavigationController(rootViewController: homeController) homeNavigationController.title = "Home" homeNavigationController.tabBarItem.image = UIImage(named: "HomeIcon") UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.lightGray], for: .selected) UITabBar.appearance().tintColor = UIColor.lightGray viewControllers = [homeNavigationController, castNavigationController, groupsNavigationController] } }
d12bd437865c0c484f9c3bad93a2c174
40.794872
125
0.734356
false
false
false
false
IngmarStein/swift
refs/heads/master
test/ClangImporter/objc_bridging.swift
apache-2.0
4
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -parse-as-library -verify %s // REQUIRES: objc_interop import Foundation import objc_structs extension String { func onlyOnString() -> String { return self } } extension Bool { func onlyOnBool() -> Bool { return self } } extension Array { func onlyOnArray() { } } extension Dictionary { func onlyOnDictionary() { } } extension Set { func onlyOnSet() { } } func foo() { _ = NSStringToNSString as (String!) -> String? _ = DummyClass().nsstringProperty.onlyOnString() as String _ = BOOLtoBOOL as (Bool) -> Bool _ = DummyClass().boolProperty.onlyOnBool() as Bool _ = arrayToArray as (Array<Any>!) -> (Array<Any>!) DummyClass().arrayProperty.onlyOnArray() _ = dictToDict as (Dictionary<AnyHashable, Any>!) -> Dictionary<AnyHashable, Any>! DummyClass().dictProperty.onlyOnDictionary() _ = setToSet as (Set<AnyHashable>!) -> Set<AnyHashable>! DummyClass().setProperty.onlyOnSet() } func allocateMagic(_ zone: NSZone) -> UnsafeMutableRawPointer { return allocate(zone) } func constPointerToObjC(_ objects: [AnyObject]) -> NSArray { return NSArray(objects: objects, count: objects.count) } func mutablePointerToObjC(_ path: String) throws -> NSString { return try NSString(contentsOfFile: path) } func objcStructs(_ s: StructOfNSStrings, sb: StructOfBlocks) { // Struct fields must not be bridged. _ = s.nsstr! as Bool // expected-error {{cannot convert value of type 'Unmanaged<NSString>' to type 'Bool' in coercion}} // FIXME: Blocks should also be Unmanaged. _ = sb.block as Bool // expected-error {{cannot convert value of type '@convention(block) () -> Void' to type 'Bool' in coercion}} sb.block() // okay }
4d7192dc5ccc3ec844444b45bd3f7ba2
25.8
132
0.695752
false
false
false
false
adrfer/swift
refs/heads/master
stdlib/public/core/EmptyCollection.swift
apache-2.0
2
//===--- EmptyCollection.swift - A collection with no elements ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Sometimes an operation is best expressed in terms of some other, // larger operation where one of the parameters is an empty // collection. For example, we can erase elements from an Array by // replacing a subrange with the empty collection. // //===----------------------------------------------------------------------===// /// A generator that never produces an element. /// /// - SeeAlso: `EmptyCollection<Element>`. public struct EmptyGenerator<Element> : GeneratorType, SequenceType { @available(*, unavailable, renamed="Element") public typealias T = Element /// Construct an instance. public init() {} /// Return `nil`, indicating that there are no more elements. public mutating func next() -> Element? { return nil } } /// A collection whose element type is `Element` but that is always empty. public struct EmptyCollection<Element> : CollectionType { @available(*, unavailable, renamed="Element") public typealias T = Element /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Int /// Construct an instance. public init() {} /// Always zero, just like `endIndex`. public var startIndex: Index { return 0 } /// Always zero, just like `startIndex`. public var endIndex: Index { return 0 } /// Returns an empty *generator*. /// /// - Complexity: O(1). public func generate() -> EmptyGenerator<Element> { return EmptyGenerator() } /// Access the element at `position`. /// /// Should never be called, since this collection is always empty. public subscript(position: Index) -> Element { _preconditionFailure("Index out of range") } /// Return the number of elements (always zero). public var count: Int { return 0 } }
b21ba66b7123dd9984d8b855f1d1dc9f
29.822785
80
0.64271
false
false
false
false
webventil/OpenSport
refs/heads/master
OpenSport/OpenSport/RecordMapViewController.swift
mit
1
// // RecordMapViewController.swift // OpenSport // // Created by Arne Tempelhof on 19.11.14. // Copyright (c) 2014 Arne Tempelhof. All rights reserved. // import UIKit import MapKit internal class RecordMapViewController: UIViewController, MKMapViewDelegate { @IBOutlet internal weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self mapView.userTrackingMode = MKUserTrackingMode.Follow // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if (overlay is MKPolyline) { var renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.openSportBlue(1) renderer.lineWidth = 5.0 return renderer } if (overlay is MKCircle) { var renderer = MKCircleRenderer(overlay: overlay) renderer.strokeColor = UIColor.redColor() renderer.lineWidth = 5.0 return renderer } return 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. } */ }
dd04d48f857878659049cc8c888fde6f
28.122807
106
0.663253
false
false
false
false
xwu/swift
refs/heads/master
test/Generics/sr11153.swift
apache-2.0
1
// RUN: %target-swift-frontend -typecheck -debug-generic-signatures -requirement-machine-protocol-signatures=on %s 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -emit-ir -requirement-machine-protocol-signatures=on %s // CHECK: Requirement signature: <Self where Self.Field : FieldAlgebra> public protocol VectorSpace { associatedtype Field: FieldAlgebra } // CHECK: Requirement signature: <Self where Self : VectorSpace, Self == Self.Field, Self.ComparableSubalgebra : ComparableFieldAlgebra> public protocol FieldAlgebra: VectorSpace where Self.Field == Self { associatedtype ComparableSubalgebra: ComparableFieldAlgebra static var zero: Self { get } } // CHECK: Requirement signature: <Self where Self : FieldAlgebra, Self == Self.ComparableSubalgebra> public protocol ComparableFieldAlgebra: FieldAlgebra where Self.ComparableSubalgebra == Self { } // CHECK: Generic signature: <F where F : FieldAlgebra> public func test<F: FieldAlgebra>(_ f: F) { _ = F.ComparableSubalgebra.zero }
f12239cfaf014235a9d582da051fa1c9
45
136
0.764822
false
false
false
false
johnno1962/Dynamo
refs/heads/master
TickTackToe/TickTackToe.swift
mit
1
// // TickTackToe.swift // Yaws // // Created by John Holdsworth on 13/06/2015. // Copyright (c) 2015 John Holdsworth. All rights reserved. // import Foundation #if !os(iOS) import Dynamo #endif private class TickTackGameEngine: NSObject { var board = [["white", "white", "white"], ["white", "white", "white"], ["white", "white", "white"]] func winner() -> String? { var won: String? let middle = board[1][1] if board[1][0] == middle && middle == board[1][2] || board[0][1] == middle && middle == board[2][1] || board[0][0] == middle && middle == board[2][2] || board[0][2] == middle && middle == board[2][0] { if middle != "white" { won = middle } } if board[0][0] == board[0][1] && board[0][1] == board[0][2] || board[0][0] == board[1][0] && board[1][0] == board[2][0] { if board[0][0] != "white" { won = board[0][0] } } if board[0][2] == board[1][2] && board[1][2] == board[2][2] || board[2][0] == board[2][1] && board[2][1] == board[2][2] { if board[2][2] != "white" { won = board[2][2] } } return won } } @objc (TickTackToeSwiftlet) open class TickTackToeSwiftlet: SessionApplication { fileprivate var engine = TickTackGameEngine() @objc override open func processRequest( out: DynamoHTTPConnection, pathInfo: String, parameters: [String:String], cookies: [String:String] ) { var cookies = cookies // reset board and keep scores if let whoWon = parameters["reset"] { engine = TickTackGameEngine() if whoWon != "draw" { let newCount = cookies[whoWon] ?? "0" let newValue = "\(Int(newCount)!+1)" out.setCookie( name: whoWon, value: newValue, expires: 60 ) cookies[whoWon] = newValue } } let scores = cookies.keys .filter( { $0 == "red" || $0 == "green" } ) .map( { "\($0) wins: \(cookies[$0]!)" } ).joined( separator: ", " ) out.print( html( nil ) + head( title( "Tick Tack Toe Example" ) + style( "body, table { font: 10pt Arial; } " + "table { border: 4px outset; } " + "td { border: 4px inset; }" ) ) + body( nil ) + h3( "Tick Tack Toe "+scores ) ) // make move let player = parameters["player"] ?? "green" if let x = parameters["x"]?.toInt(), let y = parameters["y"]?.toInt() { engine.board[y][x] = player } // print board let nextPlayer = player == "green" ? "red" : "green" var played = 0 out.print( center( nil ) + table( nil ) ) for y in 0..<3 { out.print( tr( nil ) ) for x in 0..<3 { var attrs = ["bgcolor":engine.board[y][x], "width":"100", "height":"100"] if engine.board[y][x] != "white" { played += 1 } else { attrs["onclick"] = "document.location.replace( '\(pathInfo)?player=\(nextPlayer)&x=\(x)&y=\(y)' );" } out.print( td( attrs, "&nbsp;" ) ) } out.print( _tr() ) } out.print( _table() ) // check for winner let won = engine.winner() if won != nil { out.print( script( "alert( '\(player) wins' ); document.location.href = '/ticktacktoe?reset=\(won!)';" ) ) } else if played == 9 { out.print( script( "alert( 'It\\'s a draw!' ); document.location.href = '/ticktacktoe?reset=draw';" ) ) } out.print( backButton() ) } }
a4b209d59754938c1f4f531f9633875f
31.445378
147
0.465682
false
false
false
false
AgaKhanFoundation/WCF-iOS
refs/heads/develop
Floral/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift
apache-2.0
13
// // SharedSequence.swift // RxCocoa // // Created by Krunoslav Zaher on 8/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift /** Trait that represents observable sequence that shares computation resources with following properties: - it never fails - it delivers events on `SharingStrategy.scheduler` - sharing strategy is customizable using `SharingStrategy.share` behavior `SharedSequence<Element>` can be considered a builder pattern for observable sequences that share computation resources. To find out more about units and how to use them, please visit `Documentation/Traits.md`. */ public struct SharedSequence<SharingStrategy: SharingStrategyProtocol, Element> : SharedSequenceConvertibleType { let _source: Observable<Element> init(_ source: Observable<Element>) { self._source = SharingStrategy.share(source) } init(raw: Observable<Element>) { self._source = raw } #if EXPANDABLE_SHARED_SEQUENCE /** This method is extension hook in case this unit needs to extended from outside the library. By defining `EXPANDABLE_SHARED_SEQUENCE` one agrees that it's up to him to ensure shared sequence properties are preserved after extension. */ public static func createUnsafe<Source: ObservableType>(source: Source) -> SharedSequence<Sequence, Source.Element> { return SharedSequence<Sequence, Source.Element>(raw: source.asObservable()) } #endif /** - returns: Built observable sequence. */ public func asObservable() -> Observable<Element> { return self._source } /** - returns: `self` */ public func asSharedSequence() -> SharedSequence<SharingStrategy, Element> { return self } } /** Different `SharedSequence` sharing strategies must conform to this protocol. */ public protocol SharingStrategyProtocol { /** Scheduled on which all sequence events will be delivered. */ static var scheduler: SchedulerType { get } /** Computation resources sharing strategy for multiple sequence observers. E.g. One can choose `share(replay:scope:)` as sequence event sharing strategies, but also do something more exotic, like implementing promises or lazy loading chains. */ static func share<Element>(_ source: Observable<Element>) -> Observable<Element> } /** A type that can be converted to `SharedSequence`. */ public protocol SharedSequenceConvertibleType : ObservableConvertibleType { associatedtype SharingStrategy: SharingStrategyProtocol /** Converts self to `SharedSequence`. */ func asSharedSequence() -> SharedSequence<SharingStrategy, Element> } extension SharedSequenceConvertibleType { public func asObservable() -> Observable<Element> { return self.asSharedSequence().asObservable() } } extension SharedSequence { /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - returns: An observable sequence with no elements. */ public static func empty() -> SharedSequence<SharingStrategy, Element> { return SharedSequence(raw: Observable.empty().subscribeOn(SharingStrategy.scheduler)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - returns: An observable sequence whose observers will never get called. */ public static func never() -> SharedSequence<SharingStrategy, Element> { return SharedSequence(raw: Observable.never()) } /** Returns an observable sequence that contains a single element. - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: Element) -> SharedSequence<SharingStrategy, Element> { return SharedSequence(raw: Observable.just(element).subscribeOn(SharingStrategy.scheduler)) } /** Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () -> SharedSequence<SharingStrategy, Element>) -> SharedSequence<SharingStrategy, Element> { return SharedSequence(Observable.deferred { observableFactory().asObservable() }) } /** This method creates a new Observable instance with a variable number of elements. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - returns: The observable sequence whose elements are pulled from the given arguments. */ public static func of(_ elements: Element ...) -> SharedSequence<SharingStrategy, Element> { let source = Observable.from(elements, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } } extension SharedSequence { /** This method converts an array to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from(_ array: [Element]) -> SharedSequence<SharingStrategy, Element> { let source = Observable.from(array, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } /** This method converts a sequence to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence) -> SharedSequence<SharingStrategy, Element> where Sequence.Element == Element { let source = Observable.from(sequence, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } /** This method converts a optional to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter optional: Optional element in the resulting observable sequence. - returns: An observable sequence containing the wrapped value or not from given optional. */ public static func from(optional: Element?) -> SharedSequence<SharingStrategy, Element> { let source = Observable.from(optional: optional, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } } extension SharedSequence where Element : RxAbstractInteger { /** Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) - parameter period: Period for producing the values in the resulting sequence. - returns: An observable sequence that produces a value after each period. */ public static func interval(_ period: RxTimeInterval) -> SharedSequence<SharingStrategy, Element> { return SharedSequence(Observable.interval(period, scheduler: SharingStrategy.scheduler)) } } // MARK: timer extension SharedSequence where Element: RxAbstractInteger { /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) - parameter dueTime: Relative time at which to produce the first value. - parameter period: Period to produce subsequent values. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval) -> SharedSequence<SharingStrategy, Element> { return SharedSequence(Observable.timer(dueTime, period: period, scheduler: SharingStrategy.scheduler)) } }
bc7a0b00137e35fab86bf29cc2c1b7b2
37.389381
174
0.720032
false
false
false
false
lukecharman/so-many-games
refs/heads/master
SoManyGames/Classes/Cells/GameCell.swift
mit
1
// // GameCell.swift // SoManyGames // // Created by Luke Charman on 21/03/2017. // Copyright © 2017 Luke Charman. All rights reserved. // import UIKit protocol GameCellDelegate: class { func game(_ game: Game, didUpdateProgress progress: Double) } class GameCell: UICollectionViewCell { static let height: CGFloat = iPad ? 90 : 60 static let swipeMultiplier: CGFloat = 1.7 @IBOutlet var label: UILabel! @IBOutlet var platformLabel: UILabel! @IBOutlet var percentageLabel: UILabel! @IBOutlet var progressView: NSLayoutConstraint! @IBOutlet var progressBar: UIView! var longPressRecognizer: UILongPressGestureRecognizer! var panRecognizer: UIPanGestureRecognizer! weak var delegate: GameCellDelegate? let long = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(recognizer:))) let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:))) var game: Game? { didSet { guard let game = game else { return } label.text = game.name platformLabel.text = game.activePlatform?.abbreviation ?? "???" calculateProgress(from: game.completionPercentage) } } override func prepareForReuse() { super.prepareForReuse() isSelected = false backgroundColor = .clear } override func awakeFromNib() { super.awakeFromNib() setUpRecognizers() label.layer.shadowOffset = .zero label.layer.shadowRadius = 2 progressBar.isUserInteractionEnabled = false progressBar.translatesAutoresizingMaskIntoConstraints = false platformLabel.font = platformLabel.font.withSize(Sizes.gameCellSub) percentageLabel.font = percentageLabel.font.withSize(Sizes.gameCellSub) label.font = label.font.withSize(Sizes.gameCellMain) label.numberOfLines = iPad ? 3 : 2 clipsToBounds = false } func setUpRecognizers() { longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(recognizer:))) panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:))) longPressRecognizer.delegate = self panRecognizer.delegate = self addGestureRecognizer(longPressRecognizer) addGestureRecognizer(panRecognizer) } func calculateProgress(from ratio: Double) { let size = bounds.size.width * CGFloat(ratio) progressView.constant = size progressBar.alpha = CGFloat(ratio) percentageLabel.text = String(describing: Int(ratio * 100)) + "%" layoutIfNeeded() } func calculateProgressOnRotation() { let ratio = game!.completionPercentage let size = (UIScreen.main.bounds.size.height / 2) * CGFloat(ratio) progressView.constant = size progressBar.alpha = CGFloat(ratio) percentageLabel.text = String(describing: Int(ratio * 100)) + "%" layoutIfNeeded() } @objc func handleLongPress(recognizer: UILongPressGestureRecognizer) { guard let game = game else { return } UIView.animate(withDuration: 0.3) { if recognizer.state == .began { self.beginLongPress() self.layoutIfNeeded() } else if recognizer.state == .ended || recognizer.state == .cancelled { self.endLongPress() self.calculateProgress(from: game.completionPercentage) self.layoutIfNeeded() } } } override var isSelected: Bool { didSet { guard isSelected != oldValue else { return } updateSelection() } } func updateSelection() { guard let game = game else { return } UIView.animate(withDuration: 0.3) { self.backgroundColor = self.isSelected ? Colors.darkest.withAlphaComponent(0.2) : .clear if self.isSelected { self.progressBar.alpha = 0 } else { self.calculateProgress(from: game.completionPercentage) } } } func beginLongPress() { label.alpha = 0.8 label.transform = CGAffineTransform(scaleX: 1.4, y: 1.4) label.layer.shadowOpacity = 0.2 platformLabel.alpha = 0 platformLabel.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) percentageLabel.alpha = 0 percentageLabel.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) progressBar.alpha = 0 progressView.constant = 0 } func endLongPress() { label.alpha = 1 label.transform = CGAffineTransform(scaleX: 1, y: 1) label.layer.shadowOpacity = 0 platformLabel.alpha = 1 platformLabel.transform = CGAffineTransform(scaleX: 1, y: 1) percentageLabel.alpha = 1 percentageLabel.transform = CGAffineTransform(scaleX: 1, y: 1) progressBar.alpha = 1 } @objc func handlePan(recognizer: UIPanGestureRecognizer) { guard let game = game else { return } guard !isSelected else { return } let originalValue = CGFloat(game.completionPercentage) * bounds.size.width let t = max((recognizer.translation(in: self).x * GameCell.swipeMultiplier) + originalValue, 0) let ratio = min(max(t / bounds.size.width, 0), 1) // Restrict value between 0 and 1. if recognizer.state == .changed { progressView.constant = t progressBar.alpha = ratio * 1.3 percentageLabel.text = "\(String(describing: Int(ratio * 100)))%" layoutIfNeeded() } else if recognizer.state == .ended || recognizer.state == .cancelled { let newRatio = Double(ratio) Backlog.manager.update(game) { game.completionPercentage = newRatio } delegate?.game(game, didUpdateProgress: newRatio) } } } extension GameCell: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return !(gestureRecognizer is UIPanGestureRecognizer) && !(otherGestureRecognizer is UIPanGestureRecognizer) } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == panRecognizer else { return true } let v = panRecognizer.velocity(in: self) let h = fabs(v.x) > fabs(v.y) return h // Only pan when horizontal. } }
d6081b0a890a5ca6854c3064b7ae083a
32.266332
157
0.646677
false
false
false
false
CodaFi/swift
refs/heads/main
test/decl/func/constructor.swift
apache-2.0
22
// RUN: %target-typecheck-verify-swift // User-written default constructor struct X { init() {} } X() // expected-warning{{unused}} // User-written memberwise constructor struct Y { var i : Int, f : Float init(i : Int, f : Float) {} } Y(i: 1, f: 1.5) // expected-warning{{unused}} // User-written memberwise constructor with default struct Z { var a : Int var b : Int init(a : Int, b : Int = 5) { self.a = a self.b = b } } Z(a: 1, b: 2) // expected-warning{{unused}} // User-written init suppresses implicit constructors. struct A { var i, j : Int init(x : Int) { // expected-note {{'init(x:)' declared here}} i = x j = x } } A() // expected-error{{missing argument for parameter 'x'}} A(x: 1) // expected-warning{{unused}} A(1, 1) // expected-error{{extra argument in call}} // No user-written constructors; implicit constructors are available. struct B { var i : Int = 0, j : Float = 0.0 } extension B { init(x : Int) { self.i = x self.j = 1.5 } } B() // expected-warning{{unused}} B(x: 1) // expected-warning{{unused}} B(i: 1, j: 2.5) // expected-warning{{unused}} struct F { // expected-note {{'init(d:b:c:)' declared here}} var d : D var b : B var c : C } struct C { var d : D // suppress implicit initializers init(d : D) { } // expected-note {{'init(d:)' declared here}} } struct D { var i : Int init(i : Int) { } } extension D { init() { i = 17 } } F() // expected-error{{missing arguments for parameters 'd', 'b', 'c' in call}} D() // okay // expected-warning{{unused}} B() // okay // expected-warning{{unused}} C() // expected-error{{missing argument for parameter 'd'}} struct E { init(x : Wonka) { } // expected-error{{cannot find type 'Wonka' in scope}} } var e : E //---------------------------------------------------------------------------- // Argument/parameter name separation //---------------------------------------------------------------------------- class ArgParamSep { init(_ b: Int, _: Int, forInt int: Int, c _: Int, d: Int) { } } // Tests for crashes. // rdar://14082378 struct NoCrash1a { init(_: NoCrash1b) {} // expected-error {{cannot find type 'NoCrash1b' in scope}} } var noCrash1c : NoCrash1a class MissingDef { init() // expected-error{{initializer requires a body}} }
d152d560b31b56f13704a62fe56e1d11
19.990909
83
0.568211
false
false
false
false
lixiangzhou/ZZLib
refs/heads/master
Source/ZZCustom/ZZNumberTextField.swift
mit
1
// // ZZNumberTextField.swift // ZZLib // // Created by lixiangzhou on 2018/6/20. // Copyright © 2018年 lixiangzhou. All rights reserved. // import UIKit class ZZNumberTextField: UITextField, UITextFieldDelegate { override init(frame: CGRect) { super.init(frame: frame) self.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Public Prop /// 分隔模式,例如银行卡号[4, 4, 4, 4, 4, 4]; 身份证号[6, 8, 4] var sepMode = [Int]() { didSet { var index = 0 for mode in sepMode { index += mode sepIndex.append(index) index += 1 } } } /// 长度限制,不包含空格的长度 var lengthLimit = Int.max /// 要包含的其他的字符,默认包含 CharacterSet.decimalDigits 和 " " var additionIncludeCharacterSet: CharacterSet? // MARK: - Private Prop private var sepIndex = [Int]() // MARK: - UITextFieldDelegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var text = textField.text ?? "" let emptyCharacter = Character(" ") if range.length > 0 && string.isEmpty { // 删除 if sepMode.count > 0 { if range.length == 1 { // 删除一位 // 光标前第二个字符,如果是空格需要删除 var toDeleteCharacterEmpty: Character? if range.location >= 1 { toDeleteCharacterEmpty = text[text.index(text.startIndex, offsetBy: range.location - 1)] } if range.location == text.count - 1 { // 在最后删除 if toDeleteCharacterEmpty == emptyCharacter { // 有空格,需要再往前删除一个空格 textField.deleteBackward() } return true } else { // 在中间删除 // 删除光标所在位置的字符 textField.deleteBackward() var offset = range.location if toDeleteCharacterEmpty == emptyCharacter { // 如果光标前有空格,删除 textField.deleteBackward() offset -= 1 } textField.text = formatToModeString(textField.text!) resetPosition(offset: offset) return false } } else if range.length > 1 { textField.deleteBackward() textField.text = formatToModeString(textField.text!) var location = range.location var characterBeforeLocation: Character? if location >= 1 { characterBeforeLocation = text[text.index(text.startIndex, offsetBy: location - 1)] if characterBeforeLocation == emptyCharacter { location -= 1 } } if NSMaxRange(range) != text.count { // 光标不是在最后 resetPosition(offset: location) } return false } else { return true } } else { return true } } else if string.count > 0 { // 输入文字 if sepMode.count > 0 { if (text + string).replacingOccurrences(of: " ", with: "").count > lengthLimit { // 超过限制 // 异步主线程是为了避免复制粘贴时光标错位的问题 DispatchQueue.main.async { self.resetPosition(offset: range.location) } return false } var newSet = CharacterSet.decimalDigits.union(CharacterSet(charactersIn: " ")) if let additionIncludeCharacterSet = additionIncludeCharacterSet { newSet = newSet.union(additionIncludeCharacterSet) } if string.trimmingCharacters(in: newSet).count > 0 { // 不是数字 // 异步主线程是为了避免复制粘贴时光标错位的问题 DispatchQueue.main.async { self.resetPosition(offset: range.location) } return false } let stringBeforeCursor = String(text[text.startIndex..<text.index(text.startIndex, offsetBy: range.location)]) textField.insertText(string) textField.text = formatToModeString(textField.text!) let temp = stringBeforeCursor + string let newLocation = formatToModeString(temp).count // 异步主线程是为了避免复制粘贴时光标错位的问题 DispatchQueue.main.async { self.resetPosition(offset: newLocation) } return false } else { text += string if text.replacingOccurrences(of: " ", with: "").count > lengthLimit { return false } } } return true } // MARK: - Private Method private func formatToModeString(_ text: String) -> String { var string = text.replacingOccurrences(of: " ", with: "") for index in sepIndex { if string.count > index { string.insert(" ", at: string.index(string.startIndex, offsetBy: index)) } } return string } private func resetPosition(offset: Int) { let newPosition = self.position(from: self.beginningOfDocument, offset: offset)! self.selectedTextRange = self.textRange(from: newPosition, to: newPosition) } }
a543c345aaff4831d4036f016ad88557
36.728395
129
0.472022
false
false
false
false
jtekenos/ios_schedule
refs/heads/develop
ios_schedule/ClassForum.swift
mit
1
// // ClassForum.swift // ios_schedule // // Created by Jessica Tekenos on 2015-11-27. // Copyright © 2015 Jess. All rights reserved. // import Foundation import RealmSwift import Parse import ParseUI class ClassForum: Object { dynamic var classForumId = 0 dynamic var set = "" dynamic var name = "" dynamic var instructor = "" let posts = List<Post>() // Specify properties to ignore (Realm won't persist these) // override static func ignoredProperties() -> [String] { // return [] // } }
37500a62265bd37c28fa2a229b8aa130
18.928571
63
0.625448
false
false
false
false
bazelbuild/tulsi
refs/heads/master
src/Tulsi/MessageViewController.swift
apache-2.0
1
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Cocoa import TulsiGenerator /// NSTableView that posts a notification when live resizing completes. final class MessageTableView: NSTableView { override func viewDidEndLiveResize() { super.viewDidEndLiveResize() // Give the delegate a chance to handle the resize now that the live operation is completed. NotificationCenter.default.post(name: NSTableView.columnDidResizeNotification, object: self) } } /// View controller for the message output area in the Tulsi wizard. final class MessageViewController: NSViewController, NSTableViewDelegate, NSUserInterfaceValidations { let minRowHeight = CGFloat(16.0) @IBOutlet var messageArrayController: NSArrayController! @IBOutlet weak var messageAreaScrollView: NSScrollView! // Display heights of each row in the message table. var rowHeights = [Int: CGFloat]() @objc dynamic var messageCount: Int = 0 { didSet { // Assume that a reduction in the message count means all cached heights are invalid. if messageCount < oldValue { rowHeights.removeAll(keepingCapacity: true) } scrollToNewRowIfAtBottom() } } override func loadView() { ValueTransformer.setValueTransformer(MessageTypeToImageValueTransformer(), forName: NSValueTransformerName(rawValue: "MessageTypeToImageValueTransformer")) super.loadView() bind(NSBindingName(rawValue: "messageCount"), to: messageArrayController!, withKeyPath: "arrangedObjects.@count", options: nil) } @IBAction func copy(_ sender: AnyObject?) { guard let selectedItems = messageArrayController.selectedObjects as? [NSPasteboardWriting], !selectedItems.isEmpty else { return } let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.writeObjects(selectedItems) } @IBAction func clearMessages(_ sender: AnyObject?) { (self.representedObject as! TulsiProjectDocument).clearMessages() } // MARK: - NSUserInterfaceValidations func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { if item.action == #selector(copy(_:)) { return !messageArrayController.selectedObjects.isEmpty } return false } // MARK: - NSTableViewDelegate func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { if let height = rowHeights[row] { return height } let message = (messageArrayController.arrangedObjects as! [UIMessage])[row] let column = tableView.tableColumns.first! let cell = column.dataCell as! NSTextFieldCell cell.stringValue = message.text let bounds = CGRect(x: 0, y: 0, width: column.width, height: CGFloat.greatestFiniteMagnitude) let requiredSize = cell.cellSize(forBounds: bounds) let height = max(requiredSize.height, minRowHeight) rowHeights[row] = height return height } func tableViewColumnDidResize(_ notification: Notification) { guard let tableView = notification.object as? NSTableView else { return } // Wait until resizing completes before doing a lot of work. if tableView.inLiveResize { return } // Disable animation. NSAnimationContext.beginGrouping() NSAnimationContext.current.duration = 0 rowHeights.removeAll(keepingCapacity: true) let numRows = (messageArrayController.arrangedObjects as AnyObject).count! let allRowsIndex = IndexSet(integersIn: 0..<numRows) tableView.noteHeightOfRows(withIndexesChanged: allRowsIndex) NSAnimationContext.endGrouping() } // MARK: - Private methods private func scrollToNewRowIfAtBottom() { guard messageCount > 0, let tableView = messageAreaScrollView.documentView as? NSTableView else { return } let lastRowIndex = messageCount - 1 let scrollContentViewBounds = messageAreaScrollView.contentView.bounds let contentViewHeight = scrollContentViewBounds.height let newRowHeight = self.tableView(tableView, heightOfRow: lastRowIndex) + tableView.intercellSpacing.height let bottomScrollY = tableView.frame.maxY - (contentViewHeight + newRowHeight) if scrollContentViewBounds.origin.y >= bottomScrollY { tableView.scrollRowToVisible(lastRowIndex) } } } /// Transformer that converts a UIMessage type into an image to be displayed in the message view. final class MessageTypeToImageValueTransformer : ValueTransformer { override class func transformedValueClass() -> AnyClass { return NSString.self } override class func allowsReverseTransformation() -> Bool { return false } override func transformedValue(_ value: Any?) -> Any? { guard let intValue = value as? Int, let messageType = TulsiGenerator.LogMessagePriority(rawValue: intValue) else { return nil } switch messageType { case .info, .debug, .syslog: return NSImage(named: "message_info") case .warning: return NSImage(named: "message_warning") case .error: return NSImage(named: "message_error") } } }
6773f5eb4f65ee677151e541a1b2158c
34.079755
131
0.720182
false
false
false
false
austinzheng/swift-compiler-crashes
refs/heads/master
fixed/27135-swift-patternbindingdecl-setpattern.swift
mit
4
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {{{ let : T:a<T where f enum b {struct A enum B}protocol a{ let a=f:A{var" let a { let c{ class d{{ }typealias d {func f g class A { struct d<S where B{ let : N < where h:a var f _}}}} struct S<T where g:d {{{ class B{ var b{ <f {let:d { class b:d{ " { var b{ let : d:A struct d:d { B{ struct B<T where " {{a enum B<T where f: T> : a{var b=Swift.h =1 func f g < where " "" {}struct B<T where f: d< where B : T.h =1 < where h:A func f g:a func let a = " " class d func g a<T {var b { class B<f=1 var b{ var f= let : d:P { class A class A class A{ class A { }}protocol a= func aA} "" class b<f= struct B<T> : { B<T where B{var b:e}}struct S<f:P { let a = " { func foo}typealias d<T where f func aA} struct S<T where " { let : T:e let:d{var" var b { " func a <T {let:d< {func a{{let:A }}} < where h: d B{{ " " " " func a=1 class A var b{ { where =1 class b<T where a = f: a= protocol B:a = " [ 1 {{{ protocol B{ let a func < where h: { class A {}} protocol a{var b {b{{ protocol B:a func struct S<T where =f: { { enum :a<T where g:e let:d struct S<T { func A protocol B{var f= let c{ enum B:P { enum S<T where B : d where a func let a = " {var b:d where g:a<{{var"""" class B<f:A struct S<h {var b {}typealias d< where h: d where f class d<T where g:d<T where g struct B{{ enum b { protocol B{ protocol a class A class B{ class A { { let a<T where B{ let : d:P { struct A enum S<f:d:e}}struct S<T where h:e class d let a func class A<T where f=Swift.E let a = f:d { func g a enum B<T where B : a{ func g a<T where g:d where g:d func a class a<T where " [ 1 class A {var b:d {b<T:a{ }protocol B} class d{} _}}typealias d let a {var f=1 let c{var b { class A { func aA}}}typealias d func f g:a=f:P {{ class A { protocol B} func foo}} let c<f=1 class A class {{ let : T:A{func g a{struct B{ <T { class A { class d<T where g:a var b<T where g func f g:a protocol a<T where g:d<T where h:A class A{ { class d<S where f: {{ protocol a{ class a<T.e}}}} let a{ { enum S<f class a{let:T {b {{ func g a var b:T>: T func foo} let a{ let : d:d enum B{var b{a{struct S<T:A<T <T
fd333d10e1c913ecc9e25fda8f2347c7
13.677632
87
0.619005
false
false
false
false
sopinetchat/SopinetChat-iOS
refs/heads/master
Pod/Models/SImageFile.swift
gpl-3.0
1
// // SImageFile.swift // Pods // // Created by David Moreno Lora on 26/4/16. // // import Foundation import UIKit public class SImageFile { public dynamic var id = -1 public dynamic var path = "" public var message: SMessageImage? init(id: Int, path: String, message: SMessageImage) { self.id = id self.path = path self.message = message } }
53d80e46d178be28950c34ef7719dd60
15.916667
55
0.598522
false
false
false
false
cotkjaer/Silverback
refs/heads/master
Silverback/UIPickerView.swift
mit
1
// // UIPickerView.swift // Silverback // // Created by Christian Otkjær on 08/12/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import UIKit extension UIPickerView { public func maxSizeForRowsInComponent(component: Int) -> CGSize { var size = CGSizeZero if let delegate = self.delegate, let dataSource = self.dataSource, let widthToFit = delegate.pickerView?(self, widthForComponent: component) { let sizeToFit = CGSize(width: widthToFit , height: 10000) for row in 0..<dataSource.pickerView(self, numberOfRowsInComponent: component) { let view = delegate.pickerView!(self, viewForRow: row, forComponent: component, reusingView: nil) let wantedSize = view.sizeThatFits(sizeToFit) size.width = max(size.width, wantedSize.width) size.height = max(size.height, wantedSize.height) } } return size } }
d43c1b12afb5dd41ca441ae4c6e84e7f
29.941176
148
0.596958
false
false
false
false
prachigauriar/MagazineScanCombiner
refs/heads/master
Magazine Scan Combiner/Controllers/ScanCombinerWindowController.swift
mit
1
// // ScanCombinerWindowController.swift // Magazine Scan Combiner // // Created by Prachi Gauriar on 7/3/2016. // Copyright © 2016 Prachi Gauriar. // // 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 Cocoa class ScanCombinerWindowController : NSWindowController, FileDropImageAndPathFieldViewDelegate { // MARK: - Outlets and UI-related properties @IBOutlet var frontPagesDropView: FileDropImageAndPathFieldView! @IBOutlet var reversedBackPagesDropView: FileDropImageAndPathFieldView! @IBOutlet var combinePDFsButton: NSButton! // MARK: - User input properties var frontPagesURL: URL? { didSet { updateCombinePDFsButtonEnabledState() } } var reversedBackPagesURL: URL? { didSet { updateCombinePDFsButtonEnabledState() } } // MARK: - Concurrency lazy var operationQueue: OperationQueue = { let operationQueue = OperationQueue() operationQueue.name = "\(type(of: self)).\(Unmanaged.passUnretained(self).toOpaque())" return operationQueue }() // MARK: - NSWindowController subclass overrides override var windowNibName: NSNib.Name? { return .scanCombinerWindow } override func windowDidLoad() { super.windowDidLoad() frontPagesDropView.delegate = self reversedBackPagesDropView.delegate = self updateCombinePDFsButtonEnabledState() } // MARK: - Action methods @IBAction func combinePDFs(_ sender: NSButton) { guard let window = window, let directoryURL = frontPagesURL?.deletingLastPathComponent() else { NSSound.beep() return } let savePanel = NSSavePanel() savePanel.nameFieldStringValue = NSLocalizedString("ScanCombinerWindowController.DefaultOutputFilename", comment: "Default filename for the output PDF") savePanel.directoryURL = directoryURL savePanel.allowedFileTypes = [kUTTypePDF as String] savePanel.canSelectHiddenExtension = true savePanel.beginSheetModal(for: window) { [unowned self] result in guard result == .OK, let outputURL = savePanel.url else { return } self.beginCombiningPDFs(withOutputURL: outputURL) } } private func beginCombiningPDFs(withOutputURL outputURL: URL) { guard let frontPagesURL = frontPagesURL, let reversedBackPagesURL = reversedBackPagesURL, let window = window else { return } // Create the combine scan operation with our input and output PDF URLs let operation = CombineScansOperation(frontPagesPDFURL: frontPagesURL, reversedBackPagesPDFURL: reversedBackPagesURL, outputPDFURL: outputURL) // Set up a progress sheet controller so we can show a progress sheet let progressSheetController = ProgressSheetController() progressSheetController.progress = operation.progress progressSheetController.localizedProgressMesageKey = "CombineProgress.Format" guard let progressSheet = progressSheetController.window else { return } // Add a completion block that hides the progress sheet when the operation finishes operation.completionBlock = { [weak window] in progressSheetController.progress = nil OperationQueue.main.addOperation { [weak window, weak progressSheet] in guard let progressSheet = progressSheet else { return } window?.endSheet(progressSheet) } } // Begin showing the progress sheet. On dismiss, either show an error or show the resultant PDF file window.beginSheet(progressSheet, completionHandler: { [unowned self] _ in if let error = operation.error { // If there was an error, show an alert to the user self.showAlert(for: error) } else if !operation.isCancelled { // Otherwise show the resultant PDF in the Finder if it wasn’t canceled NSWorkspace.shared.activateFileViewerSelecting([outputURL]) } }) operationQueue.addOperation(operation) } // MARK: - Updating the UI based on user input private func updateCombinePDFsButtonEnabledState() { combinePDFsButton.isEnabled = frontPagesURL != nil && reversedBackPagesURL != nil } // MARK: - Showing alerts private func showAlert(for error: CombineScansError) { let alert = NSAlert() alert.addButton(withTitle: NSLocalizedString("OK", comment: "OK button title")) switch error { case let .couldNotOpenFileURL(fileURL): updateAlert(alert, withErrorLocalizedKey: "CouldNotOpenFile", fileURL: fileURL) case let .couldNotCreateOutputPDF(fileURL): updateAlert(alert, withErrorLocalizedKey: "CouldNotCreateFile", fileURL: fileURL) } alert.beginSheetModal(for: self.window!, completionHandler: nil) } private func updateAlert(_ alert: NSAlert, withErrorLocalizedKey key: String, fileURL: URL) { alert.messageText = NSLocalizedString("Error.\(key).MessageText", comment: "") alert.informativeText = String.localizedStringWithFormat(NSLocalizedString("Error.\(key).InformativeText.Format", comment: ""), fileURL.path.abbreviatingWithTildeInPath) } // MARK: - File Drop Image and Path Field View delegate func fileDropImageAndPathFieldView(_ view: FileDropImageAndPathFieldView, shouldAcceptDraggedFileURL fileURL: URL) -> Bool { guard let resourceValues = try? fileURL.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey]), let fileType = resourceValues.typeIdentifier else { return false } return UTTypeConformsTo(fileType as CFString, kUTTypePDF) } func fileDropImageAndPathFieldView(_ view: FileDropImageAndPathFieldView, didReceiveDroppedFileURL fileURL: URL) { if view == frontPagesDropView { frontPagesURL = fileURL } else { reversedBackPagesURL = fileURL } } } private extension NSNib.Name { static let scanCombinerWindow = NSNib.Name("ScanCombinerWindow") }
640df51c7e2abacd7c286526ea0c3bb0
35.807882
150
0.673849
false
false
false
false
gkaimakas/SwiftValidatorsReactiveExtensions
refs/heads/master
Example/SwiftValidatorsReactiveExtensions/Views/TextFieldCollectionViewCell/TextFieldCollectionViewCell.swift
mit
1
// // TextFieldCollectionViewCell.swift // SwiftValidatorsReactiveExtensions_Example // // Created by George Kaimakas on 12/02/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import MagazineLayout import SnapKit import UIKit class TextFieldCollectionViewCell: MagazineLayoutCollectionViewCell { let titleLabel = UILabel(frame: .zero) let textField = UITextField(frame: .zero) let errorLabel = UILabel(frame: .zero) override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { addSubview(titleLabel) addSubview(textField) addSubview(errorLabel) titleLabel.snp.makeConstraints { (make) in make.leading.equalToSuperview() make.trailing.equalToSuperview() make.top.equalToSuperview() make.bottom.equalTo(textField.snp.top) } textField.snp.makeConstraints { (make) in make.leading.equalToSuperview() make.trailing.equalToSuperview() make.bottom.equalTo(errorLabel.snp.top) } errorLabel.snp.makeConstraints { (make) in make.leading.equalToSuperview() make.trailing.equalToSuperview() make.bottom.equalToSuperview() } titleLabel.font = UIFont.preferredFont(forTextStyle: .caption1) errorLabel.font = UIFont.preferredFont(forTextStyle: .caption1) textField.borderStyle = .roundedRect titleLabel.text = "title" textField.placeholder = "text field" errorLabel.text = "error" } }
555ad6c1f5189994bb691cb9a97e1c5e
27.934426
71
0.623229
false
false
false
false
dorentus/bna-swift
refs/heads/master
Padlock/Authenticator/Secret.swift
mit
1
// // Secret.swift // Authenticator // // Created by Rox Dorentus on 14-6-5. // Copyright (c) 2014年 rubyist.today. All rights reserved. // import Foundation public struct Secret: Printable, Equatable { public let text: String public var binary: [UInt8] { return hex2bin(text) } public var description: String { return text } public init?(text: String) { if let secret = Secret.format(secret: text) { self.text = secret } else { return nil } } public init?(binary: [UInt8]) { self.init(text: bin2hex(binary)) } public static func format(#secret: String) -> String? { let text = secret.lowercaseString if text.matches("[0-9a-f]{40}") { return text } return nil } } public func ==(lhs: Secret, rhs: Secret) -> Bool { return lhs.text == rhs.text }
463522e83a88a8b566ce52f76256669b
21.02439
59
0.578073
false
false
false
false
Narsail/relaykit
refs/heads/master
RelayKit/Shared/Relay.swift
mit
1
/// Copyright (c) 2017 David Moeller /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import Foundation import WatchConnectivity public enum RelayError: Error { case moduleIdentNotFound case messageIdentNotFound case noMessageTypeMatchFor(messageIdent: String) case receiverNotFound } open class Relay: NSObject { /// Last initiated Relay public static var shared: Relay? { didSet { debugLog(RelayKitLogCategory.configuration, ["Setting", type(of: shared), "as Relay with", type(of: shared?.core), "."]) } } internal var core: RelayCore internal var sender: [String: (Sender, [Message.Type])] = [:] internal var receiver: [String: (Receiver, [Message.Type])] = [:] public var errorHandler: ((Error) -> Void)? = nil public init(core: RelayCore) { self.core = core super.init() // Attach the receiving end of the core to the receivers self.core.didReceiveMessage = { [weak self] data, method, replyHandler in // Check for the Module Indent do { debugLog(.messageContent, ["Received Message Data", data]) guard let moduleIdent = data["moduleIdent"] as? String else { throw RelayError.moduleIdentNotFound } // Check for the receiver guard let (receiver, messageTypes) = self?.receiver[moduleIdent] else { throw RelayError.receiverNotFound } // Check for the Message Ident guard let messageIdent = data["messageIdent"] as? String else { throw RelayError.messageIdentNotFound } // Get the appropriate Message Type guard let messageType = messageTypes.first(where: { $0.messageIdent == messageIdent }) else { throw RelayError.noMessageTypeMatchFor(messageIdent: messageIdent) } let message = try messageType.decode(data) debugLog(.messages, ["Received", messageType, "with", method]) if let replyHandler = replyHandler { receiver.didReceiveMessage(message, method, { replyMessage in var encodedData = replyMessage.encode() encodedData["moduleIdent"] = moduleIdent encodedData["messageIdent"] = type(of: replyMessage).messageIdent replyHandler(encodedData) }) } else { receiver.didReceiveMessage(message, method, nil) } } catch { debugLog(.messages, ["Receiving message failed with", error, "by", method]) self?.errorHandler?(error) } } Relay.shared = self } /// Registering a Sender can only be done once per object /// /// - note: A followed call with the same sender will overwrite the old one public func register(_ sender: Sender, with messages: Message.Type ...) { self.register(sender, with: messages) } /// Registering a Sender can only be done once per object /// /// - note: A followed call with the same sender will overwrite the old one public func register(_ sender: Sender, with messages: [Message.Type]) { self.sender[sender.moduleIdent] = (sender, messages) // Set the necessary blocks sender.sendMessageBlock = { [weak self] message, method, replyHandler, errorHandler in debugLog(.messages, ["Sending Message", type(of: message), "with", method]) // Error Handling if wrong Method var data = message.encode() data["moduleIdent"] = sender.moduleIdent data["messageIdent"] = type(of: message).messageIdent debugLog(.messageContent, ["Sending Message Data", data]) do { try self?.core.sendMessage(data, method, replyHandler: { replyData in do { debugLog(.messageContent, ["Got Reply Data with", replyData]) // Find Message ident guard let messageIdent = replyData["messageIdent"] as? String else { throw RelayError.messageIdentNotFound } // Find a suitable Message to return guard let messageClass = messages.first(where: { $0.messageIdent == messageIdent }) else { throw RelayError.noMessageTypeMatchFor(messageIdent: messageIdent) } let responseMessage = try messageClass.decode(replyData) debugLog(.messages, ["Got Reply with", type(of: message), "with", method]) replyHandler(responseMessage) } catch { debugLog(.messages, ["Receiving reply failed with", error, "by", method]) errorHandler(error) } }, errorHandler: errorHandler) } catch { debugLog(.messages, ["Sending message failed with", error, "by", method]) errorHandler(error) } } } /// Registering a Receiver can only be done once per object public func register(_ receiver: Receiver, with messages: Message.Type ...) { self.register(receiver, with: messages) } /// Registering a Receiver can only be done once per object public func register(_ receiver: Receiver, with messages: [Message.Type]) { self.receiver[receiver.moduleIdent] = (receiver, messages) } /// Registering a Communicator can only be done once per object public func register(_ allrounder: Allrounder, with messages: Message.Type ...) { self.register(allrounder, with: messages) } public func register(_ allrounder: Allrounder, with messages: [Message.Type]) { self.register(allrounder as Sender, with: messages) self.register(allrounder as Receiver, with: messages) } public func deregister(_ sender: Sender) { // Set the Blocks nil sender.sendMessageBlock = nil self.sender.removeValue(forKey: sender.moduleIdent) } public func deregister(_ receiver: Receiver) { self.receiver.removeValue(forKey: receiver.moduleIdent) } public func deregister(_ allrounder: Allrounder) { self.deregister(allrounder as Sender) self.deregister(allrounder as Receiver) } }
396c745d8b0ab97b7bf566184a5c4bd1
38.191964
178
0.577628
false
false
false
false
crashoverride777/SwiftyAds
refs/heads/master
Sources/Internal/SwiftyAdsBanner.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015-2022 Dominik Ringler // // 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 GoogleMobileAds final class SwiftyAdsBanner: NSObject { // MARK: - Types private enum Configuration { static let visibleConstant: CGFloat = 0 static let hiddenConstant: CGFloat = 400 } // MARK: - Properties private let environment: SwiftyAdsEnvironment private let isDisabled: () -> Bool private let hasConsent: () -> Bool private let request: () -> GADRequest private var onOpen: (() -> Void)? private var onClose: (() -> Void)? private var onError: ((Error) -> Void)? private var onWillPresentScreen: (() -> Void)? private var onWillDismissScreen: (() -> Void)? private var onDidDismissScreen: (() -> Void)? private var bannerView: GADBannerView? private var position: SwiftyAdsBannerAdPosition = .bottom(isUsingSafeArea: true) private var animation: SwiftyAdsBannerAdAnimation = .none private var bannerViewConstraint: NSLayoutConstraint? private var animator: UIViewPropertyAnimator? // MARK: - Initialization init(environment: SwiftyAdsEnvironment, isDisabled: @escaping () -> Bool, hasConsent: @escaping () -> Bool, request: @escaping () -> GADRequest) { self.environment = environment self.isDisabled = isDisabled self.hasConsent = hasConsent self.request = request super.init() } // MARK: - Convenience func prepare(withAdUnitId adUnitId: String, in viewController: UIViewController, position: SwiftyAdsBannerAdPosition, animation: SwiftyAdsBannerAdAnimation, onOpen: (() -> Void)?, onClose: (() -> Void)?, onError: ((Error) -> Void)?, onWillPresentScreen: (() -> Void)?, onWillDismissScreen: (() -> Void)?, onDidDismissScreen: (() -> Void)?) { self.position = position self.animation = animation self.onOpen = onOpen self.onClose = onClose self.onError = onError self.onWillPresentScreen = onWillPresentScreen self.onWillDismissScreen = onWillDismissScreen self.onDidDismissScreen = onDidDismissScreen // Create banner view let bannerView = GADBannerView() // Keep reference to created banner view self.bannerView = bannerView // Set ad unit id bannerView.adUnitID = adUnitId // Set the root view controller that will display the banner view bannerView.rootViewController = viewController // Set the banner view delegate bannerView.delegate = self // Add banner view to view controller add(bannerView, to: viewController) // Hide banner without animation hide(bannerView, from: viewController, skipAnimation: true) } } // MARK: - SwiftyAdsBannerType extension SwiftyAdsBanner: SwiftyAdsBannerType { func show(isLandscape: Bool) { guard !isDisabled() else { return } guard hasConsent() else { return } guard let bannerView = bannerView else { return } guard let currentView = bannerView.rootViewController?.view else { return } // Determine the view width to use for the ad width. let frame = { () -> CGRect in switch position { case .top(let isUsingSafeArea), .bottom(let isUsingSafeArea): if isUsingSafeArea { return currentView.frame.inset(by: currentView.safeAreaInsets) } else { return currentView.frame } } }() // Get Adaptive GADAdSize and set the ad view. if isLandscape { bannerView.adSize = GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width) } else { bannerView.adSize = GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width) } // Create an ad request and load the adaptive banner ad. bannerView.load(request()) } func hide() { guard let bannerView = bannerView else { return } guard let rootViewController = bannerView.rootViewController else { return } hide(bannerView, from: rootViewController) } func remove() { guard bannerView != nil else { return } bannerView?.delegate = nil bannerView?.removeFromSuperview() bannerView = nil bannerViewConstraint = nil onClose?() } } // MARK: - GADBannerViewDelegate extension SwiftyAdsBanner: GADBannerViewDelegate { // Request lifecycle events func bannerViewDidRecordImpression(_ bannerView: GADBannerView) { if case .development = environment { print("SwiftyAdsBanner did record impression for banner ad") } } func bannerViewDidReceiveAd(_ bannerView: GADBannerView) { show(bannerView, from: bannerView.rootViewController) if case .development = environment { print("SwiftyAdsBanner did receive ad from: \(bannerView.responseInfo?.adNetworkClassName ?? "not found")") } } func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) { hide(bannerView, from: bannerView.rootViewController) onError?(error) } // Click-Time lifecycle events func bannerViewWillPresentScreen(_ bannerView: GADBannerView) { onWillPresentScreen?() } func bannerViewWillDismissScreen(_ bannerView: GADBannerView) { onWillDismissScreen?() } func bannerViewDidDismissScreen(_ bannerView: GADBannerView) { onDidDismissScreen?() } } // MARK: - Private Methods private extension SwiftyAdsBanner { func add(_ bannerView: GADBannerView, to viewController: UIViewController) { // Add banner view to view controller bannerView.translatesAutoresizingMaskIntoConstraints = false viewController.view.addSubview(bannerView) // Add constraints // We don't give the banner a width or height constraint, as the provided ad size will give the banner // an intrinsic content size switch position { case .top(let isUsingSafeArea): if isUsingSafeArea { bannerViewConstraint = bannerView.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor) } else { bannerViewConstraint = bannerView.topAnchor.constraint(equalTo: viewController.view.topAnchor) } case .bottom(let isUsingSafeArea): if let tabBarController = viewController as? UITabBarController { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: tabBarController.tabBar.topAnchor) } else { if isUsingSafeArea { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.bottomAnchor) } else { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor) } } } // Activate constraints NSLayoutConstraint.activate([ bannerView.centerXAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.centerXAnchor), bannerViewConstraint ].compactMap { $0 }) } func show(_ bannerAd: GADBannerView, from viewController: UIViewController?) { // Stop current animations stopCurrentAnimatorAnimations() // Show banner incase it was hidden bannerAd.isHidden = false // Animate if needed switch animation { case .none: animator = nil case .fade(let duration): animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { [weak bannerView] in bannerView?.alpha = 1 } case .slide(let duration): /// We can only animate the banner to its on-screen position with a valid view controller guard let viewController = viewController else { return } /// We can only animate the banner to its on-screen position if it has a constraint guard let bannerViewConstraint = bannerViewConstraint else { return } /// We can only animate the banner to its on-screen position if its not already visible guard bannerViewConstraint.constant != Configuration.visibleConstant else { return } /// Set banner constraint bannerViewConstraint.constant = Configuration.visibleConstant /// Animate constraint changes animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { viewController.view.layoutIfNeeded() } } // Add animation completion if needed animator?.addCompletion { [weak self] _ in self?.onOpen?() } // Start animation if needed animator?.startAnimation() } func hide(_ bannerAd: GADBannerView, from viewController: UIViewController?, skipAnimation: Bool = false) { // Stop current animations stopCurrentAnimatorAnimations() // Animate if needed switch animation { case .none: animator = nil bannerAd.isHidden = true case .fade(let duration): if skipAnimation { bannerView?.alpha = 0 } else { animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { [weak bannerView] in bannerView?.alpha = 0 } } case .slide(let duration): /// We can only animate the banner to its off-screen position with a valid view controller guard let viewController = viewController else { return } /// We can only animate the banner to its off-screen position if it has a constraint guard let bannerViewConstraint = bannerViewConstraint else { return } /// We can only animate the banner to its off-screen position if its already visible guard bannerViewConstraint.constant == Configuration.visibleConstant else { return } /// Get banner off-screen constant var newConstant: CGFloat { switch position { case .top: return -Configuration.hiddenConstant case .bottom: return Configuration.hiddenConstant } } /// Set banner constraint bannerViewConstraint.constant = newConstant /// Animate constraint changes if !skipAnimation { animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { viewController.view.layoutIfNeeded() } } } // Add animation completion if needed animator?.addCompletion { [weak self, weak bannerAd] _ in bannerAd?.isHidden = true self?.onClose?() } // Start animation if needed animator?.startAnimation() } func stopCurrentAnimatorAnimations() { animator?.stopAnimation(false) animator?.finishAnimation(at: .current) } }
74e8e36e1de5634324510033932caa37
36.283186
140
0.630113
false
false
false
false
avito-tech/Marshroute
refs/heads/master
MarshrouteTests/Sources/Routers/MasterRouterTests/MasterlRouterTests.swift
mit
1
import XCTest @testable import Marshroute final class MasterlRouterTests: XCTestCase { var masterAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy! var detailAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy! var targetViewController: UIViewController! var router: MasterRouter! override func setUp() { super.setUp() let transitionIdGenerator = TransitionIdGeneratorImpl() let peekAndPopTransitionsCoordinator = PeekAndPopUtilityImpl() let transitionsCoordinator = TransitionsCoordinatorImpl( stackClientProvider: TransitionContextsStackClientProviderImpl(), peekAndPopTransitionsCoordinator: peekAndPopTransitionsCoordinator ) masterAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy( transitionsCoordinator: transitionsCoordinator ) detailAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy( transitionsCoordinator: transitionsCoordinator ) targetViewController = UIViewController() router = BaseMasterDetailRouter( routerSeed: MasterDetailRouterSeed( masterTransitionsHandlerBox: .init( animatingTransitionsHandler: masterAnimatingTransitionsHandlerSpy ), detailTransitionsHandlerBox: .init( animatingTransitionsHandler: detailAnimatingTransitionsHandlerSpy ), transitionId: transitionIdGenerator.generateNewTransitionId(), presentingTransitionsHandler: nil, transitionsHandlersProvider: transitionsCoordinator, transitionIdGenerator: transitionIdGenerator, controllersProvider: RouterControllersProviderImpl() ) ) } // MARK: - Master Transitions Handler func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_SetMasterViewControllerDerivedFrom_WithCorrectResettingContext() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! // When router.setMasterViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = masterAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.rootViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_SetMasterViewControllerDerivedFrom_WithCorrectResettingContext_IfCustomAnimator() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! let resetNavigationTransitionsAnimator = ResetNavigationTransitionsAnimator() // When router.setMasterViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController }, animator: resetNavigationTransitionsAnimator ) // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = masterAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === resetNavigationTransitionsAnimator) XCTAssert(launchingContext.rootViewController! === targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_PushMasterViewControllerDerivedFrom_WithCorrectPresentationContext() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! // When router.pushMasterViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = masterAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.targetViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_PushMasterViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! let navigationTransitionsAnimator = NavigationTransitionsAnimator() // When router.pushMasterViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController }, animator: navigationTransitionsAnimator ) // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = masterAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === navigationTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === targetViewController) } else { XCTFail() } } // MARK: - Detail Transitions Handler func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_SetDetailViewControllerDerivedFrom_WithCorrectResettingContext() { // Given var nextModuleRouterSeed: RouterSeed! // When router.setDetailViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = detailAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === detailAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.rootViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_SetDetailViewControllerDerivedFrom_WithCorrectResettingContext_IfCustomAnimator() { // Given var nextModuleRouterSeed: RouterSeed! let resetNavigationTransitionsAnimator = ResetNavigationTransitionsAnimator() // When router.setDetailViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController }, animator: resetNavigationTransitionsAnimator ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = detailAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === detailAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === resetNavigationTransitionsAnimator) XCTAssert(launchingContext.rootViewController! === targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_PushDetailViewControllerDerivedFrom_WithCorrectPresentationContext() { // Given var nextModuleRouterSeed: RouterSeed! // When router.pushDetailViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.targetViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_PushDetailViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() { // Given var nextModuleRouterSeed: RouterSeed! let navigationTransitionsAnimator = NavigationTransitionsAnimator() // When router.pushDetailViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController }, animator: navigationTransitionsAnimator ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === navigationTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === targetViewController) } else { XCTFail() } } }
b83d21124ec3b0ea628110c0495ba23f
51.517647
157
0.736783
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/Common/Internals/AudioKitHelpers.swift
mit
1
// // AudioKitHelpers.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import CoreAudio import AudioToolbox public typealias MIDINoteNumber = Int public typealias MIDIVelocity = Int // MARK: - Randomization Helpers /// Global function for random integers /// /// - returns: Random integer in the range /// - parameter range: Range of valid integers to choose from /// public func randomInt(range: Range<Int>) -> Int { let width = range.maxElement()! - range.minElement()! return Int(arc4random_uniform(UInt32(width))) + range.minElement()! } /// Extension to Array for Random Element extension Array { /// Return a random element from the array public func randomElement() -> Element { let index = Int(arc4random_uniform(UInt32(self.count))) return self[index] } } /// Global function for random Doubles /// /// - returns: Random double between bounds /// - parameter minimum: Lower bound of randomization /// - parameter maximum: Upper bound of randomization /// public func random(minimum: Double, _ maximum: Double) -> Double { let precision = 1000000 let width = maximum - minimum return Double(arc4random_uniform(UInt32(precision))) / Double(precision) * width + minimum } // MARK: - Normalization Helpers /// Extension to calculate scaling factors, useful for UI controls extension Double { /// Convert a value on [min, max] to a [0, 1] range, according to a taper /// /// - parameter min: Minimum of the source range (cannot be zero if taper is not positive) /// - parameter max: Maximum of the source range /// - parameter taper: For taper > 0, there is an algebraic curve, taper = 1 is linear, and taper < 0 is exponential /// public mutating func normalize(min: Double, max: Double, taper: Double) { if taper > 0 { // algebraic taper self = pow(((self - min) / (max - min)), (1.0 / taper)) } else { // exponential taper self = log(self / min) / log(max / min) } } /// Convert a value on [0, 1] to a [min, max] range, according to a taper /// /// - parameter min: Minimum of the target range (cannot be zero if taper is not positive) /// - parameter max: Maximum of the target range /// - parameter taper: For taper > 0, there is an algebraic curve, taper = 1 is linear, and taper < 0 is exponential /// public mutating func denormalize(min: Double, max: Double, taper: Double) { if taper > 0 { // algebraic taper self = min + (max - min) * pow(self, taper) } else { // exponential taper self = min * exp(log(max / min) * self) } } } /// Extension to Int to calculate frequency from a MIDI Note Number extension Int { /// Calculate frequency from a MIDI Note Number /// /// - returns: Frequency (Double) in Hz /// public func midiNoteToFrequency(aRef: Double = 440.0) -> Double { return pow(2.0, (Double(self) - 69.0) / 12.0) * aRef } } /// Extension to Double to get the frequency from a MIDI Note Number extension Double { /// Calculate frequency from a floating point MIDI Note Number /// /// - returns: Frequency (Double) in Hz /// public func midiNoteToFrequency(aRef: Double = 440.0) -> Double { return pow(2.0, (self - 69.0) / 12.0) * aRef } }
4fc49c2ca400b9e58d527e7a04241ecd
30.5625
120
0.630835
false
false
false
false
PopcornTimeTV/PopcornTimeTV
refs/heads/master
PopcornKit/Managers/NetworkManager.swift
gpl-3.0
1
import Foundation import Alamofire public struct Trakt { static let apiKey = "d3b0811a35719a67187cba2476335b2144d31e5840d02f687fbf84e7eaadc811" static let apiSecret = "f047aa37b81c87a990e210559a797fd4af3b94c16fb6d22b62aa501ca48ea0a4" static let base = "https://api.trakt.tv" static let shows = "/shows" static let movies = "/movies" static let people = "/people" static let person = "/person" static let seasons = "/seasons" static let episodes = "/episodes" static let auth = "/oauth" static let token = "/token" static let sync = "/sync" static let playback = "/playback" static let history = "/history" static let device = "/device" static let code = "/code" static let remove = "/remove" static let related = "/related" static let watched = "/watched" static let watchlist = "/watchlist" static let scrobble = "/scrobble" static let imdb = "/imdb" static let tvdb = "/tvdb" static let search = "/search" static let extended = ["extended": "full"] public struct Headers { static let Default = [ "Content-Type": "application/json", "trakt-api-version": "2", "trakt-api-key": Trakt.apiKey ] static func Authorization(_ token: String) -> [String: String] { var Authorization = Default; Authorization["Authorization"] = "Bearer \(token)" return Authorization } } public enum MediaType: String { case movies = "movies" case shows = "shows" case episodes = "episodes" case people = "people" } /** Watched status of media. - .watching: When the video intially starts playing or is unpaused. - .paused: When the video is paused. - .finished: When the video is stopped or finishes playing on its own. */ public enum WatchedStatus: String { /// When the video intially starts playing or is unpaused. case watching = "start" /// When the video is paused. case paused = "pause" /// When the video is stopped or finishes playing on its own. case finished = "stop" } } public struct PopcornShows { static let base = "https://tv-v2.api-fetch.sh" static let shows = "/shows" static let show = "/show" } public struct PopcornMovies { static let base = "https://movies-v2.api-fetch.sh" static let movies = "/movies" static let movie = "/movie" } public struct TMDB { static let apiKey = "739eed14bc18a1d6f5dacd1ce6c2b29e" static let base = "https://api.themoviedb.org/3" static let tv = "/tv" static let person = "/person" static let images = "/images" static let season = "/season" static let episode = "/episode" public enum MediaType: String { case movies = "movie" case shows = "tv" } static let defaultHeaders = ["api_key": TMDB.apiKey] } public struct Fanart { static let apiKey = "bd2753f04538b01479e39e695308b921" static let base = "http://webservice.fanart.tv/v3" static let tv = "/tv" static let movies = "/movies" static let defaultParameters = ["api_key": Fanart.apiKey] } public struct OpenSubtitles { static let base = "https://rest.opensubtitles.org/" static let userAgent = "Popcorn Time NodeJS" // static let logIn = "LogIn" // static let logOut = "LogOut" static let search = "search/" static let defaultHeaders = ["User-Agent": OpenSubtitles.userAgent] } open class NetworkManager: NSObject { internal let manager: SessionManager = { var configuration = URLSessionConfiguration.default configuration.httpCookieAcceptPolicy = .never configuration.httpShouldSetCookies = false configuration.urlCache = nil configuration.requestCachePolicy = .reloadIgnoringCacheData return Alamofire.SessionManager(configuration: configuration) }() /// Possible orders used in API call. public enum Orders: Int { case ascending = 1 case descending = -1 } /// Possible genres used in API call. public enum Genres: String { case all = "All" case action = "Action" case adventure = "Adventure" case animation = "Animation" case comedy = "Comedy" case crime = "Crime" case disaster = "Disaster" case documentary = "Documentary" case drama = "Drama" case family = "Family" case fanFilm = "Fan Film" case fantasy = "Fantasy" case filmNoir = "Film Noir" case history = "History" case holiday = "Holiday" case horror = "Horror" case indie = "Indie" case music = "Music" case mystery = "Mystery" case road = "Road" case romance = "Romance" case sciFi = "Science Fiction" case short = "Short" case sports = "Sports" case sportingEvent = "Sporting Event" case suspense = "Suspense" case thriller = "Thriller" case war = "War" case western = "Western" public static var array = [all, action, adventure, animation, comedy, crime, disaster, documentary, drama, family, fanFilm, fantasy, filmNoir, history, holiday, horror, indie, music, mystery, road, romance, sciFi, short, sports, sportingEvent, suspense, thriller, war, western] public var string: String { return rawValue.localized } } }
842172af10621e330fe665ac34d0010e
31.770588
285
0.619458
false
false
false
false
danfsd/FolioReaderKit
refs/heads/master
Source/EPUBCore/FRResources.swift
bsd-3-clause
1
// // FRResources.swift // FolioReaderKit // // Created by Heberti Almeida on 29/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit class FRResources: NSObject { var resources = [String: FRResource]() /** Adds a resource to the resources. */ func add(_ resource: FRResource) { self.resources[resource.href] = resource } /** Gets the first resource (random order) with the give mediatype. Useful for looking up the table of contents as it's supposed to be the only resource with NCX mediatype. */ func findFirstResource(byMediaType mediaType: MediaType) -> FRResource? { for resource in resources.values { if resource.mediaType != nil && resource.mediaType == mediaType { return resource } } return nil } /** Gets the first resource (random order) with the give extension. Useful for looking up the table of contents as it's supposed to be the only resource with NCX extension. */ func findFirstResource(byExtension ext: String) -> FRResource? { for resource in resources.values { if resource.mediaType != nil && resource.mediaType.defaultExtension == ext { return resource } } return nil } /** Whether there exists a resource with the given href. */ func containsByHref(_ href: String) -> Bool { if href.isEmpty { return false } return resources.keys.contains(href) } /** Whether there exists a resource with the given id. */ func containsById(_ id: String) -> Bool { if id.isEmpty { return false } for resource in resources.values { if resource.id == id { return true } } return false } /** Gets the resource with the given href. */ func getByHref(_ href: String) -> FRResource? { if href.isEmpty { return nil } return resources[href] } /** Gets the resource with the given href. */ func getById(_ id: String) -> FRResource? { for resource in resources.values { if resource.id == id { return resource } } return nil } }
9ec1fd589d809c0852b3f14858e2176b
24.010204
109
0.552428
false
false
false
false
stripe/stripe-ios
refs/heads/master
Example/Non-Card Payment Examples/Non-Card Payment Examples/AffirmExampleViewController.swift
mit
1
// // AffirmExampleViewController.swift // Non-Card Payment Examples // // Copyright © 2022 Stripe. All rights reserved. // import Stripe import UIKit class AffirmExampleViewController: UIViewController { @objc weak var delegate: ExampleViewControllerDelegate? var inProgress: Bool = false { didSet { navigationController?.navigationBar.isUserInteractionEnabled = !inProgress payButton.isEnabled = !inProgress inProgress ? activityIndicatorView.startAnimating() : activityIndicatorView.stopAnimating() } } // UI lazy var activityIndicatorView = { return UIActivityIndicatorView(style: .gray) }() lazy var payButton: UIButton = { let button = UIButton(type: .roundedRect) button.setTitle("Pay with Affirm", for: .normal) button.addTarget(self, action: #selector(didTapPayButton), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Affirm" [payButton, activityIndicatorView].forEach { subview in view.addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = false } let constraints = [ payButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), payButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor), activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor), ] NSLayoutConstraint.activate(constraints) } @objc func didTapPayButton() { guard STPAPIClient.shared.publishableKey != nil else { delegate?.exampleViewController( self, didFinishWithMessage: "Please set a Stripe Publishable Key in Constants.m") return } inProgress = true pay() } } // MARK: - extension AffirmExampleViewController { @objc func pay() { // 1. Create an Affirm PaymentIntent MyAPIClient.shared().createPaymentIntent( completion: { (result, clientSecret, error) in guard let clientSecret = clientSecret else { self.delegate?.exampleViewController(self, didFinishWithError: error) return } // 2. Collect shipping information let shippingAddress = STPPaymentIntentShippingDetailsAddressParams(line1: "55 John St") shippingAddress.line2 = "#3B" shippingAddress.city = "New York" shippingAddress.state = "NY" shippingAddress.postalCode = "10002" shippingAddress.country = "US" let shippingDetailsParam = STPPaymentIntentShippingDetailsParams(address: shippingAddress, name: "TestName") let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret) paymentIntentParams.paymentMethodParams = STPPaymentMethodParams( affirm: STPPaymentMethodAffirmParams(), metadata: [:]) paymentIntentParams.returnURL = "payments-example://safepay/" paymentIntentParams.shipping = shippingDetailsParam // 3. Confirm payment STPPaymentHandler.shared().confirmPayment( paymentIntentParams, with: self ) { (status, intent, error) in switch status { case .canceled: self.delegate?.exampleViewController( self, didFinishWithMessage: "Cancelled") case .failed: self.delegate?.exampleViewController(self, didFinishWithError: error) case .succeeded: self.delegate?.exampleViewController( self, didFinishWithMessage: "Payment successfully created.") @unknown default: fatalError() } } }, additionalParameters: "supported_payment_methods=affirm&products[]=👛") } } extension AffirmExampleViewController: STPAuthenticationContext { func authenticationPresentingViewController() -> UIViewController { self } }
9114b9f09b9078e136f70589e125ccef
38.669565
106
0.596449
false
false
false
false
daniele-pizziconi/AlamofireImage
refs/heads/master
Source/UIImage+AlamofireImage.swift
mit
1
// // UIImage+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 CoreGraphics import Foundation import UIKit #if os(iOS) || os(tvOS) import CoreImage import YLGIFImage #endif // MARK: Initialization private let lock = NSLock() extension UIImage { /// Initializes and returns the image object with the specified data in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:)` method. /// /// - parameter data: The data object containing the image data. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data) -> UIImage? { lock.lock() let image = YLGIFImage(data: data) lock.unlock() return image } /// Initializes and returns the image object with the specified data and scale in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:scale:)` method. /// /// - parameter data: The data object containing the image data. /// - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 /// results in an image whose size matches the pixel-based dimensions of the image. Applying a /// different scale factor changes the size of the image as reported by the size property. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data, scale: CGFloat) -> UIImage? { lock.lock() let image = YLGIFImage(data: data, scale: scale) lock.unlock() return image } } // MARK: - Inflation extension UIImage { private struct AssociatedKey { static var inflated = "af_UIImage.Inflated" } /// Returns whether the image is inflated. public var af_inflated: Bool { get { if let inflated = objc_getAssociatedObject(self, &AssociatedKey.inflated) as? Bool { return inflated } else { return false } } set { objc_setAssociatedObject(self, &AssociatedKey.inflated, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation. /// /// Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it /// allows a bitmap representation to be constructed in the background rather than on the main thread. public func af_inflate() { guard !af_inflated else { return } af_inflated = true _ = cgImage?.dataProvider?.data } } // MARK: - Alpha extension UIImage { /// Returns whether the image contains an alpha component. public var af_containsAlphaComponent: Bool { let alphaInfo = cgImage?.alphaInfo return ( alphaInfo == .first || alphaInfo == .last || alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast ) } /// Returns whether the image is opaque. public var af_isOpaque: Bool { return !af_containsAlphaComponent } } // MARK: - Scaling extension UIImage { /// Returns a new version of the image scaled to the specified size. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageScaled(to size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: CGPoint.zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContextUnwrapped() UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within /// a specified size. /// /// The resulting image contains an alpha component used to pad the width or height with the necessary transparent /// pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach. /// To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize` /// method in conjunction with a `.Center` content mode to achieve the same visual result. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFit size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContextUnwrapped() UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a /// specified size. Any pixels that fall outside the specified size are clipped. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFill size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContextUnwrapped() UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounded Corners extension UIImage { /// Returns a new version of the image with the corners rounded to the specified radius. /// /// - parameter radius: The radius to use when rounding the new image. /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the /// image has the same resolution for all screen scales such as @1x, @2x and /// @3x (i.e. single image from web server). Set to `false` for images loaded /// from an asset catalog with varying resolutions for each screen scale. /// `false` by default. /// /// - returns: A new image object. public func af_imageRounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let scaledRadius = divideRadiusByImageScale ? radius / scale : radius let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() draw(in: CGRect(origin: CGPoint.zero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContextUnwrapped() UIGraphicsEndImageContext() return roundedImage } /// Returns a new version of the image rounded into a circle. /// /// - returns: A new image object. public func af_imageRoundedIntoCircle() -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = af_imageAspectScaled(toFill: squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContextUnwrapped() UIGraphicsEndImageContext() return roundedImage } } #if os(iOS) || os(tvOS) // MARK: - Core Image Filters extension UIImage { /// Returns a new version of the image using a CoreImage filter with the specified name and parameters. /// /// - parameter name: The name of the CoreImage filter to use on the new image. /// - parameter parameters: The parameters to apply to the CoreImage filter. /// /// - returns: A new image object, or `nil` if the filter failed for any reason. public func af_imageFiltered(withCoreImageFilter name: String, parameters: [String: Any]? = nil) -> UIImage? { var image: CoreImage.CIImage? = ciImage if image == nil, let CGImage = self.cgImage { image = CoreImage.CIImage(cgImage: CGImage) } guard let coreImage = image else { return nil } let context = CIContext(options: [kCIContextPriorityRequestLow: true]) var parameters: [String: Any] = parameters ?? [:] parameters[kCIInputImageKey] = coreImage guard let filter = CIFilter(name: name, withInputParameters: parameters) else { return nil } guard let outputImage = filter.outputImage else { return nil } let cgImageRef = context.createCGImage(outputImage, from: outputImage.extent) return UIImage(cgImage: cgImageRef!, scale: scale, orientation: imageOrientation) } } #endif // MARK: - Private - Graphics Context Helpers private func UIGraphicsGetImageFromCurrentImageContextUnwrapped() -> UIImage { #if swift(>=2.3) return UIGraphicsGetImageFromCurrentImageContext()! #else return UIGraphicsGetImageFromCurrentImageContext() #endif }
ab7f17f73a856f9ce98b8de94c9302d5
38.164038
122
0.665083
false
false
false
false
TimurBK/SwiftSampleProject
refs/heads/develop
Pods/JSQCoreDataKit/Source/CoreDataModel.swift
mit
1
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://www.jessesquires.com/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import CoreData import Foundation /** Describes a Core Data model file exention type based on the [Model File Format and Versions](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmModelFormat.html) documentation. */ public enum ModelFileExtension: String { /// The extension for a model bundle, or a `.xcdatamodeld` file package. case bundle = "momd" /// The extension for a versioned model file, or a `.xcdatamodel` file. case versionedFile = "mom" /// The extension for a mapping model file, or a `.xcmappingmodel` file. case mapping = "cdm" /// The extension for a sqlite store. case sqlite = "sqlite" } /** An instance of `CoreDataModel` represents a Core Data model — a `.xcdatamodeld` file package. It provides the model and store URLs as well as methods for interacting with the store. */ public struct CoreDataModel: Equatable { // MARK: Properties /// The name of the Core Data model resource. public let name: String /// The bundle in which the model is located. public let bundle: Bundle /// The type of the Core Data persistent store for the model. public let storeType: StoreType /** The file URL specifying the full path to the store. - note: If the store is in-memory, then this value will be `nil`. */ public var storeURL: URL? { get { return storeType.storeDirectory()?.appendingPathComponent(databaseFileName) } } /// The file URL specifying the model file in the bundle specified by `bundle`. public var modelURL: URL { get { guard let url = bundle.url(forResource: name, withExtension: ModelFileExtension.bundle.rawValue) else { fatalError("*** Error loading model URL for model named \(name) in bundle: \(bundle)") } return url } } /// The database file name for the store. public var databaseFileName: String { get { switch storeType { case .sqlite: return name + "." + ModelFileExtension.sqlite.rawValue default: return name } } } /// The managed object model for the model specified by `name`. public var managedObjectModel: NSManagedObjectModel { get { guard let model = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("*** Error loading managed object model at url: \(modelURL)") } return model } } /** Queries the meta data for the persistent store specified by the receiver and returns whether or not a migration is needed. - returns: `true` if the store requires a migration, `false` otherwise. */ public var needsMigration: Bool { get { guard let storeURL = storeURL else { return false } do { let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: storeType.type, at: storeURL, options: nil) return !managedObjectModel.isConfiguration(withName: nil, compatibleWithStoreMetadata: metadata) } catch { debugPrint("*** Error checking persistent store coordinator meta data: \(error)") return false } } } // MARK: Initialization /** Constructs a new `CoreDataModel` instance with the specified name and bundle. - parameter name: The name of the Core Data model. - parameter bundle: The bundle in which the model is located. The default is the main bundle. - parameter storeType: The store type for the Core Data model. The default is `.sqlite`, with the user's documents directory. - returns: A new `CoreDataModel` instance. */ public init(name: String, bundle: Bundle = .main, storeType: StoreType = .sqlite(defaultDirectoryURL())) { self.name = name self.bundle = bundle self.storeType = storeType } // MARK: Methods /** Removes the existing model store specfied by the receiver. - throws: If removing the store fails or errors, then this function throws an `NSError`. */ public func removeExistingStore() throws { let fm = FileManager.default if let storePath = storeURL?.path, fm.fileExists(atPath: storePath) { try fm.removeItem(atPath: storePath) let writeAheadLog = storePath + "-wal" _ = try? fm.removeItem(atPath: writeAheadLog) let sharedMemoryfile = storePath + "-shm" _ = try? fm.removeItem(atPath: sharedMemoryfile) } } }
6fae2cb5429487d74717570ed608c985
31.092025
152
0.615752
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios
refs/heads/develop
Example/SuperAwesomeExampleTests/Common/Mocks/MockFactory.swift
lgpl-3.0
1
// // AdMock.swift // Tests // // Created by Gunhan Sancar on 24/04/2020. // @testable import SuperAwesome class MockFactory { static func makeAdWithTagAndClickUrl(_ tag: String?, _ url: String?) -> Ad { makeAd(.tag, nil, url, tag) } static func makeAdWithImageLink(_ url: String?) -> Ad { makeAd(.imageWithLink, nil, url) } static func makeAd( _ format: CreativeFormatType = .imageWithLink, _ vast: String? = nil, _ clickUrl: String? = nil, _ tag: String? = nil, _ showPadlock: Bool = false, _ ksfRequest: String? = nil, _ bumper: Bool = true ) -> Ad { Ad(advertiserId: 10, publisherId: 20, moat: 0.1, campaignId: 30, campaignType: 40, isVpaid: true, showPadlock: showPadlock, lineItemId: 50, test: false, app: 70, device: "device", creative: Creative( id: 80, name: "name", format: format, clickUrl: clickUrl, details: CreativeDetail( url: "detailurl", image: "image", video: "video", placementFormat: "placement", tag: tag, width: 90, height: 100, duration: 110, vast: vast), bumper: bumper, payload: nil), ksfRequest: ksfRequest) } static func makeError() -> Error { NSError(domain: "", code: 404, userInfo: nil) } static func makeAdRequest() -> AdRequest { AdRequest(test: false, position: .aboveTheFold, skip: .no, playbackMethod: 0, startDelay: AdRequest.StartDelay.midRoll, instl: .off, width: 25, height: 35) } static func makeAdQueryInstance() -> QueryBundle { QueryBundle(parameters: AdQuery( test: true, sdkVersion: "", random: 1, bundle: "", name: "", dauid: 1, connectionType: .wifi, lang: "", device: "", position: 1, skip: 1, playbackMethod: 1, startDelay: 1, instl: 1, width: 1, height: 1), options: nil) } static func makeEventQueryInstance() -> QueryBundle { QueryBundle(parameters: EventQuery( placement: 1, bundle: "", creative: 1, lineItem: 1, connectionType: .wifi, sdkVersion: "", rnd: 1, type: nil, noImage: nil, data: nil), options: nil) } static func makeAdResponse() -> AdResponse { AdResponse(10, makeAd()) } static func makeVastAd(clickThrough: String? = nil) -> VastAd { VastAd(url: nil, type: .inLine, redirect: nil, errorEvents: [], impressions: [], clickThrough: clickThrough, creativeViewEvents: [], startEvents: [], firstQuartileEvents: [], midPointEvents: [], thirdQuartileEvents: [], completeEvents: [], clickTrackingEvents: [], media: []) } }
318c87460142e8222ce1636986793d81
26.092308
86
0.455991
false
false
false
false
sjtu-meow/iOS
refs/heads/master
Meow/UserRecordTableViewCell.swift
apache-2.0
1
// // UserRecordTableViewCell.swift // Meow // // Created by 林武威 on 2017/7/13. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit protocol UnfollowUserDelegate { func didClickUnfollow(profile: Profile) } protocol UserRecordTableViewCellDelegate: UnfollowUserDelegate, AvatarCellDelegate { } class UserRecordTableViewCell: UITableViewCell { var delegate: UserRecordTableViewCellDelegate? var model: Profile? @IBOutlet weak var unfollowButton: UIButton! @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nickNameLabel: UILabel! @IBOutlet weak var bioLabel: UILabel! override func awakeFromNib() { unfollowButton.addTarget(self, action: #selector(didClickUnfollow), for: UIControlEvents.touchUpInside) avatarImageView.isUserInteractionEnabled = true let tapAvatarRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.didTapAvatar(_:))) avatarImageView.addGestureRecognizer(tapAvatarRecognizer) } func configure(model: Profile) { self.model = model if let avatar = model.avatar { avatarImageView.af_setImage(withURL: avatar) } nickNameLabel.text = model.nickname bioLabel.text = model.bio } func didClickUnfollow() { guard let model = self.model else { return } delegate?.didClickUnfollow(profile: model) } func didTapAvatar(_ sender: UITapGestureRecognizer) { guard let model = self.model else { return } //delegate?.didTapAvatar() } }
e88c96451a9e07533fcf343ec9101d7a
26.508475
113
0.683303
false
false
false
false
groue/GRDB.swift
refs/heads/master
GRDB/FTS/FTS5.swift
mit
1
#if SQLITE_ENABLE_FTS5 import Foundation /// FTS5 lets you define "fts5" virtual tables. /// /// // CREATE VIRTUAL TABLE document USING fts5(content) /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// /// See <https://www.sqlite.org/fts5.html> public struct FTS5: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// /// See <https://www.sqlite.org/fts5.html> public enum Diacritics { /// Do not remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=0" tokenizer argument. case keep /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=1" tokenizer argument. case removeLegacy #if GRDBCUSTOMSQLITE /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=2" tokenizer argument, /// available from SQLite 3.27.0 case remove #elseif !GRDBCIPHER /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=2" tokenizer argument, /// available from SQLite 3.27.0 @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) case remove #endif } /// Creates a FTS5 module suitable for the Database /// `create(virtualTable:using:)` method. /// /// // CREATE VIRTUAL TABLE document USING fts5(content) /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// /// See <https://www.sqlite.org/fts5.html> public init() { } // Support for FTS5Pattern initializers. Don't make public. Users tokenize // with `FTS5Tokenizer.tokenize()` methods, which support custom tokenizers, // token flags, and query/document tokenzation. /// Tokenizes the string argument as an FTS5 query. /// /// For example: /// /// try FTS5.tokenize(query: "SQLite database") // ["sqlite", "database"] /// try FTS5.tokenize(query: "Gustave Doré") // ["gustave", "doré"]) /// /// Synonym (colocated) tokens are not present in the returned array. See /// `FTS5_TOKEN_COLOCATED` at <https://www.sqlite.org/fts5.html#custom_tokenizers> /// for more information. /// /// - parameter string: The tokenized string. /// - returns: An array of tokens. /// - throws: An error if tokenization fails. static func tokenize(query string: String) throws -> [String] { try DatabaseQueue().inDatabase { db in try db.makeTokenizer(.ascii()).tokenize(query: string).compactMap { $0.flags.contains(.colocated) ? nil : $0.token } } } // MARK: - VirtualTableModule Adoption /// The virtual table module name public let moduleName = "fts5" /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition { FTS5TableDefinition(configuration: configuration) } /// Don't use this method. public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] { var arguments: [String] = [] if definition.columns.isEmpty { // Programmer error fatalError("FTS5 virtual table requires at least one column.") } for column in definition.columns { if column.isIndexed { arguments.append("\(column.name)") } else { arguments.append("\(column.name) UNINDEXED") } } if let tokenizer = definition.tokenizer { let tokenizerSQL = try tokenizer .components .map { component in try component.sqlExpression.quotedSQL(db) } .joined(separator: " ") .sqlExpression .quotedSQL(db) arguments.append("tokenize=\(tokenizerSQL)") } switch definition.contentMode { case let .raw(content, contentRowID): if let content = content { let quotedContent = try content.sqlExpression.quotedSQL(db) arguments.append("content=\(quotedContent)") } if let contentRowID = contentRowID { let quotedContentRowID = try contentRowID.sqlExpression.quotedSQL(db) arguments.append("content_rowid=\(quotedContentRowID)") } case let .synchronized(contentTable): try arguments.append("content=\(contentTable.sqlExpression.quotedSQL(db))") if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn { let quotedRowID = try rowIDColumn.sqlExpression.quotedSQL(db) arguments.append("content_rowid=\(quotedRowID)") } } if let prefixes = definition.prefixes { let prefix = try prefixes .sorted() .map { "\($0)" } .joined(separator: " ") .sqlExpression .quotedSQL(db) arguments.append("prefix=\(prefix)") } if let columnSize = definition.columnSize { arguments.append("columnSize=\(columnSize)") } if let detail = definition.detail { arguments.append("detail=\(detail)") } return arguments } /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws { switch definition.contentMode { case .raw: break case .synchronized(let contentTable): // https://sqlite.org/fts5.html#external_content_tables let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name let ftsTable = tableName.quotedDatabaseIdentifier let content = contentTable.quotedDatabaseIdentifier let indexedColumns = definition.columns.map(\.name) let ftsColumns = (["rowid"] + indexedColumns) .map(\.quotedDatabaseIdentifier) .joined(separator: ", ") let newContentColumns = ([rowIDColumn] + indexedColumns) .map { "new.\($0.quotedDatabaseIdentifier)" } .joined(separator: ", ") let oldContentColumns = ([rowIDColumn] + indexedColumns) .map { "old.\($0.quotedDatabaseIdentifier)" } .joined(separator: ", ") let ifNotExists = definition.configuration.ifNotExists ? "IF NOT EXISTS " : "" // swiftlint:disable line_length try db.execute(sql: """ CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); END; CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; """) // swiftlint:enable line_length // https://sqlite.org/fts5.html#the_rebuild_command try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')") } } static func api(_ db: Database) -> UnsafePointer<fts5_api> { // Access to FTS5 is one of the rare SQLite api which was broken in // SQLite 3.20.0+, for security reasons: // // Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api. // The previous way to access FTS5 does not work any longer. // // So let's see which SQLite version we are linked against: #if GRDBCUSTOMSQLITE || GRDBCIPHER // GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more. return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) #else // GRDB is linked against the system SQLite. // // Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)? if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) { // SQLite 3.24.0 or more return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) } else { // SQLite 3.19.3 or less return api_v1(db) } #endif } private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> { guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else { fatalError("FTS5 is not available") } return data.withUnsafeBytes { $0.bindMemory(to: UnsafePointer<fts5_api>.self).first! } } // Technique given by Jordan Rose: // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 private static func api_v2( _ db: Database, // swiftlint:disable:next line_length _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt, // swiftlint:disable:next line_length _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) -> UnsafePointer<fts5_api> { var statement: SQLiteStatement? = nil var api: UnsafePointer<fts5_api>? = nil let type: StaticString = "fts5_api_ptr" let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil) guard code == SQLITE_OK else { fatalError("FTS5 is not available") } defer { sqlite3_finalize(statement) } type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in _ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil) } sqlite3_step(statement) guard let api else { fatalError("FTS5 is not available") } return api } } /// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table. /// /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// /// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition /// t.column("content") /// } /// /// See <https://www.sqlite.org/fts5.html> public final class FTS5TableDefinition { enum ContentMode { case raw(content: String?, contentRowID: String?) case synchronized(contentTable: String) } fileprivate let configuration: VirtualTableConfiguration fileprivate var columns: [FTS5ColumnDefinition] = [] fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil) /// The virtual table tokenizer /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.tokenizer = .porter() /// } /// /// See <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization> public var tokenizer: FTS5TokenizerDescriptor? /// The FTS5 `content` option /// /// When you want the full-text table to be synchronized with the /// content of an external table, prefer the `synchronize(withTable:)` /// method. /// /// Setting this property invalidates any synchronization previously /// established with the `synchronize(withTable:)` method. /// /// See <https://www.sqlite.org/fts5.html#external_content_and_contentless_tables> public var content: String? { get { switch contentMode { case .raw(let content, _): return content case .synchronized(let contentTable): return contentTable } } set { switch contentMode { case .raw(_, let contentRowID): contentMode = .raw(content: newValue, contentRowID: contentRowID) case .synchronized: contentMode = .raw(content: newValue, contentRowID: nil) } } } /// The FTS5 `content_rowid` option /// /// When you want the full-text table to be synchronized with the /// content of an external table, prefer the `synchronize(withTable:)` /// method. /// /// Setting this property invalidates any synchronization previously /// established with the `synchronize(withTable:)` method. /// /// See <https://sqlite.org/fts5.html#external_content_tables> public var contentRowID: String? { get { switch contentMode { case .raw(_, let contentRowID): return contentRowID case .synchronized: return nil } } set { switch contentMode { case .raw(let content, _): contentMode = .raw(content: content, contentRowID: newValue) case .synchronized: contentMode = .raw(content: nil, contentRowID: newValue) } } } /// Support for the FTS5 `prefix` option /// /// See <https://www.sqlite.org/fts5.html#prefix_indexes> public var prefixes: Set<Int>? /// Support for the FTS5 `columnsize` option /// /// <https://www.sqlite.org/fts5.html#the_columnsize_option> public var columnSize: Int? /// Support for the FTS5 `detail` option /// /// <https://www.sqlite.org/fts5.html#the_detail_option> public var detail: String? init(configuration: VirtualTableConfiguration) { self.configuration = configuration } /// Appends a table column. /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// /// - parameter name: the column name. @discardableResult public func column(_ name: String) -> FTS5ColumnDefinition { let column = FTS5ColumnDefinition(name: name) columns.append(column) return column } /// Synchronizes the full-text table with the content of an external /// table. /// /// The full-text table is initially populated with the existing /// content in the external table. SQL triggers make sure that the /// full-text table is kept up to date with the external table. /// /// See <https://sqlite.org/fts5.html#external_content_tables> public func synchronize(withTable tableName: String) { contentMode = .synchronized(contentTable: tableName) } } /// The FTS5ColumnDefinition class lets you refine a column of an FTS5 /// virtual table. /// /// You get instances of this class when you create an FTS5 table: /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") // FTS5ColumnDefinition /// } /// /// See <https://www.sqlite.org/fts5.html> public final class FTS5ColumnDefinition { fileprivate let name: String fileprivate var isIndexed: Bool init(name: String) { self.name = name self.isIndexed = true } /// Excludes the column from the full-text index. /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } /// /// See <https://www.sqlite.org/fts5.html#the_unindexed_column_option> /// /// - returns: Self so that you can further refine the column definition. @discardableResult public func notIndexed() -> Self { self.isIndexed = false return self } } extension Column { /// The FTS5 rank column public static let rank = Column("rank") } extension Database { /// Deletes the synchronization triggers for a synchronized FTS5 table. public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws { try execute(sql: """ DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier); DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier); DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier); """) } } #endif
1ab60198e018aa70eb83ccec031c2c3c
37.539474
196
0.589678
false
false
false
false
suifengqjn/swiftDemo
refs/heads/master
Swift基本语法-黑马笔记/基本数据类型/main.swift
apache-2.0
1
// // main.swift // 基本数据类型 // // Created by 李南江 on 15/2/28. // Copyright (c) 2015年 itcast. All rights reserved. // import Foundation /* 基本数据类型 OC: 整型 int intValue = 10; 浮点型 double doubleValue = 10.10; float floatValue = 5.1; 长 long 短 short 有符号 signed 无符号 unsigned 各种类型的数据的取值范围在不同位的编译器下取值范围不同 Swift:注意关键字大写 */ //整型 var intValue:Int = 10 //浮点型 var intValue1:Double = 10.10 // 表示64位浮点数 var intValue2:Float = 9.9 // 表示32位浮点数 //如果按照长度划分,Swift中的长短比OC更加精确 var intValue3:Int8 = 6 var intValue4:Int16 = 7 var intValue5:Int32 = 8 var intValue6:Int64 = 9 //有符号无符号, 默认是由符号的(UInt8/UInt16/UInt32/UInt64) var uintValue7:UInt = 10 //注意: 无符号的数比有符号的取值范围更大, 因为符号位也用来存值 //Swift是类型安全的语言, 如果取值错误会直接报错, 而OC不会 /* 取值不对 OC:unsigned int intValue = -10; 不会报错 Swift:var intValue:UInt = -10 会报错 溢出: OC:int intValue = INT_MAX + 1; 不会报错 Swift:var intValue:UInt = UInt.max + 1 会报错 */ /* 数据类型的相互赋值(隐式类型转换) OC可以 int intValue = 10; double doubleValue = intValue; Swift:不可以 var intValue:Int = 10 var doubleValue:Double = intValue 在Swift中“值永远不会被隐式转换为其他类型”(OC中可以隐式类型转换), 以上语句会报错 */
9569fc26a646afdb7ca3f1a0216078b5
15.353846
55
0.723424
false
false
false
false
gudjao/XLPagerTabStrip
refs/heads/master
Sources/ButtonBarView.swift
mit
2
// ButtonBarView.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public enum PagerScroll { case no case yes case scrollOnlyIfOutOfScreen } public enum SelectedBarAlignment { case left case center case right case progressive } public enum SelectedBarVerticalAlignment { case top case middle case bottom } open class ButtonBarView: UICollectionView { open lazy var selectedBar: UIView = { [unowned self] in let bar = UIView(frame: CGRect(x: 0, y: self.frame.size.height - CGFloat(self.selectedBarHeight), width: 0, height: CGFloat(self.selectedBarHeight))) bar.layer.zPosition = 9999 return bar }() internal var selectedBarHeight: CGFloat = 4 { didSet { updateSelectedBarYPosition() } } var selectedBarVerticalAlignment: SelectedBarVerticalAlignment = .bottom var selectedBarAlignment: SelectedBarAlignment = .center var selectedIndex = 0 required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(selectedBar) } public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) addSubview(selectedBar) } open func moveTo(index: Int, animated: Bool, swipeDirection: SwipeDirection, pagerScroll: PagerScroll) { selectedIndex = index updateSelectedBarPosition(animated, swipeDirection: swipeDirection, pagerScroll: pagerScroll) } open func move(fromIndex: Int, toIndex: Int, progressPercentage: CGFloat,pagerScroll: PagerScroll) { selectedIndex = progressPercentage > 0.5 ? toIndex : fromIndex let fromFrame = layoutAttributesForItem(at: IndexPath(item: fromIndex, section: 0))!.frame let numberOfItems = dataSource!.collectionView(self, numberOfItemsInSection: 0) var toFrame: CGRect if toIndex < 0 || toIndex > numberOfItems - 1 { if toIndex < 0 { let cellAtts = layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) toFrame = cellAtts!.frame.offsetBy(dx: -cellAtts!.frame.size.width, dy: 0) } else { let cellAtts = layoutAttributesForItem(at: IndexPath(item: (numberOfItems - 1), section: 0)) toFrame = cellAtts!.frame.offsetBy(dx: cellAtts!.frame.size.width, dy: 0) } } else { toFrame = layoutAttributesForItem(at: IndexPath(item: toIndex, section: 0))!.frame } var targetFrame = fromFrame targetFrame.size.height = selectedBar.frame.size.height targetFrame.size.width += (toFrame.size.width - fromFrame.size.width) * progressPercentage targetFrame.origin.x += (toFrame.origin.x - fromFrame.origin.x) * progressPercentage selectedBar.frame = CGRect(x: targetFrame.origin.x, y: selectedBar.frame.origin.y, width: targetFrame.size.width, height: selectedBar.frame.size.height) var targetContentOffset: CGFloat = 0.0 if contentSize.width > frame.size.width { let toContentOffset = contentOffsetForCell(withFrame: toFrame, andIndex: toIndex) let fromContentOffset = contentOffsetForCell(withFrame: fromFrame, andIndex: fromIndex) targetContentOffset = fromContentOffset + ((toContentOffset - fromContentOffset) * progressPercentage) } let animated = abs(contentOffset.x - targetContentOffset) > 30 || (fromIndex == toIndex) setContentOffset(CGPoint(x: targetContentOffset, y: 0), animated: animated) } open func updateSelectedBarPosition(_ animated: Bool, swipeDirection: SwipeDirection, pagerScroll: PagerScroll) -> Void { var selectedBarFrame = selectedBar.frame let selectedCellIndexPath = IndexPath(item: selectedIndex, section: 0) let attributes = layoutAttributesForItem(at: selectedCellIndexPath) let selectedCellFrame = attributes!.frame updateContentOffset(animated: animated, pagerScroll: pagerScroll, toFrame: selectedCellFrame, toIndex: (selectedCellIndexPath as NSIndexPath).row) selectedBarFrame.size.width = selectedCellFrame.size.width selectedBarFrame.origin.x = selectedCellFrame.origin.x if animated { UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.selectedBar.frame = selectedBarFrame }) } else { selectedBar.frame = selectedBarFrame } } // MARK: - Helpers private func updateContentOffset(animated: Bool, pagerScroll: PagerScroll, toFrame: CGRect, toIndex: Int) -> Void { guard pagerScroll != .no || (pagerScroll != .scrollOnlyIfOutOfScreen && (toFrame.origin.x < contentOffset.x || toFrame.origin.x >= (contentOffset.x + frame.size.width - contentInset.left))) else { return } let targetContentOffset = contentSize.width > frame.size.width ? contentOffsetForCell(withFrame: toFrame, andIndex: toIndex) : 0 setContentOffset(CGPoint(x: targetContentOffset, y: 0), animated: animated) } private func contentOffsetForCell(withFrame cellFrame: CGRect, andIndex index: Int) -> CGFloat { let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset var alignmentOffset: CGFloat = 0.0 switch selectedBarAlignment { case .left: alignmentOffset = sectionInset.left case .right: alignmentOffset = frame.size.width - sectionInset.right - cellFrame.size.width case .center: alignmentOffset = (frame.size.width - cellFrame.size.width) * 0.5 case .progressive: let cellHalfWidth = cellFrame.size.width * 0.5 let leftAlignmentOffset = sectionInset.left + cellHalfWidth let rightAlignmentOffset = frame.size.width - sectionInset.right - cellHalfWidth let numberOfItems = dataSource!.collectionView(self, numberOfItemsInSection: 0) let progress = index / (numberOfItems - 1) alignmentOffset = leftAlignmentOffset + (rightAlignmentOffset - leftAlignmentOffset) * CGFloat(progress) - cellHalfWidth } var contentOffset = cellFrame.origin.x - alignmentOffset contentOffset = max(0, contentOffset) contentOffset = min(contentSize.width - frame.size.width, contentOffset) return contentOffset } private func updateSelectedBarYPosition() { var selectedBarFrame = selectedBar.frame switch selectedBarVerticalAlignment { case .top: selectedBarFrame.origin.y = 0 case .middle: selectedBarFrame.origin.y = (frame.size.height - selectedBarHeight) / 2 case .bottom: selectedBarFrame.origin.y = frame.size.height - selectedBarHeight } selectedBarFrame.size.height = selectedBarHeight selectedBar.frame = selectedBarFrame } override open func layoutSubviews() { super.layoutSubviews() updateSelectedBarYPosition() } }
d97807e0874e792e8b695a0d6d2c8f6e
42.54359
213
0.675068
false
false
false
false
derrh/CanvasKit
refs/heads/master
CanvasKitTests/Model Tests/CKIAssignmentTests.swift
mit
3
// // CKIAssignmentTests.swift // CanvasKit // // Created by Nathan Lambson on 7/18/14. // Copyright (c) 2014 Instructure. All rights reserved. // import UIKit import XCTest class CKIAssignmentTests: 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 testJSONModelConversion() { let assignmentDictionary = Helpers.loadJSONFixture("assignment") as NSDictionary let assignment = CKIAssignment(fromJSONDictionary: assignmentDictionary) XCTAssertEqual(assignment.id!, "4", "Assignment id did not parse correctly") XCTAssertEqual(assignment.name!, "some assignment", "Assignment name did not parse correctly") XCTAssertEqual(assignment.position, 1, "Assignment position did not parse correctly") XCTAssertEqual(assignment.descriptionHTML!, "<p>Do the following:</p>...", "Assignment descriptionHTML did not parse correctly") let formatter = ISO8601DateFormatter() formatter.includeTime = true var date = formatter.dateFromString("2012-07-01T23:59:00-06:00") XCTAssertEqual(assignment.dueAt!, date, "Assignment dueAt did not parse correctly") XCTAssertEqual(assignment.lockAt!, date, "Assignment lockAt did not descriptionHTML correctly") XCTAssertEqual(assignment.unlockAt!, date, "Assignment unlockAt did not parse correctly") XCTAssertEqual(assignment.courseID!, "123", "Assignment courseID did not parse correctly") var url = NSURL(string:"http://canvas.example.com/courses/123/assignments/4") XCTAssertEqual(assignment.htmlURL!, url!, "Assignment htmlURL did not parse correctly") XCTAssertEqual(assignment.allowedExtensions.count, 2, "Assignment allowedExtensions did not parse correctly") XCTAssertEqual(assignment.assignmentGroupID!, "2", "Assignment assignmentGroupID did not parse correctly") XCTAssertEqual(assignment.groupCategoryID!, "1", "Assignment groupCategoryID did not parse correctly") XCTAssert(assignment.muted, "Assignment muted did not parse correctly") XCTAssert(assignment.published, "Assignment published did not parse correctly") XCTAssertEqual(assignment.pointsPossible, 12, "Assignment pointsPossible did not parse correctly") XCTAssert(assignment.gradeGroupStudentsIndividually, "Assignment gradeGroupStudentsIndividually did not parse correctly") XCTAssertEqual(assignment.gradingType!, "points", "Assignment gradingType did not parse correctly") XCTAssertEqual(assignment.scoringType, CKIAssignmentScoringType.Points, "Assignment scoringType did not parse correctly") XCTAssertEqual(assignment.submissionTypes.count, 1, "Assignment submissionTypes did not parse correctly") XCTAssert(assignment.lockedForUser, "Assignment lockedForUser did not parse correctly") XCTAssertEqual(assignment.needsGradingCount, UInt(17), "Assignment needsGradingCount did not parse correctly") XCTAssertNotNil(assignment.rubric, "Assignment rubric did not parse correctly") XCTAssert(assignment.peerReviewRequired, "Assignment peerReviewRequired did not parse correctly") XCTAssert(assignment.peerReviewsAutomaticallyAssigned, "Assignment peerReviewsAutomaticallyAssigned did not parse correctly") XCTAssertEqual(assignment.peerReviewsAutomaticallyAssignedCount, 2, "Assignment peerReviewsAutomaticallyAssignedCount did not parse correctly") XCTAssertEqual(assignment.peerReviewDueDate!, date, "Assignment peerReviewDueDate did not parse correctly") XCTAssertEqual(assignment.path!, "/api/v1/assignments/4", "Assignment path did not parse correctly") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
d846e2cd9de23f749a2f4cb4f440937c
58.112676
151
0.736717
false
true
false
false
Mrwerdo/QuickShare
refs/heads/master
LibQuickShare/Sources/Network/Select.swift
mit
1
// // Select.swift // QuickShare // // Copyright (c) 2016 Andrew Thompson // // 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 Darwin import QSFcntl //private let __DARWIN_NFDBITS = Int32(sizeof(Int32)) * __DARWIN_NBBY //private let __DARWIN_NUMBER_OF_BITS_IN_SET: Int32 = { () -> Int32 in // func howmany(x: Int32, _ y: Int32) -> Int32 { // return (x % y) == 0 ? (x / y) : (x / (y + 1)) // } // return howmany(__DARWIN_FD_SETSIZE, __DARWIN_NFDBITS) //}() extension fd_set { /// Returns the index of the highest bit set. private func highestDescriptor() -> Int32 { return qs_fd_highest_fd(self) } /// Clears the `bit` index given. public mutating func clear(fd: Int32) { qs_fd_clear(&self, fd) } /// Sets the `bit` index given. public mutating func set(fd: Int32) { qs_fd_set(&self, fd) } /// Returns non-zero if `bit` is set. public func isset(fd: Int32) -> Bool { return qs_fd_isset(self, fd) != 0 } /// Zeros `self`, so no bits are set. public mutating func zero() { qs_fd_zero(&self) } } /// Waits efficiently until a file descriptor(s) specified is marked as having /// either pending data, a penidng error, or the ability to write. /// /// Any file descriptor's added to `read` will cause `select` to observer their /// status until one or more has any pending data available to read. This is /// similar for `write` and `error` too - `select` will return once some file /// descriptors have been flagged for writing or have an error pending. /// /// The `timeout` parameter will cause `select` to wait for the specified time, /// then return, if no file descriptors have changed state. If a file descriptor /// has changed its state, then select will return immediately and mark the file /// descriptors accordingly. /// /// - parameters: /// - read: Contains a set of file descriptors which have pending /// data ready to be read. /// - write: Contains any file descriptors which can be immediately /// written to. /// - error: Contains any file descriptors which have a pending error /// on them. /// - timeout: Contains the timeout period `select` will wait until /// returning if no changes are observed on the file /// descriptor. /// - Returns: /// The number of file descriptors who's status' have been /// changed. Select modifies the given sets to contain only /// a subset of those given, which have had their status' /// changed. If you pass nil to either `read`, `write` or /// `error`, then you will receive nil out the other end. /// - Throws: /// - `SocketError.SelectFailed` public func select(read read: fd_set?, write: fd_set?, error: fd_set?, timeout: UnsafeMutablePointer<timeval>) throws -> (numberChanged: Int32, read: fd_set!, write: fd_set!, error: fd_set!) { var read_out = read var write_out = write var error_out = error var highestFD: Int32 = 0 if let k = read_out?.highestDescriptor() { if k > highestFD { highestFD = k } } if let k = write_out?.highestDescriptor() { if k > highestFD { highestFD = k } } if let k = write_out?.highestDescriptor() { if k > highestFD { highestFD = k } } let rptr = read_out != nil ? unsafeAddressOfCObj(&(read_out!)) : UnsafeMutablePointer(nil) let wptr = write_out != nil ? unsafeAddressOfCObj(&(write_out!)) : UnsafeMutablePointer(nil) let eptr = error_out != nil ? unsafeAddressOfCObj(&(error_out!)) : UnsafeMutablePointer(nil) let result = Darwin.select( highestFD + 1, rptr, wptr, eptr, timeout ) guard result != -1 else { throw SocketError.SystemCallError(errno, .Select) } return (result, read_out, write_out, error_out) } enum Error : ErrorType { case CError(Int32) } public func pipe() throws -> (readfd: Int32, writefd: Int32) { var fds: [Int32] = [-1, -1] guard pipe(&fds) == 0 else { throw Error.CError(errno) } guard fds[0] > -1 && fds[1] > -1 else { fatalError("file descriptors are invalid and pipe failed to report an error!") } return (fds[0], fds[1]) }
5f644d7acd3db1cb177a4ad785bce97e
36.472973
192
0.62189
false
false
false
false
davidozhang/spycodes
refs/heads/master
Spycodes/Views/SCSectionHeaderViewCell.swift
mit
1
import UIKit protocol SCSectionHeaderViewCellDelegate: class { func sectionHeaderViewCell(onButtonTapped sectionHeaderViewCell: SCSectionHeaderViewCell) } class SCSectionHeaderViewCell: SCTableViewCell { weak var delegate: SCSectionHeaderViewCellDelegate? fileprivate var blurView: UIVisualEffectView? @IBOutlet weak var button: SCImageButton! @IBAction func onSectionHeaderButtonTapped(_ sender: Any) { self.delegate?.sectionHeaderViewCell(onButtonTapped: self) } override func awakeFromNib() { super.awakeFromNib() self.primaryLabel.font = SCFonts.regularSizeFont(.bold) } func setButtonImage(name: String) { if let _ = self.button { self.button.setImage(UIImage(named: name), for: UIControlState()) } } func hideButton() { if let _ = self.button { self.button.isHidden = true } } func showButton() { if let _ = self.button { self.button.isHidden = false } } func showBlurBackground() { self.hideBlurBackground() if SCLocalStorageManager.instance.isLocalSettingEnabled(.nightMode) { self.blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) } else { self.blurView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) } self.blurView?.frame = self.bounds self.blurView?.clipsToBounds = true self.blurView?.tag = SCConstants.tag.sectionHeaderBlurView.rawValue self.addSubview(self.blurView!) self.sendSubview(toBack: self.blurView!) } func hideBlurBackground() { if let view = self.viewWithTag(SCConstants.tag.sectionHeaderBlurView.rawValue) { view.removeFromSuperview() } } }
9288f2a6b30db851ec6126fa46f85f9a
28.306452
93
0.659329
false
false
false
false
masters3d/xswift
refs/heads/master
exercises/luhn/Sources/LuhnExample.swift
mit
1
import Foundation struct Luhn { var number: Int64 = 0 var addends: [Int] { return addendsFunc(number) } var checksum: Int { return addends.reduce(0, +) } var isValid: Bool { return checksum % 10 == 0 } init(_ num: Int64) { self.number = num } static func create (_ num: Int64) -> Double { func createCheckDigit(_ value: Int) -> Int { let nearestTen = Int(ceil((Double(value) / 10.00)) * 10) return nearestTen - value } let zeroCheckDigitNumber = num * 10 let luhn = Luhn(zeroCheckDigitNumber) if luhn.isValid { return Double(zeroCheckDigitNumber)} return Double((zeroCheckDigitNumber) + createCheckDigit(luhn.checksum)) } func addendsFunc(_ num: Int64) -> [Int] { func oddIndexInt64Minus9( _ input: [Int]) -> [Int] { var input = input input = Array(input.reversed()) var tempArray: [Int] = [] for (inx, each) in input.enumerated() { var tempEach: Int = each if (inx+1) % 2 == 0 { tempEach *= 2 if tempEach > 10 { tempEach -= 9 } tempArray.insert(tempEach, at: 0) } else { tempArray.insert(tempEach, at: 0) } } return tempArray } func char2Int(_ input: Character) -> Int { let tempInt = Int(String(input)) ?? -1 // -1 = error return tempInt } let tempString = "\(num)" return oddIndexInt64Minus9(Array(tempString.characters).map { char2Int($0) }) } }
973eac89ed61d0ca2f5c64c11d78f9eb
27.783333
85
0.501448
false
false
false
false
open-telemetry/opentelemetry-swift
refs/heads/main
Examples/Network Sample/main.swift
apache-2.0
1
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetrySdk import StdoutExporter import URLSessionInstrumentation func simpleNetworkCall() { let url = URL(string: "http://httpbin.org/get")! let request = URLRequest(url: url) let semaphore = DispatchSemaphore(value: 0) let task = URLSession.shared.dataTask(with: request) { data, _, _ in if let data = data { let string = String(decoding: data, as: UTF8.self) print(string) } semaphore.signal() } task.resume() semaphore.wait() } class SessionDelegate: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate { let semaphore = DispatchSemaphore(value: 0) func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { semaphore.signal() } } let delegate = SessionDelegate() func simpleNetworkCallWithDelegate() { let session = URLSession(configuration: .default, delegate: delegate, delegateQueue:nil) let url = URL(string: "http://httpbin.org/get")! let request = URLRequest(url: url) let task = session.dataTask(with: request) task.resume() delegate.semaphore.wait() } let spanProcessor = SimpleSpanProcessor(spanExporter: StdoutExporter(isDebug: true)) OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor) let networkInstrumentation = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration()) simpleNetworkCall() simpleNetworkCallWithDelegate() sleep(1)
5e1b657b7b614a2e5f8b84d28e567185
25.566667
111
0.725847
false
false
false
false
RocAndTrees/DYLiveTelevision
refs/heads/master
LXLive/LXLive/Classes/Home/View/RecommendGameView.swift
mit
1
// // RecommendGameView.swift // DYZB // // Created by 1 on 16/9/21. // Copyright © 2016年 小码哥. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommendGameView: UIView { // MARK: 定义数据的属性 var groups : [BaseGameModel]? { didSet { // 1.移除前两组数据 // groups?.removeFirst() // groups?.removeFirst() // // // 2.添加更多组 // let moreGroup = AnchorGroup() // moreGroup.tag_name = "更多" // groups?.append(moreGroup) // 2.刷新表格 collectionView.reloadData() } } // MARK: 控件属性 @IBOutlet weak var collectionView: UICollectionView! // MARK: 系统回调 override func awakeFromNib() { super.awakeFromNib() // 让控件不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() // 注册Cell collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) // 给collectionView添加内边距 collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } // MARK:- 提供快速创建的类方法 extension RecommendGameView { class func recommendGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)!.first as! RecommendGameView } } // MARK:- 遵守UICollectionView的数据源协议 extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = groups![indexPath.item] return cell } }
7312ee40163912630322eef7cdaebb5e
27.534247
126
0.633221
false
false
false
false
zisko/swift
refs/heads/master
test/Inputs/clang-importer-sdk/swift-modules-without-ns/Foundation.swift
apache-2.0
1
@_exported import ObjectiveC @_exported import CoreGraphics @_exported import Foundation public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) } public let NSUTF8StringEncoding: UInt = 8 extension String : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSString { return NSString() } public static func _forceBridgeFromObjectiveC(_ x: NSString, result: inout String?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSString, result: inout String? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSString? ) -> String { return String() } } extension Int : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> Int { return Int() } } extension Array : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSArray { return NSArray() } public static func _forceBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSArray? ) -> Array { return Array() } } extension Dictionary : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSDictionary { return NSDictionary() } public static func _forceBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSDictionary? ) -> Dictionary { return Dictionary() } } extension Set : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSSet { return NSSet() } public static func _forceBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSSet? ) -> Set { return Set() } } extension CGFloat : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> CGFloat { return CGFloat() } } extension NSRange : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSValue { return NSValue() } public static func _forceBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSValue? ) -> NSRange { return NSRange() } } extension NSError : Error { public var _domain: String { return domain } public var _code: Int { return code } } public enum _GenericObjCError : Error { case nilError } public func _convertNSErrorToError(_ error: NSError?) -> Error { if let error = error { return error } return _GenericObjCError.nilError } public func _convertErrorToNSError(_ error: Error) -> NSError { return error as NSError }
417db14962bc2821f4a66b1e26b36cab
21.096774
72
0.666667
false
false
false
false
novi/proconapp
refs/heads/master
ProconApp/ProconApp/Utils.swift
bsd-3-clause
1
// // Utils.swift // ProconApp // // Created by ito on 2015/07/07. // Copyright (c) 2015年 Procon. All rights reserved. // import UIKit import ProconBase import APIKit extension UIApplication { func activatePushNotification() { dispatch_async(dispatch_get_main_queue(), { () -> Void in Logger.debug("activatePushNotification") let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil) self.registerUserNotificationSettings(settings) }) } } extension String { init?(deviceTokenData: NSData?) { if let deviceToken = deviceTokenData { let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for var i = 0; i < deviceToken.length; i++ { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } self = tokenString return } return nil } } extension UIColor { static var appTintColor: UIColor { return UIColor(red:46/255.0,green:63/255.0,blue:126/255.0,alpha:1.0) } } class SafariActivity: UIActivity { var url: NSURL? override class func activityCategory() -> UIActivityCategory { return .Action } override func activityType() -> String? { return "SafariActivity" } override func activityTitle() -> String? { return "Safariで開く" } override func activityImage() -> UIImage? { return UIImage(image: .ActivitySafari) } override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool { for obj in activityItems { if let url = obj as? NSURL { self.url = url return true } } return false } override func prepareWithActivityItems(activityItems: [AnyObject]) { for obj in activityItems { if let url = obj as? NSURL { self.url = url return } } } override func performActivity() { let completed: Bool if let url = self.url { completed = UIApplication.sharedApplication().openURL(url) } else { completed = false } self.activityDidFinish(completed) } }
53b692ee17b44e46e2749971ec80ebf8
23.773196
106
0.565362
false
false
false
false
toggl/superday
refs/heads/develop
teferi/UI/Modules/Goals/NewGoal/Views/CustomCollectionView.swift
bsd-3-clause
1
import UIKit protocol CustomCollectionViewDatasource { var initialIndex: Int { get } func numberOfItems(for collectionView: UICollectionView) -> Int func cell(at row: Int, for collectionView: UICollectionView) -> UICollectionViewCell } protocol CustomCollectionViewDelegate { func itemSelected(for collectionView: UICollectionView, at row: Int) } class CustomCollectionView: UICollectionView { let numberOfLoops: Int = 100 var loops: Bool = false var customDatasource: CustomCollectionViewDatasource? { didSet { delegate = self dataSource = self totalNumberOfItems = customDatasource!.numberOfItems(for: self) } } var customDelegate: CustomCollectionViewDelegate? private var didLayout: Bool = false fileprivate var totalNumberOfItems: Int = 0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) setup() } private func setup() { allowsSelection = false } override func layoutSubviews() { super.layoutSubviews() let layout = collectionViewLayout as! UICollectionViewFlowLayout let inset = frame.width / 2 - layout.itemSize.width / 2 contentInset = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset) firstLayoutIfNeeded() } private func firstLayoutIfNeeded() { guard !didLayout, let customDatasource = customDatasource else { return } didLayout = true let layout = collectionViewLayout as! UICollectionViewFlowLayout let cellWidth = layout.itemSize.width + layout.minimumInteritemSpacing let initialOffset = CGFloat(customDatasource.initialIndex) * cellWidth if loops { contentOffset = CGPoint(x: -contentInset.left + cellWidth * CGFloat(numberOfLoops/2 * totalNumberOfItems) + initialOffset, y: 0) } else { contentOffset = CGPoint(x: -contentInset.left + initialOffset, y: 0) } } } extension CustomCollectionView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return totalNumberOfItems * (loops ? numberOfLoops : 1) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var normalizedIndexPath = indexPath if loops { normalizedIndexPath = IndexPath(row: indexPath.row % totalNumberOfItems, section: 0) } return customDatasource!.cell(at: normalizedIndexPath.row, for: self) } } extension CustomCollectionView: UICollectionViewDelegate { func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let layout = collectionViewLayout as! UICollectionViewFlowLayout let cellWidth = layout.itemSize.width + layout.minimumInteritemSpacing let page: CGFloat let snapDelta: CGFloat = 0.7 let proposedPage = (targetContentOffset.pointee.x + contentInset.left - layout.minimumInteritemSpacing) / cellWidth if floor(proposedPage + snapDelta) == floor(proposedPage) && scrollView.contentOffset.x <= targetContentOffset.pointee.x { page = floor(proposedPage) } else { page = floor(proposedPage + 1) } targetContentOffset.pointee = CGPoint( x: cellWidth * page - contentInset.left, y: targetContentOffset.pointee.y ) } func scrollViewDidScroll(_ scrollView: UIScrollView) { let layout = collectionViewLayout as! UICollectionViewFlowLayout let cellWidth = layout.itemSize.width + layout.minimumInteritemSpacing var page = Int(round((scrollView.contentOffset.x + contentInset.left - layout.minimumInteritemSpacing) / cellWidth)) if loops { page = page % totalNumberOfItems } page = min(max(0, page), totalNumberOfItems - 1) customDelegate?.itemSelected(for: self, at: page) } }
b96d76a35163df416680ac745e1b2368
32.839695
146
0.664336
false
false
false
false
raykle/CustomTransition
refs/heads/master
CircleTransition/ViewControllerTransition/CircleTransitionAnimator.swift
mit
1
// // CircleTransitionAnimator.swift // CircleTransition // // Created by guomin on 16/3/9. // Copyright © 2016年 iBinaryOrg. All rights reserved. // import UIKit class CircleTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning { weak var transitionContext: UIViewControllerContextTransitioning? func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext let containerView = transitionContext.containerView() let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController let button = fromViewController.button containerView?.addSubview(toViewController.view) let circleMaskPathInitial = UIBezierPath(ovalInRect: button.frame) let extremePoint = CGPoint(x: button.center.x - 0, y: button.center.y - CGRectGetHeight(toViewController.view.bounds)) let radius = sqrt((extremePoint.x * extremePoint.x) + (extremePoint.y * extremePoint.y)) let circleMaskPathFinal = UIBezierPath(ovalInRect: CGRectInset(button.frame, -radius, -radius)) let maskLayer = CAShapeLayer() maskLayer.path = circleMaskPathFinal.CGPath toViewController.view.layer.mask = maskLayer let maskLayerAnimation = CABasicAnimation(keyPath: "path") maskLayerAnimation.fromValue = circleMaskPathInitial.CGPath maskLayerAnimation.toValue = circleMaskPathFinal.CGPath maskLayerAnimation.duration = self.transitionDuration(transitionContext) maskLayerAnimation.delegate = self maskLayer.addAnimation(maskLayerAnimation, forKey: "path") } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { self.transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled()) self.transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view.layer.mask = nil } }
dff59f852b731a8b90c225bcbf9b6165
45.66
132
0.74282
false
false
false
false