repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VeinGuo/VGPlayer
|
VGPlayer/Classes/VGPlayerView.swift
|
1
|
27343
|
//
// VGPlayerView.swift
// VGPlayer
//
// Created by Vein on 2017/6/5.
// Copyright © 2017年 Vein. All rights reserved.
//
import UIKit
import MediaPlayer
import SnapKit
public protocol VGPlayerViewDelegate: class {
/// Fullscreen
///
/// - Parameters:
/// - playerView: player view
/// - fullscreen: Whether full screen
func vgPlayerView(_ playerView: VGPlayerView, willFullscreen isFullscreen: Bool)
/// Close play view
///
/// - Parameter playerView: player view
func vgPlayerView(didTappedClose playerView: VGPlayerView)
/// Displaye control
///
/// - Parameter playerView: playerView
func vgPlayerView(didDisplayControl playerView: VGPlayerView)
}
// MARK: - delegate methods optional
public extension VGPlayerViewDelegate {
func vgPlayerView(_ playerView: VGPlayerView, willFullscreen fullscreen: Bool){}
func vgPlayerView(didTappedClose playerView: VGPlayerView) {}
func vgPlayerView(didDisplayControl playerView: VGPlayerView) {}
}
public enum VGPlayerViewPanGestureDirection: Int {
case vertical
case horizontal
}
open class VGPlayerView: UIView {
weak open var vgPlayer : VGPlayer?
open var controlViewDuration : TimeInterval = 5.0 /// default 5.0
open fileprivate(set) var playerLayer : AVPlayerLayer?
open fileprivate(set) var isFullScreen : Bool = false
open fileprivate(set) var isTimeSliding : Bool = false
open fileprivate(set) var isDisplayControl : Bool = true {
didSet {
if isDisplayControl != oldValue {
delegate?.vgPlayerView(didDisplayControl: self)
}
}
}
open weak var delegate : VGPlayerViewDelegate?
// top view
open var topView : UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
return view
}()
open var titleLabel : UILabel = {
let label = UILabel()
label.textAlignment = .left
label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
label.font = UIFont.boldSystemFont(ofSize: 16.0)
return label
}()
open var closeButton : UIButton = {
let button = UIButton(type: .custom)
return button
}()
// bottom view
open var bottomView : UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
return view
}()
open var timeSlider = VGPlayerSlider ()
open var loadingIndicator = VGPlayerLoadingIndicator()
open var fullscreenButton : UIButton = UIButton(type: .custom)
open var timeLabel : UILabel = UILabel()
open var playButtion : UIButton = UIButton(type: .custom)
open var volumeSlider : UISlider!
open var replayButton : UIButton = UIButton(type: .custom)
open fileprivate(set) var panGestureDirection : VGPlayerViewPanGestureDirection = .horizontal
fileprivate var isVolume : Bool = false
fileprivate var sliderSeekTimeValue : TimeInterval = .nan
fileprivate var timer : Timer = {
let time = Timer()
return time
}()
fileprivate weak var parentView : UIView?
fileprivate var viewFrame = CGRect()
// GestureRecognizer
open var singleTapGesture = UITapGestureRecognizer()
open var doubleTapGesture = UITapGestureRecognizer()
open var panGesture = UIPanGestureRecognizer()
//MARK:- life cycle
public override init(frame: CGRect) {
self.playerLayer = AVPlayerLayer(player: nil)
super.init(frame: frame)
addDeviceOrientationNotifications()
addGestureRecognizer()
configurationVolumeSlider()
configurationUI()
}
public convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
timer.invalidate()
playerLayer?.removeFromSuperlayer()
NotificationCenter.default.removeObserver(self)
}
open override func layoutSubviews() {
super.layoutSubviews()
updateDisplayerView(frame: bounds)
}
open func setvgPlayer(vgPlayer: VGPlayer) {
self.vgPlayer = vgPlayer
}
open func reloadPlayerLayer() {
playerLayer = AVPlayerLayer(player: self.vgPlayer?.player)
layer.insertSublayer(self.playerLayer!, at: 0)
updateDisplayerView(frame: self.bounds)
timeSlider.isUserInteractionEnabled = vgPlayer?.mediaFormat != .m3u8
reloadGravity()
}
/// play state did change
///
/// - Parameter state: state
open func playStateDidChange(_ state: VGPlayerState) {
playButtion.isSelected = state == .playing
replayButton.isHidden = !(state == .playFinished)
replayButton.isHidden = !(state == .playFinished)
if state == .playing || state == .playFinished {
setupTimer()
}
if state == .playFinished {
loadingIndicator.isHidden = true
}
}
/// buffer state change
///
/// - Parameter state: buffer state
open func bufferStateDidChange(_ state: VGPlayerBufferstate) {
if state == .buffering {
loadingIndicator.isHidden = false
loadingIndicator.startAnimating()
} else {
loadingIndicator.isHidden = true
loadingIndicator.stopAnimating()
}
var current = formatSecondsToString((vgPlayer?.currentDuration)!)
if (vgPlayer?.totalDuration.isNaN)! { // HLS
current = "00:00"
}
if state == .readyToPlay && !isTimeSliding {
timeLabel.text = "\(current + " / " + (formatSecondsToString((vgPlayer?.totalDuration)!)))"
}
}
/// buffer duration
///
/// - Parameters:
/// - bufferedDuration: buffer duration
/// - totalDuration: total duratiom
open func bufferedDidChange(_ bufferedDuration: TimeInterval, totalDuration: TimeInterval) {
timeSlider.setProgress(Float(bufferedDuration / totalDuration), animated: true)
}
/// player diration
///
/// - Parameters:
/// - currentDuration: current duration
/// - totalDuration: total duration
open func playerDurationDidChange(_ currentDuration: TimeInterval, totalDuration: TimeInterval) {
var current = formatSecondsToString(currentDuration)
if totalDuration.isNaN { // HLS
current = "00:00"
}
if !isTimeSliding {
timeLabel.text = "\(current + " / " + (formatSecondsToString(totalDuration)))"
timeSlider.value = Float(currentDuration / totalDuration)
}
}
open func configurationUI() {
backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
configurationTopView()
configurationBottomView()
configurationReplayButton()
setupViewAutoLayout()
}
open func reloadPlayerView() {
playerLayer = AVPlayerLayer(player: nil)
timeSlider.value = Float(0)
timeSlider.setProgress(0, animated: false)
replayButton.isHidden = true
isTimeSliding = false
loadingIndicator.isHidden = false
loadingIndicator.startAnimating()
timeLabel.text = "--:-- / --:--"
reloadPlayerLayer()
}
/// control view display
///
/// - Parameter display: is display
open func displayControlView(_ isDisplay:Bool) {
if isDisplay {
displayControlAnimation()
} else {
hiddenControlAnimation()
}
}
}
// MARK: - public
extension VGPlayerView {
open func updateDisplayerView(frame: CGRect) {
playerLayer?.frame = frame
}
open func reloadGravity() {
if vgPlayer != nil {
switch vgPlayer!.gravityMode {
case .resize:
playerLayer?.videoGravity = .resize
case .resizeAspect:
playerLayer?.videoGravity = .resizeAspect
case .resizeAspectFill:
playerLayer?.videoGravity = .resizeAspectFill
}
}
}
open func enterFullscreen() {
let statusBarOrientation = UIApplication.shared.statusBarOrientation
if statusBarOrientation == .portrait{
parentView = (self.superview)!
viewFrame = self.frame
}
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
UIApplication.shared.statusBarOrientation = .landscapeRight
UIApplication.shared.setStatusBarHidden(false, with: .fade)
}
open func exitFullscreen() {
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
UIApplication.shared.statusBarOrientation = .portrait
}
/// play failed
///
/// - Parameter error: error
open func playFailed(_ error: VGPlayerError) {
// error
}
public func formatSecondsToString(_ seconds: TimeInterval) -> String {
if seconds.isNaN{
return "00:00"
}
let interval = Int(seconds)
let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
let min = interval / 60
return String(format: "%02d:%02d", min, sec)
}
}
// MARK: - private
extension VGPlayerView {
internal func play() {
playButtion.isSelected = true
}
internal func pause() {
playButtion.isSelected = false
}
internal func displayControlAnimation() {
bottomView.isHidden = false
topView.isHidden = false
isDisplayControl = true
UIView.animate(withDuration: 0.5, animations: {
self.bottomView.alpha = 1
self.topView.alpha = 1
}) { (completion) in
self.setupTimer()
}
}
internal func hiddenControlAnimation() {
timer.invalidate()
isDisplayControl = false
UIView.animate(withDuration: 0.5, animations: {
self.bottomView.alpha = 0
self.topView.alpha = 0
}) { (completion) in
self.bottomView.isHidden = true
self.topView.isHidden = true
}
}
internal func setupTimer() {
timer.invalidate()
timer = Timer.vgPlayer_scheduledTimerWithTimeInterval(self.controlViewDuration, block: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.displayControlView(false)
}, repeats: false)
}
internal func addDeviceOrientationNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationWillChange(_:)), name: UIApplication.willChangeStatusBarOrientationNotification, object: nil)
}
internal func configurationVolumeSlider() {
let volumeView = MPVolumeView()
if let view = volumeView.subviews.first as? UISlider {
volumeSlider = view
}
}
}
// MARK: - GestureRecognizer
extension VGPlayerView {
internal func addGestureRecognizer() {
singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onSingleTapGesture(_:)))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.numberOfTouchesRequired = 1
singleTapGesture.delegate = self
addGestureRecognizer(singleTapGesture)
doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onDoubleTapGesture(_:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.numberOfTouchesRequired = 1
doubleTapGesture.delegate = self
addGestureRecognizer(doubleTapGesture)
panGesture = UIPanGestureRecognizer(target: self, action: #selector(onPanGesture(_:)))
panGesture.delegate = self
addGestureRecognizer(panGesture)
singleTapGesture.require(toFail: doubleTapGesture)
}
}
// MARK: - UIGestureRecognizerDelegate
extension VGPlayerView: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if (touch.view as? VGPlayerView != nil) {
return true
}
return false
}
}
// MARK: - Event
extension VGPlayerView {
@objc internal func timeSliderValueChanged(_ sender: VGPlayerSlider) {
isTimeSliding = true
if let duration = vgPlayer?.totalDuration {
let currentTime = Double(sender.value) * duration
timeLabel.text = "\(formatSecondsToString(currentTime) + " / " + (formatSecondsToString(duration)))"
}
}
@objc internal func timeSliderTouchDown(_ sender: VGPlayerSlider) {
isTimeSliding = true
timer.invalidate()
}
@objc internal func timeSliderTouchUpInside(_ sender: VGPlayerSlider) {
isTimeSliding = true
if let duration = vgPlayer?.totalDuration {
let currentTime = Double(sender.value) * duration
vgPlayer?.seekTime(currentTime, completion: { [weak self] (finished) in
guard let strongSelf = self else { return }
if finished {
strongSelf.isTimeSliding = false
strongSelf.setupTimer()
}
})
timeLabel.text = "\(formatSecondsToString(currentTime) + " / " + (formatSecondsToString(duration)))"
}
}
@objc internal func onPlayerButton(_ sender: UIButton) {
if !sender.isSelected {
vgPlayer?.play()
} else {
vgPlayer?.pause()
}
}
@objc internal func onFullscreen(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
isFullScreen = sender.isSelected
if isFullScreen {
enterFullscreen()
} else {
exitFullscreen()
}
}
/// Single Tap Event
///
/// - Parameter gesture: Single Tap Gesture
@objc open func onSingleTapGesture(_ gesture: UITapGestureRecognizer) {
isDisplayControl = !isDisplayControl
displayControlView(isDisplayControl)
}
/// Double Tap Event
///
/// - Parameter gesture: Double Tap Gesture
@objc open func onDoubleTapGesture(_ gesture: UITapGestureRecognizer) {
guard vgPlayer == nil else {
switch vgPlayer!.state {
case .playFinished:
break
case .playing:
vgPlayer?.pause()
case .paused:
vgPlayer?.play()
case .none:
break
case .error:
break
}
return
}
}
/// Pan Event
///
/// - Parameter gesture: Pan Gesture
@objc open func onPanGesture(_ gesture: UIPanGestureRecognizer) {
let translation = gesture.translation(in: self)
let location = gesture.location(in: self)
let velocity = gesture.velocity(in: self)
switch gesture.state {
case .began:
let x = abs(translation.x)
let y = abs(translation.y)
if x < y {
panGestureDirection = .vertical
if location.x > bounds.width / 2 {
isVolume = true
} else {
isVolume = false
}
} else if x > y{
guard vgPlayer?.mediaFormat == .m3u8 else {
panGestureDirection = .horizontal
return
}
}
case .changed:
switch panGestureDirection {
case .horizontal:
if vgPlayer?.currentDuration == 0 { break }
sliderSeekTimeValue = panGestureHorizontal(velocity.x)
case .vertical:
panGestureVertical(velocity.y)
}
case .ended:
switch panGestureDirection{
case .horizontal:
if sliderSeekTimeValue.isNaN { return }
self.vgPlayer?.seekTime(sliderSeekTimeValue, completion: { [weak self] (finished) in
guard let strongSelf = self else { return }
if finished {
strongSelf.isTimeSliding = false
strongSelf.setupTimer()
}
})
case .vertical:
isVolume = false
}
default:
break
}
}
internal func panGestureHorizontal(_ velocityX: CGFloat) -> TimeInterval {
displayControlView(true)
isTimeSliding = true
timer.invalidate()
let value = timeSlider.value
if let _ = vgPlayer?.currentDuration ,let totalDuration = vgPlayer?.totalDuration {
let sliderValue = (TimeInterval(value) * totalDuration) + TimeInterval(velocityX) / 100.0 * (TimeInterval(totalDuration) / 400)
timeSlider.setValue(Float(sliderValue/totalDuration), animated: true)
return sliderValue
} else {
return TimeInterval.nan
}
}
internal func panGestureVertical(_ velocityY: CGFloat) {
isVolume ? (volumeSlider.value -= Float(velocityY / 10000)) : (UIScreen.main.brightness -= velocityY / 10000)
}
@objc internal func onCloseView(_ sender: UIButton) {
delegate?.vgPlayerView(didTappedClose: self)
}
@objc internal func onReplay(_ sender: UIButton) {
vgPlayer?.replaceVideo((vgPlayer?.contentURL)!)
vgPlayer?.play()
}
@objc internal func deviceOrientationWillChange(_ sender: Notification) {
let orientation = UIDevice.current.orientation
let statusBarOrientation = UIApplication.shared.statusBarOrientation
if statusBarOrientation == .portrait{
if superview != nil {
parentView = (superview)!
viewFrame = frame
}
}
switch orientation {
case .unknown:
break
case .faceDown:
break
case .faceUp:
break
case .landscapeLeft:
onDeviceOrientation(true, orientation: .landscapeLeft)
case .landscapeRight:
onDeviceOrientation(true, orientation: .landscapeRight)
case .portrait:
onDeviceOrientation(false, orientation: .portrait)
case .portraitUpsideDown:
onDeviceOrientation(false, orientation: .portraitUpsideDown)
}
}
internal func onDeviceOrientation(_ fullScreen: Bool, orientation: UIInterfaceOrientation) {
let statusBarOrientation = UIApplication.shared.statusBarOrientation
if orientation == statusBarOrientation {
if orientation == .landscapeLeft || orientation == .landscapeLeft {
let rectInWindow = convert(bounds, to: UIApplication.shared.keyWindow)
removeFromSuperview()
frame = rectInWindow
UIApplication.shared.keyWindow?.addSubview(self)
self.snp.remakeConstraints({ [weak self] (make) in
guard let strongSelf = self else { return }
make.width.equalTo(strongSelf.superview!.bounds.width)
make.height.equalTo(strongSelf.superview!.bounds.height)
})
}
} else {
if orientation == .landscapeLeft || orientation == .landscapeRight {
let rectInWindow = convert(bounds, to: UIApplication.shared.keyWindow)
removeFromSuperview()
frame = rectInWindow
UIApplication.shared.keyWindow?.addSubview(self)
self.snp.remakeConstraints({ [weak self] (make) in
guard let strongSelf = self else { return }
make.width.equalTo(strongSelf.superview!.bounds.height)
make.height.equalTo(strongSelf.superview!.bounds.width)
})
} else if orientation == .portrait{
if parentView == nil { return }
removeFromSuperview()
parentView!.addSubview(self)
let frame = parentView!.convert(viewFrame, to: UIApplication.shared.keyWindow)
self.snp.remakeConstraints({ (make) in
make.centerX.equalTo(viewFrame.midX)
make.centerY.equalTo(viewFrame.midY)
make.width.equalTo(frame.width)
make.height.equalTo(frame.height)
})
viewFrame = CGRect()
parentView = nil
}
}
isFullScreen = fullScreen
fullscreenButton.isSelected = fullScreen
delegate?.vgPlayerView(self, willFullscreen: isFullScreen)
}
}
//MARK: - UI autoLayout
extension VGPlayerView {
internal func configurationReplayButton() {
addSubview(self.replayButton)
let replayImage = VGPlayerUtils.imageResource("VGPlayer_ic_replay")
replayButton.setImage(VGPlayerUtils.imageSize(image: replayImage!, scaledToSize: CGSize(width: 30, height: 30)), for: .normal)
replayButton.addTarget(self, action: #selector(onReplay(_:)), for: .touchUpInside)
replayButton.isHidden = true
}
internal func configurationTopView() {
addSubview(topView)
titleLabel.text = "this is a title."
topView.addSubview(titleLabel)
let closeImage = VGPlayerUtils.imageResource("VGPlayer_ic_nav_back")
closeButton.setImage(VGPlayerUtils.imageSize(image: closeImage!, scaledToSize: CGSize(width: 15, height: 20)), for: .normal)
closeButton.addTarget(self, action: #selector(onCloseView(_:)), for: .touchUpInside)
topView.addSubview(closeButton)
}
internal func configurationBottomView() {
addSubview(bottomView)
timeSlider.addTarget(self, action: #selector(timeSliderValueChanged(_:)),
for: .valueChanged)
timeSlider.addTarget(self, action: #selector(timeSliderTouchUpInside(_:)), for: .touchUpInside)
timeSlider.addTarget(self, action: #selector(timeSliderTouchDown(_:)), for: .touchDown)
loadingIndicator.lineWidth = 1.0
loadingIndicator.isHidden = false
loadingIndicator.startAnimating()
addSubview(loadingIndicator)
bottomView.addSubview(timeSlider)
let playImage = VGPlayerUtils.imageResource("VGPlayer_ic_play")
let pauseImage = VGPlayerUtils.imageResource("VGPlayer_ic_pause")
playButtion.setImage(VGPlayerUtils.imageSize(image: playImage!, scaledToSize: CGSize(width: 15, height: 15)), for: .normal)
playButtion.setImage(VGPlayerUtils.imageSize(image: pauseImage!, scaledToSize: CGSize(width: 15, height: 15)), for: .selected)
playButtion.addTarget(self, action: #selector(onPlayerButton(_:)), for: .touchUpInside)
bottomView.addSubview(playButtion)
timeLabel.textAlignment = .center
timeLabel.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
timeLabel.font = UIFont.systemFont(ofSize: 12.0)
timeLabel.text = "--:-- / --:--"
bottomView.addSubview(timeLabel)
let enlargeImage = VGPlayerUtils.imageResource("VGPlayer_ic_fullscreen")
let narrowImage = VGPlayerUtils.imageResource("VGPlayer_ic_fullscreen_exit")
fullscreenButton.setImage(VGPlayerUtils.imageSize(image: enlargeImage!, scaledToSize: CGSize(width: 15, height: 15)), for: .normal)
fullscreenButton.setImage(VGPlayerUtils.imageSize(image: narrowImage!, scaledToSize: CGSize(width: 15, height: 15)), for: .selected)
fullscreenButton.addTarget(self, action: #selector(onFullscreen(_:)), for: .touchUpInside)
bottomView.addSubview(fullscreenButton)
}
internal func setupViewAutoLayout() {
replayButton.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.center.equalTo(strongSelf)
make.width.equalTo(30)
make.height.equalTo(30)
}
// top view layout
topView.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.left.equalTo(strongSelf)
make.right.equalTo(strongSelf)
make.top.equalTo(strongSelf)
make.height.equalTo(64)
}
closeButton.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.left.equalTo(strongSelf.topView).offset(10)
make.top.equalTo(strongSelf.topView).offset(28)
make.height.equalTo(30)
make.width.equalTo(30)
}
titleLabel.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.left.equalTo(strongSelf.closeButton.snp.right).offset(20)
make.centerY.equalTo(strongSelf.closeButton.snp.centerY)
}
// bottom view layout
bottomView.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.left.equalTo(strongSelf)
make.right.equalTo(strongSelf)
make.bottom.equalTo(strongSelf)
make.height.equalTo(52)
}
playButtion.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.left.equalTo(strongSelf.bottomView).offset(20)
make.height.equalTo(25)
make.width.equalTo(25)
make.centerY.equalTo(strongSelf.bottomView)
}
timeLabel.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.right.equalTo(strongSelf.fullscreenButton.snp.left).offset(-10)
make.centerY.equalTo(strongSelf.playButtion)
make.height.equalTo(30)
}
timeSlider.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.centerY.equalTo(strongSelf.playButtion)
make.right.equalTo(strongSelf.timeLabel.snp.left).offset(-10)
make.left.equalTo(strongSelf.playButtion.snp.right).offset(25)
make.height.equalTo(25)
}
fullscreenButton.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.centerY.equalTo(strongSelf.playButtion)
make.right.equalTo(strongSelf.bottomView).offset(-10)
make.height.equalTo(30)
make.width.equalTo(30)
}
loadingIndicator.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.center.equalTo(strongSelf)
make.height.equalTo(30)
make.width.equalTo(30)
}
}
}
|
mit
|
20e18d7547e39a3d91f7f8b080887aad
| 35.308101 | 183 | 0.608376 | 5.133308 | false | false | false | false |
ChrisAU/Locution
|
Papyrus/DataSources/GameType.swift
|
2
|
880
|
//
// GameType.swift
// Papyrus
//
// Created by Chris Nevin on 03/09/2017.
// Copyright © 2017 CJNevin. All rights reserved.
//
import Foundation
fileprivate extension URL {
static func gameFileURL(`for` name: String) -> URL {
return URL(fileURLWithPath: Bundle.main.path(forResource: name, ofType: "json")!)
}
}
let allGameTypes: [GameType] = [
ScrabbleGameType(),
SuperScrabbleGameType(),
WordfeudGameType(),
WordsWithFriendsGameType()
]
protocol GameType {
var fileURL: URL { get }
}
struct ScrabbleGameType: GameType {
let fileURL = URL.gameFileURL(for: "Scrabble")
}
struct SuperScrabbleGameType: GameType {
let fileURL = URL.gameFileURL(for: "SuperScrabble")
}
struct WordfeudGameType: GameType {
let fileURL = URL.gameFileURL(for: "Wordfeud")
}
struct WordsWithFriendsGameType: GameType {
let fileURL = URL.gameFileURL(for: "WordsWithFriends")
}
|
mit
|
0d9c4ebd188b5416f5377089ab4ae216
| 19.928571 | 83 | 0.731513 | 3.196364 | false | false | false | false |
finngaida/healthpad
|
Shared/Animation/DotTrianglePath.swift
|
1
|
2103
|
//
// DotTrianglePath.swift
// RPLoadingAnimation
//
// Created by naoyashiga on 2015/10/12.
// Copyright © 2015年 naoyashiga. All rights reserved.
//
import UIKit
class DotTrianglePath: RPLoadingAnimationDelegate {
var baseLayer = CALayer()
var baseSize = CGSize(width: 0, height: 0)
func setup(layer: CALayer, size: CGSize, color: UIColor) {
let dotNum: CGFloat = 3
let diameter: CGFloat = size.width / 15
let dot = CALayer()
let duration: CFTimeInterval = 1.3
let frame = CGRect(
x: (layer.bounds.width - diameter) / 2,
y: (layer.bounds.height - diameter) / 2,
width: diameter,
height: diameter
)
layer.frame = frame
baseLayer = layer
baseSize = size
dot.backgroundColor = color.CGColor
dot.frame = frame
dot.cornerRadius = diameter / 2
let replicatorLayer = CAReplicatorLayer()
replicatorLayer.frame = layer.bounds
replicatorLayer.addSublayer(dot)
replicatorLayer.instanceCount = Int(dotNum)
replicatorLayer.instanceDelay = CFTimeInterval(-1 / dotNum)
layer.addSublayer(replicatorLayer)
let moveAnimation = CAKeyframeAnimation(keyPath: "position")
moveAnimation.path = getPath()
moveAnimation.duration = duration
moveAnimation.repeatCount = .infinity
moveAnimation.timingFunction = TimingFunction.EaseInOutSine.getTimingFunction()
dot.addAnimation(moveAnimation, forKey: "moveAnimation")
}
func getPath() -> CGPath {
let r: CGFloat = baseSize.width / 5
let center = CGPoint(x: baseLayer.bounds.width / 2, y: baseLayer.bounds.height / 2)
let path = UIBezierPath()
path.moveToPoint(CGPointMake(center.x, -r))
path.addLineToPoint(CGPointMake(center.x - r, r / 2))
path.addLineToPoint(CGPointMake(center.x + r, r / 2))
path.closePath()
return path.CGPath
}
}
|
apache-2.0
|
d5a171a3f3c91a2c6b080a3282c414b6
| 30.358209 | 91 | 0.60619 | 4.761905 | false | false | false | false |
sharath-cliqz/browser-ios
|
Storage/SQL/RemoteTabsTable.swift
|
2
|
5999
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
let TableClients: String = "clients"
let TableTabs = "tabs"
class RemoteClientsTable<T>: GenericTable<RemoteClient> {
override var name: String { return TableClients }
override var version: Int { return 1 }
// TODO: index on guid and last_modified.
override var rows: String { return [
"guid TEXT PRIMARY KEY",
"name TEXT NOT NULL",
"modified INTEGER NOT NULL",
"type TEXT",
"formfactor TEXT",
"os TEXT",
].joined(separator: ",")
}
// TODO: this won't work correctly with NULL fields.
override func getInsertAndArgs(_ item: inout RemoteClient) -> (String, Args)? {
let args: Args = [
item.guid,
item.name,
NSNumber(value: item.modified),
item.type,
item.formfactor,
item.os,
]
return ("INSERT INTO \(name) (guid, name, modified, type, formfactor, os) VALUES (?, ?, ?, ?, ?, ?)", args)
}
override func getUpdateAndArgs(_ item: inout RemoteClient) -> (String, Args)? {
let args: Args = [
item.name,
NSNumber(value: item.modified),
item.type,
item.formfactor,
item.os,
item.guid,
]
return ("UPDATE \(name) SET name = ?, modified = ?, type = ?, formfactor = ?, os = ? WHERE guid = ?", args)
}
override func getDeleteAndArgs(_ item: inout RemoteClient?) -> (String, Args)? {
if let item = item {
return ("DELETE FROM \(name) WHERE guid = ?", [item.guid])
}
return ("DELETE FROM \(name)", [])
}
override var factory: ((_ row: SDRow) -> RemoteClient)? {
return { row -> RemoteClient in
return RemoteClient(guid: row["guid"] as? String,
name: row["name"] as! String,
modified: (row["modified"] as! NSNumber).uint64Value,
type: row["type"] as? String,
formfactor: row["formfactor"] as? String,
os: row["os"] as? String)
}
}
override func getQueryAndArgs(_ options: QueryOptions?) -> (String, Args)? {
return ("SELECT * FROM \(name) ORDER BY modified DESC", [])
}
}
class RemoteTabsTable<T>: GenericTable<RemoteTab> {
override var name: String { return TableTabs }
override var version: Int { return 2 }
// TODO: index on id, client_guid, last_used, and position.
override var rows: String { return [
"id INTEGER PRIMARY KEY AUTOINCREMENT", // An individual tab has no GUID from Sync.
"client_guid TEXT REFERENCES clients(guid) ON DELETE CASCADE",
"url TEXT NOT NULL",
"title TEXT", // TODO: NOT NULL throughout.
"history TEXT",
"last_used INTEGER",
].joined(separator: ",")
}
private static func convertHistoryToString(_ history: [URL]) -> String? {
let historyAsStrings = optFilter(history.map { $0.absoluteString })
let data = try! JSONSerialization.data(withJSONObject: historyAsStrings, options: [])
return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String
}
private func convertStringToHistory(_ history: String?) -> [URL] {
if let data = history?.data(using: String.Encoding.utf8) {
if let urlStrings = try! JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.allowFragments]) as? [String] {
return optFilter(urlStrings.map { URL(string: $0) })
}
}
return []
}
override func getInsertAndArgs(_ item: inout RemoteTab) -> (String, Args)? {
let args: Args = [
item.clientGUID,
item.URL.absoluteString,
item.title,
RemoteTabsTable.convertHistoryToString(item.history),
NSNumber(value: item.lastUsed),
]
return ("INSERT INTO \(name) (client_guid, url, title, history, last_used) VALUES (?, ?, ?, ?, ?)", args)
}
override func getUpdateAndArgs(_ item: inout RemoteTab) -> (String, Args)? {
let args: Args = [
item.title,
RemoteTabsTable.convertHistoryToString(item.history),
NSNumber(value: item.lastUsed),
// Key by (client_guid, url) rather than (transient) id.
item.clientGUID,
item.URL.absoluteString,
]
return ("UPDATE \(name) SET title = ?, history = ?, last_used = ? WHERE client_guid IS ? AND url = ?", args)
}
override func getDeleteAndArgs(_ item: inout RemoteTab?) -> (String, Args)? {
if let item = item {
return ("DELETE FROM \(name) WHERE client_guid = IS AND url = ?", [item.clientGUID, item.URL.absoluteString])
}
return ("DELETE FROM \(name)", [])
}
override var factory: ((_ row: SDRow) -> RemoteTab)? {
return { (row: SDRow) -> RemoteTab in
return RemoteTab(
clientGUID: row["client_guid"] as? String,
URL: URL(string: row["url"] as! String)!, // TODO: find a way to make this less dangerous.
title: row["title"] as! String,
history: self.convertStringToHistory(row["history"] as? String),
lastUsed: row.getTimestamp("last_used")!,
icon: nil // TODO
)
}
}
override func getQueryAndArgs(_ options: QueryOptions?) -> (String, Args)? {
// Per-client chunks, each chunk in client-order.
return ("SELECT * FROM \(name) WHERE client_guid IS NOT NULL ORDER BY client_guid DESC, last_used DESC", [])
}
}
|
mpl-2.0
|
0dd54793c4c4075f1b90747449764021
| 36.968354 | 143 | 0.564927 | 4.460223 | false | false | false | false |
Ricky-Choi/AppcidCocoaUtil
|
AppcidCocoaUtil/LayoutExtension.swift
|
1
|
8076
|
//
// LayoutExtension.swift
// ACD
//
// Created by Jaeyoung Choi on 2015. 10. 14..
// Copyright © 2015년 Appcid. All rights reserved.
//
#if os(iOS) || os(watchOS)
import UIKit
public typealias View = UIView
public typealias LayoutPriority = UILayoutPriority
public let LayoutPriorityRequired: LayoutPriority = UILayoutPriorityRequired
public let LayoutPriorityDefaultHigh: LayoutPriority = UILayoutPriorityDefaultHigh
public let LayoutPriorityDefaultLow: LayoutPriority = UILayoutPriorityDefaultLow
#elseif os(OSX)
import AppKit
public typealias View = NSView
public typealias LayoutPriority = NSLayoutPriority
public let LayoutPriorityRequired: LayoutPriority = NSLayoutPriorityRequired
public let LayoutPriorityDefaultHigh: LayoutPriority = NSLayoutPriorityDefaultHigh
public let LayoutPriorityDefaultLow: LayoutPriority = NSLayoutPriorityDefaultLow
#endif
public struct ACDMargin {
var leading, top, trailing, bottom: CGFloat
public init(leading: CGFloat, top: CGFloat, trailing: CGFloat, bottom: CGFloat) {
self.leading = leading
self.top = top
self.trailing = trailing
self.bottom = bottom
}
}
public struct ACDOffset {
var x, y: CGFloat
public init(x: CGFloat, y: CGFloat) {
self.x = x
self.y = y
}
}
public let ACDMarginZero = ACDMargin(leading: 0, top: 0, trailing: 0, bottom: 0)
public let ACDOffsetZero = ACDOffset(x: 0, y: 0)
public typealias CenterConstraints = (xConstraint: NSLayoutConstraint, yConstraint: NSLayoutConstraint)
public typealias MarginConstraints = (leadingConstraint: NSLayoutConstraint, topConstraint: NSLayoutConstraint, trailingConstraint: NSLayoutConstraint, bottomConstraint: NSLayoutConstraint)
extension View {
public func fillXToSuperview() {
assert(superview != nil)
translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": self])
NSLayoutConstraint.activate(horizontalConstraints)
}
public func fillYToSuperview() {
assert(superview != nil)
translatesAutoresizingMaskIntoConstraints = false
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": self])
NSLayoutConstraint.activate(verticalConstraints)
}
@discardableResult
public func fillToSuperview(_ margin: ACDMargin = ACDMarginZero) -> MarginConstraints {
assert(superview != nil)
translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading, multiplier: 1.0, constant: margin.leading)
let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1.0, constant: margin.top)
let trailingConstraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: superview, attribute: .trailing, multiplier: 1.0, constant: margin.trailing)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1.0, constant: margin.bottom)
NSLayoutConstraint.activate([leadingConstraint, topConstraint, trailingConstraint, bottomConstraint])
return (leadingConstraint, topConstraint, trailingConstraint, bottomConstraint)
}
public func fixSize(_ size: CGSize) {
translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: size.width)
let heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: size.height)
NSLayoutConstraint.activate([widthConstraint, heightConstraint])
self.setContentHuggingPriority(LayoutPriorityRequired, for: .horizontal)
self.setContentHuggingPriority(LayoutPriorityRequired, for: .vertical)
}
public func fixWidth(_ width: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: width).isActive = true
self.setContentHuggingPriority(LayoutPriorityRequired, for: .horizontal)
}
public func fixHeight(_ height: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: height).isActive = true
self.setContentHuggingPriority(LayoutPriorityRequired, for: .vertical)
}
@discardableResult
public func fillAndCenterToSuperview(offset: ACDOffset = ACDOffsetZero) -> CenterConstraints {
assert(superview != nil)
translatesAutoresizingMaskIntoConstraints = false
fixSize(superview!.bounds.size)
return centerToSuperview(offset: offset)
}
@discardableResult
public func centerToSuperview(offset: ACDOffset = ACDOffsetZero) -> CenterConstraints {
assert(superview != nil)
translatesAutoresizingMaskIntoConstraints = false
let xConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1.0, constant: offset.x)
let yConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: superview, attribute: .centerY, multiplier: 1.0, constant: offset.y)
NSLayoutConstraint.activate([xConstraint, yConstraint])
return (xConstraint, yConstraint)
}
@discardableResult
public func centerXToSuperview() -> NSLayoutConstraint {
assert(superview != nil)
translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1.0, constant: 0.0)
constraint.isActive = true
return constraint
}
@discardableResult
public func centerYToSuperview() -> NSLayoutConstraint {
assert(superview != nil)
translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: superview, attribute: .centerY, multiplier: 1.0, constant: 0.0)
constraint.isActive = true
return constraint
}
public func resistSizeChange() {
self.setContentHuggingPriority(LayoutPriorityRequired, for: .horizontal)
self.setContentHuggingPriority(LayoutPriorityRequired, for: .vertical)
self.setContentCompressionResistancePriority(LayoutPriorityRequired, for: .horizontal)
self.setContentCompressionResistancePriority(LayoutPriorityRequired, for: .vertical)
}
#if os(iOS)
public static func layoutHelperView(_ superview: View? = nil) -> UIView {
let view = View()
if let superview = superview {
superview.addSubview(view)
}
view.isHidden = true
view.translatesAutoresizingMaskIntoConstraints = false
view.isAccessibilityElement = false
return view
}
#endif
}
extension NSLayoutConstraint {
public static func activateMarginConstraints(_ kc: MarginConstraints) {
activate([kc.leadingConstraint, kc.topConstraint, kc.trailingConstraint, kc.bottomConstraint])
}
}
|
mit
|
89e61a819ce4b46ec397dcd2321ed3e1
| 42.403226 | 189 | 0.7068 | 5.465809 | false | false | false | false |
OEASLAN/LetsEat
|
IOS/Let's Eat/Let's Eat/TabBar VC/GroupTableViewController.swift
|
1
|
3285
|
//
// GroupTableViewController.swift
// Let's Eat
//
// Created by Vidal_HARA on 6.04.2015.
// Copyright (c) 2015 vidal hara S002866. All rights reserved.
//
import UIKit
class GroupTableViewController: UITableViewController {
var member1 = ["name":"burak", "surname": "atalay", "email": "[email protected]", "password": "Vidal1", "username": "burak1"]
var member2 = ["name":"hasan", "surname": "sozer", "email": "[email protected]", "password": "Vidal1", "username": "hasan1"]
var members = [[String:AnyObject]]()
var group: [String: AnyObject] = ["name":"testGroup"]
var participants = [String: Bool]()
var groupList = [[String:AnyObject]]()
let apiMethods = ApiMethods()
@IBOutlet var groupsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
/*
members.append(member1)
members.append(member2)
group.updateValue(members, forKey: "members")
groupList.append(group)
groupsTable.reloadData()*/
apiMethods.getGroups(self)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
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 Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return groupList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("ownedGroupCell") as! UITableViewCell
let nameLabel = cell.viewWithTag(1) as! UILabel
let name = groupList[indexPath.item]["name"] as! String
nameLabel.text = name
let numLabel = cell.viewWithTag(2) as! UILabel
let members = groupList[indexPath.item]["members"] as! [[String:AnyObject]]
let num = members.count
if num == 1 {
numLabel.text = "One Friend"
}else{
numLabel.text = "\(num) Friends"
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if sender is UITableViewCell{
let gVC = segue.destinationViewController as! GroupViewController
if let item = groupsTable.indexPathForSelectedRow()?.item {
gVC.groupData = groupList[item]
}
}
}
}
|
gpl-2.0
|
2aedb7084a7d7e64c686a3d03ebc73a3
| 33.946809 | 121 | 0.639878 | 4.859467 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformKit/BuySellKit/Analytics/NewAnalyticsEvents+Withdrawal.swift
|
1
|
1723
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Foundation
extension AnalyticsEvents.New {
public enum Withdrawal: AnalyticsEvent {
public var type: AnalyticsEventType { .nabu }
case linkBankClicked(origin: LinkBank.Origin)
case withdrawalAmountEntered(
currency: String,
inputAmount: Double,
outputAmount: Double,
withdrawalMethod: Withdrawal.Method
)
case withdrawalAmountMaxClicked(
amountCurrency: String?,
currency: String,
withdrawalMethod: Withdrawal.Method
)
case withdrawalAmountMinClicked(
amountCurrency: String?,
currency: String,
withdrawalMethod: Withdrawal.Method
)
case withdrawalClicked(origin: Withdrawal.Origin)
case withdrawalMethodSelected(
currency: String,
withdrawalMethod: Withdrawal.Method
)
case withdrawalViewed
public enum LinkBank {
public enum Origin: String, StringRawRepresentable {
case buy = "BUY"
case deposit = "DEPOSIT"
case settings = "SETTINGS"
case withdraw = "WITHDRAW"
}
}
public enum Withdrawal {
public enum Method: String, StringRawRepresentable {
case bankAccount = "BANK_ACCOUNT"
case bankTransfer = "BANK_TRANSFER"
}
public enum Origin: String, StringRawRepresentable {
case currencyPage = "CURRENCY_PAGE"
case portfolio = "PORTFOLIO"
}
}
}
}
|
lgpl-3.0
|
97a4cdae3670abfc118b281ec8f65038
| 29.210526 | 64 | 0.578397 | 5.519231 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureTransaction/Modules/Checkout/Sources/FeatureCheckoutUI/Localization/LocalizationConstants+Checkout.swift
|
1
|
2277
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
// swiftlint:disable line_length
import Localization
extension LocalizationConstants {
enum Checkout {
enum Label {
static let from = NSLocalizedString(
"From",
comment: "From label for swap source"
)
static let to = NSLocalizedString(
"To",
comment: "To label for swap destination"
)
static let exchangeRate = NSLocalizedString(
"Exchange Rate",
comment: "Exchange Rate label title"
)
static let exchangeRateDisclaimer = NSLocalizedString(
"The exchange rate is the best price available for %@ in terms of 1 %@. [Learn more]()",
comment: "Exchange rate disclaimer"
)
static let networkFees = NSLocalizedString(
"Network Fees",
comment: "Network fees title label"
)
static let assetNetworkFees = NSLocalizedString(
"%@ Network Fees",
comment: "Asset network fees label"
)
static let noNetworkFee = NSLocalizedString(
"Free",
comment: "No network fee label"
)
static let and = NSLocalizedString(
"and",
comment: "And"
)
static let feesDisclaimer = NSLocalizedString(
"Network fees are set by the %@ and %@ network. [Learn more about fees]()",
comment: ""
)
static let refundDisclaimer = NSLocalizedString(
"Final amount may change due to market activity. By approving this Swap you agree to Blockchain.com’s [Refund Policy]().",
comment: "Refund disclaimer"
)
static let countdown = NSLocalizedString(
"New Quote in: ",
comment: "Quote time to live coundown label."
)
}
enum Button {
static let confirmSwap = NSLocalizedString(
"Swap %@ for %@",
comment: "Swap confirmation button title"
)
}
}
}
|
lgpl-3.0
|
ab70fa0727b2c47fc2160d4d800e8a2b
| 35.095238 | 138 | 0.515831 | 5.875969 | false | false | false | false |
n8iveapps/N8iveKit
|
InterfaceKit/InterfaceKit/source/extensions/UIImageExtensions.swift
|
1
|
2585
|
//
// UIImageExtensions.swift
// N8iveKit
//
// Created by Muhammad Bassio on 6/22/17.
// Copyright © 2017 N8ive Apps. All rights reserved.
//
import UIKit
public extension UIImage {
public func scaled(to size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
draw(in: CGRect(origin: .zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
public func aspectScaled(toFit size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
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 = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
public func aspectScaled(toFill size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
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, true, 0.0)
draw(in: CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
}
|
mit
|
2037d93d6e0ea608422cd80a59c37f0e
| 32.558442 | 110 | 0.684985 | 4.455172 | false | false | false | false |
kumapo/ScrollableTabs
|
Example/ScrollableTabs-Example/AnotherChildViewController.swift
|
1
|
1832
|
//
// AnotherChildViewController.swift
// ScrollableTabs
//
// Created by kumapo on 2015/09/01.
// Copyright © 2015年 CocoaPods. All rights reserved.
//
import UIKit
import ScrollableTabs
class AnotherChildViewController: UIViewController, ScrollableTabBarContentableController {
lazy var item: UIBarButtonItem = {
let content = UIButton(type: .custom)
content.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
content.setImage(UIImage(named: "tabKbPlusD"), for: UIControlState())
content.setImage(UIImage(named: "tabKbPlusE"), for: .selected)
content.imageView!.contentMode = .scaleToFill
return UIBarButtonItem(customView: content)
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.darkGray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
07ff02bcd984d3536b72c6c7e3251eec
| 30.534483 | 106 | 0.673045 | 4.877333 | false | false | false | false |
Vaseltior/OYThisUI
|
Sources/OYTProgressView.swift
|
1
|
3706
|
/*
Copyright 2011-present Samuel GRAU
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import QuartzCore
/**
A progress view that reflects a loading on the screen
*/
public class OYTProgressView: OYTView {
public var viewHeight: CGFloat = 4.0
/**
This function is called by the init(frame) and the init(coder) methods,
so that there is no need to implement further methods in the subclasses.
*/
public override func commonInitialization() {
super.commonInitialization()
}
/**
Tells the view that its superview is about to change to the specified superview.
- parameter newSuperview: A view object that will be the new superview of the receiver.
This object may be nil.
*/
public override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
// Ok, the view is about to be added/removed from the superview
if let superView = newSuperview {
// We should compute the new frame
let f = superView.frame
var newFrame = CGRect(x: 0, y: 0, width: 0, height: 0)
// Compute a different frame for the view depending on the selected position
switch OYTProgressViewManager.sharedInstance.position {
case .Top:
newFrame = CGRect(
x: 0,
y: 0,
width: f.size.width,
height: self.viewHeight
)
case .Bottom:
newFrame = CGRect(
x: 0,
y: f.size.height-self.viewHeight,
width: f.size.width,
height: self.viewHeight
)
}
self.backgroundColor = OYTProgressViewManager.sharedInstance.color
self.frame = newFrame
}
// View is removed from its parent view there is no real else
}
/**
Starts the animation
- parameter leftToRight: should the animation go from left to right or right to left
- parameter duration: the duration of the animation
*/
public func initializeAnimation(leftToRight: Bool, animationDuration duration: CFTimeInterval) {
// We remove any existing animation, because we don't want the animations
// to be cumulated.
self.layer.removeAllAnimations()
self.layer.addAnimation(
self.progressAnimation(leftToRight, animationDuration: duration),
forKey: "OYTProgressViewAnimation" // <- Prety sure there won't be collision with another animation
)
}
/**
Build the animation
- parameter leftToRight: should the animation go from left to right or right to left
- parameter duration: the duration of the animation
- returns: the configured animation to use for the progress view
*/
private func progressAnimation(leftToRight: Bool, animationDuration duration: CFTimeInterval) -> CAAnimation {
// Animation along the x axis
let animation: CABasicAnimation = CABasicAnimation(keyPath: "position.x")
animation.fromValue = leftToRight ? -frame.size.width : frame.size.width * 2
animation.toValue = leftToRight ? frame.size.width * 2 : -frame.size.width
animation.duration = duration
animation.fillMode = kCAFillModeBoth
animation.repeatCount = Float.infinity
return animation
}
}
|
apache-2.0
|
ecfcf400c805385910b97f47cdefcec1
| 31.79646 | 112 | 0.695089 | 4.751282 | false | false | false | false |
TouchInstinct/LeadKit
|
TIMoyaNetworking/Sources/NetworkService/DefaultJsonNetworkService.swift
|
1
|
9507
|
//
// Copyright (c) 2022 Touch Instinct
//
// 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 TINetworking
import Alamofire
import Moya
import TISwiftUtils
import Foundation
import TIFoundationUtils
open class DefaultJsonNetworkService: ApiInteractor {
public typealias NetworkError = MoyaError
public var session: Session
public var serializationQueue: DispatchQueue = .global(qos: .default)
public var callbackQueue: DispatchQueue = .main
public var decodableSuccessStatusCodes: Set<Int>? = nil
public var decodableFailureStatusCodes: Set<Int>? = nil
public var jsonDecoder: JSONDecoder
public var jsonEncoder: JSONEncoder
public var openApi: OpenAPI
public var plugins: [PluginType] = []
public var preprocessors: [EndpointRequestPreprocessor] = []
public init(session: Session,
jsonCodingConfigurator: JsonCodingConfigurator,
openApi: OpenAPI) {
self.session = session
self.jsonDecoder = jsonCodingConfigurator.jsonDecoder
self.jsonEncoder = jsonCodingConfigurator.jsonEncoder
self.openApi = openApi
}
open func createProvider() -> MoyaProvider<SerializedRequest> {
MoyaProvider<SerializedRequest>(callbackQueue: serializationQueue,
session: session,
plugins: plugins)
}
open func serialize<B: Encodable, S: Decodable>(request: EndpointRequest<B, S>) throws -> SerializedRequest {
try request.serialize(using: ApplicationJsonBodySerializer(jsonEncoder: jsonEncoder),
defaultServer: openApi.defaultServer)
}
open func process<B: Encodable, S: Decodable, F: Decodable, R>(request: EndpointRequest<B, S>,
mapSuccess: @escaping Closure<S, R>,
mapFailure: @escaping Closure<F, R>,
mapNetworkError: @escaping Closure<MoyaError, R>,
completion: @escaping ParameterClosure<R>) -> TIFoundationUtils.Cancellable {
ScopeCancellable { [serializationQueue, callbackQueue, preprocessors] scope in
Self.preprocess(request: request,
preprocessors: preprocessors) {
switch $0 {
case let .success(preprocessedRequest):
let workItem = DispatchWorkItem {
guard !scope.isCancelled else {
return
}
do {
let serializedRequest = try self.serialize(request: preprocessedRequest)
self.process(request: serializedRequest,
mapSuccess: mapSuccess,
mapFailure: mapFailure,
mapNetworkError: mapNetworkError,
completion: completion)
.add(to: scope)
} catch {
callbackQueue.async {
completion(mapNetworkError(.encodableMapping(error)))
}
}
}
workItem.add(to: scope)
serializationQueue.async(execute: workItem)
case let .failure(error):
callbackQueue.async {
completion(mapNetworkError(.encodableMapping(error)))
}
}
}
}
}
open func process<S: Decodable, F: Decodable, R>(request: SerializedRequest,
mapSuccess: @escaping Closure<S, R>,
mapFailure: @escaping Closure<F, R>,
mapNetworkError: @escaping Closure<MoyaError, R>,
completion: @escaping ParameterClosure<R>) -> TIFoundationUtils.Cancellable {
createProvider().request(request) { [jsonDecoder,
callbackQueue,
decodableSuccessStatusCodes,
decodableFailureStatusCodes,
plugins] in
let result: R
switch $0 {
case let .success(rawResponse):
let successStatusCodes: Set<Int>
let failureStatusCodes: Set<Int>
switch (decodableSuccessStatusCodes, decodableFailureStatusCodes) {
case let (successCodes?, failureCodes?):
successStatusCodes = successCodes
failureStatusCodes = failureCodes
case let (nil, failureCodes?):
successStatusCodes = request.acceptableStatusCodes.subtracting(failureCodes)
failureStatusCodes = failureCodes
case let (successCodes?, nil):
successStatusCodes = successCodes
failureStatusCodes = request.acceptableStatusCodes.subtracting(successCodes)
default:
successStatusCodes = HTTPCodes.success.asSet() // default success status codes if nothing was passed
failureStatusCodes = request.acceptableStatusCodes.subtracting(successStatusCodes)
}
let decodeResult = rawResponse.decode(mapping: [
((successStatusCodes, CommonMediaTypes.applicationJson.rawValue), jsonDecoder.decoding(to: mapSuccess)),
((failureStatusCodes, CommonMediaTypes.applicationJson.rawValue), jsonDecoder.decoding(to: mapFailure)),
])
let pluginResult: Result<Response, MoyaError>
switch decodeResult {
case let .success(model):
result = model
pluginResult = .success(rawResponse)
case let .failure(moyaError):
result = mapNetworkError(moyaError)
pluginResult = .failure(moyaError)
}
plugins.forEach {
$0.didReceive(pluginResult, target: request)
}
case let .failure(moyaError):
result = mapNetworkError(moyaError)
}
callbackQueue.async {
completion(result)
}
}
.asFoundationUtilsCancellable()
}
public func register<T: RawRepresentable>(securityPreprocessors: [T: SecuritySchemePreprocessor]) where T.RawValue == String {
let schemePreprocessors = Dictionary(uniqueKeysWithValues: securityPreprocessors.map {
($0.key.rawValue, $0.value)
})
let securityPreprocessor = DefaultEndpointSecurityPreprocessor(openApi: openApi,
schemePreprocessors: schemePreprocessors)
preprocessors.append(securityPreprocessor)
}
private static func preprocess<B,S,P: Collection>(request: EndpointRequest<B,S>,
preprocessors: P,
completion: @escaping (Result<EndpointRequest<B,S>, Error>) -> Void) -> TIFoundationUtils.Cancellable
where P.Element == EndpointRequestPreprocessor {
guard let preprocessor = preprocessors.first else {
completion(.success(request))
return Cancellables.nonCancellable()
}
return ScopeCancellable { scope in
preprocessor.preprocess(request: request) {
switch $0 {
case let .success(modifiedRequest):
preprocess(request: modifiedRequest,
preprocessors: preprocessors.dropFirst(),
completion: completion)
.add(to: scope)
case let .failure(error):
completion(.failure(error))
}
}
}
}
}
|
apache-2.0
|
581b594f30c96e81d458117ae9464af5
| 43.013889 | 155 | 0.551488 | 6.067007 | false | false | false | false |
vector-im/vector-ios
|
RiotSwiftUI/Modules/Template/TemplateAdvancedRoomsExample/TemplateRoomChat/Test/Unit/TemplateRoomChatViewModelTests.swift
|
1
|
2436
|
//
// Copyright 2021 New Vector Ltd
//
// 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 XCTest
import Combine
@testable import RiotSwiftUI
@available(iOS 14.0, *)
class TemplateRoomChatViewModelTests: XCTestCase {
var service: MockTemplateRoomChatService!
var viewModel: TemplateRoomChatViewModel!
var context: TemplateRoomChatViewModel.Context!
var cancellables = Set<AnyCancellable>()
override func setUpWithError() throws {
service = MockTemplateRoomChatService()
service.simulateUpdate(initializationStatus: .initialized)
viewModel = TemplateRoomChatViewModel(templateRoomChatService: service)
context = viewModel.context
}
func testInitialState() {
XCTAssertEqual(context.viewState.bubbles.count, 3)
XCTAssertEqual(context.viewState.sendButtonEnabled, false)
XCTAssertEqual(context.viewState.roomInitializationStatus, .initialized)
}
func testSendMessageUpdatesReceived() throws {
let bubblesPublisher: AnyPublisher<[[TemplateRoomChatBubble]], Never> = context.$viewState.map(\.bubbles).removeDuplicates().collect(2).first().eraseToAnyPublisher()
let awaitDeferred = xcAwaitDeferred(bubblesPublisher)
let newMessage: String = "Let's Go"
service.send(textMessage: newMessage)
let result: [[TemplateRoomChatBubble]]? = try awaitDeferred()
// Test that the update to the messages in turn updates the view's
// the last bubble by appending another text item, asserting the body.
guard let item:TemplateRoomChatBubbleItem = result?.last?.last?.items.last,
case TemplateRoomChatBubbleItemContent.message(let message) = item.content,
case let TemplateRoomChatMessageContent.text(text) = message else {
XCTFail()
return
}
XCTAssertEqual(text.body, newMessage)
}
}
|
apache-2.0
|
a22ac15b9d6d3219705b00912698ae4c
| 38.290323 | 173 | 0.714286 | 4.842942 | false | true | false | false |
liuchungui/UICollectionViewAnimationDemo
|
BGSimpleImageSelectCollectionViewDemo2/BGSimpleImageSelectCollectionView/BGFoundationKit/Extension/CGRect+BGExtension.swift
|
2
|
1987
|
//
// CGRect+BGExtension.swift
// BGSimpleImageSelectCollectionView
//
// Created by user on 15/10/29.
// Copyright © 2015年 BG. All rights reserved.
//
import UIKit
extension CGRect {
var left: CGFloat {
get {
return self.origin.x
}
set (newValue){
self.origin.x = newValue
}
}
var right: CGFloat {
get {
return self.origin.x + self.size.width
}
set (newValue){
self.origin.x = newValue - self.size.width
}
}
var top: CGFloat {
get {
return self.origin.y
}
set (newValue){
self.origin.y = newValue
}
}
var bottom: CGFloat {
get {
return self.origin.y + self.size.height
}
set (newValue){
self.origin.y = newValue - self.size.height
}
}
var width: CGFloat {
get {
return self.size.width
}
set (newValue) {
self.size.width = newValue
}
}
var height: CGFloat {
get {
return self.size.height
}
set (newValue) {
self.size.height = newValue
}
}
var center: CGPoint {
get {
return CGPointMake(self.origin.x+self.size.width/2.0, self.origin.y+self.size.height/2.0)
}
set (newValue) {
self.origin = CGPointMake(newValue.x-self.size.width/2.0, newValue.y-self.size.height/2.0)
}
}
var centerX: CGFloat {
get {
return self.origin.x+self.size.width/2.0
}
set (newValue) {
self.origin.x = newValue-self.size.width/2.0
}
}
var centerY: CGFloat {
get {
return self.origin.y+self.size.height/2.0
}
set (newValue) {
self.origin.y = newValue-self.size.height/2.0
}
}
}
|
mit
|
0d637c91c125dd25a0a139bbbb44ca5f
| 19.884211 | 102 | 0.480847 | 3.96008 | false | false | false | false |
tjw/swift
|
test/SILOptimizer/definite-init-convert-to-escape.swift
|
1
|
3526
|
// RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module -enable-sil-ownership -Xllvm -sil-disable-convert-escape-to-noescape-switch-peephole %s | %FileCheck %s --check-prefix=NOPEEPHOLE
// REQUIRES: objc_interop
import Foundation
// Make sure that we keep the escaping closures alive accross the ultimate call.
// CHECK-LABEL: sil @$S1A19bridgeNoescapeBlock5optFn0D3Fn2yySSSgcSg_AFtF
// CHECK: bb0
// CHECK: retain_value %0
// CHECK: retain_value %0
// CHECK: bb2
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release
// CHECK: bb6
// CHECK: retain_value %1
// CHECK: retain_value %1
// CHECK: bb8
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release
// CHECK: bb12
// CHECK: [[F:%.*]] = function_ref @noescapeBlock3
// CHECK: apply [[F]]
// CHECK: release_value {{.*}} : $Optional<NSString>
// CHECK: release_value %1 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>) -> ()>
// CHECK: release_value %0 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>)
public func bridgeNoescapeBlock( optFn: ((String?) -> ())?, optFn2: ((String?) -> ())?) {
noescapeBlock3(optFn, optFn2, "Foobar")
}
@_silgen_name("_returnOptionalEscape")
public func returnOptionalEscape() -> (() ->())?
// Make sure that we keep the escaping closure alive accross the ultimate call.
// CHECK-LABEL: sil @$S1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[V0:%.*]] = function_ref @_returnOptionalEscape
// CHECK: [[V1:%.*]] = apply [[V0]]
// CHECK: retain_value [[V1]]
// CHECK: switch_enum {{.*}}bb2
// CHECK: bb2([[V2:%.*]]: $@callee_guaranteed () -> ()):
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release [[V2]]
// CHECK: bb6({{.*}} : $Optional<@convention(block) @noescape () -> ()>)
// CHECK: [[F:%.*]] = function_ref @noescapeBlock
// CHECK: apply [[F]]({{.*}})
// CHECK: release_value [[V1]] : $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE-LABEL: sil @$S1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () {
// NOPEEPHOLE: bb0:
// NOPEEPHOLE: [[SLOT:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE: [[NONE:%.*]] = enum $Optional
// NOPEEPHOLE: store [[NONE]] to [[SLOT]]
// NOPEEPHOLE: [[V0:%.*]] = function_ref @_returnOptionalEscape
// NOPEEPHOLE: [[V1:%.*]] = apply [[V0]]
// NOPEEPHOLE: switch_enum {{.*}}bb2
// NOPEEPHOLE: bb2([[V2:%.*]]: $@callee_guaranteed () -> ()):
// NOPEEPHOLE: destroy_addr [[SLOT]]
// NOPEEPHOLE: [[SOME:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[V2]]
// NOPEEPHOLE: store [[SOME]] to [[SLOT]]
// NOPEEPHOLE: convert_escape_to_noescape %
// NOPEEPHOLE-NOT: strong_release
// NOPEEPHOLE: br
// NOPEEPHOLE: bb6({{.*}} : $Optional<@convention(block) @noescape () -> ()>)
// NOPEEPHOLE: [[F:%.*]] = function_ref @noescapeBlock
// NOPEEPHOLE: apply [[F]]({{.*}})
// NOPEEPHOLE: destroy_addr [[SLOT]]
// NOPEEPHOLE: dealloc_stack [[SLOT]]
public func bridgeNoescapeBlock() {
noescapeBlock(returnOptionalEscape())
}
|
apache-2.0
|
f988d5423305ce66e44ee6fb4561385a
| 44.205128 | 279 | 0.650312 | 3.18231 | false | false | false | false |
SwiftStudies/OysterKit
|
Sources/OysterKit/Decoding/Parsing Decoder.swift
|
1
|
64195
|
// Copyright (c) 2014, RED When Excited
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Createed with heavy reference to: https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/JSONEncoder.swift#L802
//
import Foundation
/**
This protocol identifies as set of additional requirements for `Node`s in order for them to be used for decoding. Some elements of the implementation are
provided through an extension.
*/
public protocol DecodeableAbstractSyntaxTree : AbstractSyntaxTree{
/// The String the was matched for the node
var stringValue : String {get}
/// Should be the `CodingKey` for this node. This is normally generated using the name of the `Token`.
var key : CodingKey {get}
/// Should be the children of this node
var contents : [DecodeableAbstractSyntaxTree] {get}
/**
Should return the child node at the supplied `index`. A default implementation is provided through an extension.
-Parameter index: The index of the desired child
-Returns: The child node
*/
subscript(_ index:Int)->DecodeableAbstractSyntaxTree {get}
/**
Should return the child node with the specified `CodingKey` or `nil` if it does not exist. A default implementation
is provided through an extension.
-Parameter key: The key of the desired child
-Returns: The child node, or `nil` if not found
*/
subscript(key codingKey:CodingKey)->DecodeableAbstractSyntaxTree? {get}
/**
Should return the child node with the specified `String` as a key or `nil` if it does not exist. A default implementation
is provided through an extension.
-Parameter name: The name of the desired child
-Returns: The child node, or `nil` if not found
*/
subscript(_ name:String)->DecodeableAbstractSyntaxTree? {get}
}
/// Provide standard implementations of the subscripting requirements
public extension DecodeableAbstractSyntaxTree{
/**
Returns the child node at the supplied `index`
-Parameter index: The index of the desired child
-Returns: The child node
*/
public subscript(key codingKey: CodingKey) -> DecodeableAbstractSyntaxTree? {
for child in contents {
if child.key.stringValue == codingKey.stringValue {
return child
}
}
return nil
}
/**
Returns the child node at the supplied `index`
-Parameter index: The index of the desired child
-Returns: The child node
*/
public subscript(_ name: String) -> DecodeableAbstractSyntaxTree? {
for child in contents {
if child.key.stringValue == name {
return child
}
}
return nil
}
/**
Returns the child node with the specified `CodingKey` or `nil` if it does not exist. A default implementation
is provided through an extension.
-Parameter key: The key of the desired child
-Returns: The child node, or `nil` if not found
*/
public subscript(_ index: Int) -> DecodeableAbstractSyntaxTree {
return contents[index]
}
}
extension CodingKey {
/**
Determines if two coding keys are equal
- Parameter rhs: The other `CodingKey` to compare to
- Returns: `true` if they are the same, `false` otherwise
*/
func equals(rhs:CodingKey)->Bool{
guard let lhsInt = self.intValue, let rhsInt = rhs.intValue else {
return self.stringValue == rhs.stringValue
}
return lhsInt == rhsInt
}
}
/// Extends the standard `HomogenousTree` so it is Decodable
extension HomogenousTree : DecodeableAbstractSyntaxTree {
/// The string that was captured by this node
public var stringValue: String {
return matchedString
}
/// The `CodingKey` for this node. This is normally generated using the name of the
/// token.
public var key: CodingKey {
return _ParsingKey(token: token)
}
/// The children of this node
public var contents: [DecodeableAbstractSyntaxTree]{
return children
}
}
/**
A standard decoder that can use any supplied `Parser` to decode `Data` into a `Decodable` conforming type.
do{
let command : Command = try ParsingDecoder().decode(Command.self, from: userInput.data(using: .utf8) ?? Data(), with: Bork.generatedLanguage)
...
} catch {
print("Something went wrong: \(error.localizedDescription)")
}
The names of the `Token`s generated by the supplied `Parser` are used as keys into the `Decodable` type being populated.
*/
public struct ParsingDecoder{
/// Create an instance of `ParsingDecoder`
public init(){
}
/**
Decodes the supplied data using the supplied parser into the specified object. The names of the `TokenType`s generated by the
supplied `Parser` are used as keys into the `Decodable` type being populated.
- Parameter type: A type conforming to `Decodable`
- Parameter ast: The AbstractSyntaxTree representation
- Returns: An instance of the type
*/
public func decode<T : Decodable>(_ type: T.Type, using ast:DecodeableAbstractSyntaxTree) throws -> T {
let decoder = _ParsingDecoder(referencing: ast)
do {
return try T(from: decoder)
} catch {
if let error = error as? DecodingError {
if #available(OSX 10.14, *) {
#if canImport(NaturalLanguage)
Log.decodingError(error)
#endif
} else {
// Fallback on earlier versions
}
}
if let ast = ast as? HomogenousTree {
print(ast.description)
}
throw error
}
}
/**
Decodes the supplied data using the supplied parser into the specified object. The names of the `TokenType`s generated by the
supplied `Parser` are used as keys into the `Decodable` type being populated.
- Parameter type: A type conforming to `Decodable`
- Parameter ast: The AbstractSyntaxTree representation
- Returns: An instance of the type
*/
public func decode<T : Decodable>(_ type: T.Type, from source:String, using language:Grammar) throws -> T {
do {
let ast = try AbstractSyntaxTreeConstructor().build(source, using: language)
let decoder = _ParsingDecoder(referencing: ast)
return try T(from: decoder)
} catch {
if let error = error as? DecodingError {
if #available(OSX 10.14, *) {
#if canImport(NaturalLanguage)
Log.decodingError(error)
#endif
} else {
// Fallback on earlier versions
}
}
throw error
}
}
}
fileprivate class _ParsingDecoder : Decoder{
// MARK: Properties
/// The decoder's storage.
fileprivate var storage: _ParsingDecodingStorage
/// The path to the current point in encoding.
private(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] = [:]
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
fileprivate init(referencing container: DecodeableAbstractSyntaxTree, at codingPath: [CodingKey] = []) {
self.storage = _ParsingDecodingStorage()
self.storage.push(container: container)
self.codingPath = codingPath
}
// MARK: - Coding Path Operations
/// Performs the given closure with the given key pushed onto the end of the current coding path.
///
/// - parameter key: The key to push. May be nil for unkeyed containers.
/// - parameter work: The work to perform with the key in the path.
fileprivate func with<T>(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T {
self.codingPath.append(key)
let ret: T = try work()
self.codingPath.removeLast()
return ret
}
// MARK: - Decoder Methods
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
let topContainer = storage.topContainer
let container = _ParsingKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
let topContainer = self.storage.topContainer
return _STLRUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
fileprivate struct _ParsingDecodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]).
private(set) fileprivate var containers: [DecodeableAbstractSyntaxTree] = []
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate var topContainer: DecodeableAbstractSyntaxTree {
precondition(self.containers.count > 0, "Empty container stack.")
return self.containers.last!
}
fileprivate mutating func push(container: DecodeableAbstractSyntaxTree) {
self.containers.append(container)
}
fileprivate mutating func popContainer() {
precondition(self.containers.count > 0, "Empty container stack.")
self.containers.removeLast()
}
}
fileprivate struct TokenKey: TokenType, CodingKey{
fileprivate var rawValue: Int
var stringValue: String
init(token:TokenType){
rawValue = token.rawValue
stringValue = "\(token)"
}
init?(stringValue: String) {
self.stringValue = stringValue
self.rawValue = 0
}
var intValue: Int? {
return rawValue
}
init?(intValue: Int) {
rawValue = intValue
stringValue = "\(intValue)"
}
}
fileprivate struct _ParsingKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _ParsingDecoder
/// A reference to the container we're reading from.
private let container: DecodeableAbstractSyntaxTree
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _ParsingDecoder, wrapping container: DecodeableAbstractSyntaxTree) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
}
// MARK: - KeyedDecodingContainerProtocol Methods
public var allKeys: [Key] {
return container.contents.map { (node) -> Key in
Key(stringValue: node.key.stringValue)!
// node.key
}
}
public func contains(_ key: Key) -> Bool {
//This can't be right
return self.container[key: key] != nil
}
public func decodeNil(forKey key: Key) throws -> Bool {
guard let _ = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
//If it's there, it's not nil
return false
}
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
return try self.decoder.with(pushedKey: key) {
guard let value = try self.decoder.unbox(entry.stringValue, as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
}
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = Int(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = Int8(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = Int16(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = Int32(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = Int64(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = UInt(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = UInt8(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = UInt16(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = UInt32(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = UInt64(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = Float(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let result = Double(entry.stringValue) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but couldn't convert \(entry) to it"))
}
return result
}
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
let stringValue = entry.stringValue
return stringValue
}
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = self.container[key: key] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
return try self.decoder.with(pushedKey: key) {
guard let value = try self.decoder.unbox(entry, as: T.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
}
public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
return try self.decoder.with(pushedKey: key) {
guard let value = self.container[key: key] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \"\(key.stringValue)\""))
}
// guard let dictionary = value as? [String : Any] else {
// throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
// }
let container = _ParsingKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: value)
return KeyedDecodingContainer(container)
}
}
public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
return try self.decoder.with(pushedKey: key) {
guard let value = self.container[key: key] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \"\(key.stringValue)\""))
}
// guard let array = value as? [Any] else {
// throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
// }
//Or should it be value.children and something clever
return _STLRUnkeyedDecodingContainer(referencing: self.decoder, wrapping: value)
}
}
private func _superDecoder(forKey key: CodingKey) throws -> Decoder {
return self.decoder.with(pushedKey: key) {
let value = self.container[key: key]
return _ParsingDecoder(referencing: value!, at: self.decoder.codingPath)
}
}
public func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: _ParsingKey.super)
}
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
}
fileprivate struct _ParsingKey : CodingKey{
public var stringValue: String
init(token:TokenType){
stringValue = "\(token)"
intValue = token.rawValue
}
init(index:Int){
stringValue="Index \(index)"
intValue = index
}
public init?(stringValue: String) {
return nil
}
public var intValue: Int?
public init?(intValue: Int) {
return nil
}
static var `super` : _ParsingKey {
fatalError()
}
}
extension _ParsingDecoder : SingleValueDecodingContainer{
var node : DecodeableAbstractSyntaxTree {
return storage.topContainer
}
func decodeNil() -> Bool {
return false
}
func decode(_ type: Bool.Type) throws -> Bool {
if let boolValue = type.init(node.stringValue){
return boolValue
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: Int.Type) throws -> Int {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: Int8.Type) throws -> Int8 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: Int16.Type) throws -> Int16 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: Int32.Type) throws -> Int32 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: Int64.Type) throws -> Int64 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: UInt.Type) throws -> UInt {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: Float.Type) throws -> Float {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: Double.Type) throws -> Double {
if let value = type.init(node.stringValue){
return value
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(node.stringValue) can't be represented as a \(type)"))
}
func decode(_ type: String.Type) throws -> String {
return node.stringValue
}
public func decode<T : Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(T.self)
return try self.unbox(self.storage.topContainer, as: T.self)!
}
private func expectNonNull<T>(_ type: T.Type) throws {
guard !self.decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
}
fileprivate struct _STLRUnkeyedDecodingContainer : UnkeyedDecodingContainer {
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _ParsingDecoder
/// A reference to the container we're reading from.
private let container: DecodeableAbstractSyntaxTree
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
/// The index of the element we're about to decode.
private(set) public var currentIndex: Int
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _ParsingDecoder, wrapping container: DecodeableAbstractSyntaxTree) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
self.currentIndex = 0
}
// MARK: - UnkeyedDecodingContainer Methods
public var count: Int? {
return self.container.contents.count
}
public var isAtEnd: Bool {
return self.currentIndex >= self.count!
}
public mutating func decodeNil() throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(intValue: self.currentIndex)!], debugDescription: "Unkeyed container is at end."))
}
return false
}
public mutating func decode(_ type: Bool.Type) throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: Int.Type) throws -> Int {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: Int8.Type) throws -> Int8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: Int16.Type) throws -> Int16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: Int32.Type) throws -> Int32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: Int64.Type) throws -> Int64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: UInt.Type) throws -> UInt {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: Float.Type) throws -> Float {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: Double.Type) throws -> Double {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode(_ type: String.Type) throws -> String {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: T.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_ParsingKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
}
public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
self.currentIndex += 1
let container = _ParsingKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: value)
return KeyedDecodingContainer(container)
}
}
public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
// guard !(value is NSNull) else {
// throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
// DecodingError.Context(codingPath: self.codingPath,
// debugDescription: "Cannot get keyed decoding container -- found null value instead."))
// }
//
// guard let array = value as? [Any] else {
// throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
// }
self.currentIndex += 1
return _STLRUnkeyedDecodingContainer(referencing: self.decoder, wrapping: value)
}
}
public mutating func superDecoder() throws -> Decoder {
return try self.decoder.with(pushedKey: _ParsingKey(index: self.currentIndex)) {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Decoder.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get superDecoder() -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
self.currentIndex += 1
return _ParsingDecoder(referencing: value, at: self.decoder.codingPath)
}
}
}
fileprivate extension _ParsingDecoder {
/// Returns the given value unboxed from a container.
fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
if let string = value as? String, let boolean = Bool(string) {
return boolean
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
// TODO: Add a flag to coerce non-boolean numbers into Bools?
// guard number._cfTypeID == CFBooleanGetTypeID() else {
// throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
// }
return number.boolValue
}
fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let int = number.intValue
guard NSNumber(value: int) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int
}
fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let int8 = number.int8Value
guard NSNumber(value: int8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int8
}
fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let int16 = number.int16Value
guard NSNumber(value: int16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int16
}
fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let int32 = number.int32Value
guard NSNumber(value: int32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int32
}
fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let int64 = number.int64Value
guard NSNumber(value: int64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int64
}
fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let uint = number.uintValue
guard NSNumber(value: uint) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint
}
fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let uint8 = number.uint8Value
guard NSNumber(value: uint8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint8
}
fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let uint16 = number.uint16Value
guard NSNumber(value: uint16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint16
}
fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let uint32 = number.uint32Value
guard NSNumber(value: uint32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint32
}
fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) and got \(value)"))
}
let uint64 = number.uint64Value
guard NSNumber(value: uint64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint64
}
fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber {
// We are willing to return a Float by losing precision:
// * If the original value was integral,
// * and the integral value was > Float.greatestFiniteMagnitude, we will fail
// * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24
// * If it was a Float, you will get back the precise value
// * If it was a Double or Decimal, you will get back the nearest approximation if it will fit
let double = number.doubleValue
guard abs(double) <= Double(Float.greatestFiniteMagnitude) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type)."))
}
return Float(double)
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
if abs(double) <= Double(Float.max) {
return Float(double)
}
overflow = true
} else if let int = value as? Int {
if let float = Float(exactly: int) {
return float
}
overflow = true
*/
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got \(value)"))
}
fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber {
// We are always willing to return the number as a Double:
// * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double
// * If it was a Float or Double, you will get back the precise value
// * If it was Decimal, you will get back the nearest approximation
return number.doubleValue
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
return double
} else if let int = value as? Int {
if let double = Double(exactly: int) {
return double
}
overflow = true
*/
}
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got \(value)"))
}
fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got \(value)"))
}
return string
}
fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
guard !(value is NSNull) else { return nil }
// switch self.options.dateDecodingStrategy {
// case .deferredToDate:
// self.storage.push(container: value)
// let date = try Date(from: self)
// self.storage.popContainer()
// return date
//
// case .secondsSince1970:
// let double = try self.unbox(value, as: Double.self)!
// return Date(timeIntervalSince1970: double)
//
// case .millisecondsSince1970:
// let double = try self.unbox(value, as: Double.self)!
// return Date(timeIntervalSince1970: double / 1000.0)
//
// case .iso8601:
// if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
// let string = try self.unbox(value, as: String.self)!
// guard let date = _iso8601Formatter.date(from: string) else {
// throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
// }
//
// return date
// } else {
// fatalError("ISO8601DateFormatter is unavailable on this platform.")
// }
//
// case .formatted(let formatter):
// let string = try self.unbox(value, as: String.self)!
// guard let date = formatter.date(from: string) else {
// throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter."))
// }
//
// return date
//
// case .custom(let closure):
// self.storage.push(container: value)
// let date = try closure(self)
// self.storage.popContainer()
// return date
// }
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Expected \(type) but got \(value)"))
}
fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "\(type) but expected \(value)"))
}
guard let data = Data(base64Encoded: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64."))
}
return data
}
fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? {
guard !(value is NSNull) else { return nil }
// On Darwin we get (value as? Decimal) since JSONSerialization can produce NSDecimalNumber values.
// FIXME: Attempt to grab a Decimal value if JSONSerialization on Linux produces one.
let doubleValue = try self.unbox(value, as: Double.self)!
return Decimal(doubleValue)
}
fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
let decoded: T
if T.self == Date.self {
guard let date = try self.unbox(value, as: Date.self) else { return nil }
decoded = date as! T
} else if T.self == Data.self {
guard let data = try self.unbox(value, as: Data.self) else { return nil }
decoded = data as! T
} else if T.self == URL.self {
guard let urlString = try self.unbox(value, as: String.self) else {
return nil
}
guard let url = URL(string: urlString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Invalid URL string."))
}
decoded = (url as! T)
} else if T.self == Decimal.self {
guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil }
decoded = decimal as! T
} else {
self.storage.push(container: value as! DecodeableAbstractSyntaxTree)
decoded = try T(from: self)
self.storage.popContainer()
}
return decoded
}
}
|
bsd-2-clause
|
ca22263be7daaf755908d1e83e00cb69
| 43.860238 | 219 | 0.62575 | 4.985632 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Widgets/PhotonActionSheet/AppMenu.swift
|
1
|
6220
|
/* 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 Shared
import Account
extension PhotonActionSheetProtocol {
//Returns a list of actions which is used to build a menu
//OpenURL is a closure that can open a given URL in some view controller. It is up to the class using the menu to know how to open it
func getLibraryActions(vcDelegate: PageOptionsVC) -> [PhotonActionSheetItem] {
guard let tab = self.tabManager.selectedTab else { return [] }
let openLibrary = PhotonActionSheetItem(title: Strings.AppMenuLibraryTitleString, iconString: "menu-library") { _, _ in
let bvc = vcDelegate as? BrowserViewController
bvc?.showLibrary()
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .library)
}
let openHomePage = PhotonActionSheetItem(title: Strings.AppMenuOpenHomePageTitleString, iconString: "menu-Home") { _, _ in
let page = NewTabAccessors.getHomePage(self.profile.prefs)
if page == .homePage, let homePageURL = HomeButtonHomePageAccessors.getHomePage(self.profile.prefs) {
tab.loadRequest(PrivilegedRequest(url: homePageURL) as URLRequest)
} else if let homePanelURL = page.url {
tab.loadRequest(PrivilegedRequest(url: homePanelURL) as URLRequest)
}
}
return [openHomePage, openLibrary]
}
func getOtherPanelActions(vcDelegate: PageOptionsVC) -> [PhotonActionSheetItem] {
var items: [PhotonActionSheetItem] = []
let noImageEnabled = NoImageModeHelper.isActivated(profile.prefs)
let noImageMode = PhotonActionSheetItem(title: Strings.AppMenuNoImageMode, iconString: "menu-NoImageMode", isEnabled: noImageEnabled, accessory: .Switch, badgeIconNamed: "menuBadge") { action,_ in
NoImageModeHelper.toggle(isEnabled: action.isEnabled, profile: self.profile, tabManager: self.tabManager)
}
items.append(noImageMode)
let nightModeEnabled = NightModeHelper.isActivated(profile.prefs)
let nightMode = PhotonActionSheetItem(title: Strings.AppMenuNightMode, iconString: "menu-NightMode", isEnabled: nightModeEnabled, accessory: .Switch) { _, _ in
NightModeHelper.toggle(self.profile.prefs, tabManager: self.tabManager)
// If we've enabled night mode and the theme is normal, enable dark theme
if NightModeHelper.isActivated(self.profile.prefs), ThemeManager.instance.currentName == .normal {
ThemeManager.instance.current = DarkTheme()
NightModeHelper.setEnabledDarkTheme(self.profile.prefs, darkTheme: true)
}
// If we've disabled night mode and dark theme was activated by it then disable dark theme
if !NightModeHelper.isActivated(self.profile.prefs), NightModeHelper.hasEnabledDarkTheme(self.profile.prefs), ThemeManager.instance.currentName == .dark {
ThemeManager.instance.current = NormalTheme()
NightModeHelper.setEnabledDarkTheme(self.profile.prefs, darkTheme: false)
}
}
items.append(nightMode)
let openSettings = PhotonActionSheetItem(title: Strings.AppMenuSettingsTitleString, iconString: "menu-Settings") { _, _ in
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = self.profile
settingsTableViewController.tabManager = self.tabManager
settingsTableViewController.settingsDelegate = vcDelegate
let controller = ThemedNavigationController(rootViewController: settingsTableViewController)
// On iPhone iOS13 the WKWebview crashes while presenting file picker if its not full screen. Ref #6232
if UIDevice.current.userInterfaceIdiom == .phone {
controller.modalPresentationStyle = .fullScreen
}
controller.presentingModalViewControllerDelegate = vcDelegate
// Wait to present VC in an async dispatch queue to prevent a case where dismissal
// of this popover on iPad seems to block the presentation of the modal VC.
DispatchQueue.main.async {
vcDelegate.present(controller, animated: true, completion: nil)
}
}
items.append(openSettings)
return items
}
func syncMenuButton(showFxA: @escaping (_ params: FxALaunchParams?, _ flowType: FxAPageType,_ referringPage: ReferringPage) -> Void) -> PhotonActionSheetItem? {
//profile.getAccount()?.updateProfile()
let action: ((PhotonActionSheetItem, UITableViewCell) -> Void) = { action,_ in
let fxaParams = FxALaunchParams(query: ["entrypoint": "browsermenu"])
showFxA(fxaParams, .emailLoginFlow, .appMenu)
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .signIntoSync)
}
let rustAccount = RustFirefoxAccounts.shared
let needsReauth = rustAccount.accountNeedsReauth()
guard let userProfile = rustAccount.userProfile else {
return PhotonActionSheetItem(title: Strings.FxASignInToSync, iconString: "menu-sync", handler: action)
}
let title: String = {
if rustAccount.accountNeedsReauth() {
return Strings.FxAAccountVerifyPassword
}
return userProfile.displayName ?? userProfile.email
}()
let iconString = needsReauth ? "menu-warning" : "placeholder-avatar"
var iconURL: URL? = nil
if let str = rustAccount.userProfile?.avatarUrl, let url = URL(string: str) {
iconURL = url
}
let iconType: PhotonActionSheetIconType = needsReauth ? .Image : .URL
let iconTint: UIColor? = needsReauth ? UIColor.Photon.Yellow60 : nil
let syncOption = PhotonActionSheetItem(title: title, iconString: iconString, iconURL: iconURL, iconType: iconType, iconTint: iconTint, accessory: .Sync, handler: action)
return syncOption
}
}
|
mpl-2.0
|
77440a9183bbd052b31b8919dbd37e86
| 52.62069 | 204 | 0.682315 | 5.127782 | false | false | false | false |
zapdroid/RXWeather
|
Pods/RxSwift/RxSwift/Observables/Implementations/TakeWhile.swift
|
1
|
3544
|
//
// TakeWhile.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class TakeWhileSink<O: ObserverType>
: Sink<O>
, ObserverType {
typealias Element = O.E
typealias Parent = TakeWhile<Element>
fileprivate let _parent: Parent
fileprivate var _running = true
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case let .next(value):
if !_running {
return
}
do {
_running = try _parent._predicate(value)
} catch let e {
forwardOn(.error(e))
dispose()
return
}
if _running {
forwardOn(.next(value))
} else {
forwardOn(.completed)
dispose()
}
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
final class TakeWhileSinkWithIndex<O: ObserverType>
: Sink<O>
, ObserverType {
typealias Element = O.E
typealias Parent = TakeWhile<Element>
fileprivate let _parent: Parent
fileprivate var _running = true
fileprivate var _index = 0
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case let .next(value):
if !_running {
return
}
do {
_running = try _parent._predicateWithIndex(value, _index)
_ = try incrementChecked(&_index)
} catch let e {
forwardOn(.error(e))
dispose()
return
}
if _running {
forwardOn(.next(value))
} else {
forwardOn(.completed)
dispose()
}
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
final class TakeWhile<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
typealias PredicateWithIndex = (Element, Int) throws -> Bool
fileprivate let _source: Observable<Element>
fileprivate let _predicate: Predicate!
fileprivate let _predicateWithIndex: PredicateWithIndex!
init(source: Observable<Element>, predicate: @escaping Predicate) {
_source = source
_predicate = predicate
_predicateWithIndex = nil
}
init(source: Observable<Element>, predicate: @escaping PredicateWithIndex) {
_source = source
_predicate = nil
_predicateWithIndex = predicate
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
if let _ = _predicate {
let sink = TakeWhileSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
} else {
let sink = TakeWhileSinkWithIndex(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
}
|
mit
|
aa9f028b147a19df3a626e06d3af1f15
| 26.679688 | 144 | 0.55151 | 4.853425 | false | false | false | false |
NGeenLibraries/NGeen
|
NGeenTemplateTests/NGeen/Network/Session/SessionManagerTests.swift
|
1
|
4438
|
//
// SessionManagerTests.swift
// Copyright (c) 2014 NGeen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
class SessionManagerTests: XCTestCase {
var session: SessionManager?
override func setUp() {
super.setUp()
self.session = SessionManager(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
self.session!.responseDisposition = NSURLSessionResponseDisposition.Allow
// 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()
self.session = nil
}
func testThatDownloadTask() {
let expectation: XCTestExpectation = expectationWithDescription("download task")
let docsDir: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
let destination: NSURL = NSURL(fileURLWithPath: "\(docsDir)/download.txt")
let request: NSURLRequest = NSURLRequest(URL: NSURL.URLWithString("/stream/\(100)", relativeToURL: kTestUrl))
let task = self.session!.downloadTaskWithRequest(request, destination: destination, progress: nil, completionHandler: {(data, urlResponse, error) in
var isDirectory: UnsafeMutablePointer<ObjCBool> = nil
NSFileManager.defaultManager().fileExistsAtPath(destination.description, isDirectory: isDirectory)
XCTAssert(isDirectory == nil, "The file should exists", file: __FUNCTION__, line: __LINE__)
expectation.fulfill()
})
task.resume()
waitForExpectationsWithTimeout(10, handler: nil)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
func testThatTaskInvokeBlock() {
let expectation: XCTestExpectation = self.expectationWithDescription("invoke block")
let request: NSURLRequest = NSURLRequest(URL: NSURL.URLWithString("/get", relativeToURL: kTestUrl))
let task = self.session!.dataTaskWithRequest(request, completionHandler: {(data, urlResponse, error) in
XCTAssertNil(error, "The error should be nil", file: __FILE__, line: __LINE__)
expectation.fulfill()
})
task.resume()
waitForExpectationsWithTimeout(10, handler: nil)
}
func testThatUploadTask() {
let expectation: XCTestExpectation = expectationWithDescription("upload task")
let request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL.URLWithString("/post", relativeToURL: kTestUrl))
request.HTTPMethod = "multipart/form-data"
let data: NSData = "Lorem ipsum dolor sit amet".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let task = self.session!.uploadTaskWithRequest(request, data: data, progress: nil, completionHandler: {(data, urlResponse, error) in
XCTAssertNil(error, "error should be nil", file: __FUNCTION__, line: __LINE__)
expectation.fulfill()
})
task.resume()
waitForExpectationsWithTimeout(10, handler: nil)
}
}
|
mit
|
7a80746b5ad1b9f38902e3373d1233bc
| 49.431818 | 164 | 0.706399 | 5.215041 | false | true | false | false |
roambotics/swift
|
test/stdlib/Strideable.swift
|
2
|
9296
|
//===--- Strideable.swift - Tests for strided iteration -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
import StdlibUnittest
// Check that the generic parameter is called 'Element'.
protocol TestProtocol1 {}
extension StrideToIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideTo where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThroughIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThrough where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var StrideTestSuite = TestSuite("Strideable")
struct R : Strideable {
typealias Distance = Int
var x: Int
init(_ x: Int) {
self.x = x
}
func distance(to rhs: R) -> Int {
return rhs.x - x
}
func advanced(by n: Int) -> R {
return R(x + n)
}
}
StrideTestSuite.test("Double") {
func checkOpen(from start: Double, to end: Double, by stepSize: Double, sum: Double) {
// Work on Doubles
expectEqual(
sum,
stride(from: start, to: end, by: stepSize).reduce(0.0, +))
}
func checkClosed(from start: Double, through end: Double, by stepSize: Double, sum: Double) {
// Work on Doubles
expectEqual(
sum,
stride(from: start, through: end, by: stepSize).reduce(0.0, +))
}
checkOpen(from: 1.0, to: 15.0, by: 3.0, sum: 35.0)
checkOpen(from: 1.0, to: 16.0, by: 3.0, sum: 35.0)
checkOpen(from: 1.0, to: 17.0, by: 3.0, sum: 51.0)
checkOpen(from: 1.0, to: -13.0, by: -3.0, sum: -25.0)
checkOpen(from: 1.0, to: -14.0, by: -3.0, sum: -25.0)
checkOpen(from: 1.0, to: -15.0, by: -3.0, sum: -39.0)
checkOpen(from: 4.0, to: 16.0, by: -3.0, sum: 0.0)
checkOpen(from: 1.0, to: -16.0, by: 3.0, sum: 0.0)
checkClosed(from: 1.0, through: 15.0, by: 3.0, sum: 35.0)
checkClosed(from: 1.0, through: 16.0, by: 3.0, sum: 51.0)
checkClosed(from: 1.0, through: 17.0, by: 3.0, sum: 51.0)
checkClosed(from: 1.0, through: -13.0, by: -3.0, sum: -25.0)
checkClosed(from: 1.0, through: -14.0, by: -3.0, sum: -39.0)
checkClosed(from: 1.0, through: -15.0, by: -3.0, sum: -39.0)
checkClosed(from: 4.0, through: 16.0, by: -3.0, sum: 0.0)
checkClosed(from: 1.0, through: -16.0, by: 3.0, sum: 0.0)
}
StrideTestSuite.test("HalfOpen") {
func check(from start: Int, to end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, to: end, by: stepSize).reduce(
0, +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), to: R(end), by: stepSize).reduce(0) { $0 + $1.x })
}
check(from: 1, to: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 16, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, to: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -14, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, to: 16, by: -3, sum: 0)
check(from: 1, to: -16, by: 3, sum: 0)
}
StrideTestSuite.test("Closed") {
func check(from start: Int, through end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, through: end, by: stepSize).reduce(
0, +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), through: R(end), by: stepSize).reduce(
0, { $0 + $1.x })
)
}
check(from: 1, through: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, through: 16, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, through: -14, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 1, through: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, through: 16, by: -3, sum: 0)
check(from: 1, through: -16, by: 3, sum: 0)
}
StrideTestSuite.test("OperatorOverloads") {
var r1 = R(50)
var r2 = R(70)
var stride: Int = 5
do {
var result = r1.advanced(by: stride)
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1.advanced(by: stride)
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1.advanced(by: -stride)
expectType(R.self, &result)
expectEqual(45, result.x)
}
do {
var result = r2.distance(to: r1)
expectType(Int.self, &result)
expectEqual(-20, result)
}
}
StrideTestSuite.test("FloatingPointStride") {
var result = [Double]()
for i in stride(from: 1.4, through: 3.4, by: 1) {
result.append(i)
}
expectEqual([ 1.4, 2.4, 3.4 ], result)
}
StrideTestSuite.test("FloatingPointStride/rounding error") {
// Ensure that there is no error accumulation
let a = Array(stride(from: 1 as Float, through: 2, by: 0.1))
expectEqual(11, a.count)
expectEqual(2 as Float, a.last)
let b = Array(stride(from: 1 as Float, to: 10, by: 0.9))
expectEqual(10, b.count)
// Ensure that there is no intermediate rounding error on supported platforms
if (-0.2).addingProduct(0.2, 6) == 1 {
let c = Array(stride(from: -0.2, through: 1, by: 0.2))
expectEqual(7, c.count)
expectEqual(1 as Double, c.last)
}
if (1 as Float).addingProduct(0.9, 6) == 6.3999996 {
let d = Array(stride(from: 1 as Float, through: 6.3999996, by: 0.9))
expectEqual(7, d.count)
// The reason that `d` has seven elements and not six is that the fused
// multiply-add operation `(1 as Float).addingProduct(0.9, 6)` gives the
// result `6.3999996`. This is nonetheless the desired behavior because
// avoiding error accumulation and intermediate rounding error wherever
// possible will produce better results more often than not (see
// https://github.com/apple/swift/issues/48927).
//
// If checking of end bounds has been inadvertently modified such that we're
// computing the distance from the penultimate element to the end (in this
// case, `6.3999996 - (1 as Float).addingProduct(0.9, 5)`), then the last
// element will be omitted here.
//
// Therefore, if the test has failed, there may have been a regression in
// the bounds-checking logic of `Stride*Iterator`. Restore the expected
// behavior here by ensuring that floating-point strides are opted out of
// any bounds checking that performs arithmetic with values other than the
// bounds themselves and the stride.
}
}
func strideIteratorTest<
Stride : Sequence
>(_ stride: Stride, nonNilResults: Int) {
var i = stride.makeIterator()
for _ in 0..<nonNilResults {
expectNotNil(i.next())
}
for _ in 0..<10 {
expectNil(i.next())
}
}
StrideTestSuite.test("StrideThroughIterator/past end") {
strideIteratorTest(stride(from: 0, through: 3, by: 1), nonNilResults: 4)
strideIteratorTest(
stride(from: UInt8(0), through: 255, by: 5), nonNilResults: 52)
}
StrideTestSuite.test("StrideThroughIterator/past end/backward") {
strideIteratorTest(stride(from: 3, through: 0, by: -1), nonNilResults: 4)
}
StrideTestSuite.test("StrideToIterator/past end") {
strideIteratorTest(stride(from: 0, to: 3, by: 1), nonNilResults: 3)
}
StrideTestSuite.test("StrideToIterator/past end/backward") {
strideIteratorTest(stride(from: 3, to: 0, by: -1), nonNilResults: 3)
}
if #available(SwiftStdlib 5.6, *) {
StrideTestSuite.test("Contains") {
expectTrue(stride(from: 1, through: 5, by: 1).contains(3))
expectTrue(stride(from: 1, to: 5, by: 1).contains(3))
expectTrue(stride(from: 1, through: 5, by: 1).contains(5))
expectFalse(stride(from: 1, to: 5, by: 1).contains(5))
expectFalse(stride(from: 1, through: 5, by: -1).contains(3))
expectFalse(stride(from: 1, to: 5, by: -1).contains(3))
expectFalse(stride(from: 1, through: 5, by: -1).contains(1))
expectFalse(stride(from: 1, to: 5, by: -1).contains(1))
expectTrue(stride(from: 5, through: 1, by: -1).contains(3))
expectTrue(stride(from: 5, to: 1, by: -1).contains(3))
expectTrue(stride(from: 5, through: 1, by: -1).contains(1))
expectFalse(stride(from: 5, to: 1, by: -1).contains(1))
expectFalse(stride(from: 5, through: 1, by: 1).contains(3))
expectFalse(stride(from: 5, to: 1, by: 1).contains(3))
expectFalse(stride(from: 5, through: 1, by: 1).contains(5))
expectFalse(stride(from: 5, to: 1, by: 1).contains(5))
}
}
runAllTests()
|
apache-2.0
|
7738bff1ac144f5def20da7c21db2427
| 31.964539 | 95 | 0.619729 | 3.033943 | false | true | false | false |
gluecode/ImagePickerSheetStoryBoard
|
Pods/ImagePickerSheet/ImagePickerSheet/ImagePickerSheet/ImageSupplementaryView.swift
|
1
|
2309
|
//
// ImageSupplementaryView.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 06/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
class ImageSupplementaryView : UICollectionReusableView {
private let button: UIButton = {
let button = UIButton()
button.tintColor = UIColor.whiteColor()
button.userInteractionEnabled = false
button.setImage(ImageSupplementaryView.checkmarkImage, forState: .Normal)
button.setImage(ImageSupplementaryView.selectedCheckmarkImage, forState: .Selected)
return button
}()
var buttonInset = UIEdgeInsetsZero
var selected: Bool = false {
didSet {
button.selected = selected
button.backgroundColor = (selected) ? tintColor : nil
}
}
class var checkmarkImage: UIImage? {
let bundle = NSBundle(forClass: ImagePickerSheet.self)
let image = UIImage(named: "ImagePickerSheet-checkmark", inBundle: bundle, compatibleWithTraitCollection: nil)
return image?.imageWithRenderingMode(.AlwaysTemplate)
}
class var selectedCheckmarkImage: UIImage? {
let bundle = NSBundle(forClass: ImagePickerSheet.self)
let image = UIImage(named: "ImagePickerSheet-checkmark-selected", inBundle: bundle, compatibleWithTraitCollection: nil)
return image?.imageWithRenderingMode(.AlwaysTemplate)
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
addSubview(button)
}
// MARK: - Other Methods
override func prepareForReuse() {
super.prepareForReuse()
selected = false
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
button.sizeToFit()
button.frame.origin = CGPointMake(buttonInset.left, CGRectGetHeight(bounds)-CGRectGetHeight(button.frame)-buttonInset.bottom)
button.layer.cornerRadius = CGRectGetHeight(button.frame) / 2.0
}
}
|
mit
|
07c30e0890bd2e849e5f6c49b1af3ea6
| 27.158537 | 133 | 0.637072 | 5.259681 | false | false | false | false |
shajrawi/swift
|
test/stdlib/Dispatch.swift
|
1
|
7281
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: libdispatch
import Dispatch
import StdlibUnittest
defer { runAllTests() }
var DispatchAPI = TestSuite("DispatchAPI")
DispatchAPI.test("constants") {
expectEqual(2147483648, DispatchSource.ProcessEvent.exit.rawValue)
expectEqual(0, DispatchData.empty.endIndex)
// This is a lousy test, but really we just care that
// DISPATCH_QUEUE_CONCURRENT comes through at all.
_ = DispatchQueue.Attributes.concurrent
}
DispatchAPI.test("OS_OBJECT support") {
let mainQueue = DispatchQueue.main as AnyObject
expectTrue(mainQueue is DispatchQueue)
// This should not be optimized out, and should succeed.
expectNotNil(mainQueue as? DispatchQueue)
}
DispatchAPI.test("DispatchGroup creation") {
let group = DispatchGroup()
expectNotNil(group)
}
DispatchAPI.test("Dispatch sync return value") {
let value = 24
let q = DispatchQueue(label: "Test")
let result = q.sync() { return 24 }
expectEqual(value, result)
}
DispatchAPI.test("dispatch_block_t conversions") {
var counter = 0
let closure = { () -> Void in
counter += 1
}
typealias Block = @convention(block) () -> ()
let block = closure as Block
block()
expectEqual(1, counter)
let closureAgain = block as () -> Void
closureAgain()
expectEqual(2, counter)
}
if #available(OSX 10.10, iOS 8.0, *) {
DispatchAPI.test("dispatch_block_t identity") {
let block = DispatchWorkItem(flags: .inheritQoS) {
_ = 1
}
DispatchQueue.main.async(execute: block)
// This will trap if the block's pointer identity is not preserved.
block.cancel()
}
}
DispatchAPI.test("DispatchTime comparisons") {
do {
let now = DispatchTime.now()
checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: {
return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt
})
}
do {
let now = DispatchWallTime.now()
checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: {
return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt
})
}
}
DispatchAPI.test("DispatchTime.create") {
var info = mach_timebase_info_data_t(numer: 1, denom: 1)
mach_timebase_info(&info)
let scales = info.numer != info.denom
// Simple tests for non-overflow behavior
var time = DispatchTime(uptimeNanoseconds: 0)
expectEqual(time.uptimeNanoseconds, 0)
time = DispatchTime(uptimeNanoseconds: 15 * NSEC_PER_SEC)
expectEqual(time.uptimeNanoseconds, 15 * NSEC_PER_SEC)
// On platforms where the timebase scale is not 1, the next two cases
// overflow and become DISPATCH_TIME_FOREVER (UInt64.max) instead of trapping.
time = DispatchTime(uptimeNanoseconds: UInt64.max - 1)
expectEqual(time.uptimeNanoseconds, scales ? UInt64.max : UInt64.max - UInt64(1))
time = DispatchTime(uptimeNanoseconds: UInt64.max / 2)
expectEqual(time.uptimeNanoseconds, scales ? UInt64.max : UInt64.max / 2)
// UInt64.max must always be returned as UInt64.max.
time = DispatchTime(uptimeNanoseconds: UInt64.max)
expectEqual(time.uptimeNanoseconds, UInt64.max)
}
DispatchAPI.test("DispatchTime.addSubtract") {
var then = DispatchTime.now() + Double.infinity
expectEqual(DispatchTime.distantFuture, then)
then = DispatchTime.now() + Double.nan
expectEqual(DispatchTime.distantFuture, then)
then = DispatchTime.now() - Double.infinity
expectEqual(DispatchTime(uptimeNanoseconds: 1), then)
then = DispatchTime.now() - Double.nan
expectEqual(DispatchTime.distantFuture, then)
}
DispatchAPI.test("DispatchWallTime.addSubtract") {
let distantPastRawValue = DispatchWallTime.distantFuture.rawValue - UInt64(1)
var then = DispatchWallTime.now() + Double.infinity
expectEqual(DispatchWallTime.distantFuture, then)
then = DispatchWallTime.now() + Double.nan
expectEqual(DispatchWallTime.distantFuture, then)
then = DispatchWallTime.now() - Double.infinity
expectEqual(distantPastRawValue, then.rawValue)
then = DispatchWallTime.now() - Double.nan
expectEqual(DispatchWallTime.distantFuture, then)
}
DispatchAPI.test("DispatchTime.uptimeNanos") {
let seconds = 1
let nowMach = DispatchTime.now()
let oneSecondFromNowMach = nowMach + .seconds(seconds)
let nowNanos = nowMach.uptimeNanoseconds
let oneSecondFromNowNanos = oneSecondFromNowMach.uptimeNanoseconds
let diffNanos = oneSecondFromNowNanos - nowNanos
expectEqual(NSEC_PER_SEC, diffNanos)
}
DispatchAPI.test("DispatchIO.initRelativePath") {
let q = DispatchQueue(label: "initRelativePath queue")
let chan = DispatchIO(type: .random, path: "_REL_PATH_", oflag: O_RDONLY, mode: 0, queue: q, cleanupHandler: { (error) in })
expectEqual(chan, nil)
}
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
var block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) {}
DispatchAPI.test("DispatchSource.replace") {
let g = DispatchGroup()
let q = DispatchQueue(label: "q")
let ds = DispatchSource.makeUserDataReplaceSource(queue: q)
var lastValue = UInt(0)
var nextValue = UInt(1)
let maxValue = UInt(1 << 24)
ds.setEventHandler() {
let value = ds.data;
expectTrue(value > lastValue) // Values must increase
expectTrue((value & (value - 1)) == 0) // Must be power of two
lastValue = value
if value == maxValue {
g.leave()
}
}
ds.activate()
g.enter()
block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) {
ds.replace(data: nextValue)
nextValue <<= 1
if nextValue <= maxValue {
q.asyncAfter(
deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1),
execute: block)
}
}
q.asyncAfter(
deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1),
execute: block)
let result = g.wait(timeout: DispatchTime.now() + .seconds(30))
expectTrue(result == .success)
}
}
DispatchAPI.test("DispatchTimeInterval") {
// Basic tests that the correct value is stored and the == method works
for i in stride(from:1, through: 100, by: 5) {
expectEqual(DispatchTimeInterval.seconds(i), DispatchTimeInterval.milliseconds(i * 1000))
expectEqual(DispatchTimeInterval.milliseconds(i), DispatchTimeInterval.microseconds(i * 1000))
expectEqual(DispatchTimeInterval.microseconds(i), DispatchTimeInterval.nanoseconds(i * 1000))
}
// Check some cases that used to cause arithmetic overflow when evaluating the rawValue for ==
var t = DispatchTimeInterval.seconds(Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.seconds(-Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.milliseconds(Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.milliseconds(-Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.microseconds(Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.microseconds(-Int.max)
expectTrue(t == t) // This would crash.
}
DispatchAPI.test("DispatchTimeInterval.never.equals") {
expectTrue(DispatchTimeInterval.never == DispatchTimeInterval.never)
expectTrue(DispatchTimeInterval.seconds(10) != DispatchTimeInterval.never);
expectTrue(DispatchTimeInterval.never != DispatchTimeInterval.seconds(10));
expectTrue(DispatchTimeInterval.seconds(10) == DispatchTimeInterval.seconds(10));
}
|
apache-2.0
|
c7b40ecb8ad66022d50c24773759519a
| 30.519481 | 125 | 0.722016 | 3.844245 | false | true | false | false |
a2/Gulliver
|
Gulliver Tests/Source/PropertyKindSpec.swift
|
1
|
8373
|
import AddressBook
import Gulliver
import Nimble
import Quick
class PropertyKindSpec: QuickSpec {
override func spec() {
describe("Invalid") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABInvalidPropertyType)
expect(PropertyKind.Invalid.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABInvalidPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.Invalid
}
it("is not valid") {
expect(PropertyKind.Invalid.isValid) == false
}
it("is not multi") {
expect(PropertyKind.Invalid.isMulti) == false
}
}
describe("String") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABStringPropertyType)
expect(PropertyKind.String.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABStringPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.String
}
it("is valid") {
expect(PropertyKind.String.isValid) == true
}
it("is not multi") {
expect(PropertyKind.String.isMulti) == false
}
}
describe("Integer") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABIntegerPropertyType)
expect(PropertyKind.Integer.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABIntegerPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.Integer
}
it("is valid") {
expect(PropertyKind.Integer.isValid) == true
}
it("is not multi") {
expect(PropertyKind.Integer.isMulti) == false
}
}
describe("Real") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABRealPropertyType)
expect(PropertyKind.Real.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABRealPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.Real
}
it("is valid") {
expect(PropertyKind.Real.isValid) == true
}
it("is not multi") {
expect(PropertyKind.Real.isMulti) == false
}
}
describe("DateTime") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABDateTimePropertyType)
expect(PropertyKind.DateTime.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABDateTimePropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.DateTime
}
it("is valid") {
expect(PropertyKind.DateTime.isValid) == true
}
it("is not multi") {
expect(PropertyKind.DateTime.isMulti) == false
}
}
describe("Dictionary") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABDictionaryPropertyType)
expect(PropertyKind.Dictionary.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABDictionaryPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.Dictionary
}
it("is valid") {
expect(PropertyKind.Dictionary.isValid) == true
}
it("is not multi") {
expect(PropertyKind.Dictionary.isMulti) == false
}
}
describe("MultiString") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABMultiStringPropertyType)
expect(PropertyKind.MultiString.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABMultiStringPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.MultiString
}
it("is valid") {
expect(PropertyKind.MultiString.isValid) == true
}
it("is multi") {
expect(PropertyKind.MultiString.isMulti) == true
}
}
describe("MultiInteger") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABMultiIntegerPropertyType)
expect(PropertyKind.MultiInteger.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABMultiIntegerPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.MultiInteger
}
it("is valid") {
expect(PropertyKind.MultiInteger.isValid) == true
}
it("is multi") {
expect(PropertyKind.MultiInteger.isMulti) == true
}
}
describe("MultiReal") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABMultiRealPropertyType)
expect(PropertyKind.MultiReal.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABMultiRealPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.MultiReal
}
it("is valid") {
expect(PropertyKind.MultiReal.isValid) == true
}
it("is multi") {
expect(PropertyKind.MultiReal.isMulti) == true
}
}
describe("MultiDateTime") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABMultiDateTimePropertyType)
expect(PropertyKind.MultiDateTime.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABMultiDateTimePropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.MultiDateTime
}
it("is valid") {
expect(PropertyKind.MultiDateTime.isValid) == true
}
it("is multi") {
expect(PropertyKind.MultiDateTime.isMulti) == true
}
}
describe("MultiDictionary") {
it("has the correct rawValue") {
let correctValue: ABPropertyType = numericCast(kABMultiDictionaryPropertyType)
expect(PropertyKind.MultiDictionary.rawValue) == correctValue
}
it("can be created with an ABPropertyType value") {
let kind = PropertyKind(rawValue: numericCast(kABMultiDictionaryPropertyType))
expect(kind).notTo(beNil())
expect(kind) == PropertyKind.MultiDictionary
}
it("is valid") {
expect(PropertyKind.MultiDictionary.isValid) == true
}
it("is multi") {
expect(PropertyKind.MultiDictionary.isMulti) == true
}
}
}
}
|
mit
|
9aa4b6962c3b703bac93da03fee551d8
| 34.033473 | 94 | 0.539353 | 5.279319 | false | false | false | false |
newlix/swift-syncable-api
|
Carthage/Checkouts/swift-less-mock/Sources/LessMock.swift
|
1
|
6784
|
//
// LessMock.swift
// LessMock
//
// Created by newlix on 2/8/16.
// Copyright © 2016 less. All rights reserved.
//
import Foundation
extension String : ErrorType {
}
public struct Request {
public let path: String
public let method:String
public let headers: [String:String]
public var json: AnyObject?
public var form: [String:AnyObject]?
public var data: NSData?
public var text: String?
public var query: [String:String]?
public var queryString: String?
public init(dict:[String:AnyObject]) {
method = dict["method"] as! String
path = dict["path"] as! String
headers = dict["headers"] as! [String:String]
if let json = dict["json"] {
self.json = json
}
if let base64 = dict["data"] as? String {
self.data = NSData(base64EncodedString: base64, options: NSDataBase64DecodingOptions())
}
if let form = dict["form"] as? [String:AnyObject] {
self.form = form
}
if let text = dict["text"] as? String {
self.text = text
}
if let query = dict["query"] as? [String:String] {
self.query = query
}
if let queryString = dict["queryString"] as? String {
self.queryString = queryString
}
}
}
public class LessMock {
private var id:String!
private var serviceURL:NSURL!
private var enqueueResponseURL:NSURL! // post
private var receivedRequestsURL:NSURL! // get
private var verifyURL:NSURL! // get
public var URL:NSURL!
public var URLString:String!
public init(URLString:String) throws {
self.serviceURL = NSURL(string: URLString + (URLString.hasSuffix("/") ? "" : "/"))!
let createURL = NSURL(string: "create", relativeToURL: self.serviceURL)!
let r = try post(createURL)
let json = try parseJSONResult(r.response, data: r.data, error: r.error) as! [String:String]
if let id = json["id"] {
self.id = id
} else {
throw "The json response should contain id \(json)"
}
self.URL = NSURL(string: id + "/server/", relativeToURL: self.serviceURL)
self.URLString = URL!.absoluteString
self.enqueueResponseURL = NSURL(string: id + "/enqueueResponse", relativeToURL: self.serviceURL)
self.receivedRequestsURL = NSURL(string: id + "/receivedRequests", relativeToURL: self.serviceURL)
self.verifyURL = NSURL(string: id + "/verify", relativeToURL: self.serviceURL)
}
private func buildResponse(status status: Int? = nil, headers:[String:AnyObject]? = nil) -> [String:AnyObject]{
var response = [String:AnyObject]()
if let headers = headers {
response["headers"] = headers
}
if let status = status {
response["status"] = status
}
return response
}
public func enqueueResponse(json json:AnyObject, headers:[String:AnyObject]? = nil, status: Int? = nil) throws {
var response = buildResponse(status: status, headers:headers)
response["json"] = json
let r = try post(enqueueResponseURL, json:response)
try parseJSONResult(r.response,data: r.data,error: r.error)
}
public func enqueueResponse(text text:String, headers:[String:AnyObject]? = nil, status: Int? = nil) throws{
var response = buildResponse(status: status, headers:headers)
response["text"] = text
let r = try post(enqueueResponseURL, json:response)
try parseJSONResult(r.response,data: r.data,error: r.error)
}
public func enqueueResponse(data data:NSData, headers:[String:AnyObject]? = nil, status: Int? = nil) throws {
var response = buildResponse(status: status, headers:headers)
response["data"] = String(data: data.base64EncodedDataWithOptions(NSDataBase64EncodingOptions()), encoding: NSUTF8StringEncoding)
let r = try post(enqueueResponseURL, json:response)
try parseJSONResult(r.response,data: r.data,error: r.error)
}
public func receivedRequests() throws -> [Request] {
let r = try get(receivedRequestsURL)
let dicts = try parseJSONResult(r.response, data: r.data, error: r.error) as![[String:AnyObject]]
return dicts.map{ return Request(dict:$0) }
}
public func verify() throws{
let r = try get(verifyURL)
try parseJSONResult(r.response,data: r.data,error: r.error)
}
}
func get(URL:NSURL) throws -> (response:NSURLResponse?, data:NSData?, error: NSError?) {
let semaphore = dispatch_semaphore_create(0)
var data:NSData?
var response:NSURLResponse?
var error:NSError?
let task = NSURLSession.sharedSession().dataTaskWithURL(URL) { (_data, _response, _error) -> Void in
data = _data
response = _response
error = _error
dispatch_semaphore_signal(semaphore)
}
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return (response,data, error)
}
func post(URL:NSURL, json:[String:AnyObject]? = nil) throws -> (response:NSURLResponse?, data:NSData?, error: NSError?) {
let request = NSMutableURLRequest(URL: URL)
if let json = json {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions())
}
request.HTTPMethod = "POST"
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("json", forHTTPHeaderField:"Data-Type")
let semaphore = dispatch_semaphore_create(0)
var response:NSURLResponse?
var data:NSData?
var error:NSError?
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ (_data, _response, _error) -> Void in
data = _data
response = _response
error = _error
dispatch_semaphore_signal(semaphore)
}
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return (response, data, error)
}
private func parseJSONResult(response:NSURLResponse?, data:NSData?, error:NSError?) throws -> AnyObject {
let statusCode = (response as? NSHTTPURLResponse)?.statusCode
if let error = error {
throw error.localizedDescription
} else {
if let data = data {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
if statusCode == 200 {
return json
} else {
let message = json["error"] as? String ?? ""
throw message
}
} else {
throw "The server should response JSON instead of nothing"
}
}
}
|
mit
|
d47e57145ec7a7b2839397d3c1d33d30
| 35.86413 | 137 | 0.629515 | 4.314885 | false | false | false | false |
cnoon/CollectionViewAnimations
|
Source/Common/Cell.swift
|
1
|
2260
|
//
// Cell.swift
// CollectionViewAnimations
//
// Created by Christian Noon on 10/29/15.
// Copyright © 2015 Noondev. All rights reserved.
//
import UIKit
class ContentCell: UICollectionViewCell {
class var reuseIdentifier: String { return "\(self)" }
class var kind: String { return "ContentCell" }
var label: UILabel!
// MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
label = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(20)
label.textColor = UIColor.whiteColor()
return label
}()
contentView.addSubview(label)
label.snp_makeConstraints { make in
make.center.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func prepareForReuse() {
UIView.performWithoutAnimation {
self.backgroundColor = nil
}
}
// MARK: Layout
override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {
super.applyLayoutAttributes(layoutAttributes)
layoutIfNeeded()
}
}
// MARK: -
class SectionHeaderCell: UICollectionReusableView {
class var reuseIdentifier: String { return "\(self)" }
class var kind: String { return "SectionHeaderCell" }
var label: UILabel!
// MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.2, alpha: 1.0)
label = {
let label = UILabel()
label.font = UIFont.boldSystemFontOfSize(14)
label.textColor = UIColor.whiteColor()
return label
}()
addSubview(label)
label.snp_makeConstraints { make in
make.leading.equalTo(self).offset(20)
make.trailing.equalTo(self).offset(-20)
make.centerY.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
// MARK: Layout
override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {
super.applyLayoutAttributes(layoutAttributes)
layoutIfNeeded()
}
}
|
mit
|
05724ea87943dfdc16970a47401a7d13
| 22.28866 | 93 | 0.618415 | 4.921569 | false | false | false | false |
FAU-Inf2/kwikshop-ios
|
Kwik Shop/AutoCompletionHelper.swift
|
1
|
9901
|
//
// AutoCompletionHelper.swift
// Kwik Shop
//
// Created by Adrian Kretschmer on 18.08.15.
// Copyright (c) 2015 FAU-Inf2. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class AutoCompletionHelper {
static let instance = AutoCompletionHelper()
private var itemNames = [String]()
private var brandNames = [String]()
private var unitsAndGroups = [String : (Unit?, Group?)]()
private let dbHelper = DatabaseHelper.instance
private let managedObjectContext : NSManagedObjectContext
private var autoCompletionData = [String : AutoCompletionData]()
private var autoCompletionBrandData = [String : AutoCompletionBrandData]()
var allAutoCompletionItemNames : [String] {
return itemNames
}
var allAutoCompletionBrandNames : [String] {
return brandNames
}
private init() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
managedObjectContext = appDelegate.managedObjectContext!
if let autoCompletion = dbHelper.loadAutoCompletionData() {
for data in autoCompletion {
let name = data.name
autoCompletionData.updateValue(data, forKey: name)
itemNames.append(name)
let unit : Unit?
if let managedUnit = data.unit {
if managedUnit.unit != nil {
unit = managedUnit.unit
} else {
unit = Unit(managedUnit: managedUnit)
}
} else {
unit = nil
}
let group : Group?
if let managedGroup = data.group {
if managedGroup.group != nil {
group = managedGroup.group
} else {
group = Group(managedGroup: managedGroup)
}
} else {
group = nil
}
if unit != nil || group != nil {
unitsAndGroups.updateValue((unit, group), forKey: name)
}
}
}
if let brandCompletion = dbHelper.loadAutoCompletionBrandData() {
for data in brandCompletion {
let brand = data.brand
autoCompletionBrandData.updateValue(data, forKey: brand)
brandNames.append(brand)
}
}
}
func createOrUpdateAutoCompletionDataForName(name: String) {
createOrUpdateAutoCompletionDataForName(name, unit: nil, group: nil)
}
func createOrUpdateAutoCompletionDataForName(name: String, unit: Unit?) {
createOrUpdateAutoCompletionDataForName(name, unit: unit, group: nil)
}
func createOrUpdateAutoCompletionDataForName(name: String, group: Group?) {
createOrUpdateAutoCompletionDataForName(name, unit: nil, group: group)
}
func createOrUpdateAutoCompletionDataForItem(item: Item) {
createOrUpdateAutoCompletionDataForName(item.name, unit: item.unit, group: item.group)
if let brand = item.brand {
createOrUpdateAutoCompletionBrandDataForBrand(brand)
}
}
func createOrUpdateAutoCompletionDataForName(name: String, unit: Unit?, group: Group?) {
var newValue = false
if !itemNames.contains(name) {
itemNames.append(name)
newValue = true
}
if unit != nil || group != nil {
unitsAndGroups.updateValue((unit, group), forKey: name)
} else if !newValue {
// unit and group are nil
unitsAndGroups.removeValueForKey(name)
}
let data : AutoCompletionData
if newValue {
data = NSEntityDescription.insertNewObjectForEntityForName("AutoCompletionData", inManagedObjectContext: managedObjectContext) as! AutoCompletionData
} else {
data = autoCompletionData[name]!
}
autoCompletionData.updateValue(data, forKey: name)
data.name = name
data.unit = unit?.managedUnit
data.group = group?.managedGroup
dbHelper.saveData()
}
func createOrUpdateAutoCompletionBrandDataForBrand(brand: String) {
let data : AutoCompletionBrandData
if !brandNames.contains(brand) {
brandNames.append(brand)
data = NSEntityDescription.insertNewObjectForEntityForName("AutoCompletionBrandData", inManagedObjectContext: managedObjectContext) as! AutoCompletionBrandData
} else {
data = autoCompletionBrandData[brand]!
}
autoCompletionBrandData.updateValue(data, forKey: brand)
data.brand = brand
dbHelper.saveData()
}
func getGroupForItem(item: Item) -> Group {
return getGroupForName(item.name)
}
func getGroupForName(name: String) -> Group {
if let unitAndGroup = unitsAndGroups[name] {
if let group = unitAndGroup.1 {
return group
}
}
return GroupHelper.instance.OTHER
}
func getUnitForItem(item: Item) -> Unit? {
return getUnitForName(item.name)
}
func getUnitForName(name: String) -> Unit? {
if let unitAndGroup = unitsAndGroups[name] {
return unitAndGroup.0
} else {
return nil
}
}
func possibleCompletionsForQuickAddTextWithNameAmountAndUnit(nameAmountAndUnit : (String, Int?, Unit?)) -> [String] {
return possibleCompletionsForQuickAddTextWithName(nameAmountAndUnit.0, amount: nameAmountAndUnit.1, andUnit: nameAmountAndUnit.2)
}
func possibleCompletionsForQuickAddTextWithName(name: String, amount: Int?, andUnit unit: Unit?) -> [String] {
var completions = possibleCompletionsForItemName(name)
if amount != nil {
let prefix : String
if unit != nil {
if amount != 1 {
prefix = "\(amount!) \(unit!.name) "
} else {
prefix = "\(amount!) \(unit!.singularName) "
}
} else {
prefix = "\(amount!) "
// also units should be suggested
let unitDelegate = AmountAndUnitDelegate()
var unitNames = [String]()
for unit in unitDelegate.unitData {
if amount != 1 {
unitNames.append("\(unit.name) ")
} else {
unitNames.append("\(unit.singularName) ")
}
}
let unitSuggestions = filteredCompletionsForSuggestions(unitNames, andString: name)
completions += unitSuggestions
}
let numberOfCompletions = completions.count
for index in 0 ..< numberOfCompletions {
completions[index] = prefix + completions[index]
}
} else if unit != nil {
let numberOfCompletions = completions.count
for index in 0 ..< numberOfCompletions {
completions[index] = "\(unit!.singularName) " + completions[index]
}
}
return completions
}
func possibleCompletionsForItemName(string: String) -> [String] {
return filteredCompletionsForSuggestions(itemNames, andString: string)
}
func possibleCompletionsForBrand(string: String) -> [String] {
return filteredCompletionsForSuggestions(brandNames, andString: string)
}
private func filteredCompletionsForSuggestions(suggestions: [String], andString string: String) -> [String] {
let completions = suggestions.filter(
{ suggestion -> Bool in
return suggestion.lowercaseString.hasPrefix(string.lowercaseString)
})
return completions
}
func deleteAutocompletionDataAtIndex(index: Int) {
deleteAutocompletionDataAtIndex(index, andSave: true)
}
func deleteAutocompletionDataWithItemName(name: String) {
if let index = itemNames.indexOf(name) {
deleteAutocompletionDataAtIndex(index)
}
}
func deleteAllAutoCompletionData() {
while !itemNames.isEmpty {
deleteAutocompletionDataAtIndex(0, andSave: false)
}
dbHelper.saveData()
}
private func deleteAutocompletionDataAtIndex(index: Int, andSave save: Bool) {
let name = itemNames.removeAtIndex(index)
let autoCompletionData = self.autoCompletionData.removeValueForKey(name)!
managedObjectContext.deleteObject(autoCompletionData)
if save {
dbHelper.saveData()
}
}
func deleteAutocompletionBrandDataAtIndex(index: Int) {
deleteAutocompletionBrandDataAtIndex(index, andSave: true)
}
func deleteAutocompletionBrandDataWithName(name: String) {
if let index = brandNames.indexOf(name) {
deleteAutocompletionBrandDataAtIndex(index)
}
}
func deleteAllAutoCompletionBrandData() {
while !brandNames.isEmpty {
deleteAutocompletionBrandDataAtIndex(0, andSave: false)
}
dbHelper.saveData()
}
private func deleteAutocompletionBrandDataAtIndex(index: Int, andSave save: Bool) {
let brand = brandNames.removeAtIndex(index)
let autoCompletionBrandData = self.autoCompletionBrandData.removeValueForKey(brand)!
managedObjectContext.deleteObject(autoCompletionBrandData)
if save {
dbHelper.saveData()
}
}
}
|
mit
|
e7cd90dcb5a964059b45b06cd72269df
| 34.238434 | 171 | 0.588021 | 5.164841 | false | false | false | false |
m-alani/contests
|
hackerrank/BonAppetit.swift
|
1
|
865
|
//
// BonAppetit.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/bon-appetit
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
import Foundation
// Read N (and ignore it, as it is not needed in this implementation) & K
let allergyIndex = String(readLine()!)!.components(separatedBy: " ").map({Int($0)!})[1]
// Read the costs
var costs = String(readLine()!)!.components(separatedBy: " ").map({Int($0)!})
// Read how much Anna was charged
let charged = Int(readLine()!)!
// Find Anna's share
costs.remove(at: allergyIndex)
let actual = Int(costs.reduce(0, +) / 2)
// Generate output, then print it
let output = (actual == charged) ? "Bon Appetit" : "\(charged - actual)"
print(output)
|
mit
|
3b9962c1ef1b8b2931a942f0163224d0
| 31.037037 | 118 | 0.690173 | 3.339768 | false | false | false | false |
angelvasa/AVXCAssets-Generator
|
AVXCAssetsGenerator/AVAssetCatalogCreator/AVIconScalar.swift
|
1
|
967
|
//
// IconGenerator.swift
// AVXCAssetsGenerator
//
// Created by Angel Vasa on 27/04/16.
// Copyright © 2016 Angel Vasa. All rights reserved.
//
import Foundation
import Cocoa
class AVIconScalar: AnyObject {
var iconSizes = [29, 40, 50, 57, 58, 72, 76, 80 ,87, 100, 114, 120, 144, 152, 167, 180]
func scaleImage(image: NSImage, withImageName: String, andSaveAtPath: String) {
let contentCreator = ContentCreator()
for size in iconSizes {
let finalImage = image.resizeImage(CGFloat(size) / 2.0, CGFloat(size) / 2.0)
let imageNameWithConvention = withImageName + "-" + "\(size)" + ".png"
let pathToSaveImage = "\(andSaveAtPath + "/" + imageNameWithConvention)"
contentCreator.writeImageToDirectory(image: finalImage, atPath: pathToSaveImage)
contentCreator.writeDictionaryContent(contentCreator.defaultAppIconSetDictionary(), atPath: andSaveAtPath)
}
}
}
|
mit
|
efa6df52e4a916028e218900bc06a7d2
| 36.153846 | 118 | 0.663561 | 3.975309 | false | false | false | false |
RiftDC/riftdc.github.io
|
XCode/Unhurt/Unhurt/SwiftGif.swift
|
1
|
5938
|
//
// SwiftGif.swift
// Unhurt
//
// Created by Rodrigo Mesquita on 10/12/2017.
// Copyright © 2017 Rift Inc. All rights reserved.
//
import Foundation
import UIKit
import ImageIO
extension UIImageView {
public func loadGif(name: String) {
DispatchQueue.global().async {
let image = UIImage.gif(name: name)
DispatchQueue.main.async {
self.image = image
}
}
}
}
extension UIImage {
public class func gif(data: Data) -> UIImage? {
// Create source from data
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
print("SwiftGif: Source for the image does not exist")
return nil
}
return UIImage.animatedImageWithSource(source)
}
public class func gif(url: String) -> UIImage? {
// Validate URL
guard let bundleURL = URL(string: url) else {
print("SwiftGif: This image named \"\(url)\" does not exist")
return nil
}
// Validate data
guard let imageData = try? Data(contentsOf: bundleURL) else {
print("SwiftGif: Cannot turn image named \"\(url)\" into NSData")
return nil
}
return gif(data: imageData)
}
public class func gif(name: String) -> UIImage? {
// Check for existance of gif
guard let bundleURL = Bundle.main
.url(forResource: name, withExtension: "gif") else {
print("SwiftGif: This image named \"\(name)\" does not exist")
return nil
}
// Validate data
guard let imageData = try? Data(contentsOf: bundleURL) else {
print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
return nil
}
return gif(data: imageData)
}
internal class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double {
var delay = 0.1
// Get dictionaries
let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0)
if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false {
return delay
}
let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self)
// Get delay time
var delayObject: AnyObject = unsafeBitCast(
CFDictionaryGetValue(gifProperties,
Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()),
to: AnyObject.self)
if delayObject.doubleValue == 0 {
delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
}
delay = delayObject as? Double ?? 0
if delay < 0.1 {
delay = 0.1 // Make sure they're not too fast
}
return delay
}
internal class func gcdForPair(_ a: Int?, _ b: Int?) -> Int {
var a = a
var b = b
// Check if one of them is nil
if b == nil || a == nil {
if b != nil {
return b!
} else if a != nil {
return a!
} else {
return 0
}
}
// Swap for modulo
if a! < b! {
let c = a
a = b
b = c
}
// Get greatest common divisor
var rest: Int
while true {
rest = a! % b!
if rest == 0 {
return b! // Found it
} else {
a = b
b = rest
}
}
}
internal class func gcdForArray(_ array: Array<Int>) -> Int {
if array.isEmpty {
return 1
}
var gcd = array[0]
for val in array {
gcd = UIImage.gcdForPair(val, gcd)
}
return gcd
}
internal class func animatedImageWithSource(_ source: CGImageSource) -> UIImage? {
let count = CGImageSourceGetCount(source)
var images = [CGImage]()
var delays = [Int]()
// Fill arrays
for i in 0..<count {
// Add image
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
images.append(image)
}
// At it's delay in cs
let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
source: source)
delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
}
// Calculate full duration
let duration: Int = {
var sum = 0
for val: Int in delays {
sum += val
}
return sum
}()
// Get frames
let gcd = gcdForArray(delays)
var frames = [UIImage]()
var frame: UIImage
var frameCount: Int
for i in 0..<count {
frame = UIImage(cgImage: images[Int(i)])
frameCount = Int(delays[Int(i)] / gcd)
for _ in 0..<frameCount {
frames.append(frame)
}
}
// Heyhey
let animation = UIImage.animatedImage(with: frames,
duration: Double(duration) / 1000.0)
return animation
}
}
|
mit
|
bbead9aa1fba7682857ea9f888b8b06a
| 28.246305 | 155 | 0.497389 | 5.291444 | false | false | false | false |
benlangmuir/swift
|
benchmark/single-source/ObserverUnappliedMethod.swift
|
10
|
1481
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 TestsUtils
public let benchmarks =
BenchmarkInfo(
name: "ObserverUnappliedMethod",
runFunction: run_ObserverUnappliedMethod,
tags: [.validation],
legacyFactor: 10)
class Observer {
@inline(never)
func receive(_ value: Int) {
}
}
protocol Sink {
func receive(_ value: Int)
}
struct Forwarder<Object>: Sink {
let object: Object
let method: (Object) -> (Int) -> ()
func receive(_ value: Int) {
method(object)(value)
}
}
class Signal {
var observers: [Sink] = []
func subscribe(_ sink: Sink) {
observers.append(sink)
}
func send(_ value: Int) {
for observer in observers {
observer.receive(value)
}
}
}
public func run_ObserverUnappliedMethod(_ iterations: Int) {
let signal = Signal()
let observer = Observer()
for _ in 0 ..< 1_000 * iterations {
let forwarder = Forwarder(object: observer, method: Observer.receive)
signal.subscribe(forwarder)
}
signal.send(1)
}
|
apache-2.0
|
30925bf12bbad4ea0ee1b853622a7c0a
| 22.507937 | 80 | 0.602971 | 4.195467 | false | false | false | false |
scottkawai/sendgrid-swift
|
Sources/SendGrid/API/Models/Stats/Statistic.Metric.swift
|
1
|
6342
|
import Foundation
public extension Statistic {
/// The `Statistic.Metric` struct represents the raw statistics for a given
/// time period.
struct Metric: Codable {
// MARK: - Properties
/// The number of block events for the given period.
public let blocks: Int
/// The number of emails dropped due to the address being on the bounce
/// list for the given period.
public let bounceDrops: Int
/// The number of bounce events for the given period.
public let bounces: Int
/// The number of click events for the given period.
public let clicks: Int
/// The number of deferred events for the given period.
public let deferred: Int
/// The number of delivered events for the given period.
public let delivered: Int
/// The number of invalid email events for the given period.
public let invalidEmails: Int
/// The number of open events for the given period.
public let opens: Int
/// The number of processed events for the given period.
public let processed: Int
/// The number of requests for the given period.
public let requests: Int
/// The number of emails dropped due to the address being on the spam
/// report list for the given period.
public let spamReportDrops: Int
/// The number of spam report events for the given period.
public let spamReports: Int
/// The number of unique click events for the given period.
public let uniqueClicks: Int
/// The number of unique open events for the given period.
public let uniqueOpens: Int
/// The number of emails dropped due to the address being on the
/// unsubscribe list for the given period.
public let unsubscribeDrops: Int
/// The number of unsubscribe events for the given period.
public let unsubscribes: Int
// MARK: - Initialization
/// Initializes the struct.
///
/// - Parameters:
/// - blocks: The number of block events for the given
/// period.
/// - bounceDrops: The number of emails dropped due to the
/// address being on the bounce list for the
/// given period.
/// - bounces: The number of bounce events for the given
/// period.
/// - clicks: The number of click events for the given
/// period.
/// - deferred: The number of deferred events for the given
/// period.
/// - delivered: The number of delivered events for the given
/// period.
/// - invalidEmails: The number of invalid email events for the
/// given period.
/// - opens: The number of open events for the given
/// period.
/// - processed: The number of processed events for the given
/// period.
/// - requests: The number of requests for the given period.
/// - spamReportDrops: The number of emails dropped due to the
/// address being on the spam report list for
/// the given period.
/// - spamReports: The number of spam report events for the
/// given period.
/// - uniqueClicks: The number of unique click events for the
/// given period.
/// - uniqueOpens: The number of unique open events for the
/// given period.
/// - unsubscribeDrops: The number of emails dropped due to the
/// address being on the unsubscribe list for
/// the given period.
/// - unsubscribes: The number of unsubscribe events for the
/// given period.
public init(blocks: Int,
bounceDrops: Int,
bounces: Int,
clicks: Int,
deferred: Int,
delivered: Int,
invalidEmails: Int,
opens: Int,
processed: Int,
requests: Int,
spamReportDrops: Int,
spamReports: Int,
uniqueClicks: Int,
uniqueOpens: Int,
unsubscribeDrops: Int,
unsubscribes: Int) {
self.blocks = blocks
self.bounceDrops = bounceDrops
self.bounces = bounces
self.clicks = clicks
self.deferred = deferred
self.delivered = delivered
self.invalidEmails = invalidEmails
self.opens = opens
self.processed = processed
self.requests = requests
self.spamReportDrops = spamReportDrops
self.spamReports = spamReports
self.uniqueClicks = uniqueClicks
self.uniqueOpens = uniqueOpens
self.unsubscribeDrops = unsubscribeDrops
self.unsubscribes = unsubscribes
}
}
}
/// Decodable conformance.
public extension Statistic.Metric {
/// :nodoc:
enum CodingKeys: String, CodingKey {
case blocks
case bounceDrops = "bounce_drops"
case bounces
case clicks
case deferred
case delivered
case invalidEmails = "invalid_emails"
case opens
case processed
case requests
case spamReportDrops = "spam_report_drops"
case spamReports = "spam_reports"
case uniqueClicks = "unique_clicks"
case uniqueOpens = "unique_opens"
case unsubscribeDrops = "unsubscribe_drops"
case unsubscribes
}
}
|
mit
|
5426879ccef89a7a6e60d7d75a9cb62e
| 39.653846 | 80 | 0.51356 | 5.612389 | false | false | false | false |
kenwilcox/WeeDate
|
WeeDate/User.swift
|
1
|
2573
|
//
// User.swift
// WeeDate
//
// Created by Kenneth Wilcox on 6/20/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import Foundation
import Parse
struct User {
let id: String
let name: String
private let pfUser: PFUser
func getPhoto(callback:(UIImage) -> ()) {
let imageFile = pfUser.objectForKey("picture") as! PFFile
imageFile.getDataInBackgroundWithBlock({
data, error in
if let data = data {
callback(UIImage(data: data)!)
}
})
}
}
func pfUserToUser(user: PFUser)->User {
return User(id: user.objectId!, name: user.objectForKey("firstName") as! String, pfUser: user)
}
func currentUser() -> User? {
if let user = PFUser.currentUser() {
return pfUserToUser(user)
}
return nil
}
func fetchUnviewedUsers(callback:([User]) -> ()) {
var currentUserId = PFUser.currentUser()!.objectId!
PFQuery(className: "Action")
.whereKey("byUser", equalTo: currentUserId).findObjectsInBackgroundWithBlock({
objects, error in
let seenIds = map((objects as! [PFObject]), {$0.objectForKey("toUser")!})
PFUser.query()!
.whereKey("objectId", notEqualTo: currentUserId)
.whereKey("objectId", notContainedIn: seenIds)
.findObjectsInBackgroundWithBlock({
objects, error in
if let pfUsers = objects as? [PFUser] {
let users = map(pfUsers, {pfUserToUser($0)})
println("callback: \(users.count)")
callback(users)
}
})
})
}
enum UserAction: String {
case Like = "liked"
case Skip = "skipped"
case Match = "matched"
}
func saveSkip(user: User) {
saveAction( user, UserAction.Skip)
}
func saveLike(user: User) {
//saveAction( user, UserAction.Like)
PFQuery(className: "Action")
.whereKey("byUser", equalTo: user.id)
.whereKey("toUser", equalTo: PFUser.currentUser()!.objectId!)
.whereKey("type", equalTo: "liked")
.getFirstObjectInBackgroundWithBlock({
object, error in
var matched = false
if object != nil {
matched = true
object!.setObject("matched", forKey: "type")
object!.saveInBackgroundWithBlock(nil)
}
saveAction(user, matched ? .Match : .Like)
})
}
private func saveAction(user: User, action: UserAction) {
let obj = PFObject(className: "Action")
obj.setObject(PFUser.currentUser()!.objectId!, forKey: "byUser")
obj.setObject(user.id, forKey: "toUser")
obj.setObject(action.rawValue, forKey: "type")
obj.saveInBackgroundWithBlock(nil)
}
|
mit
|
41d78e154a69697c03a9b66b6c64e296
| 25.255102 | 96 | 0.637388 | 4.051969 | false | false | false | false |
voytovichs/seventh-dimension-scrobbler
|
Seventh Dimension Scrobbler/ITunesNotificationService.swift
|
1
|
1191
|
//
// Created by Sergey Voytovich on 03.07.16.
// Copyright (c) 2016 voytovichs. All rights reserved.
//
import Foundation
class ITunesNotificationsService {
private let myCallbacks: PlayerCallbacks
init(calbacks: PlayerCallbacks) {
self.myCallbacks = calbacks
}
@objc
public func onItunesEventSelector(notification: NSNotification) {
let content = notification.userInfo! as? NSDictionary?
if (content != nil) {
let type: String = content!!["Player State"] as? String! ?? ""
do {
switch type {
case PlayerState.PLAYING.rawValue:
try myCallbacks.onSongPlaying(Song(notification: content!!))
case PlayerState.PAUSED.rawValue:
try myCallbacks.onSongPaused(Song(notification: content!!))
default:
NSLog("Unkown event type \(type)")
}
} catch {
NSLog("Callback calling failed. \(error)")
}
}
}
private enum PlayerState: String {
case PLAYING = "Playing"
case PAUSED = "Paused"
}
}
|
mit
|
a1fa80da83c8e07a1c1353a55a39bc49
| 28.04878 | 84 | 0.554996 | 4.802419 | false | false | false | false |
Den-Ree/InstagramAPI
|
src/InstagramAPI/InstagramAPI/Example/ViewControllers/Root/RootViewController.swift
|
2
|
2773
|
//
// RootViewController.swift
// InstagramAPI
//
// Created by Admin on 08.08.17.
// Copyright © 2017 ConceptOffice. All rights reserved.
//
import UIKit
class RootViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
fileprivate var isLogged = false
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Welcome!"
sendLogInRequest()
}
}
// MARK: // UIWebViewDelegate
extension RootViewController: UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if isLogged == false {
tryLogInAccount(forURL: request.url!)
return true
} else if isLogged {
return false
} else {
return true
}
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print(error.localizedDescription)
}
}
extension RootViewController {
func receiveLoggedInstagramAccount(_ url: URL, completion: @escaping ((Error?) -> Void)) {
//Receive logged in user from url
isLogged = false
InstagramClient().receiveLoggedUser(url, completion: { (loggedUserId: String?, error: Error?) -> Void in
if loggedUserId != nil {
self.isLogged = true
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "RequestViewController") as! RequestViewController
self.navigationController?.pushViewController(controller, animated: true)
completion(nil)
} else {
completion(error)
}
})
}
func checkIsNeedToResendAuthorizationURL(for url: URL?) -> Bool {
if let urlString = url?.absoluteString {
print("check_url - \(url!.absoluteString) with \(urlString.contains("unknown_user"))")
return urlString.contains("unknown_user")
} else {
return false
}
}
}
private extension RootViewController {
func sendLogInRequest() {
let request = URLRequest(url: InstagramClient.InstagramAuthorisationUrl().serverSideFlowUrl!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
print(request.url!)
webView.loadRequest(request)
}
func tryLogInAccount(forURL url: URL) {
receiveLoggedInstagramAccount(url, completion: { [weak self] (error) in
guard let weakSelf = self else {
return
}
if let error = error {
print(error.localizedDescription)
} else if weakSelf.isLogged {
//TODO: Notify delegate
} else if weakSelf.checkIsNeedToResendAuthorizationURL(for: url) {
weakSelf.refreshRequest()
}
})
}
func refreshRequest() {
HTTPCookieStorage.shared.cookieAcceptPolicy = .always
sendLogInRequest()
}
}
|
mit
|
7a6a6ee112561ca3df6398e1f7d33bb7
| 26.176471 | 158 | 0.684343 | 4.62 | false | false | false | false |
burla69/PayDay
|
Pods/SideMenu/Pod/Classes/SideMenuTransition.swift
|
1
|
23293
|
//
// SideMenuTransition.swift
// Pods
//
// Created by Jon Kent on 1/14/16.
//
//
import UIKit
internal class SideMenuTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = false
private var interactive = false
private static weak var originalSuperview: UIView?
private static var switchMenus = false
internal static let singleton = SideMenuTransition()
internal static var presentDirection: UIRectEdge = .Left;
internal static weak var tapView: UIView!
internal static weak var statusBarView: UIView?
// prevent instantiation
private override init() {}
private class var viewControllerForPresentedMenu: UIViewController? {
get {
return SideMenuManager.menuLeftNavigationController?.presentingViewController != nil ? SideMenuManager.menuLeftNavigationController?.presentingViewController : SideMenuManager.menuRightNavigationController?.presentingViewController
}
}
private class var visibleViewController: UIViewController? {
get {
return getVisibleViewControllerFromViewController(UIApplication.sharedApplication().keyWindow?.rootViewController)
}
}
private class func getVisibleViewControllerFromViewController(viewController: UIViewController?) -> UIViewController? {
if let navigationController = viewController as? UINavigationController {
return getVisibleViewControllerFromViewController(navigationController.visibleViewController)
} else if let tabBarController = viewController as? UITabBarController {
return getVisibleViewControllerFromViewController(tabBarController.selectedViewController)
} else if let presentedViewController = viewController?.presentedViewController {
return getVisibleViewControllerFromViewController(presentedViewController)
}
return viewController
}
class func handlePresentMenuLeftScreenEdge(edge: UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = .Left
handlePresentMenuPan(edge)
}
class func handlePresentMenuRightScreenEdge(edge: UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = .Right
handlePresentMenuPan(edge)
}
class func handlePresentMenuPan(pan: UIPanGestureRecognizer) {
// how much distance have we panned in reference to the parent view?
guard let view = viewControllerForPresentedMenu != nil ? viewControllerForPresentedMenu?.view : pan.view else {
return
}
let transform = view.transform
view.transform = CGAffineTransformIdentity
let translation = pan.translationInView(pan.view!)
view.transform = transform
// do some math to translate this to a percentage based value
if !singleton.interactive {
if translation.x == 0 {
return // not sure which way the user is swiping yet, so do nothing
}
if !(pan is UIScreenEdgePanGestureRecognizer) {
SideMenuTransition.presentDirection = translation.x > 0 ? .Left : .Right
}
if let menuViewController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController,
visibleViewController = visibleViewController {
singleton.interactive = true
visibleViewController.presentViewController(menuViewController, animated: true, completion: nil)
}
}
let direction: CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
let distance = translation.x / SideMenuManager.menuWidth
// now lets deal with different states that the gesture recognizer sends
switch (pan.state) {
case .Began, .Changed:
if pan is UIScreenEdgePanGestureRecognizer {
singleton.updateInteractiveTransition(min(distance * direction, 1))
} else if distance > 0 && SideMenuTransition.presentDirection == .Right && SideMenuManager.menuLeftNavigationController != nil {
SideMenuTransition.presentDirection = .Left
switchMenus = true
singleton.cancelInteractiveTransition()
} else if distance < 0 && SideMenuTransition.presentDirection == .Left && SideMenuManager.menuRightNavigationController != nil {
SideMenuTransition.presentDirection = .Right
switchMenus = true
singleton.cancelInteractiveTransition()
} else {
singleton.updateInteractiveTransition(min(distance * direction, 1))
}
default:
singleton.interactive = false
view.transform = CGAffineTransformIdentity
let velocity = pan.velocityInView(pan.view!).x * direction
view.transform = transform
if velocity >= 100 || velocity >= -50 && abs(distance) >= 0.5 {
// bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called.
if NSProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) {
singleton.updateInteractiveTransition(0.9999)
}
singleton.finishInteractiveTransition()
} else {
singleton.cancelInteractiveTransition()
}
}
}
class func handleHideMenuPan(pan: UIPanGestureRecognizer) {
let translation = pan.translationInView(pan.view!)
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? -1 : 1
let distance = translation.x / SideMenuManager.menuWidth * direction
switch (pan.state) {
case .Began:
singleton.interactive = true
viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil)
case .Changed:
singleton.updateInteractiveTransition(max(min(distance, 1), 0))
default:
singleton.interactive = false
let velocity = pan.velocityInView(pan.view!).x * direction
if velocity >= 100 || velocity >= -50 && distance >= 0.5 {
// bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called.
if NSProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) {
singleton.updateInteractiveTransition(0.9999)
}
singleton.finishInteractiveTransition()
} else {
singleton.cancelInteractiveTransition()
}
}
}
class func handleHideMenuTap(tap: UITapGestureRecognizer) {
viewControllerForPresentedMenu?.dismissViewControllerAnimated(true, completion: nil)
}
internal class func hideMenuStart() {
NSNotificationCenter.defaultCenter().removeObserver(SideMenuTransition.singleton)
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view
menuView.transform = CGAffineTransformIdentity
mainViewController.view.transform = CGAffineTransformIdentity
mainViewController.view.alpha = 1
SideMenuTransition.tapView.frame = CGRectMake(0, 0, mainViewController.view.frame.width, mainViewController.view.frame.height)
menuView.frame.origin.y = 0
menuView.frame.size.width = SideMenuManager.menuWidth
menuView.frame.size.height = mainViewController.view.frame.height
SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame
SideMenuTransition.statusBarView?.alpha = 0
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
menuView.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
menuView.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
case .ViewSlideInOut:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width
mainViewController.view.frame.origin.x = 0
case .MenuSlideIn:
menuView.alpha = 1
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? -menuView.frame.width : mainViewController.view.frame.width
case .MenuDissolveIn:
menuView.alpha = 0
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth
mainViewController.view.frame.origin.x = 0
}
}
internal class func hideMenuComplete() {
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController!.view : SideMenuManager.menuRightNavigationController!.view
SideMenuTransition.tapView.removeFromSuperview()
SideMenuTransition.statusBarView?.removeFromSuperview()
mainViewController.view.motionEffects.removeAll()
mainViewController.view.layer.shadowOpacity = 0
menuView.layer.shadowOpacity = 0
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.enabled = true
}
originalSuperview?.addSubview(mainViewController.view)
}
internal class func presentMenuStart(forSize size: CGSize = UIScreen.mainScreen().bounds.size) {
guard let menuView = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view else {
return
}
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
menuView.transform = CGAffineTransformIdentity
mainViewController.view.transform = CGAffineTransformIdentity
menuView.frame.size.width = SideMenuManager.menuWidth
menuView.frame.size.height = size.height
menuView.frame.origin.x = SideMenuTransition.presentDirection == .Left ? 0 : size.width - SideMenuManager.menuWidth
SideMenuTransition.statusBarView?.frame = UIApplication.sharedApplication().statusBarFrame
SideMenuTransition.statusBarView?.alpha = 1
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
menuView.alpha = 1
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
mainViewController.view.frame.origin.x = direction * (menuView.frame.width)
mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius
mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
mainViewController.view.layer.shadowOffset = CGSizeMake(0, 0)
case .ViewSlideInOut:
menuView.alpha = 1
menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius
menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
menuView.layer.shadowOffset = CGSizeMake(0, 0)
let direction:CGFloat = SideMenuTransition.presentDirection == .Left ? 1 : -1
mainViewController.view.frame.origin.x = direction * (menuView.frame.width)
mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
case .MenuSlideIn, .MenuDissolveIn:
menuView.alpha = 1
menuView.layer.shadowColor = SideMenuManager.menuShadowColor.CGColor
menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius
menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity
menuView.layer.shadowOffset = CGSizeMake(0, 0)
mainViewController.view.frame = CGRectMake(0, 0, size.width, size.height)
mainViewController.view.transform = CGAffineTransformMakeScale(SideMenuManager.menuAnimationTransformScaleFactor, SideMenuManager.menuAnimationTransformScaleFactor)
mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength
}
}
internal class func presentMenuComplete() {
NSNotificationCenter.defaultCenter().addObserver(SideMenuTransition.singleton, selector:#selector(SideMenuTransition.applicationDidEnterBackgroundNotification), name: UIApplicationDidEnterBackgroundNotification, object: nil)
let mainViewController = SideMenuTransition.viewControllerForPresentedMenu!
switch SideMenuManager.menuPresentMode {
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
if SideMenuManager.menuParallaxStrength != 0 {
let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
horizontal.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
horizontal.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
vertical.minimumRelativeValue = -SideMenuManager.menuParallaxStrength
vertical.maximumRelativeValue = SideMenuManager.menuParallaxStrength
let group = UIMotionEffectGroup()
group.motionEffects = [horizontal, vertical]
mainViewController.view.addMotionEffect(group)
}
case .ViewSlideOut: break;
}
if let topNavigationController = mainViewController as? UINavigationController {
topNavigationController.interactivePopGestureRecognizer!.enabled = false
}
}
// MARK: UIViewControllerAnimatedTransitioning protocol methods
// animate a change from one viewcontroller to another
internal func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView()!
if let menuBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
container.backgroundColor = menuBackgroundColor
}
// create a tuple of our screens
let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!)
// assign references to our menu view controller and the 'bottom' view controller from the tuple
// remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing
let menuViewController = (!presenting ? screens.from : screens.to)
let topViewController = !presenting ? screens.to : screens.from
let menuView = menuViewController.view
let topView = topViewController.view
// prepare menu items to slide in
if presenting {
let tapView = UIView()
tapView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
let exitPanGesture = UIPanGestureRecognizer()
exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:)))
let exitTapGesture = UITapGestureRecognizer()
exitTapGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuTap(_:)))
tapView.addGestureRecognizer(exitPanGesture)
tapView.addGestureRecognizer(exitTapGesture)
SideMenuTransition.tapView = tapView
SideMenuTransition.originalSuperview = topView.superview
// add the both views to our view controller
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
container.addSubview(menuView)
container.addSubview(topView)
topView.addSubview(tapView)
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
container.addSubview(topView)
container.addSubview(tapView)
container.addSubview(menuView)
}
if SideMenuManager.menuFadeStatusBar {
let blackBar = UIView()
if let menuShrinkBackgroundColor = SideMenuManager.menuAnimationBackgroundColor {
blackBar.backgroundColor = menuShrinkBackgroundColor
} else {
blackBar.backgroundColor = UIColor.blackColor()
}
blackBar.userInteractionEnabled = false
container.addSubview(blackBar)
SideMenuTransition.statusBarView = blackBar
}
SideMenuTransition.hideMenuStart() // offstage for interactive
}
// perform the animation!
let duration = transitionDuration(transitionContext)
let options: UIViewAnimationOptions = interactive ? .CurveLinear : .CurveEaseInOut
UIView.animateWithDuration(duration, delay: 0, options: options, animations: { () -> Void in
if self.presenting {
SideMenuTransition.presentMenuStart() // onstage items: slide in
}
else {
SideMenuTransition.hideMenuStart()
}
}) { (finished) -> Void in
// tell our transitionContext object that we've finished animating
if transitionContext.transitionWasCancelled() {
let viewControllerForPresentedMenu = SideMenuTransition.viewControllerForPresentedMenu
if self.presenting {
SideMenuTransition.hideMenuComplete()
} else {
SideMenuTransition.presentMenuComplete()
}
transitionContext.completeTransition(false)
if SideMenuTransition.switchMenus {
SideMenuTransition.switchMenus = false
viewControllerForPresentedMenu?.presentViewController(SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController! : SideMenuManager.menuRightNavigationController!, animated: true, completion: nil)
}
return
}
if self.presenting {
SideMenuTransition.presentMenuComplete()
transitionContext.completeTransition(true)
switch SideMenuManager.menuPresentMode {
case .ViewSlideOut:
container.addSubview(topView)
case .MenuSlideIn, .MenuDissolveIn, .ViewSlideInOut:
container.insertSubview(topView, atIndex: 0)
}
if let statusBarView = SideMenuTransition.statusBarView {
container.bringSubviewToFront(statusBarView)
}
return
}
SideMenuTransition.hideMenuComplete()
transitionContext.completeTransition(true)
menuView.removeFromSuperview()
}
}
// return how many seconds the transiton animation will take
internal func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return presenting ? SideMenuManager.menuAnimationPresentDuration : SideMenuManager.menuAnimationDismissDuration
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animator when presenting a viewcontroller
// rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
internal func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
SideMenuTransition.presentDirection = presented == SideMenuManager.menuLeftNavigationController ? .Left : .Right
return self
}
// return the animator used when dismissing from a viewcontroller
internal func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presenting = false
return self
}
internal func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
// if our interactive flag is true, return the transition manager object
// otherwise return nil
return interactive ? SideMenuTransition.singleton : nil
}
internal func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactive ? SideMenuTransition.singleton : nil
}
internal func applicationDidEnterBackgroundNotification() {
if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .Left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController {
SideMenuTransition.hideMenuStart()
SideMenuTransition.hideMenuComplete()
menuViewController.dismissViewControllerAnimated(false, completion: nil)
}
}
}
|
mit
|
3bccad6877636f0e53802e81f0472e4e
| 52.547126 | 253 | 0.679732 | 6.911869 | false | false | false | false |
ksco/swift-algorithm-club-cn
|
Shunting Yard/ShuntingYard.playground/Contents.swift
|
1
|
5306
|
//: Playground - noun: a place where people can play
internal enum OperatorAssociativity {
case LeftAssociative
case RightAssociative
}
public enum OperatorType: CustomStringConvertible {
case Add
case Subtract
case Divide
case Multiply
case Percent
case Exponent
public var description: String {
switch self {
case Add:
return "+"
case Subtract:
return "-"
case Divide:
return "/"
case Multiply:
return "*"
case Percent:
return "%"
case Exponent:
return "^"
}
}
}
public enum TokenType: CustomStringConvertible {
case OpenBracket
case CloseBracket
case Operator(OperatorToken)
case Operand(Double)
public var description: String {
switch self {
case OpenBracket:
return "("
case CloseBracket:
return ")"
case Operator(let operatorToken):
return operatorToken.description
case Operand(let value):
return "\(value)"
}
}
}
public struct OperatorToken: CustomStringConvertible {
let operatorType: OperatorType
init(operatorType: OperatorType) {
self.operatorType = operatorType
}
var precedence: Int {
switch operatorType {
case .Add, .Subtract:
return 0
case .Divide, .Multiply, .Percent:
return 5
case .Exponent:
return 10
}
}
var associativity: OperatorAssociativity {
switch operatorType {
case .Add, .Subtract, .Divide, .Multiply, .Percent:
return .LeftAssociative;
case .Exponent:
return .RightAssociative
}
}
public var description: String {
return operatorType.description
}
}
func <=(left: OperatorToken, right: OperatorToken) -> Bool {
return left.precedence <= right.precedence
}
func <(left: OperatorToken, right: OperatorToken) -> Bool {
return left.precedence < right.precedence
}
public struct Token: CustomStringConvertible {
let tokenType: TokenType
init(tokenType: TokenType) {
self.tokenType = tokenType
}
init(operand: Double) {
tokenType = .Operand(operand)
}
init(operatorType: OperatorType) {
tokenType = .Operator(OperatorToken(operatorType: operatorType))
}
var isOpenBracket: Bool {
switch tokenType {
case .OpenBracket:
return true
default:
return false
}
}
var isOperator: Bool {
switch tokenType {
case .Operator(_):
return true
default:
return false
}
}
var operatorToken: OperatorToken? {
switch tokenType {
case .Operator(let operatorToken):
return operatorToken
default:
return nil
}
}
public var description: String {
return tokenType.description
}
}
public class InfixExpressionBuilder {
private var expression = [Token]()
public func addOperator(operatorType: OperatorType) -> InfixExpressionBuilder {
expression.append(Token(operatorType: operatorType))
return self
}
public func addOperand(operand: Double) -> InfixExpressionBuilder {
expression.append(Token(operand: operand))
return self
}
public func addOpenBracket() -> InfixExpressionBuilder {
expression.append(Token(tokenType: .OpenBracket))
return self
}
public func addCloseBracket() -> InfixExpressionBuilder {
expression.append(Token(tokenType: .CloseBracket))
return self
}
public func build() -> [Token] {
// Maybe do some validation here
return expression
}
}
// This returns the result of the shunting yard algorithm
public func reversePolishNotation(expression: [Token]) -> String {
var tokenStack = Stack<Token>()
var reversePolishNotation = [Token]()
for token in expression {
switch token.tokenType {
case .Operand(_):
reversePolishNotation.append(token)
case .OpenBracket:
tokenStack.push(token)
case .CloseBracket:
while tokenStack.count > 0, let tempToken = tokenStack.pop() where !tempToken.isOpenBracket {
reversePolishNotation.append(tempToken)
}
case .Operator(let operatorToken):
for tempToken in tokenStack.generate() {
if !tempToken.isOperator {
break
}
if let tempOperatorToken = tempToken.operatorToken {
if operatorToken.associativity == .LeftAssociative && operatorToken <= tempOperatorToken
|| operatorToken.associativity == .RightAssociative && operatorToken < tempOperatorToken {
reversePolishNotation.append(tokenStack.pop()!)
} else {
break
}
}
}
tokenStack.push(token)
}
}
while tokenStack.count > 0 {
reversePolishNotation.append(tokenStack.pop()!)
}
return reversePolishNotation.map({token in token.description}).joinWithSeparator(" ")
}
// Simple demo
let expr = InfixExpressionBuilder().addOperand(3).addOperator(.Add).addOperand(4).addOperator(.Multiply).addOperand(2).addOperator(.Divide).addOpenBracket().addOperand(1).addOperator(.Subtract).addOperand(5).addCloseBracket().addOperator(.Exponent).addOperand(2).addOperator(.Exponent).addOperand(3).build()
print(expr.description)
print(reversePolishNotation(expr))
|
mit
|
eb556b5e7768ce20031698e21453f899
| 22.900901 | 307 | 0.655673 | 4.899354 | false | false | false | false |
jkandzi/Colors.swift
|
Sources/Colors.swift
|
1
|
2646
|
//
// Colors.swift
// Colors
//
// Created by Justus Kandzi on 22/10/15.
// Copyright © 2015 justus kandzi. All rights reserved.
//
import Foundation
private let colorsSupported: Bool = {
if Process.arguments.contains("--no-color")
|| Process.arguments.contains("--color=false") {
return false
}
if Process.arguments.contains("--color")
|| Process.arguments.contains("--color=true")
|| Process.arguments.contains("--color=always") {
return true
}
let cString = getenv("TERM")
guard let term = String.fromCString(cString) else {
return false
}
return term.hasPrefix("screen")
|| term.hasPrefix("xterm")
|| term.hasPrefix("vt100")
|| term.containsString("color")
|| term.containsString("ansi")
|| term.containsString("cygwin")
|| term.containsString("linux")
}()
public extension String {
public enum ColorsColor: Int {
case Black = 30
case Red
case Green
case Yellow
case Blue
case Magenta
case Cyan
case White
case Gray = 90
}
public enum ColorsBackground: Int {
case OnBlack = 40
case OnRed
case OnGreen
case OnYellow
case OnBlue
case OnMagenta
case OnCyan
case OnWhite
case OnGray = 90
}
public enum ColorsStyle: Int {
case Bold = 1
case Dim
case Italic
case Underline
case Inverse = 7
case Hidden
case Strikethrough
}
public func paint(color: ColorsColor) -> String {
return applyCode((color.rawValue, 39))
}
public func paint(background: ColorsBackground) -> String {
return applyCode((background.rawValue, 49))
}
public func paint(color: ColorsColor, _ background: ColorsBackground) -> String {
return paint(color).paint(background)
}
public func paint(color: ColorsColor, _ background: ColorsBackground, _ style: ColorsStyle) -> String {
return paint(color).paint(background).style(style)
}
public func style(style: ColorsStyle) -> String {
if style == .Bold {
return applyCode((style.rawValue, 22))
}
else {
return applyCode((style.rawValue, style.rawValue + 20))
}
}
private func applyCode(code: (start: Int, end: Int)) -> String {
if !colorsSupported {
return self
}
return "\u{001b}[\(code.start)m\(self)\u{001b}[\(code.end)m"
}
}
|
mit
|
bc7e186c3cbba1fa16115dc817bda339
| 24.190476 | 107 | 0.567486 | 4.400998 | false | false | false | false |
ksco/swift-algorithm-club-cn
|
Select Minimum Maximum/SelectMinimumMaximum.playground/Contents.swift
|
1
|
1574
|
// Compare each item to find minimum
func minimum<T: Comparable>(var array: [T]) -> T? {
guard !array.isEmpty else {
return nil
}
var minimum = array.removeFirst()
for element in array {
minimum = element < minimum ? element : minimum
}
return minimum
}
// Compare each item to find maximum
func maximum<T: Comparable>(var array: [T]) -> T? {
guard !array.isEmpty else {
return nil
}
var maximum = array.removeFirst()
for element in array {
maximum = element > maximum ? element : maximum
}
return maximum
}
// Compare in pairs to find minimum and maximum
func minimumMaximum<T: Comparable>(var array: [T]) -> (minimum: T, maximum: T)?
{
guard !array.isEmpty else {
return nil
}
var minimum = array.first!
var maximum = array.first!
let hasOddNumberOfItems = array.count % 2 != 0
if hasOddNumberOfItems {
array.removeFirst()
}
while !array.isEmpty {
let pair = (array.removeFirst(), array.removeFirst())
if pair.0 > pair.1 {
if pair.0 > maximum {
maximum = pair.0
}
if pair.1 < minimum {
minimum = pair.1
}
} else {
if pair.1 > maximum {
maximum = pair.1
}
if pair.0 < minimum {
minimum = pair.0
}
}
}
return (minimum, maximum)
}
// Test of minimum and maximum functions
let array = [ 8, 3, 9, 4, 6 ]
minimum(array)
maximum(array)
// Test of minimumMaximum function
let result = minimumMaximum(array)!
result.minimum
result.maximum
// Built-in Swift functions
array.minElement()
array.maxElement()
|
mit
|
21ee27878946149e64e4468c0b83ac13
| 19.441558 | 79 | 0.630241 | 3.729858 | false | false | false | false |
RemyDCF/tpg-offline
|
tpg offline watchOS Extension/Departures/ReminderInterfaceController.swift
|
1
|
4415
|
//
// ReminderInterfaceController.swift
// tpg offline watchOS Extension
//
// Created by Rémy Da Costa Faro on 06/04/2018.
// Copyright © 2018 Rémy Da Costa Faro. All rights reserved.
//
import WatchKit
import Foundation
import Alamofire
import UserNotifications
class ReminderInterfaceController: WKInterfaceController, WKCrownDelegate {
@IBOutlet weak var beforeTimeImageView: WKInterfaceImage!
var minutesBeforeDeparture = 10
let expectedMoveDelta = 0.2617995
var crownRotationalDelta = 0.0
var departure: Departure?
var maximum = 60
override func awake(withContext context: Any?) {
super.awake(withContext: context)
guard let option = context as? Departure else {
print("Context is not in a valid format")
return
}
departure = option
if Int(departure?.leftTime ?? "") ?? 0 < 60 {
maximum = Int(departure?.leftTime ?? "") ?? 0
}
if let leftTime = departure?.leftTime, Int(leftTime) ?? 0 < 10 {
beforeTimeImageView.setImageNamed("reminderCircle-\(leftTime)")
}
crownSequencer.delegate = self
crownSequencer.focus()
}
override func willActivate() {
super.willActivate()
crownSequencer.focus()
}
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
crownRotationalDelta += rotationalDelta
if crownRotationalDelta > expectedMoveDelta {
let newValue = minutesBeforeDeparture + 1
if newValue < 0 {
minutesBeforeDeparture = 0
} else if newValue > maximum {
minutesBeforeDeparture = maximum
} else {
minutesBeforeDeparture = newValue
}
beforeTimeImageView.setImageNamed("reminderCircle-\(minutesBeforeDeparture)")
crownRotationalDelta = 0.0
} else if crownRotationalDelta < -expectedMoveDelta {
let newValue = minutesBeforeDeparture - 1
if newValue < 0 {
minutesBeforeDeparture = 0
} else if newValue > maximum {
minutesBeforeDeparture = maximum
} else {
minutesBeforeDeparture = newValue
}
beforeTimeImageView.setImageNamed("reminderCircle-\(minutesBeforeDeparture)")
crownRotationalDelta = 0.0
}
}
@IBAction func setReminder() {
guard let departure = self.departure else { return }
setAlert(with: minutesBeforeDeparture, departure: departure)
}
func setAlert(with timeBefore: Int,
departure: Departure,
forceDisableSmartReminders: Bool = false) {
var departure = departure
departure.calculateLeftTime()
let date = departure.dateCompenents?.date?
.addingTimeInterval(TimeInterval(timeBefore * -60))
let components = Calendar.current.dateComponents([.hour,
.minute,
.day,
.month,
.year],
from: date ?? Date())
let trigger = UNCalendarNotificationTrigger(dateMatching: components,
repeats: false)
let content = UNMutableNotificationContent()
content.title = timeBefore == 0 ?
Text.busIsCommingNow : Text.minutesLeft(timeBefore)
content.body = Text.take(line: departure.line.code,
to: departure.line.destination)
content.sound = UNNotificationSound.default
let request =
UNNotificationRequest(identifier:
"departureNotification-\(String.random(30))",
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
let action = WKAlertAction(title: Text.ok, style: .default, handler: {})
self.presentAlert(withTitle: Text.error,
message: Text.sorryError,
preferredStyle: .alert, actions: [action])
} else {
let action = WKAlertAction(title: Text.ok, style: .default, handler: {
self.dismiss()
})
self.presentAlert(
withTitle: Text.youWillBeReminded,
message: Text.notificationWillBeSend(minutes: timeBefore),
preferredStyle: .alert,
actions: [action])
}
}
}
}
|
mit
|
7d77f6b151d0f94e42b539794a2177d2
| 34.580645 | 85 | 0.616727 | 4.929609 | false | false | false | false |
amco/couchbase-lite-ios
|
Swift/ArrayObject.swift
|
1
|
8309
|
//
// ArrayObject.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// ArrayProtocol defines a set of methods for readonly accessing array data.
protocol ArrayProtocol: ArrayFragment {
var count: Int { get }
func value(at index: Int) -> Any?
func string(at index: Int) -> String?
func int(at index: Int) -> Int
func int64(at index: Int) -> Int64
func float(at index: Int) -> Float
func double(at index: Int) -> Double
func number(at index: Int) -> NSNumber?
func boolean(at index: Int) -> Bool
func blob(at index: Int) -> Blob?
func date(at index: Int) -> Date?
func array(at index: Int) -> ArrayObject?
func dictionary(at index: Int) -> DictionaryObject?
func toArray() -> Array<Any>
}
/// ArrayObject provides readonly access to array data.
public class ArrayObject: ArrayProtocol, Equatable, Hashable, Sequence {
/// Gets a number of the items in the array.
public var count: Int {
return Int(_impl.count)
}
/// Gets the value at the given index. The value types are Blob, ArrayObject,
/// DictionaryObject, Number, or String based on the underlying data type.
///
/// - Parameter index: The index.
/// - Returns: The value located at the index.
public func value(at index: Int) -> Any? {
return DataConverter.convertGETValue(_impl.value(at: UInt(index)))
}
/// Gets the value at the given index as a string.
/// Returns nil if the value doesn't exist, or its value is not a string
///
/// - Parameter index: The index.
/// - Returns: The String object.
public func string(at index: Int) -> String? {
return _impl.string(at: UInt(index))
}
/// Gets value at the given index as a Number value.
///
/// - Parameter index: The index.
/// - Returns: The number value located at the index.
public func number(at index: Int) -> NSNumber? {
return _impl.number(at: UInt(index))
}
/// Gets value at the given index as an int value.
/// Floating point values will be rounded. The value `true` is returned as 1, `false` as 0.
/// Returns 0 if the value doesn't exist or does not have a numeric value.
///
/// - Parameter index: The index.
/// - Returns: The int value located at the index.
public func int(at index: Int) -> Int {
return _impl.integer(at: UInt(index))
}
/// Gets value at the given index as an int64 value.
/// Floating point values will be rounded. The value `true` is returned as 1, `false` as 0.
/// Returns 0 if the value doesn't exist or does not have a numeric value.
///
/// - Parameter index: The index.
/// - Returns: The int64 value located at the index.
public func int64(at index: Int) -> Int64 {
return _impl.longLong(at: UInt(index))
}
/// Gets the value at the given index as a float value.
/// Integers will be converted to float. The value `true` is returned as 1.0, `false` as 0.0.
//// Returns 0.0 if the value doesn't exist or does not have a numeric value.
///
/// - Parameter index: The index.
/// - Returns: The Float value located at the index.
public func float(at index: Int) -> Float {
return _impl.float(at: UInt(index))
}
/// Gets the value at the given index as a double value.
/// Integers will be converted to double. The value `true` is returned as 1.0, `false` as 0.0.
/// Returns 0.0 if the property doesn't exist or does not have a numeric value.
///
/// - Parameter index: The index.
/// - Returns: The Double value located at the index.
public func double(at index: Int) -> Double {
return _impl.double(at: UInt(index))
}
/// Gets the value at the given index as a boolean value.
/// Returns true if the value exists, and is either `true` or a nonzero number.
///
/// - Parameter index: The index.
/// - Returns: The Bool value located at the index.
public func boolean(at index: Int) -> Bool {
return _impl.boolean(at: UInt(index))
}
/// Gets value at the given index as an Date.
/// JSON does not directly support dates, so the actual property value must be a string, which
/// is then parsed according to the ISO-8601 date format (the default used in JSON.)
/// Returns nil if the value doesn't exist, is not a string, or is not parseable as a date.
/// NOTE: This is not a generic date parser! It only recognizes the ISO-8601 format, with or
/// without milliseconds.
///
/// - Parameter index: The index.
/// - Returns: The Date value at the given index.
public func date(at index: Int) -> Date? {
return _impl.date(at: UInt(index))
}
/// Get the Blob value at the given index.
/// Returns nil if the value doesn't exist, or its value is not a blob.
///
/// - Parameter index: The index.
/// - Returns: The Blob value located at the index.
public func blob(at index: Int) -> Blob? {
return _impl.blob(at: UInt(index))
}
/// Gets the value at the given index as a ArrayObject value, which is a mapping object
/// of an array value.
/// Returns nil if the value doesn't exists, or its value is not an array.
///
/// - Parameter index: The index.
/// - Returns: The ArrayObject at the given index.
public func array(at index: Int) -> ArrayObject? {
return value(at: index) as? ArrayObject
}
/// Get the value at the given index as a DictionaryObject value, which is a
/// mapping object of a dictionary value.
/// Returns nil if the value doesn't exists, or its value is not a dictionary.
///
/// - Parameter index: The index.
/// - Returns: The DictionaryObject
public func dictionary(at index: Int) -> DictionaryObject? {
return value(at: index) as? DictionaryObject
}
/// Gets content of the current object as an Array. The value types of the values
/// contained in the returned Array object are Array, Blob, Dictionary,
/// Number types, NSNull, and String.
///
/// - Returns: The Array representing the content of the current object.
public func toArray() -> Array<Any> {
return _impl.toArray()
}
// MARK: Sequence
/// Gets an iterator over items in the array.
///
/// - Returns: The array item iterator.
public func makeIterator() -> AnyIterator<Any> {
var index = 0;
let count = self.count
return AnyIterator {
if index < count {
let v = self.value(at: index)
index += 1
return v;
}
return nil
}
}
// MARK: Subscript
/// Subscript access to a Fragment object by index
///
/// - Parameter index: The Index.
public subscript(index: Int) -> Fragment {
return Fragment(_impl[UInt(index)])
}
// MARK: Equality
/// Equal to operator for comparing two Array objects.
public static func == (array1: ArrayObject, array2: ArrayObject) -> Bool {
return array1._impl == array2._impl
}
// MARK: Hashable
public var hashValue: Int {
return _impl.hash;
}
// MARK: Internal
init(_ impl: CBLArray) {
_impl = impl
_impl.swiftObject = self
}
deinit {
_impl.swiftObject = nil
}
let _impl: CBLArray
}
|
apache-2.0
|
fda063b1fb451a8bec6d789ca2cea4a7
| 30.593156 | 98 | 0.607534 | 4.269784 | false | false | false | false |
ninjaprawn/iFW
|
iOS/iFW/FirmwareTableViewController.swift
|
1
|
1188
|
//
// FirmwareTableViewController.swift
// iFW
//
// Created by George Dan on 31/03/2016.
// Copyright © 2016 George Dan. All rights reserved.
//
import UIKit
class FirmwareTableViewController: UITableViewController {
var device: Device!
override func viewDidLoad() {
super.viewDidLoad()
self.title = device.deviceName
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return device.firmwares.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("detail", forIndexPath: indexPath)
cell.textLabel?.text = device.firmwares[indexPath.row].version
cell.detailTextLabel?.text = device.firmwares[indexPath.row].buildID
if device.firmwares[indexPath.row].signed {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
|
mit
|
0f7f879ae330992a2b9abaaec496a6e1
| 25.377778 | 118 | 0.723673 | 4.618677 | false | false | false | false |
MartinGao/MartinWheel
|
Pod/Classes/UITabBarController+MartinWheel.swift
|
1
|
1343
|
//
// UITabBarController+MartinWheel.swift
// DigestsCard
//
// Created by Martin Gao on 3/5/15.
// Copyright (c) 2015 SirioLabs. All rights reserved.
//
import Foundation
extension UITabBarController{
func MTSetupTabBarColor(color:UIColor){
self.tabBar.barTintColor = color;
self.tabBar.tintColor = UIColor(contrastingBlackOrWhiteColorOn: color, isFlat: false)
}
func MTSetTitleForSelectedTabItem(title:String){
if let tabBarItems = self.tabBar.items{
let selectedIndex = self.selectedIndex
if let item = tabBarItems[selectedIndex] as? UITabBarItem{
item.title = title;
}
else{
println("[ERROR] NO TABBAR ITEM");
}
}
else{
println("[ERROR] NO TABBAR ITEMS");
}
}
func MTSetTitleAndImageForSelectedTabItem(title:String,image:UIImage){
if let tabBarItems = self.tabBar.items{
let selectedIndex = self.selectedIndex
if let item = tabBarItems[selectedIndex] as? UITabBarItem{
item.title = title;
item.image = image;
}
else{
println("[ERROR] NO TABBAR ITEM");
}
}
else{
println("[ERROR] NO TABBAR ITEMS");
}
}
}
|
mit
|
caa4e38d1e4145624968411f2d2b3698
| 27.595745 | 93 | 0.572599 | 4.599315 | false | false | false | false |
RoverPlatform/rover-ios-beta
|
Sources/UI/Views/Polls/ImagePollOptionCaption.swift
|
2
|
2496
|
//
// ImagePollOptionCaption.swift
// Rover
//
// Created by Sean Rucker on 2019-08-15.
// Copyright © 2019 Rover Labs Inc. All rights reserved.
//
import UIKit
class ImagePollOptionCaption: UIView {
let indicator = UILabel()
let optionLabel = UILabel()
let stackView = UIStackView()
let option: ImagePollBlock.ImagePoll.Option
var isSelected = false {
didSet {
if isSelected {
if !stackView.arrangedSubviews.contains(indicator) {
stackView.insertArrangedSubview(indicator, at: 1)
}
} else {
indicator.removeFromSuperview()
}
}
}
init(option: ImagePollBlock.ImagePoll.Option) {
self.option = option
super.init(frame: .zero)
heightAnchor.constraint(equalToConstant: 40).isActive = true
// stackView
stackView.spacing = 8
stackView.layoutMargins = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
stackView.isLayoutMarginsRelativeArrangement = true
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.bottomAnchor.constraint(equalTo: bottomAnchor),
stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
stackView.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor),
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor)
])
// optionLabel
optionLabel.font = option.text.font.uiFont
optionLabel.text = option.text.rawValue
optionLabel.textColor = option.text.color.uiColor
optionLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
optionLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
stackView.addArrangedSubview(optionLabel)
// indicator
indicator.font = option.text.font.uiFont
indicator.text = "•"
indicator.textColor = option.text.color.uiColor
indicator.setContentHuggingPriority(.defaultHigh, for: .horizontal)
indicator.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
680ca5b9e1e8310786413c6591b0d7d5
| 33.625 | 90 | 0.645808 | 5.407809 | false | false | false | false |
shyamalschandra/Design-Patterns-In-Swift
|
source/behavioral/command.swift
|
26
|
1257
|
/*:
👫 Command
----------
The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
### Example:
*/
protocol DoorCommand {
func execute() -> String
}
class OpenCommand : DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
class CloseCommand : DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
/*:
### Usage:
*/
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
|
gpl-3.0
|
9025116880495f207dd7e2a44cb75597
| 19.557377 | 204 | 0.633174 | 3.8 | false | false | false | false |
codepgq/WeiBoDemo
|
PQWeiboDemo/PQWeiboDemo/classes/Oauth/PQOAuthViewController.swift
|
1
|
5115
|
//
// PQLoginViewController.swift
// PQWeiboDemo
//
// Created by ios on 16/9/26.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
import WebKit
import SVProgressHUD
class PQOAuthViewController: UIViewController{
private lazy var webView : UIWebView = {
let web = UIWebView(frame: UIScreen.main.bounds)
web.delegate = self
return web
}()
// private lazy var webView : WKWebView = {
// let web = WKWebView(frame: UIScreen.main.bounds)
// web.navigationDelegate = self
// return web
// }()
/// app key
let WB_App_ID = "822933555"
let WB_App_Secret = "46e328943e0daab0fb7c458482d18f38"
let WB_redirect_uri = "https://www.baidu.com/"
// 1、把当前的View替换成为webView
override func loadView() {
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// 1、设置web代理 默认加载项
setUpWebView()
// 2、添加一个关闭按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action: #selector(PQOAuthViewController.close))
// 3、设置标题
navigationItem.title = "使用微博登录"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
}
private func setUpWebView(){
let url = NSURL.init(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_ID)&redirect_uri=\(WB_redirect_uri)")
let request = NSURLRequest(url: url! as URL)
webView.loadRequest(request as URLRequest)
//WKWebView
// webView.load(request as URLRequest)
}
@objc func close(){
dismiss(animated: true, completion: nil)
}
deinit {
print("退出了当前页面")
}
}
// WKWebView delegate
extension PQOAuthViewController : WKNavigationDelegate{
}
// UIWebView
extension PQOAuthViewController : UIWebViewDelegate{
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.show(withStatus: "正在加载……")
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss()
}
// 加载失败
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
close()
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
// 这里做跳转处理
print((request.url?.absoluteString)! as String)
let absoluteString = request.url!.absoluteString
//如果是回调页 并且授权成功就继续
if !absoluteString.hasPrefix(WB_redirect_uri) {
// 不是回调页就继续
return true
}
//如果成功了表示点击了授权
let codeStr = "code="
if request.url!.query!.hasPrefix(codeStr) {
//这句就是先比较code=,然后从最后一个取出request_Token
// print("...........\(request.url?.query?.substring(from: codeStr.endIndex))")
let code = request.url!.query?.substring(from: codeStr.endIndex)
//利用以及授权的RequestToken 换区 AccessToken
loadAccessToken(code: code!)
}
else{//点击取消授权了
close()
}
return true
}
// 用已经授权的RequestToken换取AccessToken
private func loadAccessToken(code :String){
// 1、定义路径
let url = "oauth2/access_token"
// 2、包装参数
let parames = [
"client_id":WB_App_ID,
"client_secret":WB_App_Secret,
"grant_type":"authorization_code",
"code":code,
"redirect_uri":WB_redirect_uri
]
// 3、发送请求
PQNetWorkManager.shareNetWorkManager().post(url, parameters: parames, progress: nil, success: { (_, JSON) in
// print(JSON)
let account = PQOauthInfo(dict: JSON as! [String:AnyObject] as NSDictionary)
print(account)
// 通过accessToken、uid去获取个人信息
account.loadUserInfo(finished: { (account, error) in
if error == nil{
//把信息归档保存
account?.saveAccountInfo()
SVProgressHUD.showSuccess(withStatus: "授权成功")
// 去欢迎回来页面
NotificationCenter.default.post(name: NSNotification.Name(rawValue: PQChangeRootViewControllerKey), object: false)
}
})
}) { (_, error) in
print(error)
}
}
}
|
mit
|
25ffd1ea9cce7cfb09c4153b4fc8c5f4
| 26.604651 | 170 | 0.567397 | 4.574181 | false | false | false | false |
dreamsxin/swift
|
test/IRGen/closure.swift
|
3
|
3226
|
// RUN: %target-swift-frontend -primary-file %s -emit-ir | FileCheck %s
// REQUIRES: CPU=x86_64
// -- partial_apply context metadata
// CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 64 }, i32 16, i8* bitcast (<{ i32, i32, i32, i32 }>* @"\01l__swift3_capture_descriptor" to i8*) }
func a(i i: Int) -> (Int) -> Int {
return { x in i }
}
// -- Closure entry point
// CHECK: define linkonce_odr hidden i64 @_TFF7closure1aFT1iSi_FSiSiU_FSiSi(i64, i64)
protocol Ordinable {
func ord() -> Int
}
func b<T : Ordinable>(seq seq: T) -> (Int) -> Int {
return { i in i + seq.ord() }
}
// -- partial_apply stub
// CHECK: define internal i64 @_TPA__TFF7closure1aFT1iSi_FSiSiU_FSiSi(i64, %swift.refcounted*)
// CHECK: }
// -- Closure entry point
// CHECK: define linkonce_odr hidden i64 @[[CLOSURE2:_TFF7closure1buRxS_9OrdinablerFT3seqx_FSiSiU_FSiSi]](i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} {
// -- partial_apply stub
// CHECK: define internal i64 @_TPA_[[CLOSURE2]](i64, %swift.refcounted*) {{.*}} {
// CHECK: entry:
// CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>*
// CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1
// CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]]
// CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8
// CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1
// CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]]
// CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8
// CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2
// CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8
// CHECK: call void @rt_swift_retain(%swift.refcounted* [[BOX]])
// CHECK: call void @rt_swift_release(%swift.refcounted* %1)
// CHECK: [[RES:%.*]] = tail call i64 @[[CLOSURE2]](i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]])
// CHECK: ret i64 [[RES]]
// CHECK: }
// -- <rdar://problem/14443343> Boxing of tuples with generic elements
// CHECK: define hidden { i8*, %swift.refcounted* } @_TF7closure14captures_tupleu0_rFT1xTxq___FT_Txq__(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U)
func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null)
// CHECK-NOT: @swift_getTupleTypeMetadata2
// CHECK: [[BOX:%.*]] = call { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]])
// CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1
// CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>*
return {x}
}
|
apache-2.0
|
e5a1c103a4d536f114d1bf97a9626728
| 54.62069 | 241 | 0.625232 | 3.110897 | false | false | false | false |
etiennemartin/jugglez
|
Jugglez/Button.swift
|
1
|
2201
|
//
// Button.swift
// Jugglez
//
// Created by Etienne Martin on 2015-03-14.
// Copyright (c) 2015 Etienne Martin. All rights reserved.
//
import SpriteKit
class Button: SKShapeNode {
private var _button: SKShapeNode = SKShapeNode()
private var _label: SKLabelNode = SKLabelNode()
private let _shadowColor = SKColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.20)
init(size: CGSize, position: CGPoint, text: String) {
let frame: CGRect = CGRect(x: position.x, y: position.y, width: size.width, height: size.height)
super.init()
bootstrapInit(frame, text:text)
}
init (frame: CGRect, text: String) {
super.init()
bootstrapInit(frame, text:text)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bootstrapInit(frame: CGRect, text: String) {
let cornerRadius: CGFloat = 10
let shadowOffset: CGFloat = 2
_button = SKShapeNode(rect: frame, cornerRadius: cornerRadius)
_button.strokeColor = SKColor.themeLightBackgroundColor()
_button.fillColor = SKColor.themeLightBackgroundColor()
let shadow = SKShapeNode(rect: frame, cornerRadius: cornerRadius)
shadow.strokeColor = _shadowColor
shadow.fillColor = _shadowColor
shadow.position.x += shadowOffset
shadow.position.y -= shadowOffset
_label = SKLabelNode(text: text)
_label.fontName = SKLabelNode.defaultFontName()
_label.fontSize = 30
_label.fontColor = SKColor.themeDarkFontColor()
_label.position = CGPoint(x: _button.frame.size.width / 2, y: _button.frame.size.height / 4)
addChild(shadow)
addChild(_button)
_button.addChild(_label)
calculateAccumulatedFrame()
}
var foregroundColor: SKColor {
get {
return _button.fillColor
}
set(value) {
_button.fillColor = value
_button.strokeColor = value
}
}
var textColor: SKColor {
get {
return _label.fontColor!
}
set (value) {
_label.fontColor = value
}
}
}
|
mit
|
ef9357b3862acf7abf13ccb0498d5505
| 27.584416 | 104 | 0.613358 | 4.273786 | false | false | false | false |
scottsievert/Pythonic.swift
|
src/Pythonic-test.swift
|
1
|
34417
|
#!/usr/bin/env xcrun swift -I .
import Pythonic
// ** (power operator)
assert(1 + 2**2 + 2 == 7)
assert(1 + 2.0**2.0 + 2 == 7)
assert(1**1 + 2.0**2.0 + 2 == 7)
assert(2 * 2 ** 2 * 3 ** 2 * 3 ** 3 == 1944)
assert(2**2 == 4)
assert(2.0**2.0 == 4)
// abs
assert(abs(-0.1) == 0.1)
assert(abs(-1) == 1)
// all
assert(!all(["", "bar", "baz"]))
assert(!all([false, false, false]))
assert(!all([false, false, true]))
assert(all(["foo", "bar", "baz"]))
assert(all([0.0001, 0.0001]))
assert(all([true, true, true]))
// any
assert(!any([0, 0]))
assert(!any([false, false, false]))
assert(any(["", "foo", "bar", "baz"]))
assert(any([0.1, 0]))
assert(any([false, false, true]))
// bin
assert(bin(2) == "0b10")
assert(bin(7) == "0b111")
assert(bin(1024) == "0b10000000000")
// bool
assert(!bool(""))
assert(!bool(0))
assert(bool("foo"))
assert(bool(1))
assert(bool([1]))
// assert(!bool(set([]))) // error: could not find an overload for 'assert' that accepts the supplied arguments
// chr
assert(chr(97) == "a")
assert(chr(ord("b")) == "b")
assert(ord(chr(255)) == 255)
// cmp
assert(cmp("bar", "bar") == 0)
assert(cmp("bar", "foo") == -1)
assert(cmp("foo", "bar") == 1)
assert(cmp(0, 0) == 0)
assert(cmp(0, 1) == -1)
assert(cmp(1, 0) == 1)
// assert(cmp([1, 2, 3, 100], [2, 3, 4, 5]) == -1) – assertion fails
// double (truthness)
assert(bool(0.00000001))
assert(bool(1.0))
assert(!bool(0.0))
// double.is_integer/isInteger
assert(!0.000000000001.is_integer())
assert(!1.1.is_integer())
assert(1.0.is_integer())
// file
// TODO: Missing test.
// float
assert(!bool(float(0.0)))
assert(bool(float(0 + 0.0001)))
assert(bool(float(0.00000001)))
assert(bool(float(1.0)))
// float.is_integer
assert(!float(1.1).is_integer())
assert(float(1.0).is_integer())
assert(float(100).is_integer())
// hex
assert(hex(0) == "0x0")
assert(hex(1) == "0x1")
assert(hex(10) == "0xa")
assert(hex(100) == "0x64")
assert(hex(1000) == "0x3e8")
assert(hex(10000000) == "0x989680")
// int
assert(int(1.1) == 1)
assert(int(9.9) == 9)
// int (truthness)
assert(bool(1))
assert(!bool(0))
// json
assert(json.dumps([1, 2, 3]).replace("\n", "").replace(" ", "") == "[1,2,3]")
// len
assert(len("") == 0)
assert(len("\t") == 1)
assert(len("foo") == 3)
assert(len(["foo", "bar", "baz"]) == 3)
assert(len(["foo", "bar"]) == 2)
assert(len(["foo"]) == 1)
// list
assert(list([1, 2, 3]) == [1, 2, 3])
// assert(list([1, 2, 3]).count(1) == 1)
// list (truthness)
assert(bool([1, 2, 3]))
assert(bool([1, 2]))
assert(bool([1]))
// list(set)
// assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(0) == 0)
// assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(1) == 1)
// assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(2) == 1)
// assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(3) == 1)
// assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(4) == 1)
// assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(5) == 0)
// list.count
// assert([1, 2, 2, 3, 3, 3].count(1) == 1)
// assert([1, 2, 2, 3, 3, 3].count(2) == 2)
// assert([1, 2, 2, 3, 3, 3].count(3) == 3)
// assert([1, 2, 3].count(4) == 0)
// list.index
// assert(["foo", "bar", "baz"].index("baz") == 2)
// assert([1, 2, 3].index(3) == 2)
// assert(list(["a", "b", "c"]).index("b") == 1)
// literals
assert(0b0 == 0)
assert(0b111111111111111111111111111111111111111111111111111111111111111 == 9223372036854775807)
assert(0o00 == 0)
assert(0o10 == 8)
assert(0o11 == 9)
assert(0x00 == 0)
assert(0xff == 255)
assert(1.25e-2 == 0.0125)
assert(1.25e2 == 125)
// long
assert(long(1.1) == 1)
// math.acos
assert(math.acos(-1) == math.pi)
// math.asin
assert(math.asin(1) == math.pi / 2)
// math.atan
assert(math.atan(1) == math.pi / 4)
// math.cos
assert(math.cos(math.pi) == -1)
// math.degrees
assert(math.degrees(math.pi) == 180)
// math.factorial
assert(math.factorial(0) == 1)
assert(math.factorial(20) == 2432902008176640000)
// math.pow
assert(math.pow(2, 2) == 4)
assert(math.pow(2.0, 2.0) == 4.0)
// math.radians
assert(math.radians(270) == math.pi * 1.5)
// math.sin
assert(math.sin(math.pi / 2) == 1)
// math.sqrt
assert(math.sqrt(9) == 3)
// math.tan
// Python returns 0.999... for tan(π / 4)
assert(math.tan(math.pi / 4) <= 1)
assert(math.tan(math.pi / 4) > 0.9999999)
// max
assert(max(1, 2) == 2)
assert(max(1, 2, 3) == 3)
assert(max([1, 2, 3]) == 3)
assert(max([1, 2]) == 2)
// min
assert(min(1, 2) == 1)
assert(min(1, 2, 3) == 1)
assert(min([1, 2, 3]) == 1)
assert(min([1, 2]) == 1)
// object
assert(bool(object()))
// oct
assert(oct(0) == "0")
assert(oct(1) == "01")
assert(oct(10) == "012")
assert(oct(100) == "0144")
assert(oct(1000) == "01750")
// assert(oct(100000000000) == "01351035564000") – assertion fails
// open
assert(open("Pythonic-test.txt").read().splitlines()[2] == "This test file is being read")
// ord
assert(ord("a") == 97)
assert(ord(chr(98)) == 98)
// os.getcwd()
assert(bool(os.getcwd()))
// os.path.exists
assert(!os.path.exists("/tmp.foo/"))
assert(os.path.exists("/tmp/"))
assert(os.path.exists("Pythonic-test.txt"))
// os.path.join
assert(os.path.join("a", "b", "c") == "a/b/c")
assert(os.path.join("/a", "b", "c") == "/a/b/c")
// os.system (+ os.unlink + os.path.exists)
os.unlink("/tmp/pythonic-test.txt")
assert(os.system("/usr/bin/touch /tmp/pythonic-test.txt") == 0)
assert(os.path.exists("/tmp/pythonic-test.txt"))
os.unlink("/tmp/pythonic-test.txt")
// pow
assert(pow(2, 2) == 4)
assert(pow(2.0, 2.0) == 4.0)
// random.random
assert(random.random() < 1)
// random.randint
assert(random.randint(0, 10) <= 10)
// random.randrange
assert(random.randrange(0, 10) <= 9)
// range
assert(range(0) == [])
assert(range(0, 10, 2) == [0, 2, 4, 6, 8])
assert(range(0, 5, -1) == [])
assert(range(0, 50, 7) == [0, 7, 14, 21, 28, 35, 42, 49])
assert(range(1, 0) == [])
assert(range(1, 11) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
assert(range(10) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// re.search
assert(!re.search("^bar", "foobarbaz"))
assert(!re.search("hello", "foobarbaz"))
assert(re.search("[\r\n]", "foo\rfoo").group(0) == "\r")
assert(re.search("\r\n", "foo\r\nfoo").group(0) == "\r\n")
assert(bool(re.search("^foo", "foobarbaz")))
assert(re.search("^foo", "foobarbaz").group(0) == "foo")
assert(bool(re.search("^foo.*baz$", "foobarbaz")))
assert(bool(re.search("foo", "foobarbaz")))
assert(bool(re.search("o", "foobarbaz")))
// re.match
assert(!re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[2])
assert(!re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[4])
assert(!re.match("o", "foobarbaz"))
assert(!re.search("zoo", "barfoobar"))
assert(len(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()) == 2)
assert(len(re.search("foo", "barfoobar").groups()) == 0)
assert(list(re.match("(.*) down (.*) on (.*)", "Bugger all down here on earth!").groups()) == ["Bugger all", "here", "earth!"])
assert(list(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").groups()) == ["Hello foo bar baz", "foo", "bar", "baz"])
assert(list(re.match("Hello[ \t]*(.*)world", "Hello Python world").groups())[0] == "Python ")
assert(list(re.search("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()) == ["var", "tmp", "foo"])
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(0) == "Hello foo bar baz")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(1) == "Hello foo bar baz")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(2) == "foo")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(3) == "bar")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(4) == "baz")
assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[0] == "var")
assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[1] == "tmp")
assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[2] == "foo")
assert(re.match("Hello[ \t]*(.*)world", "Hello Python world").group(0) == "Hello Python world")
assert(re.match("Hello[ \t]*(.*)world", "Hello Python world").group(1) == "Python ")
assert(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()[0] == "baz")
assert(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()[1] == "baz")
assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[0] == "foobarbazfoobarba")
assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[1] == "z")
assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[3] == "z")
assert(bool(re.match("^foo", "foobarbaz")))
assert(bool(re.match("foo", "foobarbaz")))
assert(bool(re.search("foo", "barfoobar")))
// re.split
assert(re.split("/", "") == [""])
assert(re.split("/", "/") == ["", ""])
assert(re.split("/", "foo/") == ["foo", ""])
assert(re.split("/", "foo/bar") == ["foo", "bar"])
assert(re.split("/", "foo/bar/") == ["foo", "bar", ""])
assert(re.split("/", "foo/bar/baz") == ["foo", "bar", "baz"])
assert(re.split("/", "foo/bar/baz/") == ["foo", "bar", "baz", ""])
assert(re.split("[0-9]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e", "f", "z", "", "", "ee", "", "ch", "", "", "h", "", "fhh", "h", "ui", "", "", "sh", ""])
assert(re.split("[0-9]", "foo/bar/baz") == ["foo/bar/baz"])
assert(re.split("[0-9]", "foo/bar/baz/") == ["foo/bar/baz/"])
assert(re.split("[XY]+", "aXYbXYc") == ["a", "b", "c"])
assert(re.split("[\r\n]", "\r\n\t\t\r\n\r\t\n\r\r\n\n\t\t") == ["", "", "\t\t", "", "", "\t", "", "", "", "", "\t\t"])
assert(re.split("[\r\n]+", "foo\naw\tef\roa\r\nwef") == ["foo", "aw\tef", "oa", "wef"])
assert(re.split("[^a-z]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e", "f", "z", "", "", "ee", "", "ch", "", "", "h", "", "fhh", "h", "ui", "", "", "sh", ""])
assert(re.split("[a-z]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["", "8", "8", "888", "", "88", "", "838", "23", "", "", "3", "2", "", "388", "", "3"])
assert(re.split("a-z", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e8f8z888ee88ch838h23fhh3h2ui388sh3"])
assert(re.split("[^a-zA-Z0-9]", "foo bar baz") == ["foo", "bar", "baz"])
assert(re.split("\\s(?=\\w+:)", "foo:bar baz:foobar") == ["foo:bar", "baz:foobar"])
assert(re.split("[^a-z]", "foo1bar2baz3foo11bar22baz33foo111bar222baz333") == ["foo", "bar", "baz", "foo", "", "bar", "", "baz", "", "foo", "", "", "bar", "", "", "baz", "", "", ""])
assert(re.split("[^a-z]+", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo") == ["foo", "foobar", "baz", "foobarbaz", "bazbarfoo"])
assert(re.split("[^a-z]+", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["foo", "foobar", "baz", "foobarbaz", "bazbarfoo", ""])
assert(re.split("[^a-z]+", "12345foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["", "foo", "foobar", "baz", "foobarbaz", "bazbarfoo", ""])
assert(re.split("([^a-z]+)", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo") == ["foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo"])
assert(re.split("([^a-z]+)", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo", "12345", ""])
assert(re.split("([^a-z]+)", "12345foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["", "12345", "foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo", "12345", ""])
assert(re.split("([^a-zA-Z0-9])", "foo bar baz") == ["foo", " ", "bar", " ", "baz"])
assert(re.split("(abc)", "abcfooabcfooabcfoo") == ["", "abc", "foo", "abc", "foo", "abc", "foo"])
assert(re.split("abc", "abcfooabcfooabcfoo") == ["", "foo", "foo", "foo"])
// assert(re.split("(a)b(c)", "abcfooabcfooabcfoo") == ["", "a", "c", "foo", "a", "c", "foo", "a", "c", "foo"]) // Failing edge case which is not Python compatible yet.
// re.sub
assert(re.sub("^foo", "bar", "foofoo") == "barfoo")
assert(re.sub("^zfoo", "bar", "foofoo") == "foofoo")
assert(re.sub("([^a-zA-Z0-9])foo([^a-zA-Z0-9])", "\\1bar\\2", "foobarfoobar foo bar foo bar") == "foobarfoobar bar bar bar bar")
// round
assert(round(1.1) == 1)
// set
assert(!(set([1, 2, 3]) < set([1, 2, 3])))
assert(!(set([4]) < set([1, 2, 3])))
assert(set([1, 1, 1, 2, 2, 3, 3, 4]) == set([1, 2, 3, 4]))
assert(set([1, 2, 3]) & set([3, 4, 5]) == set([3]))
assert(set([1, 2, 3]) - set([3, 4, 5]) == set([1, 2]))
assert(set([1, 2, 3]) | set([3, 4, 5]) == set([1, 2, 3, 4, 5]))
assert(bool(set([1, 2, 3])))
assert(set([1, 2]) < set([1, 2, 3]))
assert(bool(set([1, 2])))
assert(set([1]) < set([1, 2, 3]))
assert(bool(set([1])))
// set.isdisjoint
assert(!set([1, 2, 3]).isdisjoint(set([3, 4, 5])))
assert(set([1, 2, 3]).isdisjoint(set([4, 8, 16])))
// str (conversion)
assert(str(123) == "123")
// assert(str(1.23) == "1.23")
// str (indexing)
assert("foobar"[0] == "f")
assert("\r\t"[0] == "\r")
assert("\r\t"[1] == "\t")
// str (truthness)
assert(bool(" "))
assert(!bool(""))
// str (positive and negative indexing)
assert("foo"[-1] == "o")
assert("foo"[-2] == "o")
assert("foo"[0] == "f")
assert("foo"[len("foo")-1] == "o")
// str * int (repeat string)
assert("foo" * 3 == "foofoofoo")
assert("foo" * 3 == "foofoofoo")
assert(-1 * "foo" == "")
assert(0 * "foo" == "")
assert(1 * "foo" == "foo")
assert(2 * "foo" * 2 == "foofoofoofoo")
assert(2 * "foo" == "foofoo")
// str % tuple
assert("Hello %d! Number %s" % (1, "world") == "Hello 1! Number world")
assert("Hello %d!" % (1) == "Hello 1!")
assert("Hello %s! Number %d" % ("world", 1) == "Hello world! Number 1")
assert("Hello %s!" % ("world") == "Hello world!")
assert("With commit %d, this string building syntax is now %s!" % (197, "supported") == "With commit 197, this string building syntax is now supported!")
assert("foo %% bar %011d baz %s" % (100, "foobar") == "foo % bar 00000000100 baz foobar")
assert("foo %d" % (123) == "foo 123")
// str.capitalize
assert("".capitalize() == "")
assert("f".capitalize() == "F")
assert("fo".capitalize() == "Fo")
assert("foo baR".capitalize() == "Foo bar")
assert("foo".capitalize() == "Foo")
// str.center
assert("foo".center(5) == " foo ")
assert("foo".center(6, "-") == "-foo--")
assert("foobar".center(9, "-") == "--foobar-")
assert("foobar".center(4) == "foobar")
// str.count
assert("foo".count("f") == 1)
assert("foo".count("o") == 2)
assert("foo".count("b") == 0)
// str.endswith
assert("foobar".endswith("bar"))
// str.expandtabs
assert(len("\t".expandtabs()) == 8)
assert(len("\t".expandtabs(10)) == 10)
assert(len("\t\t".expandtabs(10)) == 20)
assert(len(("\t" * 2).expandtabs()) == 16)
assert("\t".expandtabs() == " " * 8)
// str.find
assert("foo".find("foobarfoobar") == -1)
assert("foobar".find("") == 0)
assert("foobar".find("bar") == 3)
assert("foobar".find("f") == 0)
assert("foobar".find("foobar") == 0)
assert("foobar".find("foobars") == -1)
assert("foobar".find("zbar") == -1)
// str.in (translated to "str1 in str" when running as Python code)
assert(!"foo".`in`("baz"))
assert(!"foobar".`in`(""))
assert("".`in`("foobar"))
assert("foo".`in`("foobar"))
assert("ob".`in`("foobar"))
// str.index
assert("foobar".index("foobar") == 0)
assert("foobar".index("") == 0)
assert("foobar".index("f") == 0)
assert("foobar".index("bar") == 3)
// str.isalnum
assert(!"foo ".isalnum())
assert("foo1".isalnum())
// str.isalpha
assert(!"foo1".isalpha())
assert("fooo".isalpha())
// str.isdigit
assert(!"foo1".isdigit())
assert("123".isdigit())
// str.islower
assert(!"FOO".islower())
assert("foo".islower())
// str.isspace
assert(!" x ".isspace())
assert(!" a\t".isspace())
assert(" ".isspace())
assert(" \t".isspace())
// str.istitle
assert(!"foo foo".istitle())
assert(!"foo".istitle())
assert("Foo Foo".istitle())
assert("Foo".istitle())
// str.isupper
assert(!"foo".isupper())
assert("FOO".isupper())
// str.join
assert(":".join(["foo", "bar", "baz"]) == "foo:bar:baz")
// str.ljust
assert("foo".ljust(5) == "foo ")
assert("foo".ljust(10, "-") == "foo-------")
assert("foobar".ljust(4) == "foobar")
// str.lower
assert("FooBar".lower() == "foobar")
// str.lstrip
assert(" \n\t foobar \n\t ".lstrip() == "foobar \n\t ")
// str.partition
assert("the first part\nthe second part".partition("\n") == ("the first part", "\n", "the second part"))
assert("the first part".partition("\n") == ("the first part", "", ""))
assert("the first part\n".partition("\n") == ("the first part", "\n", ""))
assert("\nthe second part".partition("\n") == ("", "\n", "the second part"))
// str.replace
assert("fzzbar".replace("z", "o") == "foobar")
// str.rjust
assert("foo".rjust(5) == " foo")
assert("foo".rjust(10, "-") == "-------foo")
assert("foobar".rjust(4) == "foobar")
// str.rstrip
assert(" \n\t foobar \n\t ".rstrip() == " \n\t foobar")
// str.split
assert("a\t\n\r\t\n\t\n\r\nb\r\nc\t".split() == ["a", "b", "c"])
assert("foo bar".split(" ") == ["foo", "bar"])
assert("foo:bar:baz".split(":") == ["foo", "bar", "baz"])
assert("foo\r\n \r\nbar\rfoo\nfoo\n\nfoo\n\n\nfoo".split() == ["foo", "bar", "foo", "foo", "foo", "foo"])
assert("foo\r\nbar\rfoo\nfoo\n\nfoo\n\n\nfoo".split() == ["foo", "bar", "foo", "foo", "foo", "foo"])
assert(len(open("Pythonic-test.txt").read().split()) == 23)
// str.splitlines
assert("foo\naw\tef\roa\r\nwef".splitlines() == ["foo", "aw\tef", "oa", "wef"])
assert("foo\rfoo\nfoo\r\nfoo\n\rfoo\nfoo".splitlines() == ["foo", "foo", "foo", "foo", "", "foo", "foo"])
assert("\nfoo\rfoo\nfoo\r\nfoo\n\rfoo\nfoo\n".splitlines() == ["", "foo", "foo", "foo", "foo", "", "foo", "foo"])
// str.startswith
assert("foobar".startswith("foo"))
// str.strip
assert(" \n foobar \n ".strip() == "foobar")
assert(" foobar ".strip() == "foobar")
assert("".strip() == "")
assert("foobar".strip() == "foobar")
assert(" \n\t foobar \n\t ".strip() == "foobar")
// str.swapcase
assert("foo".swapcase() == "FOO")
assert("FooBar".swapcase() == "fOObAR")
assert("›ƒé".swapcase() == "›ƒé")
// str.title
assert("foo bar".title() == "Foo Bar")
// str.upper
assert("FooBar".upper() == "FOOBAR")
// str.zfill
assert("foo".zfill(-1) == "foo")
assert("foo".zfill(0) == "foo")
assert("foo".zfill(1) == "foo")
assert("foo".zfill(10) == "0000000foo")
assert(len("foo".zfill(1000)) == 1000)
// sum
assert(sum([1, 2, 3]) == 6)
assert(sum([1, 2, 3], 1) == 7)
assert(sum([1.1, 1.2]) == 2.3)
// sys.argv
if len(sys.argv) == 1 && sys.argv[0] == "./Pythonic-test.swift" {
// Make sure test case passes also when run using shebang line.
sys.argv = ["./Pythonic-test", "arg1", "arg2"]
}
assert(sys.argv[0].startswith("./Pythonic-test"))
assert(sys.argv[1] == "arg1")
assert(sys.argv[2] == "arg2")
assert(len(sys.argv) == 3)
// sys.platform
assert(sys.platform == "darwin")
// time.time
assert(time.time() > 1405028001.224846)
// datetime
assert(datetime(2014, 7, 4) == datetime.strptime("07/04/14", "%m/%d/%y"))
assert(datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M").strftime("%d/%m/%y %H:%M") == "21/11/06 16:30")
assert(datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M").strftime("%d/%m/%y %H:%M") == "21/11/06 16:30")
// tuple – comparison of 2-part tuples
assert((1, 1) == (1, 1))
assert(!((1, 1) == (1, 214)))
// tuple – comparison of 3-part tuples
assert((1, 1, 1) == (1, 1, 1))
assert(!((1, 1, 1) == (1, 1, 214)))
// uuid
assert(len(uuid.uuid4().hex) == 32)
// xrange
assert(list(xrange(10)) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
assert(list(xrange(1, 10)) == [1, 2, 3, 4, 5, 6, 7, 8, 9])
// BUG: Due to a strange compiler bug (?) the following cannot be imported. Must be in same source file.
// Same as http://www.openradar.me/17500497 ?
extension Array {
mutating func pop(index: Int?) -> Array.Element? {
var i = index ?? self.count - 1
if self.count == 0 || i < 0 || i >= self.count {
return nil
}
var ret = self[i]
self.removeAtIndex(i)
return ret
}
mutating func pop() -> Array.Element? {
return self.pop(nil)
}
}
// // BUG: Due to a strange compiler bug (?) the following cannot be imported. Must be in same source file.
// // Same as http://www.openradar.me/17500497 ?
// public extension Dictionary {
// public func get(key: Key) -> Value? {
// return self[key]
// }
//
// public func hasKey(key: Key) -> Bool {
// if let _ = self.get(key) {
// return true
// }
// return false
// }
//
// public func has_key(key: Key) -> Bool {
// return hasKey(key)
// }
//
// public mutating func pop(key: Key) -> Value? {
// if let val = self.get(key) {
// self.removeValueForKey(key)
// return val
// }
// return nil
// }
//
// public mutating func popItem() -> (Key, Value)? {
// if self.count == 0 {
// return nil
// }
// var key = Array(self.keys)[0]
// var value = self.pop(key)!
// return (key, value)
// }
//
// public mutating func popitem() -> (Key, Value)? {
// return popItem()
// }
//
// public func items() -> [(Key, Value)] {
// return zip(self.keys, self.values)
// }
//
// public static func fromKeys(sequence: [Key], _ defaultValue: Value) -> [Key : Value]{
// var dict = [Key : Value]()
// for key in sequence {
// dict[key] = defaultValue
// }
// return dict
// }
//
// public static func fromkeys(sequence: [Key], _ defaultValue: Value) -> [Key : Value] {
// return fromKeys(sequence, defaultValue)
// }
//
// public func copy() -> [Key : Value] {
// return self
// }
// }
//
// // BUG: has_attr does not work due to the following compiler bug (?)
// // invalid linkage type for global declaration
// // %swift.full_heapmetadata* @_TMdC4mainL_3Baz
// // LLVM ERROR: Broken module found, compilation aborted!
// // func hasattr(object: Any, searchedPropertyName: String) -> Bool {
// // var mirror = reflect(object)
// // for var propertyNumber = 0; propertyNumber < mirror.count; propertyNumber++ {
// // let (propertyName, propertyMirror) = mirror[propertyNumber]
// // // println("\(propertyName) = \(propertyMirror.summary), \(propertyMirror.count) children")
// // if propertyName == searchedPropertyName {
// // return true
// // }
// // }
// // return false
// // }
// This could probably be turned into valid Python code if we implemented the StringIO module
func fileHandleFromString(text: String) -> NSFileHandle {
let pipe = NSPipe()
let input = pipe.fileHandleForWriting
input.writeData(text.dataUsingEncoding(NSUTF8StringEncoding)!)
input.closeFile()
return pipe.fileHandleForReading
}
let performPythonIncompatibleTests = true
if performPythonIncompatibleTests {
// dict (semantics + copy())
var dict1 = ["foo": 1]
assert(dict1["foo"] != nil)
assert(dict1["bar"] == nil)
var dict2 = dict1
dict2["bar"] = 2
assert(dict1["foo"] != nil)
assert(dict1["bar"] == nil)
assert(dict2["foo"] != nil)
assert(dict2["bar"] != nil)
var dict3 = dict1
dict3["bar"] = 3
assert(dict1["foo"] != nil)
assert(dict1["bar"] == nil)
assert(dict3["foo"] != nil)
assert(dict3["bar"] != nil)
// dict
// assert(!dict<str, str>())
assert(bool(["foo": "bar"]))
// assert(len(dict<str, str>()) == 0)
// dict.fromkeys
// assert(dict.fromkeys(["a", "b", "c"], 1) == ["a": 1, "c": 1, "b": 1])
// dict.items
// var h = ["foo": 1, "bar": 2, "baz": 3]
// var arrayOfTuples = h.items()
// arrayOfTuples.sort() { $0.1 < $1.1 }
// assert(arrayOfTuples[0].0 == "foo" && arrayOfTuples[0].1 == 1)
// assert(arrayOfTuples[1].0 == "bar" && arrayOfTuples[1].1 == 2)
// assert(arrayOfTuples[2].0 == "baz" && arrayOfTuples[2].1 == 3)
// divmod
assert(divmod(100, 9).0 == 11)
assert(divmod(100, 9).1 == 1)
assert(divmod(101.0, 8.0).0 == 12.0)
assert(divmod(101.0, 8.0).1 == 5.0)
assert(divmod(102.0, 7).0 == 14.0)
assert(divmod(102.0, 7).1 == 4.0)
assert(divmod(103, 6.0).0 == 17.0)
assert(divmod(103, 6.0).1 == 1.0)
// double.isInteger
var d1 = 1.0
var d2 = 1.1
assert(d1.isInteger())
assert(!d2.isInteger())
// float.isInteger
assert(float(1.0).isInteger())
assert(!float(1.1).isInteger())
// hasattr (commented out due to compiler bug)
// class Baz {
// var foo = "foobar"
// var bar = "foobar"
// }
// var baz = Baz()
// assert(hasattr(baz, "foo"))
// assert(hasattr(baz, "baz") == false)
// list
// assert(!list<int>())
// list.count + list.index + list.reverseInPlace
// var arr: [String] = ["foo", "bar", "baz", "foo"]
// assert(arr.count("foo") == 2)
// arr.remove("foo")
// assert(arr.count("foo") == 1)
// assert(arr.index("bar") == 0)
// arr.append("hello")
// assert(arr.index("hello") == 3)
// arr.reverseInPlace()
// assert(arr.index("hello") == 0)
// list.index
// assert(["foo", "bar", "baz"].index(1) == nil)
// assert([1, 2, 3].index("foo") == nil)
// assert([1, 2, 3].index(4) == nil)
// list.pop
// var mutableArray = [1, 2, 3]
// assert(mutableArray.pop() == 3)
// assert(mutableArray.pop(0) == 1)
// assert(mutableArray.pop(1) == nil)
// assert(mutableArray.pop(0) == 2)
// assert(mutableArray.pop() == nil)
// list.remove
// var anotherMutableArray = [3, 2, 1, 3]
// anotherMutableArray.remove(0)
// assert(anotherMutableArray == [3, 2, 1, 3])
// anotherMutableArray.remove(2)
// assert(anotherMutableArray == [3, 1, 3])
// anotherMutableArray.remove(1)
// assert(anotherMutableArray == [3, 3])
// anotherMutableArray.remove(3)
// assert(anotherMutableArray == [3])
// anotherMutableArray.remove(3)
// assert(anotherMutableArray == [])
// len
assert(len(list<str>()) == 0)
assert(len(["foo": "bar"]) == 1)
assert(len(["foo": "bar", "baz": "foo"]) == 2)
// map
var mapObj = ["foo": "foobar"]
assert(len(mapObj) == 1)
assert(mapObj["foo"] != nil)
// map.get
// assert(mapObj.get("foo") == "foobar")
// map.has_key/hasKey
// assert(mapObj.has_key("foo"))
// assert(mapObj.hasKey("foo"))
// map.pop
// assert(mapObj.pop("foo") == "foobar")
// assert(len(mapObj) == 0)
// map.popItem
// mapObj["foo"] = "bar"
// let t = mapObj.popItem()
// assert(len(mapObj) == 0)
// map.clear
// mapObj.clear()
// assert(len(mapObj) == 0)
// assert(mapObj["foobar"] == nil)
// open(…) [modes: w, a, r (default)] + fh.write + fh.close + os.path.exists
let temporaryTestFile = "/tmp/pythonic-io.txt"
var f = open(temporaryTestFile, "w")
f.write("foo")
f.close()
f = open(temporaryTestFile, "a")
f.write("bar\n")
f.close()
f = open(temporaryTestFile)
var foundText = false
for line in f {
if line == "foobar" {
foundText = true
}
}
assert(foundText)
assert(os.path.exists(temporaryTestFile))
os.unlink(temporaryTestFile)
assert(!os.path.exists(temporaryTestFile))
// os.popen3
var (stdin, stdout, stderr) = os.popen3("/bin/echo foo")
var foundOutput = false
for line in stdout {
if line == "foo" {
foundOutput = true
}
}
assert(foundOutput)
// os.popen2
foundOutput = false
(stdin, stdout) = os.popen2("/bin/echo foo")
for line in stdout {
if line == "foo" {
foundOutput = true
}
}
assert(foundOutput)
// random.choice
var array = ["foo", "bar"]
var randomChoice = random.choice(array)
assert(randomChoice == "foo" || randomChoice == "bar")
// re.search
assert(!re.search("", "foobarbaz"))
// re.search.group
assert(re.search("^foo", "foobarbaz")[0] == "foo")
// set
var emptyIntSet: Set<Int> = set()
assert(!emptyIntSet)
// assert(set([1, 2, 3]) + set([3, 4, 5]) == set([1, 2, 3, 4, 5])) // Swift compiler bug: Enabling this test increases compilation time by roughly 1.5 seconds.
// assert(set([set([1, 2, 3]), set([1, 2, 3]), set([2, 4, 8])]) != set([set([1, 2, 3]), set([2, 4, 9])])) // Swift compiler bug: Enabling this test increases compilation time by >60 seconds.
// assert(set([set([1, 2, 3]), set([1, 2, 3]), set([2, 4, 8])]) == set([set([1, 2, 3]), set([2, 4, 8])])) // Swift compiler bug: Enabling this test increases compilation time by >60 seconds.
assert(bool(set([1, 2, 3])))
var set1 = Set<Int>()
assert(countElements(set1) == 0)
set1 += 1
assert(countElements(set1) == 1)
assert(set1 == Set([1]))
set1.add(2)
assert(set1 == Set([1, 2]))
set1.add(3)
assert(set1 == Set([1, 2, 3]))
set1.add(1)
assert(set1 == Set([1, 2, 3]))
set1.add(2)
assert(set1 == Set([1, 2, 3]))
set1.add(3)
assert(set1 == Set([1, 2, 3]))
set1.remove(2)
assert(set1 == Set([1, 3]))
set1.remove(2)
assert(set1 == Set([1, 3]))
set1 -= 2
assert(set1 == Set([1, 3]))
var set2 = Set([1, 8, 16, 32, 64, 128])
assert(set2 == Set([128, 64, 32, 16, 8, 1]))
var set3 = set1 + set2
assert(set3 == Set([128, 64, 32, 16, 8, 1, 3]))
var set4 = set1 - set2
assert(set4 == Set([3]))
set4 += set2
assert(set4 == Set([128, 64, 32, 16, 8, 1, 3]))
set4 -= set2
assert(set4 == Set([3]))
var set5 = Set(set4)
assert(set5 == Set([3]))
assert(set5 == set4)
var set6 = Set([1, 2, 3]) & Set([1, 3])
assert(set6 == Set([1, 3]))
set6 &= set6
assert(set6 == Set([1, 3]))
var set7 = Set([1, 2, 3]) | Set([1, 3])
assert(set7 == Set([1, 2, 3]))
set7 |= set7
assert(set7 == Set([1, 2, 3]))
var set8: Set<Int> = [1, 2, 3]
assert(len(set8) == 3)
var set9 = Set([0, 1, 2])
set9.add(3)
set9.add(3)
assert(set9 == Set([0, 1, 2, 3]))
var set10 = Set([2, 4, 8, 16])
assert(set9 + set10 == Set([0, 1, 2, 3, 4, 8, 16]))
assert(set9 - set10 == Set([0, 1, 3]))
assert(set9 & set10 == Set([2]))
assert(set([1, 2, 3]).contains(1))
assert(!set([1, 2, 3]).contains(4))
// statistics.mean
assert(statistics.mean([-1.0, 2.5, 3.25, 5.75]) == 2.625)
assert(statistics.mean([0.5, 0.75, 0.625, 0.375]) == 0.5625)
assert(statistics.mean([1, 2, 3, 4, 4]) == 2.8)
// statistics.median
assert(statistics.median([1, 3, 5, 7]) == 4.0)
assert(statistics.median([1, 3, 5]) == 3)
assert(statistics.median([2, 3, 4, 5]) == 3.5)
// statistics.median_high
assert(statistics.median_high([1, 3, 5]) == 3)
assert(statistics.median_high([1, 3, 5, 7]) == 5)
// statistics.median_low
assert(statistics.median_low([1, 3, 5]) == 3)
assert(statistics.median_low([1, 3, 5, 7]) == 3)
// str (handling of "\r\n" not compatible with Python)
assert("\r\n\t"[0] == "\r\n")
assert("\r\n\t"[1] == "\t")
// str.endsWith
assert("foobar".endsWith("bar"))
// str.index
assert("foobar".index("foobars") == -1)
assert("foobar".index("zbar") == -1)
// str.split
assert("foobar".split("") == ["foobar"])
// str.startsWith
assert("foobar".startsWith("foo"))
// str.title
assert("they're bill's friends from the UK".title() == "They're Bill's Friends From The Uk")
// str[(Int?, Int?)]
assert("Python"[(nil, 2)] == "Py")
assert("Python"[(2, nil)] == "thon")
assert("Python"[(2, 4)] == "th")
assert("Python"[(nil, -3)] == "Pyt")
assert("Python"[(-3, nil)] == "hon")
// str[range]
assert("foobar"[0..<3] == "foo")
// time.sleep
time.sleep(0.001)
// datetime
let day = NSDate.strptime("11/08/14 21:13", "%d/%m/%y %H:%M")
assert(day.strftime("%a %A %w %d %b %B %m %y %Y") == "Mon Monday 1 11 Aug August 08 14 2014")
assert(day.strftime("%H %I %p %M %S %f %j %%") == "21 09 pm 13 00 000000 223 %" || day.strftime("%H %I %p %M %S %f %j %%") == "21 09 PM 13 00 000000 223 %")
assert(day.strftime("It's day number %d; the month is %B.") == "It's day number 11; the month is August.")
assert(day.isoformat(" ") == "2014-08-11 21:13:00")
// timedelta
let year = timedelta(days: 365)
let anotherYear = timedelta(weeks: 40, days: 84, hours: 23, minutes: 50, seconds: 600)
assert(year.total_seconds() == 31536000.0)
assert(year == anotherYear)
// datetime & timedelta
let oneDayDelta = timedelta(days: 1)
let nextDay = day + oneDayDelta
let previousDay = day - oneDayDelta
assert(nextDay - previousDay == oneDayDelta * 2)
let otherDay = day.replace(day: 15, hour: 22)
assert(otherDay - nextDay == timedelta(days: 3, seconds: 60 * 60))
// zip
var zipped = zip([3, 4], [9, 16])
var (l1, r1) = zipped[0]
assert(l1 == 3 && r1 == 9)
var (l2, r2) = zipped[1]
assert(l2 == 4 && r2 == 16)
// file.__iter__ , as in "for line in open(filename)"
var filehandletest = ""
for line in fileHandleFromString("line 1\nline 2\n") {
filehandletest += line + "\n"
}
assert(filehandletest == "line 1\nline 2\n")
assert(["line 1", "line 2"] == Array(fileHandleFromString("line 1\nline 2\n")))
assert(["line 1"] == Array(fileHandleFromString("line 1\n")))
assert(["line 1"] == Array(fileHandleFromString("line 1")))
assert(["line 1", "", "line 3"] == Array(fileHandleFromString("line 1\n\nline 3")))
assert(["", "line 2", "line 3"] == Array(fileHandleFromString("\nline 2\nline 3")))
assert(["", "", "line 3"] == Array(fileHandleFromString("\n\nline 3")))
// Others:
assert("foobar"[0..<2] == "fo")
assert(bool("x" as Character))
}
var performTestsRequiringNetworkConnectivity = false
if performTestsRequiringNetworkConnectivity &&
performPythonIncompatibleTests {
var getTest = requests.get("http://httpbin.org/get")
println("GET:")
println(getTest.text)
var postDataString = "…"
var postTestWithString = requests.post("http://httpbin.org/post", postDataString)
println("POST(str):")
println(postTestWithString.text)
var postDataDict = ["…": "…", "key": "value", "number": "123"]
var postTestWithDict = requests.post("http://httpbin.org/post", postDataDict)
println("POST(dict):")
println(postTestWithDict.text)
}
sys.exit()
|
mit
|
d1254fff6eee10963389bc1f932d4820
| 31.626186 | 217 | 0.560864 | 2.75567 | false | false | false | false |
typelift/Basis
|
Basis/Folds.swift
|
2
|
12355
|
//
// Folds.swift
// Basis
//
// Created by Robert Widmann on 9/7/14.
// Copyright (c) 2014 TypeLift. All rights reserved.
// Released under the MIT license.
//
/// Takes a binary function, a starting value, and an array of values, then folds the function over
/// the array from left to right to yield a final value.
public func foldl<A, B>(f: B -> A -> B) -> B -> [A] -> B {
return { z in { l in
switch match(l) {
case .Nil:
return z
case .Cons(let x, let xs):
return foldl(f)(f(z)(x))(xs)
}
} }
}
/// Takes a binary operator, a starting value, and an array of values, then folds the function over
/// the array from left to right to yield a final value.
public func foldl<A, B>(f: (B, A) -> B) -> B -> [A] -> B {
return { z in { l in
switch match(l) {
case .Nil:
return z
case .Cons(let x, let xs):
return foldl(f)(f(z, x))(xs)
}
} }
}
/// Takes a binary function, a starting value, and a list of values, then folds the function over
/// the list from left to right to yield a final value.
public func foldl<A, B>(f: B -> A -> B) -> B -> List<A> -> B {
return { z in { l in
switch l.match() {
case .Nil:
return z
case .Cons(let x, let xs):
return foldl(f)(f(z)(x))(xs)
}
} }
}
/// Takes a binary operator, a starting value, and a list of values, then folds the function over
/// the list from left to right to yield a final value.
public func foldl<A, B>(f: (B, A) -> B) -> B -> List<A> -> B {
return { z in { l in
switch l.match() {
case .Nil:
return z
case .Cons(let x, let xs):
return foldl(f)(f(z, x))(xs)
}
} }
}
/// Takes a binary function and an array of values, then folds the function over the array from left
/// to right. It takes its initial value from the head of the array.
///
/// Because this function draws its initial value from the head of an array, it is non-total with
/// respect to the empty array.
public func foldl1<A>(f: A -> A -> A) -> [A] -> A {
return { l in
switch match(l) {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return foldl(f)(x)(xs)
case .Nil:
fatalError("Cannot invoke foldl1 with an empty list.")
}
}
}
/// Takes a binary operator and an array of values, then folds the function over the array from left
/// to right. It takes its initial value from the head of the array.
///
/// Because this function draws its initial value from the head of an array, it is non-total with
/// respect to the empty array.
public func foldl1<A>(f: (A, A) -> A) -> [A] -> A {
return { l in
switch match(l) {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return foldl(f)(x)(xs)
case .Nil:
fatalError("Cannot invoke foldl1 with an empty list.")
}
}
}
/// Takes a binary function and a list of values, then folds the function over the list from left
/// to right. It takes its initial value from the head of the list.
///
/// Because this function draws its initial value from the head of a list, it is non-total with
/// respect to the empty list.
public func foldl1<A>(f: A -> A -> A) -> List<A> -> A {
return { l in
switch l.match() {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return foldl(f)(x)(xs)
case .Nil:
fatalError("Cannot invoke foldl1 with an empty list.")
}
}
}
/// Takes a binary operator and a list of values, then folds the function over the list from left
/// to right. It takes its initial value from the head of the list.
///
/// Because this function draws its initial value from the head of a list, it is non-total with
/// respect to the empty list.
public func foldl1<A>(f: (A, A) -> A) -> List<A> -> A {
return { l in
switch l.match() {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return foldl(f)(x)(xs)
case .Nil:
fatalError("Cannot invoke foldl1 with an empty list.")
}
}
}
/// Takes a binary function, a starting value, and an array of values, then folds the function over
/// the array from right to left to yield a final value.
public func foldr<A, B>(k: A -> B -> B) -> B -> [A] -> B {
return { z in { l in
switch match(l) {
case .Nil:
return z
case .Cons(let x, let xs):
return k(x)(foldr(k)(z)(xs))
}
} }
}
/// Takes a binary operator, a starting value, and an array of values, then folds the function over
/// the array from right to left to yield a final value.
public func foldr<A, B>(k: (A, B) -> B) -> B -> [A] -> B {
return { z in { l in
switch match(l) {
case .Nil:
return z
case .Cons(let x, let xs):
return k(x, foldr(k)(z)(xs))
}
} }
}
/// Takes a binary function, a starting value, and a list of values, then folds the function over
/// the list from right to left to yield a final value.
public func foldr<A, B>(k: A -> B -> B) -> B -> List<A> -> B {
return { z in { l in
switch l.match() {
case .Nil:
return z
case .Cons(let x, let xs):
return k(x)(foldr(k)(z)(xs))
}
} }
}
/// Takes a binary operator, a starting value, and a list of values, then folds the function over
/// the list from right to left to yield a final value.
public func foldr<A, B>(k: (A, B) -> B) -> B -> List<A> -> B {
return { z in { l in
switch l.match() {
case .Nil:
return z
case .Cons(let x, let xs):
return k(x, foldr(k)(z)(xs))
}
} }
}
/// Takes a binary function and an array of values, then folds the function over the array from
/// right to left. It takes its initial value from the head of the array.
///
/// Because this function draws its initial value from the head of an array, it is non-total with
/// respect to the empty array.
public func foldr1<A>(f: A -> A -> A) -> [A] -> A {
return { l in
switch match(l) {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return f(x)(foldr1(f)(xs))
case .Nil:
fatalError("Cannot invoke foldr1 with an empty list.")
}
}
}
/// Takes a binary operator and an array of values, then folds the function over the array from
/// right to left. It takes its initial value from the head of the list.
///
/// Because this function draws its initial value from the head of an array, it is non-total with
/// respect to the empty array.
public func foldr1<A>(f: (A, A) -> A) -> [A] -> A {
return { l in
switch match(l) {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return f(x, foldr1(f)(xs))
case .Nil:
fatalError("Cannot invoke foldr1 with an empty list.")
}
}
}
/// Takes a binary function and a list of values, then folds the function over the list from right
/// to left. It takes its initial value from the head of the list.
///
/// Because this function draws its initial value from the head of a list, it is non-total with
/// respect to the empty list.
public func foldr1<A>(f: A -> A -> A) -> List<A> -> A {
return { l in
switch l.match() {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return f(x)(foldr1(f)(xs))
case .Nil:
fatalError("Cannot invoke foldr1 with an empty list.")
}
}
}
/// Takes a binary operator and a list of values, then folds the function over the list from right
/// to left. It takes its initial value from the head of the list.
///
/// Because this function draws its initial value from the head of a list, it is non-total with
/// respect to the empty list.
public func foldr1<A>(f: (A, A) -> A) -> List<A> -> A {
return { l in
switch l.match() {
case .Cons(let x, let xs) where xs.count == 0:
return x
case .Cons(let x, let xs):
return f(x, foldr1(f)(xs))
case .Nil:
fatalError("Cannot invoke foldr1 with an empty list.")
}
}
}
/// Takes a function and an initial seed value and constructs an array.
///
/// unfoldr is the dual to foldr. Where foldr reduces an array given a function and an initial
/// value, unfoldr uses the initial value and the function to iteratively build an array. If array
/// building should continue the function should return .Some(x, y), else it should return .None.
public func unfoldr<A, B>(f : B -> Optional<(A, B)>) -> B -> [A] {
return { b in
switch f(b) {
case .Some(let (a, b2)):
return a <| unfoldr(f)(b2)
case .None:
return []
}
}
}
/// Takes a function and an initial seed value and constructs a list.
///
/// unfoldr is the dual to foldr. Where foldr reduces a list given a function and an initial value,
/// unfoldr uses the initial value and the function to iteratively build a list. If list building
/// should continue the function should return .Some(x, y), else it should return .None.
public func unfoldr<A, B>(f : B -> Optional<(A, B)>) -> B -> List<A> {
return { b in
switch f(b) {
case .Some(let (a, b2)):
return a <| unfoldr(f)(b2)
case .None:
return List()
}
}
}
/// Returns the conjunction of an array of Booleans
public func and(l : [Bool]) -> Bool {
return foldr({$0 && $1})(true)(l)
}
/// Returns the disjunction of an array of Booleans
public func or(l : [Bool]) -> Bool {
return foldr({$0 || $1})(false)(l)
}
/// Returns the conjunction of a Boolean list.
public func and(l : List<Bool>) -> Bool {
return foldr({$0 && $1})(true)(l)
}
/// Returns the disjunction of a Boolean list.
public func or(l : List<Bool>) -> Bool {
return foldr({$0 || $1})(false)(l)
}
/// Maps a predicate over an array. For the result to be true, the predicate must be satisfied at
/// least once by an element of the array.
public func any<A>(p : A -> Bool) -> [A] -> Bool {
return { l in or(l.map(p)) }
}
/// Maps a predicate over an array. For the result to be true, the predicate must be satisfied by
/// all elemenets of the array.
public func all<A>(p : A -> Bool) -> [A] -> Bool {
return { l in and(l.map(p)) }
}
/// Maps a predicate over a list. For the result to be true, the predicate must be satisfied at
/// least once by an element of the list.
public func any<A>(p : A -> Bool) -> List<A> -> Bool {
return { l in or(l.map(p)) }
}
/// Maps a predicate over a list. For the result to be true, the predicate must be satisfied by
/// all elemenets of the list.
public func all<A>(p : A -> Bool) -> List<A> -> Bool {
return { l in and(l.map(p)) }
}
/// Concatenate an array of arrays.
public func concat<A>(xss : [[A]]) -> [A] {
return foldr({ $0 + $1 })([])(xss)
}
/// Map a function over an array and concatenate the results.
public func concatMap<A, B>(f : A -> [B]) -> [A] -> [B] {
return { l in foldr({ f($0) + $1 })([])(l) }
}
/// Concatenate a list of lists.
public func concat<A>(xss : List<List<A>>) -> List<A> {
return foldr({ $0 + $1 })(List())(xss)
}
/// Map a function over a list and concatenate the results.
public func concatMap<A, B>(f : A -> List<B>) -> List<A> -> List<B> {
return { l in foldr({ f($0) + $1 })(List())(l) }
}
/// Returns the maximum value in an array of comparable values.
public func maximum<A : Comparable>(l : [A]) -> A {
assert(l.count != 0, "Cannot find the maximum value of an empty list.")
return foldl1(max)(l)
}
/// Returns the minimum value in an array of comparable values.
public func minimum<A : Comparable>(l : [A]) -> A {
assert(l.count != 0, "Cannot find the minimum value of an empty list.")
return foldl1(min)(l)
}
/// Returns the maximum value in a list of comparable values.
public func maximum<A : Comparable>(l : List<A>) -> A {
assert(l.count != 0, "Cannot find the maximum value of an empty list.")
return foldl1(max)(l)
}
/// Returns the minimum value in a list of comparable values.
public func minimum<A : Comparable>(l : List<A>) -> A {
assert(l.count != 0, "Cannot find the minimum value of an empty list.")
return foldl1(min)(l)
}
/// Returns the sum of an array of numbers.
public func sum<N : IntegerType>(l : [N]) -> N {
return foldl({ $0 + $1 })(0)(l)
}
/// Returns the product of an array of numbers.
public func product<N : IntegerType>(l : [N]) -> N {
return foldl({ $0 * $1 })(1)(l)
}
/// Returns the sum of a list of numbers.
public func sum<N : IntegerType>(l : List<N>) -> N {
return foldl({ $0 + $1 })(0)(l)
}
/// Returns the product of a list of numbers.
public func product<N : IntegerType>(l : List<N>) -> N {
return foldl({ $0 * $1 })(1)(l)
}
|
mit
|
716cbf097fb437924c84a2ea0c158326
| 29.8875 | 100 | 0.630757 | 3.071855 | false | false | false | false |
rnystrom/GitHawk
|
Pods/StyledTextKit/Source/StyledTextView.swift
|
1
|
8670
|
//
// StyledTextKitView.swift
// StyledTextKit
//
// Created by Ryan Nystrom on 12/14/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
public protocol StyledTextViewDelegate: class {
func didTap(view: StyledTextView, attributes: [NSAttributedStringKey: Any], point: CGPoint)
func didLongPress(view: StyledTextView, attributes: [NSAttributedStringKey: Any], point: CGPoint)
}
open class StyledTextView: UIView {
open weak var delegate: StyledTextViewDelegate?
open var gesturableAttributes = Set<NSAttributedStringKey>()
open var drawsAsync = false
private var renderer: StyledTextRenderer?
private var tapGesture: UITapGestureRecognizer?
private var longPressGesture: UILongPressGestureRecognizer?
private var highlightLayer = CAShapeLayer()
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
translatesAutoresizingMaskIntoConstraints = false
layer.contentsGravity = kCAGravityTopLeft
let tap = UITapGestureRecognizer(target: self, action: #selector(onTap(recognizer:)))
tap.cancelsTouchesInView = false
addGestureRecognizer(tap)
self.tapGesture = tap
let long = UILongPressGestureRecognizer(target: self, action: #selector(onLong(recognizer:)))
addGestureRecognizer(long)
self.longPressGesture = long
self.highlightColor = UIColor.black.withAlphaComponent(0.1)
layer.addSublayer(highlightLayer)
}
public var highlightColor: UIColor? {
get {
guard let color = highlightLayer.fillColor else { return nil }
return UIColor(cgColor: color)
}
set { highlightLayer.fillColor = newValue?.cgColor }
}
// MARK: Overrides
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let touch = touches.first else { return }
highlight(at: touch.location(in: self))
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
clearHighlight()
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
clearHighlight()
}
// MARK: UIGestureRecognizerDelegate
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard (gestureRecognizer === tapGesture || gestureRecognizer === longPressGesture),
let attributes = renderer?.attributes(at: gestureRecognizer.location(in: self)) else {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
for attribute in attributes.attributes {
if gesturableAttributes.contains(attribute.key) {
return true
}
}
return false
}
// MARK: Private API
@objc func onTap(recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
guard let attributes = renderer?.attributes(at: point) else { return }
delegate?.didTap(view: self, attributes: attributes.attributes, point: point)
}
@objc func onLong(recognizer: UILongPressGestureRecognizer) {
let point = recognizer.location(in: self)
guard recognizer.state == .began,
let attributes = renderer?.attributes(at: point)
else { return }
delegate?.didLongPress(view: self, attributes: attributes.attributes, point: point)
}
private func highlight(at point: CGPoint) {
guard let renderer = renderer,
let attributes = renderer.attributes(at: point),
attributes.attributes[.highlight] != nil
else { return }
let storage = renderer.storage
let maxLen = storage.length
var min = attributes.index
var max = attributes.index
storage.enumerateAttributes(
in: NSRange(location: 0, length: attributes.index),
options: .reverse
) { (attrs, range, stop) in
if attrs[.highlight] != nil && min > 0 {
min = range.location
} else {
stop.pointee = true
}
}
storage.enumerateAttributes(
in: NSRange(location: attributes.index, length: maxLen - attributes.index),
options: []
){ (attrs, range, stop) in
if attrs[.highlight] != nil && max < maxLen {
max = range.location + range.length
} else {
stop.pointee = true
}
}
let range = NSRange(location: min, length: max - min)
var firstRect: CGRect = CGRect.null
var bodyRect: CGRect = CGRect.null
var lastRect: CGRect = CGRect.null
let path = UIBezierPath()
renderer.layoutManager.enumerateEnclosingRects(
forGlyphRange: range,
withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0),
in: renderer.textContainer
) { (rect, stop) in
if firstRect.isNull {
firstRect = rect
} else if lastRect.isNull {
lastRect = rect
} else {
// We have a lastRect that was previously filled, now it needs to be dumped into the body
bodyRect = lastRect.intersection(bodyRect)
// and save the current rect as the new "lastRect"
lastRect = rect
}
}
if !firstRect.isNull {
path.append(UIBezierPath(roundedRect: firstRect.insetBy(dx: -2, dy: -2), cornerRadius: 3))
}
if !bodyRect.isNull {
path.append(UIBezierPath(roundedRect: bodyRect.insetBy(dx: -2, dy: -2), cornerRadius: 3))
}
if !lastRect.isNull {
path.append(UIBezierPath(roundedRect: lastRect.insetBy(dx: -2, dy: -2), cornerRadius: 3))
}
highlightLayer.frame = bounds
highlightLayer.path = path.cgPath
}
private func clearHighlight() {
highlightLayer.path = nil
}
private func setRenderResults(renderer: StyledTextRenderer, result: (CGImage?, CGSize)) {
layer.contents = result.0
frame = CGRect(origin: CGPoint(x: renderer.inset.left, y: renderer.inset.top), size: result.1)
}
static var renderQueue = DispatchQueue(
label: "com.whoisryannystrom.StyledText.renderQueue",
qos: .default, attributes: DispatchQueue.Attributes(rawValue: 0),
autoreleaseFrequency: .workItem,
target: nil
)
// MARK: Public API
open func configure(with renderer: StyledTextRenderer, width: CGFloat) {
self.renderer = renderer
layer.contentsScale = renderer.scale
reposition(for: width)
accessibilityLabel = renderer.string.allText
}
open func reposition(for width: CGFloat) {
guard let capturedRenderer = self.renderer else { return }
// First, we check if we can immediately apply a previously cached render result.
let cachedResult = capturedRenderer.cachedRender(for: width)
if let cachedImage = cachedResult.image, let cachedSize = cachedResult.size {
setRenderResults(renderer: capturedRenderer, result: (cachedImage, cachedSize))
return
}
// We have to do a full render, so if we are drawing async it's time to dispatch:
if drawsAsync {
StyledTextView.renderQueue.async {
// Compute the render result (sizing and rendering to an image) on a bg thread
let result = capturedRenderer.render(for: width)
DispatchQueue.main.async {
// If the renderer changed, then our computed result is now invalid, so we have to throw it out.
if capturedRenderer !== self.renderer { return }
// If the renderer hasn't changed, we're OK to actually apply the result of our computation.
self.setRenderResults(renderer: capturedRenderer, result: result)
}
}
} else {
// We're in fully-synchronous mode. Immediately compute the result and set it.
let result = capturedRenderer.render(for: width)
setRenderResults(renderer: capturedRenderer, result: result)
}
}
}
|
mit
|
7849765475c3816eabed5f1d3d4cacf1
| 35.578059 | 116 | 0.627639 | 4.953714 | false | false | false | false |
gavinpardoe/OfficeUpdateHelper
|
officeUpdateHelper/AppDelegate.swift
|
1
|
6187
|
/*
AppDelegate.swift
officeUpdateHelper
Created by Gavin Pardoe on 03/03/2016.
Updated 15/03/2016.
Designed for Use with JAMF Casper Suite.
The MIT License (MIT)
Copyright (c) 2016 Gavin Pardoe
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
import WebKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var webView: WebView!
@IBOutlet weak var activityWheel: NSProgressIndicator!
@IBOutlet weak var label: NSTextField!
@IBOutlet weak var deferButtonDisable: NSButton!
@IBOutlet weak var installButtonDisable: NSButton!
var appCheckTimer = NSTimer()
func applicationDidFinishLaunching(aNotification: NSNotification) {
let htmlPage = NSBundle.mainBundle().URLForResource("index", withExtension: "html")
webView.mainFrame.loadRequest(NSURLRequest(URL: htmlPage!))
activityWheel.displayedWhenStopped = false
self.window.makeKeyAndOrderFront(nil)
self.window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
self.window.level = Int(CGWindowLevelForKey(.MaximumWindowLevelKey))
label.allowsEditingTextAttributes = true
label.stringValue = "Checking for Running Office Apps"
installButtonDisable.enabled = false
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
appCheck()
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
}
func appCheck() {
appCheckTimer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(AppDelegate.officeAppsRunning), userInfo: nil, repeats: true)
}
func officeAppsRunning() {
for runningApps in NSWorkspace.sharedWorkspace().runningApplications {
if let _ = runningApps.localizedName {
}
}
let appName = NSWorkspace.sharedWorkspace().runningApplications.flatMap { $0.localizedName }
if appName.contains("Microsoft Word") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft Excel") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft PowerPoint") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft Outlook") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft OneNote") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else {
installUpdates()
}
}
func installUpdates() {
appCheckTimer.invalidate()
label.textColor = NSColor.blackColor()
label.stringValue = "Click Install to Begin Updating Office"
installButtonDisable.enabled = true
}
@IBAction func installButton(sender: AnyObject) {
installButtonDisable.enabled = false
deferButtonDisable.enabled = false
self.activityWheel.startAnimation(self)
let notification = NSUserNotification()
notification.title = "Office Updater"
notification.informativeText = "Installing Updates..."
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
label.stringValue = "Installing Updates, Window will Close Once Completed"
NSAppleScript(source: "do shell script \"/usr/local/jamf/bin/jamf policy -event officeUpdate\" with administrator " + "privileges")!.executeAndReturnError(nil)
// For Testing
//let alert = NSAlert()
//alert.messageText = "Testing Completed..!"
//alert.addButtonWithTitle("OK")
//alert.runModal()
}
@IBAction func deferButton(sender: AnyObject) {
let notification = NSUserNotification()
notification.title = "Office Updater"
notification.informativeText = "Installation has Been Defered..."
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
NSApplication.sharedApplication().terminate(self)
}
}
|
mit
|
641b94ed571a36646e97af682caa4d83
| 36.047904 | 170 | 0.674317 | 5.665751 | false | false | false | false |
JamieScanlon/AugmentKit
|
AugmentKit/Renderer/Passes/GPUPassBuffer.swift
|
1
|
6366
|
//
// GPUPassBuffer.swift
//
// MIT License
//
// Copyright (c) 2019 JamieScanlon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Metal
/// A class that holds a reference to a `MTLBuffer` that is used as an attachment to a GPU shader. This class helps to initialize and update the buffer by making the following assumptions
/// - The buffer contains a homogenious sequnce of `T` objects. Interleaving heterogeneous objects can be achieved by wrapping them in a stuct and using that struct as the buffer type `T`
/// - The buffer may contain one or more instances of type `T` per draw call or dispatch as represented by the `instanceCount` parameter.
/// - The buffer may contain one or more frames worth of data as represented by the `frameCount` parameter. Each frame would contain `instanceCount` instances of `T`
class GPUPassBuffer<T> {
var buffer: MTLBuffer?
var currentBufferFrameOffset: Int = 0
var currentBufferFrameAddress: UnsafeMutableRawPointer?
var alignedSize: Int = 0
var frameCount: Int = 1
var instanceCount: Int = 1
var label: String?
var resourceOptions: MTLResourceOptions = []
var shaderAttributeIndex: Int
/// Get a pointer to the beginning og the current frame
var currentBufferFramePointer: UnsafeMutablePointer<T>? {
return currentBufferFrameAddress?.assumingMemoryBound(to: T.self)
}
/// Get the total buffer size which is the size of `T` x `instanceCount` x `frameCount`
var totalBufferSize: Int {
return alignedSize * frameCount
}
/// Initialize with the number of instances of `T` per frame and the number of frames. Creating a `GPUPassBuffer` instance does not create the buffer. This lets you control when and how this is done. To create the buffer you can either call `initialize(withDevice device:, options:)` or you can create an `MTLBuffer` yourself and assign it ti the `buffer` property. Until a buffer is initialized, all of the pointer methods will return nil.
/// - Parameter shaderAttributeIndex: The metal buffer attribute index. This index should correspond with the shader argument definition (i.e. `device T *myBuffer [[buffer(shaderAttributeIndex)]]`)
/// - Parameter instanceCount: The number of instances of `T` per pass. Defaults to `1`
/// - Parameter frameCount: The number of frames worth of data that the buffer contains. Defaults to `1`
/// - Parameter label: A label used for helping to identify this buffer. If a label is provided, it will be assigned to the buffers label property when calling `initialize(withDevice device:, options:)`
init(shaderAttributeIndex: Int, instanceCount: Int = 1, frameCount: Int = 1, label: String? = nil, resourceOptions: MTLResourceOptions = []) {
self.shaderAttributeIndex = shaderAttributeIndex
self.instanceCount = instanceCount
self.frameCount = frameCount
self.label = label
self.resourceOptions = resourceOptions
}
/// Initialize a new buffer with the `MTLDevice` and `MTLResourceOptions` provided. If a buffer was previously initialized, calling this again will replace the existing buffer
/// - Parameter device: the `MTLDevice` that will be used to create the buffer
/// - Parameter options: the `MTLResourceOptions` that will be used to create the buffer
/// - Parameter bytes: an optional`UnsafeRawPointer`pointing to bytes in memory that will be copied into the buffer
func initialize(withDevice device: MTLDevice, bytes: UnsafeRawPointer? = nil) {
alignedSize = ((MemoryLayout<T>.stride * instanceCount) & ~0xFF) + 0x100
if let bytes = bytes {
buffer = device.makeBuffer(bytes: bytes, length: totalBufferSize, options: resourceOptions)
} else {
buffer = device.makeBuffer(length: totalBufferSize, options: resourceOptions)
}
if let label = label {
buffer?.label = label
}
}
/// Update the current frame index. When `resourceOptions` is `.storageModeShared`, this will cause subsequent calls to `currentBufferFramePointer` and `currentBufferInstancePointer(withInstanceIndex:)` to return updated pointer addresses. When `resourceOptions` is `.storageModePrivate` or `.storageModeMemoryless` access to the buffer is restricted and attempting to retrieve a pointer fails.
/// - Parameter frameIndex: The frame index. Must be less than the frame count.
func update(toFrame frameIndex: Int) {
guard frameIndex < frameCount else {
return
}
currentBufferFrameOffset = alignedSize * frameIndex
if resourceOptions == .storageModeShared {
currentBufferFrameAddress = buffer?.contents().advanced(by: currentBufferFrameOffset)
}
}
/// Returns a pointer to the instance of the `T` object at the given inxex. This method takes into account the frame index as set by `update(toFrame:)`
/// - Parameter instanceIndex: The index of the `T` object
func currentBufferInstancePointer(withInstanceIndex instanceIndex: Int = 0) -> UnsafeMutablePointer<T>? {
guard instanceIndex < instanceCount else {
return nil
}
return currentBufferFramePointer?.advanced(by: instanceIndex)
}
}
|
mit
|
64ad8fc4ca7ca941cc87e51c712c3174
| 59.056604 | 444 | 0.722746 | 4.733086 | false | false | false | false |
iluuu1994/Conway-s-Game-of-Life
|
Conway's Game of Life/Conway's Game of Life/TileView.swift
|
1
|
2365
|
//
// CGOLTileView.swift
// Conway's Game of Life
//
// Created by Ilija Tovilo on 26/08/14.
// Copyright (c) 2014 Ilija Tovilo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class TileView: UIView {
// --------------------
// MARK: - Properties -
// --------------------
public var coordinates: TileCoordinates!
public var twoWayBinding: TwoWayBinding?
// -----------------
// MARK: - Touches -
// -----------------
override public func canBecomeFirstResponder() -> Bool {
return true
}
override public func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
alive = !alive
}
public dynamic var alive: Bool = false {
didSet {
layer.backgroundColor = !alive ?
UIColor.whiteColor().CGColor :
UIColor(white: 0.3, alpha: 1.0).CGColor
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
// Init design
layer.borderWidth = 1.0
layer.borderColor = UIColor(white: 0.0, alpha: 0.03).CGColor
layer.backgroundColor = UIColor.whiteColor().CGColor
}
required public init(coder: NSCoder) {
super.init(coder: coder)
}
}
|
bsd-2-clause
|
5e8c864e79647d63c4aa3d237bac3ce2
| 32.309859 | 82 | 0.641015 | 4.530651 | false | false | false | false |
adrfer/swift
|
test/IDE/complete_decl_attribute.swift
|
4
|
9479
|
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY1 | FileCheck %s -check-prefix=AVAILABILITY1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY2 | FileCheck %s -check-prefix=AVAILABILITY2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD1 | FileCheck %s -check-prefix=KEYWORD1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD2 | FileCheck %s -check-prefix=KEYWORD2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3 | FileCheck %s -check-prefix=KEYWORD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD4 | FileCheck %s -check-prefix=KEYWORD4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD5 | FileCheck %s -check-prefix=KEYWORD5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_LAST | FileCheck %s -check-prefix=KEYWORD_LAST
@available(#^AVAILABILITY1^#)
// AVAILABILITY1: Begin completions, 9 items
// AVAILABILITY1-NEXT: Keyword/None: *[#Platform#]; name=*{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOS[#Platform#]; name=iOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOS[#Platform#]; name=tvOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOS[#Platform#]; name=watchOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: OSX[#Platform#]; name=OSX{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOSApplicationExtension[#Platform#]; name=iOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOSApplicationExtension[#Platform#]; name=tvOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOSApplicationExtension[#Platform#]; name=watchOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: OSXApplicationExtension[#Platform#]; name=OSXApplicationExtension{{$}}
// AVAILABILITY1-NEXT: End completions
@available(*, #^AVAILABILITY2^#)
// AVAILABILITY2: Begin completions, 5 items
// AVAILABILITY2-NEXT: Keyword/None: unavailable; name=unavailable{{$}}
// AVAILABILITY2-NEXT: Keyword/None: message=[#Specify message#]; name=message{{$}}
// AVAILABILITY2-NEXT: Keyword/None: renamed=[#Specify replacing name#]; name=renamed{{$}}
// AVAILABILITY2-NEXT: Keyword/None: introduced=[#Specify version number#]; name=introduced{{$}}
// AVAILABILITY2-NEXT: Keyword/None: deprecated=[#Specify version number#]; name=deprecated{{$}}
// AVAILABILITY2-NEXT: End completions
func method(@#^KEYWORD1^#) {}
// KEYWORD1: Begin completions, 2 items
// KEYWORD1-NEXT: Keyword/None: autoclosure[#Param Attribute#]; name=autoclosure{{$}}
// KEYWORD1-NEXT: Keyword/None: noescape[#Param Attribute#]; name=noescape{{$}}
// KEYWORD1-NEXT: End completions
@#^KEYWORD2^#
func method(){}
// KEYWORD2: Begin completions, 10 items
// KEYWORD2-NEXT: Keyword/None: available[#Func Attribute#]; name=available{{$}}
// KEYWORD2-NEXT: Keyword/None: objc[#Func Attribute#]; name=objc{{$}}
// KEYWORD2-NEXT: Keyword/None: swift3_migration[#Func Attribute#]; name=swift3_migration{{$}}
// KEYWORD2-NEXT: Keyword/None: noreturn[#Func Attribute#]; name=noreturn{{$}}
// KEYWORD2-NEXT: Keyword/None: IBAction[#Func Attribute#]; name=IBAction{{$}}
// KEYWORD2-NEXT: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged{{$}}
// KEYWORD2-NEXT: Keyword/None: inline[#Func Attribute#]; name=inline{{$}}
// KEYWORD2-NEXT: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc{{$}}
// KEYWORD2-NEXT: Keyword/None: warn_unused_result[#Func Attribute#]; name=warn_unused_result{{$}}
// KEYWORD2-NEXT: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access{{$}}
// KEYWORD2-NEXT: End completions
@#^KEYWORD3^#
class C {}
// KEYWORD3: Begin completions, 8 items
// KEYWORD3-NEXT: Keyword/None: available[#Class Attribute#]; name=available{{$}}
// KEYWORD3-NEXT: Keyword/None: objc[#Class Attribute#]; name=objc{{$}}
// KEYWORD3-NEXT: Keyword/None: swift3_migration[#Class Attribute#]; name=swift3_migration{{$}}
// KEYWORD3-NEXT: Keyword/None: IBDesignable[#Class Attribute#]; name=IBDesignable{{$}}
// KEYWORD3-NEXT: Keyword/None: UIApplicationMain[#Class Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: requires_stored_property_inits[#Class Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD3-NEXT: Keyword/None: NSApplicationMain[#Class Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: objc_non_lazy_realization[#Class Attribute#]; name=objc_non_lazy_realization{{$}}
// KEYWORD3-NEXT: End completions
@#^KEYWORD4^#
enum E {}
// KEYWORD4: Begin completions, 3 items
// KEYWORD4-NEXT: Keyword/None: available[#Enum Attribute#]; name=available{{$}}
// KEYWORD4-NEXT: Keyword/None: objc[#Enum Attribute#]; name=objc{{$}}
// KEYWORD4-NEXT: Keyword/None: swift3_migration[#Enum Attribute#]; name=swift3_migration{{$}}
// KEYWORD4-NEXT: End completions
@#^KEYWORD5^#
struct S{}
// KEYWORD5: Begin completions, 2 items
// KEYWORD5-NEXT: Keyword/None: available[#Struct Attribute#]; name=available{{$}}
// KEYWORD5-NEXT: Keyword/None: swift3_migration[#Struct Attribute#]; name=swift3_migration{{$}}
// KEYWORD5-NEXT: End completions
@#^KEYWORD_LAST^#
// KEYWORD_LAST: Begin completions, 20 items
// KEYWORD_LAST-NEXT: Keyword/None: available[#Declaration Attribute#]; name=available{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: objc[#Declaration Attribute#]; name=objc{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: swift3_migration[#Declaration Attribute#]; name=swift3_migration{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: noreturn[#Declaration Attribute#]; name=noreturn{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: inline[#Declaration Attribute#]; name=inline{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: autoclosure[#Declaration Attribute#]; name=autoclosure{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: noescape[#Declaration Attribute#]; name=noescape{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: objc_non_lazy_realization[#Declaration Attribute#]; name=objc_non_lazy_realization{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: warn_unused_result[#Declaration Attribute#]; name=warn_unused_result
// KEYWORD_LAST-NEXT: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access
// KEYWORD_LAST-NEXT: End completions
|
apache-2.0
|
112f4c5a963fc7b33416588612cf79a2
| 82.884956 | 167 | 0.579913 | 4.718268 | false | true | false | false |
SwiftValidatorCommunity/SwiftValidator
|
SwiftValidator/Rules/MinLengthRule.swift
|
2
|
1775
|
//
// LengthRule.swift
// Validator
//
// Created by Jeff Potter on 3/6/15.
// Copyright (c) 2015 jpotts18. All rights reserved.
//
import Foundation
/**
`MinLengthRule` is a subclass of Rule that defines how minimum character length is validated.
*/
public class MinLengthRule: Rule {
/// Default minimum character length.
private var DEFAULT_LENGTH: Int = 3
/// Default error message to be displayed if validation fails.
private var message : String = "Must be at least 3 characters long"
/// - returns: An initialized `MinLengthRule` object, or nil if an object could not be created for some reason that would not result in an exception.
public init(){}
/**
Initializes a `MaxLengthRule` object that is to validate the length of the text of a field.
- parameter length: Minimum character length.
- parameter message: String of error message.
- returns: An initialized `MinLengthRule` object, or nil if an object could not be created for some reason that would not result in an exception.
*/
public init(length: Int, message : String = "Must be at least %ld characters long"){
self.DEFAULT_LENGTH = length
self.message = String(format: message, self.DEFAULT_LENGTH)
}
/**
Validates a field.
- parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails.
*/
public func validate(_ value: String) -> Bool {
return value.count >= DEFAULT_LENGTH
}
/**
Displays error message when field has failed validation.
- returns: String of error message.
*/
public func errorMessage() -> String {
return message
}
}
|
mit
|
4539ed956ba4a157b80a5d08bbaed4bb
| 33.134615 | 153 | 0.668732 | 4.586563 | false | false | false | false |
Bartlebys/Bartleby
|
Vendors/CommandLine/CommandLineKit/CommandLine.swift
|
1
|
19137
|
/*
* CommandLine.swift
* Copyright (c) 2014 Ben Gollmer.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
#if os(OSX)
import Darwin
#elseif os(Linux)
import Glibc
#endif
let ShortOptionPrefix = "-"
let LongOptionPrefix = "--"
/* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt
* convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
*/
let ArgumentStopper = "--"
/* Allow arguments to be attached to flags when separated by this character.
* --flag=argument is equivalent to --flag argument
*/
let ArgumentAttacher: Character = "="
/* An output stream to stderr; used by CommandLine.printUsage(). */
#if swift(>=3.0)
private struct StderrOutputStream: TextOutputStream {
static let stream = StderrOutputStream()
func write(_ s: String) {
fputs(s, stderr)
}
}
#else
private struct StderrOutputStream: OutputStreamType {
static let stream = StderrOutputStream()
func write(s: String) {
fputs(s, stderr)
}
}
#endif
/**
* The CommandLine class implements a command-line interface for your app.
*
* To use it, define one or more Options (see Option.swift) and add them to your
* CommandLine object, then invoke `parse()`. Each Option object will be populated with
* the value given by the user.
*
* If any required options are missing or if an invalid value is found, `parse()` will throw
* a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage
* message.
*/
public class CommandLine {
private var _arguments: [String]
private var _options: [Option] = [Option]()
private var _maxFlagDescriptionWidth: Int = 0
private var _usedFlags: Set<String> {
var usedFlags = Set<String>(minimumCapacity: _options.count * 2)
for option in _options {
for case let flag? in [option.shortFlag, option.longFlag] {
usedFlags.insert(flag)
}
}
return usedFlags
}
/**
* After calling `parse()`, this property will contain any values that weren't captured
* by an Option. For example:
*
* ```
* let cli = CommandLine()
* let fileType = StringOption(shortFlag: "t", longFlag: "type", required: true, helpMessage: "Type of file")
*
* do {
* try cli.parse()
* print("File type is \(type), files are \(cli.unparsedArguments)")
* catch {
* cli.printUsage(error)
* exit(EX_USAGE)
* }
*
* ---
*
* $ ./readfiles --type=pdf ~/file1.pdf ~/file2.pdf
* File type is pdf, files are ["~/file1.pdf", "~/file2.pdf"]
* ```
*/
public private(set) var unparsedArguments: [String] = [String]()
/**
* If supplied, this function will be called when printing usage messages.
*
* You can use the `defaultFormat` function to get the normally-formatted
* output, either before or after modifying the provided string. For example:
*
* ```
* let cli = CommandLine()
* cli.formatOutput = { str, type in
* switch(type) {
* case .Error:
* // Make errors shouty
* return defaultFormat(str.uppercaseString, type: type)
* case .OptionHelp:
* // Don't use the default indenting
* return ">> \(s)\n"
* default:
* return defaultFormat(str, type: type)
* }
* }
* ```
*
* - note: Newlines are not appended to the result of this function. If you don't use
* `defaultFormat()`, be sure to add them before returning.
*/
public var formatOutput: ((String, OutputType) -> String)?
/**
* The maximum width of all options' `flagDescription` properties; provided for use by
* output formatters.
*
* - seealso: `defaultFormat`, `formatOutput`
*/
public var maxFlagDescriptionWidth: Int {
if _maxFlagDescriptionWidth == 0 {
#if swift(>=3.0)
_maxFlagDescriptionWidth = _options.map { $0.flagDescription.count }.sorted().first ?? 0
#else
_maxFlagDescriptionWidth = _options.map { $0.flagDescription.count }.sort().first ?? 0
#endif
}
return _maxFlagDescriptionWidth
}
/**
* The type of output being supplied to an output formatter.
*
* - seealso: `formatOutput`
*/
public enum OutputType {
/** About text: `Usage: command-example [options]` and the like */
case About
/** An error message: `Missing required option --extract` */
case Error
/** An Option's `flagDescription`: `-h, --help:` */
case OptionFlag
/** An Option's help message */
case OptionHelp
}
#if swift(>=3.0)
/** A ParseError is thrown if the `parse()` method fails. */
public enum ParseError: Error, CustomStringConvertible {
/** Thrown if an unrecognized argument is passed to `parse()` in strict mode */
case InvalidArgument(String)
/** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */
case InvalidValueForOption(Option, [String])
/** Thrown if an Option with required: true is missing */
case MissingRequiredOptions([Option])
public var description: String {
switch self {
case let .InvalidArgument(arg):
return "Invalid argument: \(arg)"
case let .InvalidValueForOption(opt, vals):
let vs = vals.joined(separator: ", ")
return "Invalid value(s) for option \(opt.flagDescription): \(vs)"
case let .MissingRequiredOptions(opts):
return "Missing required options: \(opts.map { return $0.flagDescription })"
}
}
}
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = Swift.CommandLine.arguments) {
self._arguments = arguments
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
private func _getFlagValues(_ flagIndex: Int, _ attachedArg: String? = nil) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
if let a = attachedArg {
args.append(a)
}
for i in flagIndex + 1 ..< _arguments.count {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
_arguments[i].toDouble() == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
public func addOption(_ option: Option) {
let uf = _usedFlags
for case let flag? in [option.shortFlag, option.longFlag] {
assert(!uf.contains(flag), "Flag '\(flag)' already in use")
}
_options.append(option)
_maxFlagDescriptionWidth = 0
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
public func addOptions(_ options: [Option]) {
for o in options {
addOption(o)
}
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
public func addOptions(_ options: Option...) {
for o in options {
addOption(o)
}
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
public func setOptions(_ options: [Option]) {
_options = [Option]()
addOptions(options)
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
public func setOptions(_ options: Option...) {
_options = [Option]()
addOptions(options)
}
#else
/** A ParseError is thrown if the `parse()` method fails. */
public enum ParseError: ErrorType, CustomStringConvertible {
/** Thrown if an unrecognized argument is passed to `parse()` in strict mode */
case InvalidArgument(String)
/** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */
case InvalidValueForOption(Option, [String])
/** Thrown if an Option with required: true is missing */
case MissingRequiredOptions([Option])
public var description: String {
switch self {
case let .InvalidArgument(arg):
return "Invalid argument: \(arg)"
case let .InvalidValueForOption(opt, vals):
let vs = vals.joinWithSeparator(", ")
return "Invalid value(s) for option \(opt.flagDescription): \(vs)"
case let .MissingRequiredOptions(opts):
return "Missing required options: \(opts.map { return $0.flagDescription })"
}
}
}
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = Process.arguments) {
self._arguments = arguments
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
private func _getFlagValues(flagIndex: Int, _ attachedArg: String? = nil) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
if let a = attachedArg {
args.append(a)
}
for i in flagIndex + 1 ..< _arguments.count {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
_arguments[i].toDouble() == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
public func addOption(option: Option) {
let uf = _usedFlags
for case let flag? in [option.shortFlag, option.longFlag] {
assert(!uf.contains(flag), "Flag '\(flag)' already in use")
}
_options.append(option)
_maxFlagDescriptionWidth = 0
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
public func addOptions(options: [Option]) {
for o in options {
addOption(o)
}
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
public func addOptions(options: Option...) {
for o in options {
addOption(o)
}
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
public func setOptions(options: [Option]) {
_options = [Option]()
addOptions(options)
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
public func setOptions(options: Option...) {
_options = [Option]()
addOptions(options)
}
#endif
/**
* Parses command-line arguments into their matching Option values.
*
* - parameter strict: Fail if any unrecognized flags are present (default: false).
*
* - throws: A `ParseError` if argument parsing fails:
* - `.InvalidArgument` if an unrecognized flag is present and `strict` is true
* - `.InvalidValueForOption` if the value supplied to an option is not valid (for
* example, a string is supplied for an IntOption)
* - `.MissingRequiredOptions` if a required option isn't present
*/
public func parse(strict: Bool = false) throws {
var strays = _arguments
/* Nuke executable name */
strays[0] = ""
#if swift(>=3.0)
let argumentsEnumerator = _arguments.enumerated()
#else
let argumentsEnumerator = _arguments.enumerate()
#endif
for (idx, arg) in argumentsEnumerator {
if arg == ArgumentStopper {
break
}
if !arg.hasPrefix(ShortOptionPrefix) {
continue
}
let skipChars = arg.hasPrefix(LongOptionPrefix) ?
LongOptionPrefix.count : ShortOptionPrefix.count
#if swift(>=3.0)
let flagWithArg = arg[arg.index(arg.startIndex, offsetBy: skipChars)..<arg.endIndex]
#else
let flagWithArg = arg[arg.startIndex.advancedBy(skipChars)..<arg.endIndex]
#endif
/* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */
if flagWithArg.isEmpty {
continue
}
/* Remove attached argument from flag */
let splitFlag = flagWithArg.split(separator: ArgumentAttacher, maxSplits: 1)
let flag = String(splitFlag[0])
let attachedArg: String? = splitFlag.count == 2 ? String(splitFlag[1]) : nil
var flagMatched = false
for option in _options where option.flagMatch(flag) {
let vals = self._getFlagValues(idx, attachedArg)
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
var claimedIdx = idx + option.claimedValues
if attachedArg != nil { claimedIdx -= 1 }
for i in idx...claimedIdx {
strays[i] = ""
}
flagMatched = true
break
}
/* Flags that do not take any arguments can be concatenated */
let flagLength = flag.count
if !flagMatched && !arg.hasPrefix(LongOptionPrefix) {
#if swift(>=3.0)
let flagCharactersEnumerator = flag.enumerated()
#else
let flagCharactersEnumerator = flag.characters.enumerate()
#endif
for (i, c) in flagCharactersEnumerator {
for option in _options where option.flagMatch(String(c)) {
/* Values are allowed at the end of the concatenated flags, e.g.
* -xvf <file1> <file2>
*/
let vals = (i == flagLength - 1) ? self._getFlagValues(idx, attachedArg) : [String]()
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
var claimedIdx = idx + option.claimedValues
if attachedArg != nil { claimedIdx -= 1 }
for i in idx...claimedIdx {
strays[i] = ""
}
flagMatched = true
break
}
}
}
/* Invalid flag */
guard !strict || flagMatched else {
throw ParseError.InvalidArgument(arg)
}
}
/* Check to see if any required options were not matched */
let missingOptions = _options.filter { $0.required && !$0.wasSet }
guard missingOptions.count == 0 else {
throw ParseError.MissingRequiredOptions(missingOptions)
}
unparsedArguments = strays.filter { $0 != "" }
}
/**
* Provides the default formatting of `printUsage()` output.
*
* - parameter s: The string to format.
* - parameter type: Type of output.
*
* - returns: The formatted string.
* - seealso: `formatOutput`
*/
public func defaultFormat(s: String, type: OutputType) -> String {
switch type {
case .About:
return "\(s)\n"
case .Error:
return "\(s)\n\n"
case .OptionFlag:
return " \(s.padded(toWidth: maxFlagDescriptionWidth)):\n"
case .OptionHelp:
return " \(s)\n"
}
}
/* printUsage() is generic for OutputStreamType because the Swift compiler crashes
* on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694).
*/
/**
* Prints a usage message.
*
* - parameter to: An OutputStreamType to write the error message to.
*/
#if swift(>=3.0)
public func printUsage<TargetStream: TextOutputStream>(_ to: inout TargetStream) {
/* Nil coalescing operator (??) doesn't work on closures :( */
let format = formatOutput != nil ? formatOutput! : defaultFormat
let name = _arguments[0]
print(format("Usage: \(name) [options]", .About), terminator: "", to: &to)
for opt in _options {
print(format(opt.flagDescription, .OptionFlag), terminator: "", to: &to)
print(format(opt.helpMessage, .OptionHelp), terminator: "", to: &to)
}
}
#else
public func printUsage<TargetStream: OutputStreamType>(inout to: TargetStream) {
/* Nil coalescing operator (??) doesn't work on closures :( */
let format = formatOutput != nil ? formatOutput! : defaultFormat
let name = _arguments[0]
print(format("Usage: \(name) [options]", .About), terminator: "", toStream: &to)
for opt in _options {
print(format(opt.flagDescription, .OptionFlag), terminator: "", toStream: &to)
print(format(opt.helpMessage, .OptionHelp), terminator: "", toStream: &to)
}
}
#endif
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
* - parameter to: An OutputStreamType to write the error message to.
*/
#if swift(>=3.0)
public func printUsage<TargetStream: TextOutputStream>(_ error: Error, to: inout TargetStream) {
let format = formatOutput != nil ? formatOutput! : defaultFormat
print(format("\(error)", .Error), terminator: "", to: &to)
printUsage(&to)
}
#else
public func printUsage<TargetStream: OutputStreamType>(error: ErrorType, inout to: TargetStream) {
let format = formatOutput != nil ? formatOutput! : defaultFormat
print(format("\(error)", .Error), terminator: "", toStream: &to)
printUsage(&to)
}
#endif
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
*/
#if swift(>=3.0)
public func printUsage(_ error: Error) {
var out = StderrOutputStream.stream
printUsage(error, to: &out)
}
#else
public func printUsage(error: ErrorType) {
var out = StderrOutputStream.stream
printUsage(error, to: &out)
}
#endif
/**
* Prints a usage message.
*/
public func printUsage() {
var out = StderrOutputStream.stream
printUsage(&out)
}
}
|
apache-2.0
|
8fcdb570b115dae299156f6e6560d071
| 29.184543 | 111 | 0.62805 | 4.253612 | false | false | false | false |
liruqi/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Contacts/ContactsBaseViewController.swift
|
8
|
2066
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class ContactsBaseViewController: EngineListController {
override func bindTable(table: UITableView, fade: Bool) {
view.backgroundColor = MainAppTheme.list.bgColor
table.rowHeight = 56
table.separatorStyle = UITableViewCellSeparatorStyle.None
table.backgroundColor = MainAppTheme.list.backyardColor
super.bindTable(table, fade: fade)
}
override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
let reuseId = "cell_contact";
var cell = tableView.dequeueReusableCellWithIdentifier(reuseId) as! ContactCell?;
if (cell == nil) {
cell = ContactCell(reuseIdentifier:reuseId);
}
return cell!;
}
override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
let contact = item as! ACContact;
var isLast = false
if (indexPath.section == tableView.numberOfSections - 1) {
isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section)
}
// Building short name
var shortName : String? = nil;
if (indexPath.row == 0) {
shortName = contact.getName().smallValue();
} else {
let prevContact = objectAtIndexPath(NSIndexPath(forRow: indexPath.row-1, inSection: indexPath.section)) as! ACContact;
let prevName = prevContact.getName().smallValue();
let name = contact.getName().smallValue();
if (prevName != name) {
shortName = name;
}
}
(cell as! ContactCell).bindContact(contact, shortValue: shortName, isLast: isLast);
}
override func buildDisplayList() -> ARBindedDisplayList {
return Actor.buildContactsDisplayList()
}
}
|
mit
|
a07d0b19e507617f177dc1c3c2f20a96
| 34.033898 | 139 | 0.621491 | 5.243655 | false | false | false | false |
radex/swift-compiler-crashes
|
crashes-fuzzing/03937-no-stacktrace.swift
|
11
|
2245
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T where g: T where g: A<T>: A {
let h = [Void{
Void{
(([Void{
let h = [Void{
struct B<T where B : Any)
case c,
protocol a {
struct d
var d = 0.e : Any)?
class
() as a<I : A.c,
struct B<T where g: Any)?
case c,
Void{
struct d
case c] = [Void{
case c
{
let end = 0
Void{
([Void{
case c,
d
{
case c,
case c,
protocol P {
class
{
var d where H.c,
struct d<T>: A.c
(([Void{
let a {
case c] = 0
d
struct B)?
class
{
struct A {
let h = 0
class
struct A {
func a
{
{
d<T where g: T where A.c,
{
var d where B : b { func a<T where A<T where B : d = 0.c
class
{
struct B<T : Any)?
case c,
class
case c] = 0
class
class
case c,
Void{
struct A {
class
class
var d = B)
{
struct A {
static let a {
case c] = 0.g : A {
struct B<T where H.g : b { func c
let h = a<T {
func c
{
class
protocol a {
}
class
() as a
case c
{
var d where g: A.g : b { func a
struct B<T where H.e : b { func c
typealias e : T {
struct B<T>: A.c
struct A {
protocol a {
class a
func a<T where B : e
([Void{
struct d<T where H.c] = B)?
class
protocol a {
class
class
case c,
{
case c,
}
{
case c,
{
struct A<T where H.c] = B<T where g: T where A.c,
case c,
{
struct B<T where H.e : T where g: Any)
}
{
case c] = 0.c,
}
func a
func b
}
typealias e : Any)
let a {
() as a
case c] = [Void{
struct A.c,
case c,
{
protocol a {
d<T {
class
func b
class
class
{
let h = [Void{
}
class a<I : T where A<T : d
protocol a {
struct d
(((([Void{
([Void{
let end = a<I : A {
let end = a<T>: d where g: d
case c
struct A.c,
class
func c,
struct d<T : A {
let a {
(e == B<T>: T : d
func a
protocol a {
class
struct A.e : d<T where H.c,
class
struct B)
case c
d<T where g: A.c,
((e : A {
class a
case c,
struct A {
}
struct B<T>: b { func b
class
{
() as a<T where B : d<T where g: Any)
class
case c
case c,
static let end = [[Void{
case c,
d
var d = [Void{
class
{
{
([Void{
func a
struct B<I : A<T {
{
class
class
}
((() as a
struct A {
class
(([Void{
(() as a
Void{
func c,
var d where g: A {
}
case c,
{
case c] = a<T>: d
([Void{
{
struct A<T where B : A.c] = [Void{
{
class
{
{
([[[Void{
case c] = a
(([Void{
{
case c,
|
mit
|
a0935dd136a18cf298f435970bef7cac
| 10.113861 | 87 | 0.5951 | 2.258551 | false | false | false | false |
swiftcodex/Swift-Radio-Pro
|
SwiftRadio/Libraries/Spring/Spring.swift
|
1
|
23961
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@objc public protocol Springable {
var autostart: Bool { get set }
var autohide: Bool { get set }
var animation: String { get set }
var force: CGFloat { get set }
var delay: CGFloat { get set }
var duration: CGFloat { get set }
var damping: CGFloat { get set }
var velocity: CGFloat { get set }
var repeatCount: Float { get set }
var x: CGFloat { get set }
var y: CGFloat { get set }
var scaleX: CGFloat { get set }
var scaleY: CGFloat { get set }
var rotate: CGFloat { get set }
var opacity: CGFloat { get set }
var animateFrom: Bool { get set }
var curve: String { get set }
// UIView
var layer : CALayer { get }
var transform : CGAffineTransform { get set }
var alpha : CGFloat { get set }
func animate()
func animateNext(completion: @escaping () -> ())
func animateTo()
func animateToNext(completion: @escaping () -> ())
}
public class Spring : NSObject {
private unowned var view : Springable
private var shouldAnimateAfterActive = false
private var shouldAnimateInLayoutSubviews = true
init(_ view: Springable) {
self.view = view
super.init()
commonInit()
}
func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(Spring.didBecomeActiveNotification(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
}
@objc func didBecomeActiveNotification(_ notification: NSNotification) {
if shouldAnimateAfterActive {
alpha = 0
animate()
shouldAnimateAfterActive = false
}
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
private var autostart: Bool { set { self.view.autostart = newValue } get { return self.view.autostart }}
private var autohide: Bool { set { self.view.autohide = newValue } get { return self.view.autohide }}
private var animation: String { set { self.view.animation = newValue } get { return self.view.animation }}
private var force: CGFloat { set { self.view.force = newValue } get { return self.view.force }}
private var delay: CGFloat { set { self.view.delay = newValue } get { return self.view.delay }}
private var duration: CGFloat { set { self.view.duration = newValue } get { return self.view.duration }}
private var damping: CGFloat { set { self.view.damping = newValue } get { return self.view.damping }}
private var velocity: CGFloat { set { self.view.velocity = newValue } get { return self.view.velocity }}
private var repeatCount: Float { set { self.view.repeatCount = newValue } get { return self.view.repeatCount }}
private var x: CGFloat { set { self.view.x = newValue } get { return self.view.x }}
private var y: CGFloat { set { self.view.y = newValue } get { return self.view.y }}
private var scaleX: CGFloat { set { self.view.scaleX = newValue } get { return self.view.scaleX }}
private var scaleY: CGFloat { set { self.view.scaleY = newValue } get { return self.view.scaleY }}
private var rotate: CGFloat { set { self.view.rotate = newValue } get { return self.view.rotate }}
private var opacity: CGFloat { set { self.view.opacity = newValue } get { return self.view.opacity }}
private var animateFrom: Bool { set { self.view.animateFrom = newValue } get { return self.view.animateFrom }}
private var curve: String { set { self.view.curve = newValue } get { return self.view.curve }}
// UIView
private var layer : CALayer { return view.layer }
private var transform : CGAffineTransform { get { return view.transform } set { view.transform = newValue }}
private var alpha: CGFloat { get { return view.alpha } set { view.alpha = newValue } }
public enum AnimationPreset: String {
case SlideLeft = "slideLeft"
case SlideRight = "slideRight"
case SlideDown = "slideDown"
case SlideUp = "slideUp"
case SqueezeLeft = "squeezeLeft"
case SqueezeRight = "squeezeRight"
case SqueezeDown = "squeezeDown"
case SqueezeUp = "squeezeUp"
case FadeIn = "fadeIn"
case FadeOut = "fadeOut"
case FadeOutIn = "fadeOutIn"
case FadeInLeft = "fadeInLeft"
case FadeInRight = "fadeInRight"
case FadeInDown = "fadeInDown"
case FadeInUp = "fadeInUp"
case ZoomIn = "zoomIn"
case ZoomOut = "zoomOut"
case Fall = "fall"
case Shake = "shake"
case Pop = "pop"
case FlipX = "flipX"
case FlipY = "flipY"
case Morph = "morph"
case Squeeze = "squeeze"
case Flash = "flash"
case Wobble = "wobble"
case Swing = "swing"
}
public enum AnimationCurve: String {
case EaseIn = "easeIn"
case EaseOut = "easeOut"
case EaseInOut = "easeInOut"
case Linear = "linear"
case Spring = "spring"
case EaseInSine = "easeInSine"
case EaseOutSine = "easeOutSine"
case EaseInOutSine = "easeInOutSine"
case EaseInQuad = "easeInQuad"
case EaseOutQuad = "easeOutQuad"
case EaseInOutQuad = "easeInOutQuad"
case EaseInCubic = "easeInCubic"
case EaseOutCubic = "easeOutCubic"
case EaseInOutCubic = "easeInOutCubic"
case EaseInQuart = "easeInQuart"
case EaseOutQuart = "easeOutQuart"
case EaseInOutQuart = "easeInOutQuart"
case EaseInQuint = "easeInQuint"
case EaseOutQuint = "easeOutQuint"
case EaseInOutQuint = "easeInOutQuint"
case EaseInExpo = "easeInExpo"
case EaseOutExpo = "easeOutExpo"
case EaseInOutExpo = "easeInOutExpo"
case EaseInCirc = "easeInCirc"
case EaseOutCirc = "easeOutCirc"
case EaseInOutCirc = "easeInOutCirc"
case EaseInBack = "easeInBack"
case EaseOutBack = "easeOutBack"
case EaseInOutBack = "easeInOutBack"
}
func animatePreset() {
alpha = 0.99
if let animation = AnimationPreset(rawValue: animation) {
switch animation {
case .SlideLeft:
x = 300*force
case .SlideRight:
x = -300*force
case .SlideDown:
y = -300*force
case .SlideUp:
y = 300*force
case .SqueezeLeft:
x = 300
scaleX = 3*force
case .SqueezeRight:
x = -300
scaleX = 3*force
case .SqueezeDown:
y = -300
scaleY = 3*force
case .SqueezeUp:
y = 300
scaleY = 3*force
case .FadeIn:
opacity = 0
case .FadeOut:
animateFrom = false
opacity = 0
case .FadeOutIn:
let animation = CABasicAnimation()
animation.keyPath = "opacity"
animation.fromValue = 1
animation.toValue = 0
animation.timingFunction = getTimingFunction(curve: curve)
animation.duration = CFTimeInterval(duration)
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
animation.autoreverses = true
layer.add(animation, forKey: "fade")
case .FadeInLeft:
opacity = 0
x = 300*force
case .FadeInRight:
x = -300*force
opacity = 0
case .FadeInDown:
y = -300*force
opacity = 0
case .FadeInUp:
y = 300*force
opacity = 0
case .ZoomIn:
opacity = 0
scaleX = 2*force
scaleY = 2*force
case .ZoomOut:
animateFrom = false
opacity = 0
scaleX = 2*force
scaleY = 2*force
case .Fall:
animateFrom = false
rotate = 15 * CGFloat(CGFloat.pi/180)
y = 600*force
case .Shake:
let animation = CAKeyframeAnimation()
animation.keyPath = "position.x"
animation.values = [0, 30*force, -30*force, 30*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.timingFunction = getTimingFunction(curve: curve)
animation.duration = CFTimeInterval(duration)
animation.isAdditive = true
animation.repeatCount = repeatCount
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(animation, forKey: "shake")
case .Pop:
let animation = CAKeyframeAnimation()
animation.keyPath = "transform.scale"
animation.values = [0, 0.2*force, -0.2*force, 0.2*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.timingFunction = getTimingFunction(curve: curve)
animation.duration = CFTimeInterval(duration)
animation.isAdditive = true
animation.repeatCount = repeatCount
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(animation, forKey: "pop")
case .FlipX:
rotate = 0
scaleX = 1
scaleY = 1
var perspective = CATransform3DIdentity
perspective.m34 = -1.0 / layer.frame.size.width/2
let animation = CABasicAnimation()
animation.keyPath = "transform"
animation.fromValue = NSValue(caTransform3D: CATransform3DMakeRotation(0, 0, 0, 0))
animation.toValue = NSValue(caTransform3D:
CATransform3DConcat(perspective, CATransform3DMakeRotation(CGFloat(CGFloat.pi), 0, 1, 0)))
animation.duration = CFTimeInterval(duration)
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
animation.timingFunction = getTimingFunction(curve: curve)
layer.add(animation, forKey: "3d")
case .FlipY:
var perspective = CATransform3DIdentity
perspective.m34 = -1.0 / layer.frame.size.width/2
let animation = CABasicAnimation()
animation.keyPath = "transform"
animation.fromValue = NSValue(caTransform3D:
CATransform3DMakeRotation(0, 0, 0, 0))
animation.toValue = NSValue(caTransform3D:
CATransform3DConcat(perspective,CATransform3DMakeRotation(CGFloat(CGFloat.pi), 1, 0, 0)))
animation.duration = CFTimeInterval(duration)
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
animation.timingFunction = getTimingFunction(curve: curve)
layer.add(animation, forKey: "3d")
case .Morph:
let morphX = CAKeyframeAnimation()
morphX.keyPath = "transform.scale.x"
morphX.values = [1, 1.3*force, 0.7, 1.3*force, 1]
morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphX.timingFunction = getTimingFunction(curve: curve)
morphX.duration = CFTimeInterval(duration)
morphX.repeatCount = repeatCount
morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(morphX, forKey: "morphX")
let morphY = CAKeyframeAnimation()
morphY.keyPath = "transform.scale.y"
morphY.values = [1, 0.7, 1.3*force, 0.7, 1]
morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphY.timingFunction = getTimingFunction(curve: curve)
morphY.duration = CFTimeInterval(duration)
morphY.repeatCount = repeatCount
morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(morphY, forKey: "morphY")
case .Squeeze:
let morphX = CAKeyframeAnimation()
morphX.keyPath = "transform.scale.x"
morphX.values = [1, 1.5*force, 0.5, 1.5*force, 1]
morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphX.timingFunction = getTimingFunction(curve: curve)
morphX.duration = CFTimeInterval(duration)
morphX.repeatCount = repeatCount
morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(morphX, forKey: "morphX")
let morphY = CAKeyframeAnimation()
morphY.keyPath = "transform.scale.y"
morphY.values = [1, 0.5, 1, 0.5, 1]
morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
morphY.timingFunction = getTimingFunction(curve: curve)
morphY.duration = CFTimeInterval(duration)
morphY.repeatCount = repeatCount
morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(morphY, forKey: "morphY")
case .Flash:
let animation = CABasicAnimation()
animation.keyPath = "opacity"
animation.fromValue = 1
animation.toValue = 0
animation.duration = CFTimeInterval(duration)
animation.repeatCount = repeatCount * 2.0
animation.autoreverses = true
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(animation, forKey: "flash")
case .Wobble:
let animation = CAKeyframeAnimation()
animation.keyPath = "transform.rotation"
animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.duration = CFTimeInterval(duration)
animation.isAdditive = true
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(animation, forKey: "wobble")
let x = CAKeyframeAnimation()
x.keyPath = "position.x"
x.values = [0, 30*force, -30*force, 30*force, 0]
x.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
x.timingFunction = getTimingFunction(curve: curve)
x.duration = CFTimeInterval(duration)
x.isAdditive = true
x.repeatCount = repeatCount
x.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(x, forKey: "x")
case .Swing:
let animation = CAKeyframeAnimation()
animation.keyPath = "transform.rotation"
animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0]
animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1]
animation.duration = CFTimeInterval(duration)
animation.isAdditive = true
animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay)
layer.add(animation, forKey: "swing")
}
}
}
func getTimingFunction(curve: String) -> CAMediaTimingFunction {
if let curve = AnimationCurve(rawValue: curve) {
switch curve {
case .EaseIn: return CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
case .EaseOut: return CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
case .EaseInOut: return CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
case .Linear: return CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
case .Spring: return CAMediaTimingFunction(controlPoints: 0.5, 1.1+Float(force/3), 1, 1)
case .EaseInSine: return CAMediaTimingFunction(controlPoints: 0.47, 0, 0.745, 0.715)
case .EaseOutSine: return CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1)
case .EaseInOutSine: return CAMediaTimingFunction(controlPoints: 0.445, 0.05, 0.55, 0.95)
case .EaseInQuad: return CAMediaTimingFunction(controlPoints: 0.55, 0.085, 0.68, 0.53)
case .EaseOutQuad: return CAMediaTimingFunction(controlPoints: 0.25, 0.46, 0.45, 0.94)
case .EaseInOutQuad: return CAMediaTimingFunction(controlPoints: 0.455, 0.03, 0.515, 0.955)
case .EaseInCubic: return CAMediaTimingFunction(controlPoints: 0.55, 0.055, 0.675, 0.19)
case .EaseOutCubic: return CAMediaTimingFunction(controlPoints: 0.215, 0.61, 0.355, 1)
case .EaseInOutCubic: return CAMediaTimingFunction(controlPoints: 0.645, 0.045, 0.355, 1)
case .EaseInQuart: return CAMediaTimingFunction(controlPoints: 0.895, 0.03, 0.685, 0.22)
case .EaseOutQuart: return CAMediaTimingFunction(controlPoints: 0.165, 0.84, 0.44, 1)
case .EaseInOutQuart: return CAMediaTimingFunction(controlPoints: 0.77, 0, 0.175, 1)
case .EaseInQuint: return CAMediaTimingFunction(controlPoints: 0.755, 0.05, 0.855, 0.06)
case .EaseOutQuint: return CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1)
case .EaseInOutQuint: return CAMediaTimingFunction(controlPoints: 0.86, 0, 0.07, 1)
case .EaseInExpo: return CAMediaTimingFunction(controlPoints: 0.95, 0.05, 0.795, 0.035)
case .EaseOutExpo: return CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1)
case .EaseInOutExpo: return CAMediaTimingFunction(controlPoints: 1, 0, 0, 1)
case .EaseInCirc: return CAMediaTimingFunction(controlPoints: 0.6, 0.04, 0.98, 0.335)
case .EaseOutCirc: return CAMediaTimingFunction(controlPoints: 0.075, 0.82, 0.165, 1)
case .EaseInOutCirc: return CAMediaTimingFunction(controlPoints: 0.785, 0.135, 0.15, 0.86)
case .EaseInBack: return CAMediaTimingFunction(controlPoints: 0.6, -0.28, 0.735, 0.045)
case .EaseOutBack: return CAMediaTimingFunction(controlPoints: 0.175, 0.885, 0.32, 1.275)
case .EaseInOutBack: return CAMediaTimingFunction(controlPoints: 0.68, -0.55, 0.265, 1.55)
}
}
return CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
}
func getAnimationOptions(curve: String) -> UIView.AnimationOptions {
if let curve = AnimationCurve(rawValue: curve) {
switch curve {
case .EaseIn: return UIView.AnimationOptions.curveEaseIn
case .EaseOut: return UIView.AnimationOptions.curveEaseOut
case .EaseInOut: return UIView.AnimationOptions()
default: break
}
}
return UIView.AnimationOptions.curveLinear
}
public func animate() {
animateFrom = true
animatePreset()
setView {}
}
public func animateNext(completion: @escaping () -> ()) {
animateFrom = true
animatePreset()
setView {
completion()
}
}
public func animateTo() {
animateFrom = false
animatePreset()
setView {}
}
public func animateToNext(completion: @escaping () -> ()) {
animateFrom = false
animatePreset()
setView {
completion()
}
}
public func customAwakeFromNib() {
if autohide {
alpha = 0
}
}
public func customLayoutSubviews() {
if shouldAnimateInLayoutSubviews {
shouldAnimateInLayoutSubviews = false
if autostart {
if UIApplication.shared.applicationState != .active {
shouldAnimateAfterActive = true
return
}
alpha = 0
animate()
}
}
}
func setView(completion: @escaping () -> ()) {
if animateFrom {
let translate = CGAffineTransform(translationX: self.x, y: self.y)
let scale = CGAffineTransform(scaleX: self.scaleX, y: self.scaleY)
let rotate = CGAffineTransform(rotationAngle: self.rotate)
let translateAndScale = translate.concatenating(scale)
self.transform = rotate.concatenating(translateAndScale)
self.alpha = self.opacity
}
UIView.animate( withDuration: TimeInterval(duration),
delay: TimeInterval(delay),
usingSpringWithDamping: damping,
initialSpringVelocity: velocity,
options: [getAnimationOptions(curve: curve), UIView.AnimationOptions.allowUserInteraction],
animations: { [weak self] in
if let _self = self
{
if _self.animateFrom {
_self.transform = CGAffineTransform.identity
_self.alpha = 1
}
else {
let translate = CGAffineTransform(translationX: _self.x, y: _self.y)
let scale = CGAffineTransform(scaleX: _self.scaleX, y: _self.scaleY)
let rotate = CGAffineTransform(rotationAngle: _self.rotate)
let translateAndScale = translate.concatenating(scale)
_self.transform = rotate.concatenating(translateAndScale)
_self.alpha = _self.opacity
}
}
}, completion: { [weak self] finished in
completion()
self?.resetAll()
})
}
func reset() {
x = 0
y = 0
opacity = 1
}
func resetAll() {
x = 0
y = 0
animation = ""
opacity = 1
scaleX = 1
scaleY = 1
rotate = 0
damping = 0.7
velocity = 0.7
repeatCount = 1
delay = 0
duration = 0.7
}
}
|
mit
|
34a3e0e0e79d5e5649239a326acf1c32
| 44.294896 | 175 | 0.572514 | 4.891997 | false | false | false | false |
Allow2CEO/browser-ios
|
Client/Frontend/Widgets/SiteTableViewController.swift
|
1
|
6882
|
/* 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 UIKit
import Storage
struct SiteTableViewControllerUX {
static let HeaderHeight = CGFloat(25)
static let RowHeight = CGFloat(58)
static let HeaderBorderColor = UIColor(rgb: 0xCFD5D9).withAlphaComponent(0.8)
static let HeaderTextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor(rgb: 0x232323)
static let HeaderBackgroundColor = UIColor(rgb: 0xECF0F3).withAlphaComponent(0.3)
static let HeaderFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightMedium)
static let HeaderTextMargin = CGFloat(10)
}
class SiteTableViewHeader : UITableViewHeaderFooterView {
// I can't get drawRect to play nicely with the glass background. As a fallback
// we just use views for the top and bottom borders.
let topBorder = UIView()
let bottomBorder = UIView()
let titleLabel = UILabel()
override var textLabel: UILabel? {
return titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
topBorder.backgroundColor = UIColor.white
bottomBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
contentView.backgroundColor = UIColor.white
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
titleLabel.textColor = SiteTableViewControllerUX.HeaderTextColor
titleLabel.textAlignment = .left
addSubview(topBorder)
addSubview(bottomBorder)
contentView.addSubview(titleLabel)
topBorder.snp.makeConstraints { make in
make.left.right.equalTo(self)
make.top.equalTo(self).offset(-0.5)
make.height.equalTo(0.5)
}
bottomBorder.snp.makeConstraints { make in
make.left.right.bottom.equalTo(self)
make.height.equalTo(0.5)
}
// A table view will initialize the header with CGSizeZero before applying the actual size. Hence, the label's constraints
// must not impose a minimum width on the content view.
titleLabel.snp.makeConstraints { make in
make.left.equalTo(contentView).offset(SiteTableViewControllerUX.HeaderTextMargin).priority(999)
make.right.equalTo(contentView).offset(-SiteTableViewControllerUX.HeaderTextMargin).priority(999)
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/**
* Provides base shared functionality for site rows and headers.
*/
class SiteTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
fileprivate let DefaultCellIdentifier = "Cell"
fileprivate let CellIdentifier = "CellIdentifier"
fileprivate let HeaderIdentifier = "HeaderIdentifier"
var iconForSiteId = [Int : Favicon]()
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
return
}
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: DefaultCellIdentifier)
tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: CellIdentifier)
tableView.register(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: HeaderIdentifier)
tableView.layoutMargins = UIEdgeInsets.zero
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
tableView.backgroundColor = UIConstants.PanelBackgroundColor
tableView.separatorColor = UIConstants.SeparatorColor
tableView.accessibilityIdentifier = "SiteTable"
tableView.cellLayoutMarginsFollowReadableWidth = false
// Set an empty footer to prevent empty cells from appearing in the list.
tableView.tableFooterView = UIView()
}
deinit {
// The view might outlive this view controller thanks to animations;
// explicitly nil out its references to us to avoid crashes. Bug 1218826.
tableView.dataSource = nil
tableView.delegate = nil
}
func reloadData() {
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath)
if self.tableView(tableView, hasFullWidthSeparatorForRowAtIndexPath: indexPath) {
cell.separatorInset = UIEdgeInsets.zero
}
if tableView.isEditing == false {
cell.gestureRecognizers?.forEach { cell.removeGestureRecognizer($0) }
let lp = UILongPressGestureRecognizer(target: self, action: #selector(longPressOnCell))
cell.addGestureRecognizer(lp)
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderIdentifier)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return SiteTableViewControllerUX.HeaderHeight
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return SiteTableViewControllerUX.RowHeight
}
func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool {
return false
}
func getLongPressUrl(forIndexPath indexPath: IndexPath) -> (URL?, [Int]?) {
print("override in subclass for long press behaviour")
return (nil, nil)
}
@objc func longPressOnCell(_ gesture: UILongPressGestureRecognizer) {
if tableView.isEditing { //disable context menu on editing mode
return
}
if gesture.state != .began {
return
}
guard let cell = gesture.view as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) else { return }
let (url, folder) = getLongPressUrl(forIndexPath: indexPath)
let tappedElement = ContextMenuHelper.Elements(link: url, image: nil, folder: folder)
var p = getApp().window!.convert(cell.center, from:cell.superview!)
p.x += cell.frame.width * 0.33
getApp().browserViewController.showContextMenu(tappedElement, touchPoint: p)
}
}
|
mpl-2.0
|
01443ffab75f9f93e6bfd311eaa88466
| 38.551724 | 130 | 0.698198 | 5.347319 | false | false | false | false |
gifsy/Gifsy
|
Frameworks/Bond/BondTests/UIViewTests.swift
|
18
|
2524
|
//
// UIViewTests.swift
// Bond
//
// Created by Anthony Egerton on 11/03/2015.
// Copyright (c) 2015 Bond. All rights reserved.
//
import UIKit
import XCTest
import Bond
class UIViewTests: XCTestCase {
func testUIViewHiddenBond() {
let observable = Observable<Bool>(false)
let view = UIView()
view.hidden = true
XCTAssert(view.hidden == true, "Initial value")
observable.bindTo(view.bnd_hidden)
XCTAssert(view.hidden == false, "Value after binding")
observable.value = true
XCTAssert(view.hidden == true, "Value after observable change")
}
func testUIViewAlphaBond() {
let observable = Observable<CGFloat>(0.1)
let view = UIView()
view.alpha = 0.0
XCTAssert(abs(view.alpha - 0.0) < 0.0001, "Initial value")
observable.bindTo(view.bnd_alpha)
XCTAssert(abs(view.alpha - 0.1) < 0.0001, "Value after binding")
observable.value = 0.5
XCTAssert(abs(view.alpha - 0.5) < 0.0001, "Value after observable change")
}
func testUIViewBackgroundColorBond() {
let observable = Observable<UIColor>(UIColor.blackColor())
let view = UIView()
view.backgroundColor = UIColor.redColor()
XCTAssert(view.backgroundColor == UIColor.redColor(), "Initial value")
observable.bindTo(view.bnd_backgroundColor)
XCTAssert(view.backgroundColor == UIColor.blackColor(), "Value after binding")
observable.value = UIColor.blueColor()
XCTAssert(view.backgroundColor == UIColor.blueColor(), "Value after observable change")
}
func testUIViewUserInteractionEnabledBond() {
let observable = Observable<Bool>(false)
let view = UIView()
view.userInteractionEnabled = true
XCTAssert(view.userInteractionEnabled == true, "Initial value")
observable.bindTo(view.bnd_userInteractionEnabled)
XCTAssert(view.userInteractionEnabled == false, "Value After Binding")
observable.value = true
XCTAssert(view.userInteractionEnabled == true, "Value after observable change")
}
func testUIViewTintColorBond() {
let observable = Observable<UIColor>(UIColor.blackColor())
let view = UIView()
view.tintColor = UIColor.redColor()
XCTAssert(view.tintColor == UIColor.redColor(), "Initial value")
observable.bindTo(view.bnd_tintColor)
XCTAssert(view.tintColor == UIColor.blackColor(), "Value after binding")
observable.value = UIColor.blueColor()
XCTAssert(view.tintColor == UIColor.blueColor(), "Value after observable change")
}
}
|
apache-2.0
|
a7ece1a73493e0ac4cf4962a845d554d
| 28.694118 | 91 | 0.692552 | 4.33677 | false | true | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/PageSortKeys.swift
|
1
|
1761
|
//
// PageSortKeys.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
extension Storefront {
/// The set of valid sort keys for the Page query.
public enum PageSortKeys: String {
/// Sort by the `id` value.
case id = "ID"
/// Sort by relevance to the search terms when the `query` parameter is
/// specified on the connection. Don't use this sort key when no search query
/// is specified.
case relevance = "RELEVANCE"
/// Sort by the `title` value.
case title = "TITLE"
/// Sort by the `updated_at` value.
case updatedAt = "UPDATED_AT"
case unknownValue = ""
}
}
|
mit
|
628b9508033263ab5de546e3d465b7b6
| 35.6875 | 81 | 0.71891 | 3.966216 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/CustomerResetByUrlPayload.swift
|
1
|
6950
|
//
// CustomerResetByUrlPayload.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
extension Storefront {
/// Return type for `customerResetByUrl` mutation.
open class CustomerResetByUrlPayloadQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CustomerResetByUrlPayload
/// The customer object which was reset.
@discardableResult
open func customer(alias: String? = nil, _ subfields: (CustomerQuery) -> Void) -> CustomerResetByUrlPayloadQuery {
let subquery = CustomerQuery()
subfields(subquery)
addField(field: "customer", aliasSuffix: alias, subfields: subquery)
return self
}
/// A newly created customer access token object for the customer.
@discardableResult
open func customerAccessToken(alias: String? = nil, _ subfields: (CustomerAccessTokenQuery) -> Void) -> CustomerResetByUrlPayloadQuery {
let subquery = CustomerAccessTokenQuery()
subfields(subquery)
addField(field: "customerAccessToken", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@discardableResult
open func customerUserErrors(alias: String? = nil, _ subfields: (CustomerUserErrorQuery) -> Void) -> CustomerResetByUrlPayloadQuery {
let subquery = CustomerUserErrorQuery()
subfields(subquery)
addField(field: "customerUserErrors", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `customerUserErrors` instead.")
@discardableResult
open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CustomerResetByUrlPayloadQuery {
let subquery = UserErrorQuery()
subfields(subquery)
addField(field: "userErrors", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Return type for `customerResetByUrl` mutation.
open class CustomerResetByUrlPayload: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CustomerResetByUrlPayloadQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "customer":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CustomerResetByUrlPayload.self, field: fieldName, value: fieldValue)
}
return try Customer(fields: value)
case "customerAccessToken":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CustomerResetByUrlPayload.self, field: fieldName, value: fieldValue)
}
return try CustomerAccessToken(fields: value)
case "customerUserErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CustomerResetByUrlPayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try CustomerUserError(fields: $0) }
case "userErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CustomerResetByUrlPayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try UserError(fields: $0) }
default:
throw SchemaViolationError(type: CustomerResetByUrlPayload.self, field: fieldName, value: fieldValue)
}
}
/// The customer object which was reset.
open var customer: Storefront.Customer? {
return internalGetCustomer()
}
func internalGetCustomer(alias: String? = nil) -> Storefront.Customer? {
return field(field: "customer", aliasSuffix: alias) as! Storefront.Customer?
}
/// A newly created customer access token object for the customer.
open var customerAccessToken: Storefront.CustomerAccessToken? {
return internalGetCustomerAccessToken()
}
func internalGetCustomerAccessToken(alias: String? = nil) -> Storefront.CustomerAccessToken? {
return field(field: "customerAccessToken", aliasSuffix: alias) as! Storefront.CustomerAccessToken?
}
/// The list of errors that occurred from executing the mutation.
open var customerUserErrors: [Storefront.CustomerUserError] {
return internalGetCustomerUserErrors()
}
func internalGetCustomerUserErrors(alias: String? = nil) -> [Storefront.CustomerUserError] {
return field(field: "customerUserErrors", aliasSuffix: alias) as! [Storefront.CustomerUserError]
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `customerUserErrors` instead.")
open var userErrors: [Storefront.UserError] {
return internalGetUserErrors()
}
func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] {
return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "customer":
if let value = internalGetCustomer() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAccessToken":
if let value = internalGetCustomerAccessToken() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerUserErrors":
internalGetCustomerUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "userErrors":
internalGetUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
|
mit
|
6f55579396e3223760db870700f48403
| 36.365591 | 138 | 0.731511 | 4.266421 | false | false | false | false |
realm/SwiftLint
|
Source/SwiftLintFramework/Extensions/SourceKittenDictionary+SwiftUI.swift
|
1
|
7957
|
import SourceKittenFramework
/// Struct to represent SwiftUI ViewModifiers for the purpose of finding modifiers in a substructure.
struct SwiftUIModifier {
/// Name of the modifier.
let name: String
/// List of arguments to check for in the modifier.
let arguments: [Argument]
struct Argument {
/// Name of the argument we want to find. For single unnamed arguments, use the empty string.
let name: String
/// Whether or not the argument is required. If the argument is present, value checks are enforced.
/// Allows for better handling of modifiers with default values for certain arguments where we want
/// to ensure that the default value is used.
let required: Bool
/// List of possible values for the argument. Typically should just be a list with a single element,
/// but allows for the flexibility of checking for multiple possible values. To only check for the presence
/// of the modifier and not enforce any certain values, pass an empty array. All values are parsed as
/// Strings; for other types (boolean, numeric, optional, etc) types you can check for "true", "5", "nil", etc.
let values: [String]
/// Success criteria used for matching values (prefix, suffix, substring, exact match, or none).
let matchType: MatchType
init(name: String, required: Bool = true, values: [String], matchType: MatchType = .exactMatch) {
self.name = name
self.required = required
self.values = values
self.matchType = matchType
}
}
enum MatchType {
case prefix, suffix, substring, exactMatch
/// Compares the parsed argument value to a target value for the given match type
/// and returns true is a match is found.
func matches(argumentValue: String, targetValue: String) -> Bool {
switch self {
case .prefix:
return argumentValue.hasPrefix(targetValue)
case .suffix:
return argumentValue.hasSuffix(targetValue)
case .substring:
return argumentValue.contains(targetValue)
case .exactMatch:
return argumentValue == targetValue
}
}
}
}
/// Extensions for recursively checking SwiftUI code for certain modifiers.
extension SourceKittenDictionary {
/// Call on a SwiftUI View to recursively check the substructure for a certain modifier with certain arguments.
/// - Parameters:
/// - modifiers: A list of `SwiftUIModifier` structs to check for in the view's substructure.
/// In most cases, this can just be a single modifier, but since some modifiers have
/// multiple versions, this enables checking for any modifier from the list.
/// - file: The SwiftLintFile object for the current file, used to extract argument values.
/// - Returns: A boolean value representing whether or not the given modifier with the specified
/// arguments appears in the view's substructure.
func hasModifier(anyOf modifiers: [SwiftUIModifier], in file: SwiftLintFile) -> Bool {
// SwiftUI ViewModifiers are treated as `call` expressions, and we make sure we can get the expression's name.
guard expressionKind == .call, let name = name else {
return false
}
// If any modifier from the list matches, return true.
for modifier in modifiers {
// Check for the given modifier name
guard name.hasSuffix(modifier.name) else {
continue
}
// Check arguments.
var matchesArgs = true
for argument in modifier.arguments {
var foundArg = false
var argValue: String?
// Check for single unnamed argument.
if argument.name.isEmpty {
foundArg = true
argValue = getSingleUnnamedArgumentValue(in: file)
} else if let parsedArgument = enclosedArguments.first(where: { $0.name == argument.name }) {
foundArg = true
argValue = parsedArgument.getArgumentValue(in: file)
}
// If argument is not required and we didn't find it, continue.
if !foundArg && !argument.required {
continue
}
// Otherwise, we must have found an argument with a non-nil value to continue.
guard foundArg, let argumentValue = argValue else {
matchesArgs = false
break
}
// Argument value can match any of the options given in the argument struct.
if argument.values.isEmpty || argument.values.contains(where: {
argument.matchType.matches(argumentValue: argumentValue, targetValue: $0)
}) {
// Found a match, continue to next argument.
continue
} else {
// Did not find a match, exit loop over arguments.
matchesArgs = false
break
}
}
// Return true if all arguments matched
if matchesArgs {
return true
}
}
// Recursively check substructure.
// SwiftUI literal Views with modifiers will have a SourceKittenDictionary structure like:
// Image("myImage").resizable().accessibility(hidden: true).frame
// --> Image("myImage").resizable().accessibility
// --> Image("myImage").resizable
// --> Image
return substructure.contains(where: { $0.hasModifier(anyOf: modifiers, in: file) })
}
// MARK: Sample use cases of `hasModifier` that are used in multiple rules
/// Whether or not the dictionary represents a SwiftUI View with an `accesibilityHidden(true)`
/// or `accessibility(hidden: true)` modifier.
func hasAccessibilityHiddenModifier(in file: SwiftLintFile) -> Bool {
return hasModifier(
anyOf: [
SwiftUIModifier(
name: "accessibilityHidden",
arguments: [.init(name: "", values: ["true"])]
),
SwiftUIModifier(
name: "accessibility",
arguments: [.init(name: "hidden", values: ["true"])]
)
],
in: file
)
}
/// Whether or not the dictionary represents a SwiftUI View with an `accessibilityElement()` or
/// `accessibilityElement(children: .ignore)` modifier (`.ignore` is the default parameter value).
func hasAccessibilityElementChildrenIgnoreModifier(in file: SwiftLintFile) -> Bool {
return hasModifier(
anyOf: [
SwiftUIModifier(
name: "accessibilityElement",
arguments: [.init(name: "children", required: false, values: [".ignore"], matchType: .suffix)]
)
],
in: file
)
}
// MARK: Helpers to extract argument values
/// Helper to get the value of an argument.
func getArgumentValue(in file: SwiftLintFile) -> String? {
guard expressionKind == .argument, let bodyByteRange = bodyByteRange else {
return nil
}
return file.stringView.substringWithByteRange(bodyByteRange)
}
/// Helper to get the value of a single unnamed argument to a function call.
func getSingleUnnamedArgumentValue(in file: SwiftLintFile) -> String? {
guard expressionKind == .call, let bodyByteRange = bodyByteRange else {
return nil
}
return file.stringView.substringWithByteRange(bodyByteRange)
}
}
|
mit
|
0a5eac2ec796ba51d5e3064494e82dd8
| 41.550802 | 119 | 0.593691 | 5.383627 | false | false | false | false |
apple/swift-experimental-string-processing
|
Sources/_StringProcessing/Algorithms/Algorithms/Split.swift
|
1
|
13077
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
// MARK: `SplitCollection`
struct SplitCollection<Searcher: CollectionSearcher> {
public typealias Base = Searcher.Searched
let ranges: RangesCollection<Searcher>
var maxSplits: Int
var omittingEmptySubsequences: Bool
init(
ranges: RangesCollection<Searcher>,
maxSplits: Int,
omittingEmptySubsequences: Bool)
{
self.ranges = ranges
self.maxSplits = maxSplits
self.omittingEmptySubsequences = omittingEmptySubsequences
}
init(
base: Base,
searcher: Searcher,
maxSplits: Int,
omittingEmptySubsequences: Bool)
{
self.ranges = base._ranges(of: searcher)
self.maxSplits = maxSplits
self.omittingEmptySubsequences = omittingEmptySubsequences
}
}
extension SplitCollection: Sequence {
public struct Iterator: IteratorProtocol {
let base: Base
var index: Base.Index
var ranges: RangesCollection<Searcher>.Iterator
var maxSplits: Int
var omittingEmptySubsequences: Bool
var splitCounter = 0
var isDone = false
init(
ranges: RangesCollection<Searcher>,
maxSplits: Int,
omittingEmptySubsequences: Bool
) {
self.base = ranges.base
self.index = base.startIndex
self.ranges = ranges.makeIterator()
self.maxSplits = maxSplits
self.omittingEmptySubsequences = omittingEmptySubsequences
}
public mutating func next() -> Base.SubSequence? {
guard !isDone else { return nil }
/// Return the rest of base if it's non-empty or we're including
/// empty subsequences.
func finish() -> Base.SubSequence? {
isDone = true
return index == base.endIndex && omittingEmptySubsequences
? nil
: base[index...]
}
if index == base.endIndex {
return finish()
}
if splitCounter >= maxSplits {
return finish()
}
while true {
// If there are no more ranges that matched, return the rest of `base`.
guard let range = ranges.next() else {
return finish()
}
defer { index = range.upperBound }
if omittingEmptySubsequences && index == range.lowerBound {
continue
}
splitCounter += 1
return base[index..<range.lowerBound]
}
}
}
public func makeIterator() -> Iterator {
Iterator(ranges: ranges, maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences)
}
}
//extension SplitCollection: Collection {
// public struct Index {
// var start: Base.Index
// var base: RangesCollection<Searcher>.Index
// var isEndIndex: Bool
// }
//
// public var startIndex: Index {
// let base = ranges.startIndex
// return Index(start: ranges.base.startIndex, base: base, isEndIndex: false)
// }
//
// public var endIndex: Index {
// Index(start: ranges.base.endIndex, base: ranges.endIndex, isEndIndex: true)
// }
//
// public func formIndex(after index: inout Index) {
// guard !index.isEndIndex else { fatalError("Cannot advance past endIndex") }
//
// if let range = index.base.range {
// let newStart = range.upperBound
// ranges.formIndex(after: &index.base)
// index.start = newStart
// } else {
// index.isEndIndex = true
// }
// }
//
// public func index(after index: Index) -> Index {
// var index = index
// formIndex(after: &index)
// return index
// }
//
// public subscript(index: Index) -> Base.SubSequence {
// guard !index.isEndIndex else {
// fatalError("Cannot subscript using endIndex")
// }
// let end = index.base.range?.lowerBound ?? ranges.base.endIndex
// return ranges.base[index.start..<end]
// }
//}
//
//extension SplitCollection.Index: Comparable {
// static func == (lhs: Self, rhs: Self) -> Bool {
// switch (lhs.isEndIndex, rhs.isEndIndex) {
// case (false, false):
// return lhs.start == rhs.start
// case (let lhs, let rhs):
// return lhs == rhs
// }
// }
//
// static func < (lhs: Self, rhs: Self) -> Bool {
// switch (lhs.isEndIndex, rhs.isEndIndex) {
// case (true, _):
// return false
// case (_, true):
// return true
// case (false, false):
// return lhs.start < rhs.start
// }
// }
//}
// MARK: `ReversedSplitCollection`
struct ReversedSplitCollection<Searcher: BackwardCollectionSearcher> {
public typealias Base = Searcher.BackwardSearched
let ranges: ReversedRangesCollection<Searcher>
init(ranges: ReversedRangesCollection<Searcher>) {
self.ranges = ranges
}
init(base: Base, searcher: Searcher) {
self.ranges = base._rangesFromBack(of: searcher)
}
}
extension ReversedSplitCollection: Sequence {
public struct Iterator: IteratorProtocol {
let base: Base
var index: Base.Index
var ranges: ReversedRangesCollection<Searcher>.Iterator
var isDone: Bool
init(ranges: ReversedRangesCollection<Searcher>) {
self.base = ranges.base
self.index = base.endIndex
self.ranges = ranges.makeIterator()
self.isDone = false
}
public mutating func next() -> Base.SubSequence? {
guard !isDone else { return nil }
guard let range = ranges.next() else {
isDone = true
return base[..<index]
}
defer { index = range.lowerBound }
return base[range.upperBound..<index]
}
}
public func makeIterator() -> Iterator {
Iterator(ranges: ranges)
}
}
// TODO: `Collection` conformance
// MARK: `CollectionSearcher` algorithms
extension Collection {
func split<Searcher: CollectionSearcher>(
by separator: Searcher,
maxSplits: Int,
omittingEmptySubsequences: Bool
) -> SplitCollection<Searcher> where Searcher.Searched == Self {
SplitCollection(
base: self,
searcher: separator,
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences)
}
}
extension BidirectionalCollection {
func splitFromBack<Searcher: BackwardCollectionSearcher>(
by separator: Searcher
) -> ReversedSplitCollection<Searcher>
where Searcher.BackwardSearched == Self
{
ReversedSplitCollection(base: self, searcher: separator)
}
}
// MARK: Predicate algorithms
extension Collection {
// TODO: Non-escaping and throwing
func split(
whereSeparator predicate: @escaping (Element) -> Bool,
maxSplits: Int,
omittingEmptySubsequences: Bool
) -> SplitCollection<PredicateConsumer<Self>> {
split(by: PredicateConsumer(predicate: predicate), maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences)
}
}
extension BidirectionalCollection where Element: Equatable {
func splitFromBack(
whereSeparator predicate: @escaping (Element) -> Bool
) -> ReversedSplitCollection<PredicateConsumer<Self>> {
splitFromBack(by: PredicateConsumer(predicate: predicate))
}
}
// MARK: Single element algorithms
extension Collection where Element: Equatable {
func split(
by separator: Element,
maxSplits: Int,
omittingEmptySubsequences: Bool
) -> SplitCollection<PredicateConsumer<Self>> {
split(whereSeparator: { $0 == separator }, maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences)
}
}
extension BidirectionalCollection where Element: Equatable {
func splitFromBack(
by separator: Element
) -> ReversedSplitCollection<PredicateConsumer<Self>> {
splitFromBack(whereSeparator: { $0 == separator })
}
}
// MARK: Fixed pattern algorithms
extension Collection where Element: Equatable {
@_disfavoredOverload
func split<C: Collection>(
by separator: C,
maxSplits: Int,
omittingEmptySubsequences: Bool
) -> SplitCollection<ZSearcher<Self>> where C.Element == Element {
split(by: ZSearcher(pattern: Array(separator), by: ==), maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences)
}
// FIXME: Return `some Collection<SubSequence>` for SE-0346
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given separator.
///
/// - Parameter separator: The element to be split upon.
/// - Returns: A collection of subsequences, split from this collection's
/// elements.
@_disfavoredOverload
@available(SwiftStdlib 5.7, *)
public func split<C: Collection>(
separator: C,
maxSplits: Int = .max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] where C.Element == Element {
Array(split(
by: ZSearcher(pattern: Array(separator), by: ==),
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences))
}
}
extension BidirectionalCollection where Element: Equatable {
// FIXME
// public func splitFromBack<S: Sequence>(
// separator: S
// ) -> ReversedSplitCollection<ZSearcher<SubSequence>>
// where S.Element == Element
// {
// splitFromBack(separator: ZSearcher(pattern: Array(separator), by: ==))
// }
}
extension BidirectionalCollection where Element: Comparable {
func split<C: Collection>(
by separator: C,
maxSplits: Int,
omittingEmptySubsequences: Bool
) -> SplitCollection<PatternOrEmpty<TwoWaySearcher<Self>>>
where C.Element == Element
{
split(
by: PatternOrEmpty(searcher: TwoWaySearcher(pattern: Array(separator))),
maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences)
}
// FIXME
// public func splitFromBack<S: Sequence>(
// separator: S
// ) -> ReversedSplitCollection<PatternOrEmpty<TwoWaySearcher<SubSequence>>>
// where S.Element == Element
// {
// splitFromBack(separator: PatternOrEmpty(
// searcher: TwoWaySearcher(pattern: Array(separator))))
// }
}
// String split overload breakers
//
// These are underscored and marked as SPI so that the *actual* public overloads
// are only visible in RegexBuilder, to avoid breaking source with the
// standard library's function of the same name that takes a `Character`
// as the separator. *Those* overloads are necessary as tie-breakers between
// the Collection-based and Regex-based `split`s, which in turn are both marked
// @_disfavoredOverload to avoid the wrong overload being selected when a
// collection's element type could be used interchangably with a collection of
// that element (e.g. `Array<OptionSet>.split(separator: [])`).
extension StringProtocol where SubSequence == Substring {
@_spi(RegexBuilder)
@available(SwiftStdlib 5.7, *)
public func _split(
separator: String,
maxSplits: Int = .max,
omittingEmptySubsequences: Bool = true
) -> [Substring] {
Array(split(
by: ZSearcher(pattern: Array(separator), by: ==),
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences))
}
@_spi(RegexBuilder)
@available(SwiftStdlib 5.7, *)
public func _split(
separator: Substring,
maxSplits: Int = .max,
omittingEmptySubsequences: Bool = true
) -> [Substring] {
Array(split(
by: ZSearcher(pattern: Array(separator), by: ==),
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences))
}
}
// MARK: Regex algorithms
@available(SwiftStdlib 5.7, *)
extension BidirectionalCollection where SubSequence == Substring {
@_disfavoredOverload
func split<R: RegexComponent>(
by separator: R,
maxSplits: Int,
omittingEmptySubsequences: Bool
) -> SplitCollection<RegexConsumer<R, Self>> {
split(by: RegexConsumer(separator), maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences)
}
func splitFromBack<R: RegexComponent>(
by separator: R
) -> ReversedSplitCollection<RegexConsumer<R, Self>> {
splitFromBack(by: RegexConsumer(separator))
}
// TODO: Is this @_disfavoredOverload necessary?
// It prevents split(separator: String) from choosing this overload instead
// of the collection-based version when String has RegexComponent conformance
// FIXME: Return `some Collection<Subsequence>` for SE-0346
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given separator.
///
/// - Parameter separator: A regex describing elements to be split upon.
/// - Returns: A collection of substrings, split from this collection's
/// elements.
@_disfavoredOverload
public func split(
separator: some RegexComponent,
maxSplits: Int = .max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] {
Array(split(
by: RegexConsumer(separator),
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences))
}
}
|
apache-2.0
|
d5f7c507fce7884ef0e4723a65a3988e
| 28.788155 | 135 | 0.67592 | 4.46314 | false | false | false | false |
balitm/Sherpany
|
Sherpany/URLRouter.swift
|
1
|
1701
|
//
// URLRouter.swift
// Sherpany
//
// Created by Balázs Kilvády on 4/20/16.
// Copyright © 2016 kil-dev. All rights reserved.
//
import Foundation
enum URLRouter {
static var kBaseURL: NSURL! = nil
static var kURLs: DataURLs! = nil
// values
case Users
case Albums
case Photos
static func setup(urls: DataURLs) {
URLRouter.kURLs = urls
guard let url = NSURL(string: urls.kBaseURL) else {
return
}
URLRouter.kBaseURL = url
}
// endpoint method
var method: String {
return "GET"
}
// endpoint path
var path : String {
switch self {
case .Users:
return URLRouter.kURLs.kUsersPath
case .Albums:
return URLRouter.kURLs.kAlbumsPath
case .Photos:
return URLRouter.kURLs.kPhotosPath
}
}
// endpoint parameters
var parameters: [String : AnyObject]? {
return nil
}
var url: NSURL {
switch self {
case .Users:
return NSURL(string: URLRouter.kURLs.kUsersPath, relativeToURL: URLRouter.kBaseURL)!
case .Albums:
return NSURL(string: URLRouter.kURLs.kAlbumsPath, relativeToURL: URLRouter.kBaseURL)!
case .Photos:
return NSURL(string: URLRouter.kURLs.kPhotosPath, relativeToURL: URLRouter.kBaseURL)!
}
}
// URL generation routine
var URLRequest: NSMutableURLRequest {
let urlValue = URLRouter.kBaseURL.URLByAppendingPathComponent(self.path)
let mutableURLRequest = NSMutableURLRequest(URL: urlValue)
mutableURLRequest.HTTPMethod = method
return mutableURLRequest
}
}
|
mit
|
4f0a291cc881067823eda6a414591dcc
| 23.970588 | 97 | 0.61543 | 4.298734 | false | false | false | false |
wrengels/Amplify4
|
Amplify4/Amplify4/AmplifyHelpController.swift
|
1
|
3213
|
//
// AmplifyHelpController.swift
// Amplify4
//
// Created by Bill Engels on 2/19/15.
// Copyright (c) 2015 Bill Engels. All rights reserved.
//
import Cocoa
class AmplifyHelpController: NSWindowController, NSWindowDelegate {
@IBOutlet var helpTextView: NSTextView!
@IBOutlet var helpWindow: NSWindow!
@IBOutlet weak var topicsMenu: NSPopUpButton!
@IBOutlet weak var faqMenu: NSPopUpButton!
override func windowDidLoad() {
super.windowDidLoad()
if let helpPath = NSBundle.mainBundle().pathForResource("Amplify Help", ofType: "rtfd") {
let didit = helpTextView.readRTFDFromFile(helpPath)
helpWindow.releasedWhenClosed = false
if didit {
let newline = NSCharacterSet(charactersInString: "\r\n")
let bullits = NSCharacterSet(charactersInString: "▪️•◆")
let smallbullit = NSCharacterSet(charactersInString: "•")
let faqset = NSCharacterSet(charactersInString: "▪︎")
let helpLines = (helpTextView.string! as NSString).componentsSeparatedByCharactersInSet(newline) as! [NSString]
for line in helpLines {
if line.rangeOfCharacterFromSet(bullits).location != NSNotFound {
topicsMenu.addItemWithTitle(line as String)
}
if line.rangeOfCharacterFromSet(faqset).location != NSNotFound{
faqMenu.addItemWithTitle(line as String)
}
}
for mitem in (topicsMenu.itemArray as! [NSMenuItem]) {
let mitemTitle = mitem.title as NSString
if mitemTitle.rangeOfCharacterFromSet(smallbullit).location != NSNotFound {
mitem.indentationLevel = 2
}
}
}
}
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
@IBOutlet var helpScroll: NSScroller!
@IBOutlet var helpClip: NSClipView!
func scrollToString(theString : NSString) {
let helpString = helpTextView.string! as NSString
let stringRange : NSRange = helpString.rangeOfString(theString as String)
if stringRange.location == NSNotFound {return}
var effectiveRange = NSRange(location: 0, length: 0)
let stringRect = helpTextView.layoutManager!.lineFragmentRectForGlyphAtIndex(stringRange.location, effectiveRange: &effectiveRange)
helpTextView.setSelectedRange(stringRange)
helpClip.scrollToPoint(stringRect.origin)
// helpScroll.reflectScrolledClipView(helpClip)
}
@IBAction func goToTopic(sender: AnyObject) {
let popup = sender as! NSPopUpButton
if let topic = popup.selectedItem?.title {
let helpString = helpTextView.string! as NSString
let nstopic = topic as NSString
self.scrollToString(nstopic)
}
}
func windowShouldClose(sender: AnyObject) -> Bool {
helpWindow.orderOut(self)
return true
}
}
|
gpl-2.0
|
019402baa5260703f6f52fc6adcab528
| 40.012821 | 139 | 0.623632 | 5.1184 | false | false | false | false |
loanburger/ImocNZ
|
HomeModel.swift
|
1
|
1943
|
//
// HomeModel.swift
// ImocNZ - Retrieves Home Page content from
//
// Created by Loan Burger on 6/11/14.
// Copyright (c) 2014 Loan Burger. All rights reserved.
//
import Foundation
public class HomeModel
{
public var ParagraphOne = "";
public var ParagraphTwo = "";
public var ParagraphThree = "";
public var ParagraphFour = "";
private let siteContent:String = "http://www.imoc.co.nz/MobileApp/HomeContent"
func Get(completionHandler: ((String!) -> Void)?)
{
var url : NSURL! = NSURL(string:siteContent)
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error) as? NSDictionary!
var returnText:String! = ""
if(jsonResult != nil)
{
// Working
let siteContent = jsonResult.objectForKey("SiteContent") as! NSDictionary
self.ParagraphOne = siteContent.objectForKey("HomePageParagraphOne") as! String
self.ParagraphTwo = siteContent.objectForKey("HomePageParagraphTwo") as! String
self.ParagraphThree = siteContent.objectForKey("HomePageParagraphThree") as! String
self.ParagraphFour = siteContent.objectForKey("HomePageParagraphFour") as! String
returnText = self.ParagraphOne + "\n\n" + self.ParagraphTwo + "\n\n" + self.ParagraphThree + "\n\n" + self.ParagraphFour;
}
completionHandler?(returnText);
});
task.resume()
}
}
|
mit
|
6cd417264dcce285620a7435922d16fa
| 39.5 | 137 | 0.644364 | 4.762255 | false | true | false | false |
aventurella/RxKit
|
RxKit/RxPublisherType.swift
|
1
|
1638
|
//
// RxPublisherType.swift
// RxKit
//
// Created by Adam Venturella on 10/11/15.
// Copyright © 2015 Adam Venturella. All rights reserved.
//
import Foundation
import RxSwift
public protocol RxPublisherType{
typealias EventType = RxEvent<Self>
var publisher: PublishSubject<EventType> {get}
}
extension RxPublisherType{
public func initRxPublisher() -> PublishSubject<EventType>{
// we use EventType here as the compiler thinks it's
// using an operator when we initialize something like
// PublishSubject<RxEvent<Self>>()
// Specifically: Non-associative operator is adjacent to
// operator of same precedence
let subject = PublishSubject<EventType>()
return subject
}
public func trigger(type: String){
// the compiler complains about using
// evt: EventType = EventType(type: type, data: nil, sender: self)
// 1) it says it has no accessible initializers
// 2) it says it cannot convert the value of RxEvent<Self> to Self.EventType
let evt: RxEvent<Self> = RxEvent(type: type, data: nil, sender: self)
publisher.on(.Next(evt as! EventType))
}
public func trigger<T>(type: String, data: T){
// the compiler complains about using
// evt: EventType = EventType(type: type, data: nil, sender: self)
// 1) it says it has no accessible initializers
// 2) it says it cannot convert the value of RxEvent<Self> to Self.EventType
let evt: RxEvent<Self> = RxEvent(type: type, data: data, sender: self)
publisher.on(.Next(evt as! EventType))
}
}
|
mit
|
1fd3eb886b01e6d9ba005531dae814e1
| 33.851064 | 84 | 0.659133 | 4.186701 | false | false | false | false |
zhuhaow/NEKit
|
src/Utils/IPMask.swift
|
2
|
1524
|
import Foundation
public enum IPMask {
case IPv4(UInt32), IPv6(UInt128)
func mask(baseIP: IPAddress) -> (IPAddress, IPAddress)? {
switch (self, baseIP.address) {
case (.IPv4(var m), .IPv4(let addr)):
guard m <= 32 else {
return nil
}
if m == 32 {
return (baseIP, baseIP)
}
if m == 0 {
return (IPAddress(ipv4InNetworkOrder: 0), IPAddress(ipv4InNetworkOrder: UInt32.max))
}
m = 32 - m
let base = (addr.s_addr.byteSwapped >> m) << m
let end = base | ~((UInt32.max >> m) << m)
let b = IPAddress(ipv4InNetworkOrder: base.byteSwapped)
let e = IPAddress(ipv4InNetworkOrder: end.byteSwapped)
return (b, e)
case (.IPv6(var m), .IPv6):
guard m <= 128 else {
return nil
}
if m == 128 {
return (baseIP, baseIP)
}
if m == 0 {
return (IPAddress(ipv6InNetworkOrder: 0), IPAddress(ipv6InNetworkOrder: UInt128.max))
}
m = 128 - m
let base = (baseIP.address.asUInt128.byteSwapped >> m) << m
let end = base | ~((UInt128.max >> m) << m)
let b = IPAddress(ipv6InNetworkOrder: base.byteSwapped)
let e = IPAddress(ipv6InNetworkOrder: end.byteSwapped)
return (b, e)
default:
return nil
}
}
}
|
bsd-3-clause
|
04e13d7dad2f995af049ba90a0a5dea3
| 29.48 | 101 | 0.48294 | 4.186813 | false | false | false | false |
ocrickard/Theodolite
|
Example/TheodoliteFeed/TheodoliteFeed/Generic/NetworkImageComponent.swift
|
1
|
2763
|
//
// NetworkImageComponent.swift
// TheodoliteFeed
//
// Created by Oliver Rickard on 11/1/17.
// Copyright © 2017 Oliver Rickard. All rights reserved.
//
import UIKit
import Theodolite
final class NetworkImageComponent: Component, TypedComponent {
typealias PropType = (
URL,
size: CGSize,
insets: UIEdgeInsets,
backgroundColor: UIColor,
contentMode: UIView.ContentMode
)
typealias StateType = UIImage?
func initialState() -> UIImage? {
return nil
}
func scaledImage(image:UIImage, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
defer { UIGraphicsEndImageContext() }
image.draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
return UIGraphicsGetImageFromCurrentImageContext()!
}
func resizedImage(image:UIImage, size:CGSize) -> UIImage {
let aspect = image.size.width / image.size.height
if size.width / aspect <= size.height {
return scaledImage(image:image, size:CGSize(width: size.width, height: size.width / aspect))
} else {
return scaledImage(image:image, size:CGSize(width: size.height * aspect, height: size.height))
}
}
override func render() -> [Component] {
// Don't capture self here
let props = self.props
let state = self.state
return [
NetworkDataComponent(
(props.0,
{ [weak self] (networkState: NetworkDataComponent.State) -> Component? in
var component: Component? = nil
switch networkState {
case .pending:
component = SizeComponent(
(size: SizeRange(props.size),
component: ViewComponent(
ViewConfiguration(
view: UIView.self,
attributes:
ViewOptions(backgroundColor: props.backgroundColor)
.viewAttributes())
))
)
break
case .data(let data):
guard let image = state ?? UIImage(data: data) else {
break
}
let resized = self!.resizedImage(image:image, size:props.size)
if state == nil {
self!.updateState(state: resized)
}
component = ImageComponent(
({ resized },
size: props.size,
options: ViewOptions(
clipsToBounds: true,
contentMode: props.contentMode))
)
break
case .error:
break
}
if let component = component {
return InsetComponent(
(insets: props.insets,
component:component))
}
return nil
})
)
]
}
}
|
mit
|
e10591f8384fdec33061add89837e9ab
| 28.382979 | 100 | 0.571325 | 4.786828 | false | false | false | false |
chenchangqing/travelMapMvvm
|
travelMapMvvm/travelMapMvvm/ViewModels/CommentFormViewModel.swift
|
1
|
1632
|
//
// CommentFormViewModel.swift
// travelMapMvvm
//
// Created by green on 15/9/14.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import ReactiveCocoa
import ReactiveViewModel
class CommentFormViewModel: RVMViewModel {
// MARK: - 提示信息
dynamic var failureMsg : String = "" // 操作失败提示
dynamic var successMsg : String = "" // 操作失败提示
// MARK: - View Model
var moreCommentsViewModel:MoreCommentsViewModel!
// MARK: - DataSource Protocol
private let commentModelDataSourceProtocol = JSONCommentModelDataSource.shareInstance()
// MARK: - Data From UI
dynamic var content : String! // 评论内容
dynamic var rating : NSNumber! // 评分
// MARK: - 新增评论命令
var addCommentCommand: RACCommand!
// MARK: - Init
init(moreCommentsViewModel:MoreCommentsViewModel) {
super.init()
self.moreCommentsViewModel = moreCommentsViewModel
setup()
}
// MARK: - Set Up
private func setup() {
setupCommands()
}
// MARK: - Set Up Commands
private func setupCommands() {
self.addCommentCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in
let level = POILevelEnum.instance(self.rating.integerValue - 1)!
return self.commentModelDataSourceProtocol.addPOIComment(self.content, level: level, poiId: self.moreCommentsViewModel.poiDetailViewModel.poiModel.poiId!).materialize()
})
}
}
|
apache-2.0
|
368100a42916d119d71fc21b8dcea59c
| 23.984127 | 180 | 0.620076 | 4.471591 | false | false | false | false |
quadro5/swift3_L
|
swift_question.playground/Pages/Let41 First Missing Positive.xcplaygroundpage/Contents.swift
|
1
|
747
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
// o(n) + o(n)
class Solution {
func firstMissingPositive(_ nums: [Int]) -> Int {
if nums.isEmpty {
return 1
}
var nums = nums
let len = nums.count
var index: Int = 0
while index < len {
while nums[index] > 0 && nums[index] <= len && nums[index] != nums[nums[index] - 1] {
swap(&nums[index], &nums[nums[index]-1])
}
index += 1
}
index = 0
while index < len {
if index != nums[index] - 1 {
return index + 1
}
index += 1
}
return len + 1
}
}
|
unlicense
|
9c848dc1d4c441d9db28c91546f0cac5
| 21.666667 | 97 | 0.441767 | 3.890625 | false | false | false | false |
coreyauger/Swift-YouTube-Player
|
YouTubePlayer/YouTubePlayer/VideoPlayerView.swift
|
1
|
9799
|
//
// VideoPlayerView.swift
// YouTubePlayer
//
// Created by Giles Van Gruisen on 12/21/14.
// Copyright (c) 2014 Giles Van Gruisen. All rights reserved.
//
import UIKit
public enum YouTubePlayerState: String {
case Unstarted = "-1"
case Ended = "0"
case Playing = "1"
case Paused = "2"
case Buffering = "3"
case Queued = "4"
}
public enum YouTubePlayerEvents: String {
case YouTubeIframeAPIReady = "onYouTubeIframeAPIReady"
case Ready = "onReady"
case StateChange = "onStateChange"
case PlaybackQualityChange = "onPlaybackQualityChange"
}
public enum YouTubePlaybackQuality: String {
case Small = "small"
case Medium = "medium"
case Large = "large"
case HD720 = "hd720"
case HD1080 = "hd1080"
case HighResolution = "highres"
}
public protocol YouTubePlayerDelegate {
func playerReady(_ videoPlayer: YouTubePlayerView)
func playerStateChanged(_ videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState)
func playerQualityChanged(_ videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality)
}
private extension URL {
func queryStringComponents() -> [String: AnyObject] {
var dict = [String: AnyObject]()
// Check for query string
if let query = self.query {
// Loop through pairings (separated by &)
for pair in query.components(separatedBy: "&") {
// Pull key, val from from pair parts (separated by =) and set dict[key] = value
let components = pair.components(separatedBy: "=")
dict[components[0]] = components[1] as AnyObject?
}
}
return dict
}
}
public func videoIDFromYouTubeURL(_ videoURL: URL) -> String? {
return videoURL.queryStringComponents()["v"] as! String?
}
/** Embed and control YouTube videos */
open class YouTubePlayerView: UIView, UIWebViewDelegate {
public typealias YouTubePlayerParameters = [String: AnyObject]
fileprivate var webView: UIWebView!
/** The readiness of the player */
fileprivate(set) open var ready = false
/** The current state of the video player */
fileprivate(set) open var playerState = YouTubePlayerState.Unstarted
/** The current playback quality of the video player */
fileprivate(set) open var playbackQuality = YouTubePlaybackQuality.Small
/** Used to configure the player */
open var playerVars = YouTubePlayerParameters()
/** Used to respond to player events */
open var delegate: YouTubePlayerDelegate?
// MARK: Various methods for initialization
/*
public init() {
super.init()
self.buildWebView(playerParameters())
}
*/
override public init(frame: CGRect) {
super.init(frame: frame)
buildWebView(playerParameters())
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
buildWebView(playerParameters())
}
override open func layoutSubviews() {
super.layoutSubviews()
// Remove web view in case it's within view hierarchy, reset frame, add as subview
webView.removeFromSuperview()
webView.frame = bounds
addSubview(webView)
}
// MARK: Web view initialization
fileprivate func buildWebView(_ parameters: [String: AnyObject]) {
webView = UIWebView()
webView.allowsInlineMediaPlayback = true
webView.mediaPlaybackRequiresUserAction = false
webView.delegate = self
webView.backgroundColor = UIColor.clear
webView.isOpaque = false
webView.scrollView.bounces = false
webView.scrollView.isScrollEnabled = false
}
// MARK: Load player
open func loadVideoURL(_ videoURL: URL) {
if let videoID = videoIDFromYouTubeURL(videoURL) {
loadVideoID(videoID)
}
}
open func loadVideoID(_ videoID: String) {
var playerParams = playerParameters()
playerParams["videoId"] = videoID as AnyObject?
loadWebViewWithParameters(playerParams)
}
open func loadPlaylistID(_ playlistID: String) {
// No videoId necessary when listType = playlist, list = [playlist Id]
playerVars["listType"] = "playlist" as AnyObject?
playerVars["list"] = playlistID as AnyObject?
loadWebViewWithParameters(playerParameters())
}
// MARK: Player controls
open func play() {
evaluatePlayerCommand("playVideo()")
}
open func pause() {
evaluatePlayerCommand("pauseVideo()")
}
open func stop() {
evaluatePlayerCommand("stopVideo()")
}
open func clear() {
evaluatePlayerCommand("clearVideo()")
}
open func seekTo(_ seconds: Float, seekAhead: Bool) {
evaluatePlayerCommand("seekTo(\(seconds), \(seekAhead))")
}
// MARK: Playlist controls
open func previousVideo() {
evaluatePlayerCommand("previousVideo()")
}
open func nextVideo() {
evaluatePlayerCommand("nextVideo()")
}
fileprivate func evaluatePlayerCommand(_ command: String) {
let fullCommand = "player." + command + ";"
webView.stringByEvaluatingJavaScript(from: fullCommand)
}
// MARK: Player setup
fileprivate func loadWebViewWithParameters(_ parameters: YouTubePlayerParameters) {
// Get HTML from player file in bundle
let rawHTMLString = htmlStringWithFilePath(playerHTMLPath())!
// Get JSON serialized parameters string
let jsonParameters = serializedJSON(parameters as AnyObject)!
// Replace %@ in rawHTMLString with jsonParameters string
let htmlString = rawHTMLString.replacingOccurrences(of: "%@", with: jsonParameters, options: [], range: nil)
// Load HTML in web view
webView.loadHTMLString(htmlString, baseURL: URL(string: "about:blank"))
}
fileprivate func playerHTMLPath() -> String {
return Bundle(for: self.classForCoder).path(forResource: "YTPlayer", ofType: "html")!
}
fileprivate func htmlStringWithFilePath(_ path: String) -> String? {
// Error optional for error handling
var error: NSError?
// Get HTML string from path
let htmlString: NSString?
do {
htmlString = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue)
} catch let error1 as NSError {
error = error1
htmlString = nil
}
// Check for error
if let _ = error {
print("Lookup error: no HTML file found for path, \(path)")
}
return htmlString! as String
}
// MARK: Player parameters and defaults
fileprivate func playerParameters() -> YouTubePlayerParameters {
return [
"height": "100%" as AnyObject,
"width": "100%" as AnyObject,
"events": playerCallbacks() as AnyObject,
"playerVars": playerVars as AnyObject
]
}
fileprivate func playerCallbacks() -> YouTubePlayerParameters {
return [
"onReady": "onReady" as AnyObject,
"onStateChange": "onStateChange" as AnyObject,
"onPlaybackQualityChange": "onPlaybackQualityChange" as AnyObject,
"onError": "onPlayerError" as AnyObject
]
}
fileprivate func serializedJSON(_ object: AnyObject) -> String? {
// Empty error
var error: NSError?
// Serialize json into NSData
let jsonData: Data?
do {
jsonData = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch let error1 as NSError {
error = error1
jsonData = nil
}
// Check for error and return nil
if let _ = error {
print("Error parsing JSON")
return nil
}
// Success, return JSON string
return NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue) as? String
}
// MARK: JS Event Handling
fileprivate func handleJSEvent(_ eventURL: URL) {
// Grab the last component of the queryString as string
let data: String? = eventURL.queryStringComponents()["data"] as? String
if let host = eventURL.host {
if let event = YouTubePlayerEvents(rawValue: host) {
// Check event type and handle accordingly
switch event {
case .YouTubeIframeAPIReady:
ready = true
break
case .Ready:
delegate?.playerReady(self)
break
case .StateChange:
if let newState = YouTubePlayerState(rawValue: data!) {
playerState = newState
delegate?.playerStateChanged(self, playerState: newState)
}
break
case .PlaybackQualityChange:
if let newQuality = YouTubePlaybackQuality(rawValue: data!) {
playbackQuality = newQuality
delegate?.playerQualityChanged(self, playbackQuality: newQuality)
}
break
}
}
}
}
// MARK: UIWebViewDelegate
open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
let url = request.url
// Check if ytplayer event and, if so, pass to handleJSEvent
if url!.scheme == "ytplayer" { handleJSEvent(url!) }
return true
}
}
|
mit
|
f61953e7a4713c4b461eeac791975716
| 28.250746 | 136 | 0.615267 | 5.149238 | false | false | false | false |
zivboy/jetstream-ios
|
Jetstream/PingMessage.swift
|
3
|
2611
|
//
// PingMessage.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public class PingMessage: NetworkMessage {
class var messageType: String {
return "Ping"
}
override var type: String {
return PingMessage.messageType
}
public let ack: UInt
public let resendMissing: Bool
init(index: UInt, ack: UInt, resendMissing: Bool) {
self.ack = ack
self.resendMissing = resendMissing
super.init(index: index)
}
public convenience init(session: Session) {
self.init(index: 0, ack: session.serverIndex, resendMissing: false)
}
public convenience init(session: Session, resendMissing: Bool) {
self.init(index: 0, ack: session.serverIndex, resendMissing: resendMissing)
}
public override func serialize() -> [String: AnyObject] {
var dictionary = super.serialize()
dictionary["ack"] = ack
dictionary["resendMissing"] = resendMissing
return dictionary
}
public class func unserialize(dictionary: [String: AnyObject]) -> NetworkMessage? {
let index = dictionary["index"] as? UInt
let ack = dictionary["ack"] as? UInt
let resendMissing = dictionary["resendMissing"] as? Bool
if index == nil || ack == nil || resendMissing == nil {
return nil
} else {
return PingMessage(index: index!, ack: ack!, resendMissing: resendMissing!)
}
}
}
|
mit
|
42cf4db3a1c78751db9647664f6045c0
| 35.774648 | 87 | 0.675603 | 4.463248 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
Objects/processes/GoDProcess.swift
|
1
|
9931
|
//
// GoDProcess.swift
// GoD Tool
//
// Created by Stars Momodu on 27/09/2021.
//
import Foundation
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#endif
struct VMRegionInfo {
let virtualAddress: UInt
let size: UInt
}
#if canImport(Darwin)
class GoDProcess {
private let process: Process
private var task: mach_port_name_t?
private var baseAddress: vm_address_t?
var pid: Int32 {
return process.processIdentifier
}
var isRunning: Bool {
return process.isRunning
}
private var threads: [thread_act_t] {
guard let task = self.task else {
printg("Couldn't get threads for unloaded process")
return []
}
var threadList: thread_act_array_t?
var threadCount: mach_msg_type_number_t = 0
let kret = task_threads(task, &threadList, &threadCount)
guard kret == KERN_SUCCESS,
let threads = threadList else {
printg("Couldn't load process threads for pid: \(pid). You may need to run the app with root permissions.")
return []
}
var threadArray = [thread_act_t]()
for i in 0 ..< threadCount.int {
threadArray.append(threads[i])
}
return threadArray
}
init(process: Process) {
self.process = process
load()
}
func await() {
process.waitUntilExit()
}
func terminate() {
process.terminate()
}
func pause() {
process.suspend()
}
func resume() {
process.resume()
}
func readVirtualMemory(at offset: UInt, length: UInt, relativeToRegion region: VMRegionInfo? = nil) -> XGMutableData? {
guard let task = self.task, let baseAddress = self.baseAddress else {
if XGSettings.current.verbose {
printg("Couldn't read virtual memory for unloaded process")
}
return nil
}
let relativeToAddress = region?.virtualAddress ?? baseAddress
var pointer: vm_offset_t = 0
var sizeRead: mach_msg_type_number_t = 0
var kret = vm_read(task, relativeToAddress + offset, length, &pointer, &sizeRead)
guard kret == KERN_SUCCESS else {
if XGSettings.current.verbose {
printg("Couldn't read virtual memory for process: \(pid). Length: \(length)")
printg(kret == KERN_INVALID_ADDRESS ? "Invalid Address" : "KRETURN:\(kret)")
}
return nil
}
guard let rawPointer = UnsafeRawPointer.init(bitPattern: pointer) else {
return nil
}
let data = Data(bytes: rawPointer, count: sizeRead.int)
kret = vm_deallocate(mach_task_self_, pointer, vm_size_t(sizeRead))
if kret != KERN_SUCCESS {
printg("Couldn't free virtual memory for process: \(pid). Length: \(length)")
printg(kret == KERN_INVALID_ADDRESS ? "Invalid Address" : "KRETURN:\(kret)")
}
return XGMutableData(data: data)
}
@discardableResult
func writeVirtualMemory(at offset: UInt, data: XGMutableData, relativeToRegion region: VMRegionInfo? = nil) -> Bool {
guard let task = self.task, let baseAddress = self.baseAddress else {
if XGSettings.current.verbose {
printg("Couldn't write virtual memory for unloaded process")
}
return false
}
let relativeToAddress = region?.virtualAddress ?? baseAddress
var rawBytes = data.rawBytes
let count = rawBytes.count
let buffer = UnsafeMutableRawPointer.allocate(byteCount: data.length, alignment: 4)
memcpy(buffer, &rawBytes, count)
let pointer: vm_offset_t = UInt(bitPattern: buffer)
let kret = vm_write(task, relativeToAddress + offset, pointer, count.unsigned)
if kret != KERN_SUCCESS {
if XGSettings.current.verbose {
printg("Couldn't write virtual memory for process: \(pid).", kret)
if kret == KERN_INVALID_ADDRESS {
print("Invalid Address")
}
}
}
buffer.deallocate()
return kret == KERN_SUCCESS
}
func getNextRegion(fromOffset offset: UInt) -> VMRegionInfo? {
guard let task = self.task else {
printg("Couldn't scan virtual memory for unloaded process")
return nil
}
let VM_REGION_BASIC_INFO_COUNT_64 = MemoryLayout<vm_region_basic_info_data_64_t>.size/4
var info: [Int32] = [Int32](repeating: 0, count: VM_REGION_BASIC_INFO_COUNT_64)
var size: mach_vm_size_t = 0
var object_name: mach_port_t = 0
var count: mach_msg_type_number_t = VM_REGION_BASIC_INFO_COUNT_64.unsigned
var address: mach_vm_address_t = mach_vm_address_t(offset)
let kret = mach_vm_region(task, &address, &size, VM_REGION_BASIC_INFO, &info, &count, &object_name)
guard kret == KERN_SUCCESS else {
if XGSettings.current.verbose {
printg("Couldn't load base address for task: \(task).")
printg("Error no:", kret)
}
return nil
}
return VMRegionInfo(virtualAddress: vm_address_t(address), size: UInt(size))
}
func getRegions(maxOffset: UInt) -> [VMRegionInfo] {
var regions = [VMRegionInfo]()
var totalSize: UInt = 0
var lastRegion: VMRegionInfo?
repeat {
var searchFromAddres: UInt = 0
if let region = lastRegion {
searchFromAddres = region.virtualAddress + region.size
}
lastRegion = getNextRegion(fromOffset: searchFromAddres)
if let region = lastRegion {
regions.append(region)
totalSize += region.size
}
} while lastRegion != nil && totalSize < maxOffset
return regions
}
private func load() {
// You may need to run the app with root permissions
var task: mach_port_name_t = 0
let kret = task_for_pid(mach_task_self_, pid, &task)
guard kret == KERN_SUCCESS else {
printg("Couldn't load process for pid: \(pid). You may need to run the app with root permissions.")
printg("K Return:", kret)
return
}
self.task = task
guard let baseAddress = GoDProcess.getBaseAddress(forTask: task) else {
return
}
self.baseAddress = baseAddress
}
private static func getBaseAddress(forTask task: mach_port_t) -> vm_address_t? {
let VM_REGION_BASIC_INFO_COUNT_64 = MemoryLayout<vm_region_basic_info_data_64_t>.size/4
var info: [Int32] = [Int32](repeating: 0, count: VM_REGION_BASIC_INFO_COUNT_64)
var size: mach_vm_size_t = 0
var object_name: mach_port_t = 0
var count: mach_msg_type_number_t = VM_REGION_BASIC_INFO_COUNT_64.unsigned
var address: mach_vm_address_t = 1
let kret = mach_vm_region(task, &address, &size, VM_REGION_BASIC_INFO, &info, &count, &object_name);
guard kret == KERN_SUCCESS else {
printg("Couldn't load base address for task: \(task). Make sure the application is running and the tool is running with root permissions.")
return nil
}
return UInt(address)
}
}
#elseif canImport(Glibc) && os(Linux)
class GoDProcess {
private let process: Process
private let fileDescriptor: Int32
var pid: Int32 {
return process.processIdentifier
}
var isRunning: Bool {
return process.isRunning
}
init(process: Process) {
self.process = process
self.fileDescriptor = open("/proc/\(process.processIdentifier)/mem", O_RDWR)
}
func await() {
process.waitUntilExit()
close(self.fileDescriptor)
}
func terminate() {
process.terminate()
close(self.fileDescriptor)
}
func pause() {
process.suspend()
}
func resume() {
process.resume()
}
func readVirtualMemory(at offset: UInt, length: UInt, relativeToRegion region: VMRegionInfo? = nil) -> XGMutableData? {
var address = offset
if let regionInfo = region {
address += regionInfo.virtualAddress
}
var buffer = [UInt8](repeating: 0, count: Int(length))
let bytesRead = pread(self.fileDescriptor, &buffer, Int(length), Int(address))
let data = XGMutableData(byteStream: buffer)
return data
}
@discardableResult
func writeVirtualMemory(at offset: UInt, data: XGMutableData, relativeToRegion region: VMRegionInfo? = nil) -> Bool {
var address = offset
if let regionInfo = region {
address += regionInfo.virtualAddress
}
var bytes = data.rawBytes
let bytesWritten = pwrite(self.fileDescriptor, &bytes, Int(data.length), Int(address))
return bytesWritten != -1
}
func getNextRegion(fromOffset offset: UInt) -> VMRegionInfo? {
let processFile = XGFiles.path("/proc/\(pid)/maps")
if processFile.exists {
let text = processFile.text
let lines = text.split(separator: "\n")
for line in lines {
let parts = line.split(separator: " ")
if parts.count > 0 {
let addressRange = parts[0]
let addressParts = addressRange.split(separator: "-")
if addressParts.count > 1 {
let startAddress = String(addressParts[0]).hexStringToUInt()
let endAddress = String(addressParts[1]).hexStringToUInt()
if offset <= startAddress {
let length = endAddress - startAddress
return VMRegionInfo(virtualAddress: startAddress, size: length)
}
}
}
}
} else {
print("file doesn't exist:", processFile.path)
}
return nil
}
func getRegions(maxOffset: UInt) -> [VMRegionInfo] {
var regions = [VMRegionInfo]()
var totalSize: UInt = 0
var lastRegion: VMRegionInfo?
repeat {
var searchFromAddres: UInt = 0
if let region = lastRegion {
searchFromAddres = region.virtualAddress + region.size
}
lastRegion = getNextRegion(fromOffset: searchFromAddres)
if let region = lastRegion {
regions.append(region)
totalSize += region.size
}
} while lastRegion != nil && totalSize < maxOffset
return regions
}
}
#else
class GoDProcess {
private let process: Process
var pid: Int32 {
return process.processIdentifier
}
var isRunning: Bool {
return process.isRunning
}
init(process: Process) {
self.process = process
}
func await() {
process.waitUntilExit()
}
func terminate() {
process.terminate()
}
func pause() {
process.suspend()
}
func resume() {
process.resume()
}
func readVirtualMemory(at offset: UInt, length: UInt, relativeToRegion region: VMRegionInfo? = nil) -> XGMutableData? {
return nil
}
@discardableResult
func writeVirtualMemory(at offset: UInt, data: XGMutableData, relativeToRegion region: VMRegionInfo? = nil) -> Bool {
return false
}
func getNextRegion(fromOffset offset: UInt) -> VMRegionInfo? {
return nil
}
func getRegions(maxOffset: UInt) -> [VMRegionInfo] {
return []
}
}
#endif
|
gpl-2.0
|
226b6ab24c36e242eed0c90f3165a95c
| 25.342175 | 142 | 0.692982 | 3.279723 | false | false | false | false |
ljcoder2015/LJTool
|
LJToolDemo/LJToolDemo/LJTool+ImageViewController.swift
|
1
|
2094
|
//
// LJTool+ImageViewController.swift
// LJToolDemo
//
// Created by ljcoder on 2017/7/13.
// Copyright © 2017年 ljcoder. All rights reserved.
//
import UIKit
import LJTool
class LJTool_ImageViewController: UIViewController {
fileprivate lazy var QRLabel: UILabel = {
let label = UILabel.lj.label()
label.text = "create a QR image"
return label
}()
fileprivate lazy var QRImageView: UIImageView = {
let imageView = UIImageView.lj.imageView()
return imageView
}()
fileprivate lazy var colorLabel: UILabel = {
let label = UILabel.lj.label()
label.text = "create a color image"
return label
}()
fileprivate lazy var colorImageView: UIImageView = {
let imageView = UIImageView.lj.imageView()
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
QRLabel.frame = CGRect(x: 10, y: 100, width: 300, height: 30)
QRImageView.frame = CGRect(x: 10, y: 150, width: 100, height: 100)
colorLabel.frame = CGRect(x: 10, y: 270, width: 300, height: 30)
colorImageView.frame = CGRect(x: 10, y: 320, width: 100, height: 100)
view.addSubview(QRLabel)
view.addSubview(QRImageView)
view.addSubview(colorLabel)
view.addSubview(colorImageView)
QRImageView.image = UIImage.lj.QRImage("test")
colorImageView.image = UIImage.lj.image(with: UIColor.red)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
0bdb8500fe9c8fc05a88f9ed7417f697
| 28.041667 | 106 | 0.630799 | 4.430085 | false | false | false | false |
VirgilSecurity/virgil-sdk-pfs-x
|
Source/Client/Models/Responses/CredentialsResponse.swift
|
1
|
1623
|
//
// CredentialsResponse.swift
// VirgilSDKPFS
//
// Created by Oleksandr Deundiak on 6/13/17.
// Copyright © 2017 VirgilSecurity. All rights reserved.
//
import Foundation
final class CredentialsResponse: NSObject, Deserializable {
let ltc: [AnyHashable: Any]
let otc: [AnyHashable: Any]?
fileprivate init(ltc: [AnyHashable: Any], otc: [AnyHashable: Any]?) {
self.ltc = ltc
self.otc = otc
}
required convenience init?(dictionary: Any) {
guard let dictionary = dictionary as? [String: Any] else {
return nil
}
guard let ltc = dictionary["long_time_card"] as? [AnyHashable: Any] else {
return nil
}
self.init(ltc: ltc, otc: dictionary["one_time_card"] as? [AnyHashable: Any])
}
}
final class CredentialsCollectionResponse: NSObject, Deserializable {
let credentials: [CredentialsResponse]
fileprivate init(credentials: [CredentialsResponse]) {
self.credentials = credentials
}
required convenience init?(dictionary: Any) {
guard let dictionary = dictionary as? [[AnyHashable: Any]] else {
return nil
}
var credentialsArr: [CredentialsResponse] = []
credentialsArr.reserveCapacity(dictionary.count)
for dict in dictionary {
guard let credentials = CredentialsResponse(dictionary: dict) else {
return nil
}
credentialsArr.append(credentials)
}
self.init(credentials: credentialsArr)
}
}
|
bsd-3-clause
|
66b0c57996097dd7e54e41a2b0061cd6
| 26.965517 | 84 | 0.603576 | 4.621083 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/UI/ViewConstants.swift
|
1
|
2025
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Dialogs_ColorThemer
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
/// Shared view constants for Science Journal.
struct ViewConstants {
/// The height to use for Science Journal toolbars.
/// MDCFlexibleHeaderView's height (76) minus statusBar height (20).
static let toolbarHeight: CGFloat = 56
/// The height of the MDCFlexibleHeaderView's.
static let headerHeight: CGFloat = 76
/// The width of the drawer on iPad.
static let iPadDrawerSidebarWidth: CGFloat = 375
/// The total (half left, half right) horizontal inset for collection view cells in regular
/// display type.
static let cellHorizontalInsetRegularDisplayType: CGFloat = 200
/// The total (half left, half right) horizontal inset for collection view cells in regular
/// display type.
static let cellHorizontalInsetRegularWideDisplayType: CGFloat = 300
// MARK: - Color schemes
/// The color scheme for alerts.
static let alertColorScheme = MDCBasicColorScheme(primaryColor: .black)
/// The color scheme for feature highlights.
static var featureHighlightColorScheme: MDCSemanticColorScheme {
let scheme = MDCSemanticColorScheme()
scheme.primaryColor = MDCPalette.blue.tint500
scheme.backgroundColor = .appBarDefaultBackgroundColor
return scheme
}
}
|
apache-2.0
|
5a6984544a409f7ea453ddd335a3df39
| 35.160714 | 93 | 0.75358 | 4.5 | false | false | false | false |
Nocookieleft/Jump-r-Drop
|
Tower/Tower/Platform.swift
|
1
|
1651
|
//
// Platform.swift
// Tower
//
// Created by Evil Cookie on 05/06/15.
// Copyright (c) 2015 Evil Cookie. All rights reserved.
//
import Foundation
import SpriteKit
class Platform: SKSpriteNode {
var isMoving = false
init(size: CGSize) {
// render the platforms by sprite from the image assets
let platformTexture = SKTexture(imageNamed: "floor")
super.init(texture: platformTexture, color: nil, size: size)
self.name = "platform"
// use physicsbody to simulate gravity, should not happen for platforms
// self.physicsBody = SKPhysicsBody(edgeLoopFromRect: CGRect(x: 0, y: 0, width: size.width, height: size.height))
self.physicsBody = SKPhysicsBody(rectangleOfSize: size)
self.physicsBody?.categoryBitMask = platformCategory
self.physicsBody?.contactTestBitMask = playerCategory | rockBottomCategory
self.physicsBody?.collisionBitMask = platformCategory
self.physicsBody?.affectedByGravity = false
self.physicsBody?.dynamic = false
}
// start moving platform down the screen
func startMoving(){
let moveDown = SKAction.moveByX(0, y: -kDefaultSpeed , duration: 1.0)
runAction(SKAction.repeatActionForever(moveDown))
isMoving = true
}
// stop platform from moving
func stopMoving(){
if self.hasActions()
{
self.removeAllActions()
isMoving = false
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
a6bac242847c07e387180d47526e7a62
| 25.629032 | 120 | 0.631738 | 4.813411 | false | false | false | false |
johnno1962d/swift
|
stdlib/public/SDK/ObjectiveC/ObjectiveC.swift
|
1
|
7513
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported
import ObjectiveC
//===----------------------------------------------------------------------===//
// Objective-C Primitive Types
//===----------------------------------------------------------------------===//
public typealias Boolean = Swift.Boolean
/// The Objective-C BOOL type.
///
/// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++
/// bool. Elsewhere, it is "signed char". The Clang importer imports it as
/// ObjCBool.
@_fixed_layout
public struct ObjCBool : Boolean, BooleanLiteralConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
}
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value : Bool
public init(_ value: Bool) {
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension ObjCBool : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension ObjCBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool {
return ObjCBool(x)
}
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool {
return Bool(x)
}
/// The Objective-C SEL type.
///
/// The Objective-C SEL type is typically an opaque pointer. Swift
/// treats it as a distinct struct type, with operations to
/// convert between C strings and selectors.
///
/// The compiler has special knowledge of this type.
@_fixed_layout
public struct Selector : StringLiteralConvertible {
var ptr : OpaquePointer
/// Create a selector from a string.
public init(_ str : String) {
ptr = str.withCString { sel_registerName($0).ptr }
}
/// Create an instance initialized to `value`.
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
/// Construct a selector from `value`.
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
// FIXME: Fast-path this in the compiler, so we don't end up with
// the sel_registerName call at compile time.
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = sel_registerName(value)
}
}
@warn_unused_result
public func ==(lhs: Selector, rhs: Selector) -> Bool {
return sel_isEqual(lhs, rhs)
}
extension Selector : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return ptr.hashValue
}
}
extension Selector : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
let name = sel_getName(self)
if name == nil {
return "<NULL>"
}
return String(cString: name)
}
}
extension String {
/// Construct the C string representation of an Objective-C selector.
public init(_sel: Selector) {
// FIXME: This misses the ASCII optimization.
self = String(cString: sel_getName(_sel))
}
}
extension Selector : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: String(_sel: self))
}
}
//===----------------------------------------------------------------------===//
// NSZone
//===----------------------------------------------------------------------===//
@_fixed_layout
public struct NSZone {
var pointer : OpaquePointer
}
// Note: NSZone becomes Zone in Swift 3.
typealias Zone = NSZone
//===----------------------------------------------------------------------===//
// FIXME: @autoreleasepool substitute
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("_swift_objc_autoreleasePoolPush")
func __pushAutoreleasePool() -> OpaquePointer
@_silgen_name("_swift_objc_autoreleasePoolPop")
func __popAutoreleasePool(_ pool: OpaquePointer)
public func autoreleasepool(_ code: @noescape () -> Void) {
let pool = __pushAutoreleasePool()
code()
__popAutoreleasePool(pool)
}
//===----------------------------------------------------------------------===//
// Mark YES and NO unavailable.
//===----------------------------------------------------------------------===//
@available(*, unavailable, message: "Use 'Bool' value 'true' instead")
public var YES: ObjCBool {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, message: "Use 'Bool' value 'false' instead")
public var NO: ObjCBool {
fatalError("can't retrieve unavailable property")
}
// FIXME: We can't make the fully-generic versions @_transparent due to
// rdar://problem/19418937, so here are some @_transparent overloads
// for ObjCBool
@_transparent
@warn_unused_result
public func && <T : Boolean>(
lhs: T, rhs: @autoclosure () -> ObjCBool
) -> Bool {
return lhs.boolValue ? rhs().boolValue : false
}
@_transparent
@warn_unused_result
public func || <T : Boolean>(
lhs: T, rhs: @autoclosure () -> ObjCBool
) -> Bool {
return lhs.boolValue ? true : rhs().boolValue
}
//===----------------------------------------------------------------------===//
// NSObject
//===----------------------------------------------------------------------===//
// NSObject implements Equatable's == as -[NSObject isEqual:]
// NSObject implements Hashable's hashValue() as -[NSObject hash]
// FIXME: what about NSObjectProtocol?
extension NSObject : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return hash
}
}
@warn_unused_result
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
extension NSObject : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
public var _cVarArgEncoding: [Int] {
_autorelease(self)
return _encodeBitsAsWords(self)
}
}
|
apache-2.0
|
1fece029a3f20a452a778f1789c4f716
| 27.244361 | 80 | 0.598429 | 4.414219 | false | false | false | false |
Antondomashnev/Sourcery
|
SourceryTests/Stub/Performance-Code/Kiosk/Auction Listings/TableCollectionViewCell.swift
|
2
|
3560
|
import UIKit
import RxCocoa
class TableCollectionViewCell: ListingsCollectionViewCell {
fileprivate lazy var infoView: UIView = {
let view = UIView()
view.addSubview(self.lotNumberLabel)
view.addSubview(self.artistNameLabel)
view.addSubview(self.artworkTitleLabel)
self.lotNumberLabel.alignTop("0", bottom: nil, to: view)
self.lotNumberLabel.alignLeading("0", trailing: "0", to: view)
self.artistNameLabel.alignAttribute(.top, to: .bottom, of: self.lotNumberLabel, predicate: "5")
self.artistNameLabel.alignLeading("0", trailing: "0", to: view)
self.artworkTitleLabel.alignLeading("0", trailing: "0", to: view)
self.artworkTitleLabel.alignAttribute(.top, to: .bottom, of: self.artistNameLabel, predicate: "0")
self.artworkTitleLabel.alignTop(nil, bottom: "0", to: view)
return view
}()
fileprivate lazy var cellSubviews: [UIView] = [self.artworkImageView, self.infoView, self.currentBidLabel, self.numberOfBidsLabel, self.bidButton]
override func setup() {
super.setup()
contentView.constrainWidth("\(TableCollectionViewCell.Width)")
// Configure subviews
numberOfBidsLabel.textAlignment = .center
artworkImageView.contentMode = .scaleAspectFill
artworkImageView.clipsToBounds = true
// Add subviews
cellSubviews.forEach { self.contentView.addSubview($0) }
// Constrain subviews
artworkImageView.alignAttribute(.width, to: .height, of: artworkImageView, predicate: nil)
artworkImageView.alignTop("14", leading: "0", bottom: "-14", trailing: nil, to: contentView)
artworkImageView.constrainHeight("56")
infoView.alignAttribute(.left, to: .right, of: artworkImageView, predicate: "28")
infoView.alignCenterY(with: artworkImageView, predicate: "0")
infoView.constrainWidth("300")
currentBidLabel.alignAttribute(.left, to: .right, of: infoView, predicate: "33")
currentBidLabel.alignCenterY(with: artworkImageView, predicate: "0")
currentBidLabel.constrainWidth("180")
numberOfBidsLabel.alignAttribute(.left, to: .right, of: currentBidLabel, predicate: "33")
numberOfBidsLabel.alignCenterY(with: artworkImageView, predicate: "0")
numberOfBidsLabel.alignAttribute(.right, to: .left, of: bidButton, predicate: "-33")
bidButton.alignBottom(nil, trailing: "0", to: contentView)
bidButton.alignCenterY(with: artworkImageView, predicate: "0")
bidButton.constrainWidth("127")
// Replaces the observable defined in the superclass, normally used to emit taps to a "More Info" label, which we don't have.
let recognizer = UITapGestureRecognizer()
contentView.addGestureRecognizer(recognizer)
self.moreInfo = recognizer.rx.event.map { _ -> Date in
return Date()
}
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.drawBottomSolidBorder(with: .artsyGrayMedium())
}
}
extension TableCollectionViewCell {
fileprivate struct SharedDimensions {
var width: CGFloat = 0
var height: CGFloat = 84
static var instance = SharedDimensions()
}
class var Width: CGFloat {
get {
return SharedDimensions.instance.width
}
set (newWidth) {
SharedDimensions.instance.width = newWidth
}
}
class var Height: CGFloat {
return SharedDimensions.instance.height
}
}
|
mit
|
2f8a61b56881530228fcb9efa868d225
| 38.120879 | 150 | 0.674157 | 4.870041 | false | false | false | false |
haawa799/WaniKit2
|
Sources/WaniKit/WaniKit operations/StudyQueue/ParseStudyQueueOperation.swift
|
2
|
1010
|
//
// ParseStudyQueue.swift
// Pods
//
// Created by Andriy K. on 12/10/15.
//
//
import Foundation
public typealias StudyQueueResponse = (userInfo: UserInfo?, studyQInfo: StudyQueueInfo?)
public typealias StudyQueueRecieveBlock = (Result<StudyQueueResponse, NSError>) -> Void
public class ParseStudyQueueOperation: ParseOperation<StudyQueueResponse> {
override init(cacheFile: NSURL, handler: ResponseHandler) {
super.init(cacheFile: cacheFile, handler: handler)
name = "Parse LevelProgression"
}
override func parsedValue(rootDictionary: NSDictionary?) -> StudyQueueResponse? {
var user: UserInfo?
var studyQ: StudyQueueInfo?
if let userInfo = rootDictionary?[WaniKitConstants.ResponseKeys.UserInfoKey] as? NSDictionary {
user = UserInfo(dict: userInfo)
}
if let studyQInfo = rootDictionary?[WaniKitConstants.ResponseKeys.RequestedInfoKey] as? NSDictionary {
studyQ = StudyQueueInfo(dict: studyQInfo)
}
return (user, studyQ)
}
}
|
mit
|
e597b9e006ac0a76e5f3648b1c69ac46
| 27.857143 | 106 | 0.728713 | 4.04 | false | false | false | false |
esheppard/travel-lingo
|
xcode/Travel Lingo/Source/Features/Phrases/Models/Iso639LanguageMapping.swift
|
1
|
754
|
//
// Iso639LanguageMapping.swift
// Travel Lingo
//
// Created by Elijah Sheppard on 20/04/2016.
// Copyright © 2016 Elijah Sheppard. All rights reserved.
//
import Foundation
class Iso639LanguageMapping
{
let language: String
let iso6391Code: String?
let iso6393Code: String?
let name: String?
init(language: String, iso6391Code: String)
{
self.name = nil
self.language = language
self.iso6391Code = iso6391Code
self.iso6393Code = nil
}
init(language: String, iso6393Code: String, name: String)
{
self.name = name
self.language = language
self.iso6391Code = nil
self.iso6393Code = iso6393Code
}
}
|
gpl-3.0
|
96f66bc57d8d10035498293811b5f169
| 18.307692 | 61 | 0.606906 | 3.70936 | false | false | false | false |
danielsanfr/hackatruck-apps-project
|
HACKATRUCK Apps/AppDetailViewController.swift
|
1
|
2382
|
//
// AppDetailViewController.swift
// HACKATRUCK Apps
//
// Created by Student on 3/7/17.
// Copyright © 2017 Daniel San. All rights reserved.
//
import UIKit
import ISScrollViewPageSwift
class AppDetailViewController: UIViewController, ISScrollViewPageDelegate {
var app = App()
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var company: UILabel!
@IBOutlet weak var likes: UILabel!
@IBOutlet weak var tabs: UISegmentedControl!
@IBOutlet weak var scrollViewPage: ISScrollViewPage!
override func viewDidLoad() {
super.viewDidLoad()
name.text = app.name
company.text = app.company
likes.text = "\(app.likes) Likes"
scrollViewPage.scrollViewPageDelegate = self;
scrollViewPage.setEnableBounces(false)
scrollViewPage.setPaging(false)
scrollViewPage.scrollViewPageType = ISScrollViewPageType.horizontally
if let detailView = Bundle.main.loadNibNamed("AppDetailView", owner: self, options: nil)?.first as? AppDetailView {
if let relatedsView = Bundle.main.loadNibNamed("View1", owner: self, options: nil)?.first as? UIView {
detailView.bind(app)
scrollViewPage.setCustomViews([detailView, relatedsView])
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scrollViewPageDidChanged(_ scrollViewPage: ISScrollViewPage, index: Int) {
print("You are at index: \(index)")
}
@IBAction func onClickOpenInfo() {
let url = URL(string: app.relevantLink)!
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
@IBAction func onTabSelectionChanged() {
scrollViewPage.goToIndex(tabs.selectedSegmentIndex, animated: true)
print("\(tabs.selectedSegmentIndex)")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
unlicense
|
4cc373c2e7fcad693d42d9202c096d00
| 31.175676 | 123 | 0.666947 | 4.849287 | false | false | false | false |
liuweicode/LinkimFoundation
|
Example/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift
|
1
|
1465
|
//
// CTR.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/03/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
// Counter (CTR)
//
struct CTRModeWorker: BlockModeWorker {
typealias Element = Array<UInt8>
let cipherOperation: CipherOperationOnBlock
private let iv: Element
private var counter: UInt = 0
init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock) {
self.iv = iv
self.cipherOperation = cipherOperation
}
mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
let nonce = buildNonce(iv, counter: UInt64(counter))
counter = counter + 1
guard let ciphertext = cipherOperation(block: nonce) else {
return plaintext
}
return xor(plaintext, ciphertext)
}
mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
let nonce = buildNonce(iv, counter: UInt64(counter))
counter = counter + 1
guard let plaintext = cipherOperation(block: nonce) else {
return ciphertext
}
return xor(plaintext, ciphertext)
}
}
private func buildNonce(iv: Array<UInt8>, counter: UInt64) -> Array<UInt8> {
let noncePartLen = AES.blockSize / 2
let noncePrefix = Array(iv[0..<noncePartLen])
let nonceSuffix = Array(iv[noncePartLen..<iv.count])
let c = UInt64.withBytes(nonceSuffix) + counter
return noncePrefix + arrayOfBytes(c)
}
|
mit
|
f64e4fda143bf4181757cd98c6b8279d
| 27.705882 | 76 | 0.655738 | 4.159091 | false | false | false | false |
SweetzpotAS/TCXZpot-Swift
|
TCXZpot-Swift/Version.swift
|
1
|
1654
|
//
// Version.swift
// TCXZpot
//
// Created by Tomás Ruiz López on 19/5/17.
// Copyright 2017 SweetZpot AS
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public struct Version {
fileprivate let versionMajor : Int
fileprivate let versionMinor : Int
fileprivate let buildMajor : Int
fileprivate let buildMinor : Int
public init(versionMajor : Int, versionMinor : Int, buildMajor : Int = 0, buildMinor : Int = 0) {
self.versionMajor = versionMajor
self.versionMinor = versionMinor
self.buildMajor = buildMajor
self.buildMinor = buildMinor
}
}
extension Version : TCXSerializable {
public func serialize(to serializer : Serializer) {
serializer.print(line: "<Version>")
serializer.print(line: "<VersionMajor>\(self.versionMajor)</VersionMajor>")
serializer.print(line: "<VersionMinor>\(self.versionMinor)</VersionMinor>")
serializer.print(line: "<BuildMajor>\(self.buildMajor)</BuildMajor>")
serializer.print(line: "<BuildMinor>\(self.buildMinor)</BuildMinor>")
serializer.print(line: "</Version>")
}
}
|
apache-2.0
|
b05d6c1fdc12584769169455c340389d
| 35.711111 | 101 | 0.699758 | 4.13 | false | false | false | false |
vamsikvk915/fusion
|
Fusion/Fusion/ShowNearbyTheatresViewController.swift
|
2
|
9119
|
//
// ShowNearbyTheatresViewController.swift
// Fusion
//
// Created by Abhishek Jaykrishna Khapare on 8/9/17.
// Copyright © 2017 Mohammad Irteza Khan. All rights reserved.
//
import UIKit
import MapKit
import CoreData
import CoreLocation
class ShowNearbyTheatresViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var tableView: UITableView!
let locationManager = CLLocationManager()
var theatreDetails = [[String:String]]()
var zipCode = ""
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.showsPointsOfInterest = true
mapView.showsScale = true
mapView.showsUserLocation = true
locationManager.delegate = self
guard let userZip = UserDataProvider.getUserZipCode() else{
requestAuthorization()
return
}
zipCode = userZip
fetchTheatreLocations()
}
func fetchTheatreLocations(){
theatreDetails.removeAll()
print(zipCode)
let urlString = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D%27\(zipCode)%27%20and%20query%3D%27movie_theatre%27&format=json&callback="
let modal = MapViewModel()
modal.NetworkCall(urlString: urlString) {
details in
self.theatreDetails = details
if self.theatreDetails.count == 0{
let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed, Try After Sometime!", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
self.present(ac, animated : true)
}
self.showLocations()
self.tableView.reloadData()
}
// // let urlString = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D%2760070%27%20and%20query%3D%27movie_theatre%27&format=json&callback="
// // print(zipCode)
//
// let url = URL(string: urlString)!
// print(zipCode)
// print(url)
//
// do{
// let data = try Data.init(contentsOf: url)
//
// //parsing the data
// let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : Any]
//
// print(json)
// if let query = json["query"] as? [String : Any]{
// print(query)
//
// let results = query["results"] as! [String : Any]
// let result = results["Result"] as! [[String : Any]]
// for theatre in result{
//
// let title = theatre["Title"] as! String
// let address = theatre["Address"] as! String
// let city = theatre["City"] as! String
// let state = theatre["State"] as! String
// let phone = theatre["Phone"] as! String
// print(phone)
// //let phone = "7732172181"
//
// let latitude = theatre["Latitude"] as! String
// let longitude = theatre["Longitude"] as! String
//
// let url = theatre["Url"] as! String
//
// let rating = theatre["Rating"] as! [String: Any]
// let averageRating = rating["AverageRating"] as! String
//
// theatreDetails.append(["Title":title,"Address":address,"City":city,"State":state,"Phone":phone,"Latitude":latitude,"Longitude":longitude,"Url":url,"AverageRating":averageRating])
// }
// }
//
// }catch let error{
// print(error)
// }
//
// showLocations()
// tableView.reloadData()
//
}
func showLocations(){
for i in 0..<theatreDetails.count{
let theatre = theatreDetails[i]
let latitude = theatre["Latitude"]
let longitude = theatre["Longitude"]
let coordinates = CLLocationCoordinate2D.init(latitude: CLLocationDegrees(latitude!)!, longitude: CLLocationDegrees(longitude!)!)
let span = MKCoordinateSpanMake(0.1, 0.1)
let theatreLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(CLLocationDegrees(latitude!)!, CLLocationDegrees(longitude!)!)
let region: MKCoordinateRegion = MKCoordinateRegionMake(theatreLocation, span)
self.mapView.setRegion(region, animated: true)
let annotation = AnnotationDetails(coordinates: coordinates,title: theatre["Title"]!,
address: theatre["Address"]!, city: theatre["City"]!, state: theatre["State"]!, phone: theatre["Phone"]!, url: theatre["Url"]!,averageRating:theatre["AverageRating"]!)
mapView.addAnnotation(annotation)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let theatre = theatreDetails[indexPath.row]
let latitude = theatreDetails[indexPath.row]["Latitude"]
let longitude = theatreDetails[indexPath.row]["Longitude"]
let coordinates = CLLocationCoordinate2D.init(latitude: CLLocationDegrees(latitude!)!, longitude: CLLocationDegrees(longitude!)!)
let span = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(CLLocationDegrees(latitude!)!, CLLocationDegrees(longitude!)!)
let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapView.setRegion(region, animated: true)
let annotation = AnnotationDetails(coordinates: coordinates,title: theatre["Title"]!,
address: theatre["Address"]!, city: theatre["City"]!, state: theatre["State"]!, phone: theatre["Phone"]!, url: theatre["Url"]!,averageRating:theatre["AverageRating"]!)
mapView.addAnnotation(annotation)
mapView.selectAnnotation(annotation, animated: true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation{
return nil
}
let pin = CustomAnnotationView(annotation: annotation, reuseIdentifier: "pin1")
return pin
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
performSegue(withIdentifier: "showTheatreDetailSegue", sender: view)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showTheatreDetailSegue" {
let dest = segue.destination as! TheatreDetails
let view = sender as! CustomAnnotationView
let annotation = view.annotation as! AnnotationDetails
dest.title = annotation.title!
dest.address = annotation.address!
dest.city = annotation.city!
dest.state = annotation.state!
dest.phone = annotation.phone!
dest.url = annotation.url!
dest.averageRating = annotation.averageRating!
}
}
func requestAuthorization()
{
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
@IBAction func currentLocation(_ sender: UIButton) {
requestAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.stopUpdatingLocation()
CLGeocoder().reverseGeocodeLocation(locations.last!, completionHandler: {(placemark, error) -> Void in
if error == nil && placemark!.count > 0{
print(placemark![0].postalCode!)
self.zipCode = placemark![0].postalCode!
self.fetchTheatreLocations()
}
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return theatreDetails.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "theatreTableViewCell", for: indexPath)
let theatre = theatreDetails[indexPath.row]
cell.textLabel?.text = theatre["Title"]
cell.detailTextLabel?.text = theatre["Address"]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
apache-2.0
|
b4f2420dce5c6c8a419359a604dbbe70
| 35.91498 | 214 | 0.592893 | 4.862933 | false | false | false | false |
tjboneman/NSPredicate-MongoDB-Adaptor
|
Tests/MongoDBPredicateAdaptorTests/MongoDBPredicateAdaptorTests.swift
|
1
|
2952
|
import XCTest
@testable import MongoDBPredicateAdaptor
class MongoDBPredicateAdaptorTests: XCTestCase {
func testAndNotOptimized() {
let predicate = NSPredicate(format: "name == %@ AND age > %@", "Victor", NSNumber(value: 18))
let _mongoDBQuery = predicate.mongoDBQuery(optimize: false)
guard let mongoDBQuery = _mongoDBQuery else {
XCTAssertNotNil(_mongoDBQuery)
return
}
XCTAssertEqual(mongoDBQuery.count, 1)
let _and = mongoDBQuery["$and"] as? [[String : Any]]
guard let and = _and else {
XCTAssertNotNil(_and)
return
}
XCTAssertEqual(and.count, 2)
let components = and.compactMap({ $0.first })
XCTAssertEqual(components.filter({ $0.key == "name" }).first?.value as? String, "Victor")
let _age = components.filter({ $0.key == "age" }).first?.value as? [String : Any]
guard let age = _age else {
XCTAssertNotNil(_age)
return
}
XCTAssertEqual(age.count, 1)
XCTAssertEqual(age["$gt"] as? Int, 18)
}
func testAndOptimized() {
let predicate = NSPredicate(format: "name == %@ AND age > %@", "Victor", NSNumber(value: 18))
let _mongoDBQuery = predicate.mongoDBQuery
guard let mongoDBQuery = _mongoDBQuery else {
XCTAssertNotNil(_mongoDBQuery)
return
}
XCTAssertEqual(mongoDBQuery.count, 2)
XCTAssertEqual(mongoDBQuery["name"] as? String, "Victor")
let _age = mongoDBQuery["age"] as? [String : Any]
guard let age = _age else {
XCTAssertNotNil(_age)
return
}
XCTAssertEqual(age.count, 1)
XCTAssertEqual(age["$gt"] as? Int, 18)
}
func testAndCannotOptimize() {
let predicate = NSPredicate(format: "age > %@ AND age < %@", NSNumber(value: 18), NSNumber(value: 21))
let _mongoDBQuery = predicate.mongoDBQuery
guard let mongoDBQuery = _mongoDBQuery else {
XCTAssertNotNil(_mongoDBQuery)
return
}
XCTAssertEqual(mongoDBQuery.count, 1)
let _and = mongoDBQuery["$and"] as? [[String : Any]]
guard let and = _and else {
XCTAssertNotNil(_and)
return
}
XCTAssertEqual(and.count, 2)
let components = and.compactMap({ $0.first })
.filter({ $0.key == "age" })
.compactMap({ $0.value as? [String : Int] })
.compactMap({ $0.first })
let gt = components.filter({ $0.key == "$gt" }).first?.value
let lt = components.filter({ $0.key == "$lt" }).first?.value
XCTAssertEqual(gt, 18)
XCTAssertEqual(lt, 21)
}
static var allTests = [
("testAndNotOptimized", testAndNotOptimized),
("testAndOptimized", testAndOptimized),
("testAndCannotOptimize", testAndCannotOptimize),
]
}
|
apache-2.0
|
c7114bdda4dfe36e459b0e63f4086504
| 35.9 | 110 | 0.574187 | 4.169492 | false | true | false | false |
Ramotion/showroom
|
Showroom/ViewControllers/MenuPopUpViewController/MenuPopUpViewController.swift
|
1
|
5363
|
import UIKit
import SwiftyAttributes
import NSObject_Rx
import RxCocoa
import RxSwift
fileprivate struct C {
static let Copied = NSLocalizedString("COPIED", comment: "COPIED")
}
class MenuPopUpViewController: UIViewController {
var backButtonTap: () -> Void = {}
@IBOutlet weak var menuViewHeight: NSLayoutConstraint!
@IBOutlet weak var infoViewHeight: NSLayoutConstraint!
@IBOutlet weak var infoViewBottom: NSLayoutConstraint!
@IBOutlet weak var copiedLabel: UILabel!
@IBOutlet weak var exitContainer: UIView!
@IBOutlet weak var shareContainer: UIView!
@IBOutlet weak var copyLinkContainer: UIView!
@IBOutlet weak var infoView: UIView!
@IBOutlet weak var menuView: UIView!
var presenter: PopUpPresenter?
var isAutorotate: Bool = false
fileprivate var shareUrlString: String!
}
// MARK: Life Cycle
extension MenuPopUpViewController {
override func viewDidLoad() {
super.viewDidLoad()
copiedLabel.attributedText = C.Copied.withKern(1)
infoViewBottom.constant = -infoViewHeight.constant
infoView.alpha = 0
// let gesture = UITapGestureRecognizer()
// view.addGestureRecognizer(gesture)
// _ = gesture.rx.event.asObservable().subscribe { [weak self] _ in
// self?.dismiss(animated: true, completion: nil)
// }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
containerAnimations()
shareContainer.alpha = 0
copyLinkContainer.alpha = 0
exitContainer.alpha = 0
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
infoView.alpha = 0
}
override open var shouldAutorotate: Bool {
return isAutorotate
}
}
// MARK: Methods
extension MenuPopUpViewController {
@discardableResult
class func showPopup(on: UIViewController, url: String, isRotate: Bool = false, backButtonTap: @escaping () -> Void) -> MenuPopUpViewController {
let storybord = UIStoryboard(storyboard: .Navigation)
let vc: MenuPopUpViewController = storybord.instantiateViewController()
vc.isAutorotate = isRotate
on.threeThingersToch.subscribe { [weak on] _ in
guard let on = on else { return }
vc.shareUrlString = url
vc.backButtonTap = backButtonTap
vc.presenter = PopUpPresenter(controller: vc,
on: on,
showTransition: ShowMenuPopUpTransition(duration: 0.2),
hideTransition: HideMenuPopUpTransition(duration: 0.2))
}.disposed(by: on.rx.disposeBag)
return vc
}
}
// MARK: Animations
extension MenuPopUpViewController {
func containerAnimations() {
exitContainer.animate(duration: 0.001, delay: 0, [.alpha(to: 1)], timing: .easyOut)
exitContainer.animate(duration: 0.4,
delay: 0,
[.layerPositionY(from: menuViewHeight.constant + exitContainer.bounds.size.height / 2,
to: menuViewHeight.constant / 2)],
timing: .easyOut)
copyLinkContainer.animate(duration: 0.001, delay: 0.08, [.alpha(to: 1)], timing: .easyOut)
copyLinkContainer.animate(duration: 0.4,
delay: 0.08,
[.layerPositionY(from: menuViewHeight.constant + copyLinkContainer.bounds.size.height / 2,
to: menuViewHeight.constant / 2)],
timing: .easyOut)
shareContainer.animate(duration: 0.001, delay: 0.16, [.alpha(to: 1)], timing: .easyOut)
shareContainer.animate(duration: 0.4,
delay: 0.16,
[.layerPositionY(from: menuViewHeight.constant + shareContainer.bounds.size.height / 2,
to: menuViewHeight.constant / 2)],
timing: .easyOut)
}
func showInfoView() {
if infoView.alpha == 1 { return }
infoView.alpha = 1
let from = Showroom.screen.height - menuViewHeight.constant + infoViewHeight.constant / 2
let to = Showroom.screen.height - menuViewHeight.constant - infoViewHeight.constant / 2
infoView.animate(duration: 0.2, [.layerPositionY(from: from, to: to)], timing: .easyInEasyOut)
infoView.animate(duration: 0.2, delay:1, [.layerPositionY(from: to, to: from)], timing: .easyInEasyOut) { [weak self] in
self?.infoView.alpha = 0
}
}
}
// MARK: Actions
extension MenuPopUpViewController {
@IBAction func copyLinkHandler(_ sender: Any) {
showInfoView()
AppAnalytics.event(.google(name: "Buttons", parametr: "copy link popup: \(shareUrlString ?? "")"))
UIPasteboard.general.string = shareUrlString
}
@IBAction func sharedHandler(_ sender: Any) {
AppAnalytics.event(.google(name: "Buttons", parametr: "shared link popup: \(shareUrlString ?? "")"))
let activity = UIActivityViewController(activityItems: [shareUrlString ?? ""], applicationActivities: nil)
present(activity, animated: true, completion: nil)
}
@IBAction func backHandler(_ sender: Any) {
AppAnalytics.event(.google(name: "Buttons", parametr: "back button popup"))
dismiss(animated: true, completion: nil)
backButtonTap()
}
}
|
gpl-3.0
|
fcbca8fd4039105d9d939d9c0ab72160
| 32.72956 | 148 | 0.642364 | 4.487866 | false | false | false | false |
hollance/swift-algorithm-club
|
3Sum and 4Sum/4Sum.playground/Contents.swift
|
3
|
2178
|
// last checked with Xcode 10.1
#if swift(>=4.2)
print("Hello, Swift 4.2!")
#endif
extension Collection where Element: Equatable {
/// In a sorted collection, replaces the given index with a successor mapping to a unique element.
///
/// - Parameter index: A valid index of the collection. `index` must be less than `endIndex`
func formUniqueIndex(after index: inout Index) {
var prev = index
repeat {
prev = index
formIndex(after: &index)
} while index < endIndex && self[prev] == self[index]
}
}
extension BidirectionalCollection where Element: Equatable {
/// In a sorted collection, replaces the given index with a predecessor that maps to a unique element.
///
/// - Parameter index: A valid index of the collection. `index` must be greater than `startIndex`.
func formUniqueIndex(before index: inout Index) {
var prev = index
repeat {
prev = index
formIndex(before: &index)
} while index > startIndex && self[prev] == self[index]
}
}
func fourSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) -> [[T.Element]] where T.Element: Numeric & Comparable {
let sorted = collection.sorted()
var ret: [[T.Element]] = []
var l = sorted.startIndex
FourSum: while l < sorted.endIndex { defer { sorted.formUniqueIndex(after: &l) }
var ml = sorted.index(after: l)
ThreeSum: while ml < sorted.endIndex { defer { sorted.formUniqueIndex(after: &ml) }
var mr = sorted.index(after: ml)
var r = sorted.index(before: sorted.endIndex)
TwoSum: while mr < r && r < sorted.endIndex {
let sum = sorted[l] + sorted[ml] + sorted[mr] + sorted[r]
if sum == target {
ret.append([sorted[l], sorted[ml], sorted[mr], sorted[r]])
sorted.formUniqueIndex(after: &mr)
sorted.formUniqueIndex(before: &r)
} else if sum < target {
sorted.formUniqueIndex(after: &mr)
} else {
sorted.formUniqueIndex(before: &r)
}
}
}
}
return ret
}
// answer: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
fourSum([1, 0, -1, 0, -2, 2], target: 0)
|
mit
|
6fdece17123cd40562f7037c21f5a94b
| 33.03125 | 133 | 0.614325 | 3.691525 | false | false | false | false |
VernonVan/SmartClass
|
SmartClass/Student/Model/Student.swift
|
1
|
765
|
//
// Student.swift
// SmartClass
//
// Created by Vernon on 16/8/26.
// Copyright © 2016年 Vernon. All rights reserved.
//
import Foundation
import RealmSwift
class Student: Object
{
/// 姓名
dynamic var name = ""
/// 学号
dynamic var number = ""
/// 专业
dynamic var major: String?
/// 学校
dynamic var school: String?
override static func primaryKey() -> String?
{
return "number"
}
override static func indexedProperties() -> [String]
{
return ["number"]
}
}
//extension Student: Equatable {}
func == (lhs: Student, rhs: Student) -> Bool
{
return lhs.name == rhs.name && lhs.number == rhs.number && lhs.major == rhs.major && lhs.school == rhs.school
}
|
mit
|
a764b0fe95ed10456d7819528d3222cb
| 17.65 | 113 | 0.58445 | 3.693069 | false | false | false | false |
BelledonneCommunications/linphone-iphone
|
Classes/Swift/Conference/Views/ConferenceWaitingRoomFragment.swift
|
1
|
10497
|
/*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* 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 UIKit
import linphonesw
@objc class ConferenceWaitingRoomFragment: UIViewController, UICompositeViewDelegate { // Replaces CallView
// Layout constants
let common_margin = 17.0
let switch_camera_button_size = 35
let switch_camera_button_margins = 7.0
let content_inset = 12.0
let button_spacing = 15.0
let center_view_corner_radius = 20.0
let button_width = 150
let layout_picker_inset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
var audioRoutesView : AudioRoutesView? = nil
let subject = StyledLabel(VoipTheme.conference_preview_subject_font)
let localVideo = UIView()
let switchCamera = UIImageView(image: UIImage(named:"voip_change_camera")?.tinted(with:.white))
let noVideoLabel = StyledLabel(VoipTheme.conference_waiting_room_no_video_font, VoipTexts.conference_waiting_room_video_disabled)
let buttonsView = UIStackView()
let cancel = FormButton(title: VoipTexts.cancel.uppercased(), backgroundStateColors: VoipTheme.primary_colors_background_gray, bold:false)
let start = FormButton(title: VoipTexts.conference_waiting_room_start_call.uppercased(), backgroundStateColors: VoipTheme.primary_colors_background)
let conferenceJoinSpinner = RotatingSpinner()
var conferenceUrl : String? = nil
let conferenceSubject = MutableLiveData<String>()
let controlsView = ControlsView(showVideo: true, controlsViewModel: ConferenceWaitingRoomViewModel.sharedModel)
var layoutPicker : CallControlButton? = nil
let layoutPickerView = ConferenceLayoutPickerView(orientation: UIDevice.current.orientation)
static let compositeDescription = UICompositeViewDescription(ConferenceWaitingRoomFragment.self, statusBar: StatusBarView.self, tabBar: nil, sideMenu: SideMenuView.self, fullscreen: false, isLeftFragment: false,fragmentWith: nil)
static func compositeViewDescription() -> UICompositeViewDescription! { return compositeDescription }
func compositeViewDescription() -> UICompositeViewDescription! { return type(of: self).compositeDescription }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = VoipTheme.voipBackgroundColor.get()
view.addSubview(subject)
subject.centerX().alignParentTop(withMargin: common_margin).done()
conferenceSubject.observe { subject in
self.subject.text = subject
}
// Controls
view.addSubview(controlsView)
controlsView.alignParentBottom(withMargin:SharedLayoutConstants.buttons_bottom_margin).centerX().done()
// Layoout picker
layoutPicker = CallControlButton(imageInset : layout_picker_inset,buttonTheme: VoipTheme.conf_waiting_room_layout_picker, onClickAction: {
ConferenceWaitingRoomViewModel.sharedModel.showLayoutPicker.value = ConferenceWaitingRoomViewModel.sharedModel.showLayoutPicker.value != true
})
view.addSubview(layoutPicker!)
layoutPicker!.alignParentBottom(withMargin:SharedLayoutConstants.buttons_bottom_margin).alignParentRight(withMargin:SharedLayoutConstants.buttons_bottom_margin).done()
ConferenceWaitingRoomViewModel.sharedModel.joinLayout.readCurrentAndObserve { layout in
var icon = ""
switch (layout!) {
case .Grid: icon = "voip_conference_mosaic"; break
case .ActiveSpeaker: icon = "voip_conference_active_speaker"; break
case .AudioOnly:
icon = "voip_conference_audio_only"
ConferenceWaitingRoomViewModel.sharedModel.isVideoEnabled.value = false
break
}
self.layoutPicker?.applyTintedIcons(tintedIcons: [UIButton.State.normal.rawValue : TintableIcon(name: icon ,tintColor: LightDarkColor(.white,.white))])
}
ConferenceWaitingRoomViewModel.sharedModel.isVideoEnabled.observe { video in
if (video == true && ConferenceWaitingRoomViewModel.sharedModel.joinLayout.value == .AudioOnly) {
ConferenceWaitingRoomViewModel.sharedModel.joinLayout.value = .ActiveSpeaker
}
}
view.addSubview(layoutPickerView)
ConferenceWaitingRoomViewModel.sharedModel.showLayoutPicker.readCurrentAndObserve { show in
self.layoutPicker?.isSelected = show == true
self.layoutPickerView.isHidden = show != true
if (show == true) {
self.view.bringSubviewToFront(self.layoutPickerView)
}
}
// Form buttons
buttonsView.axis = .horizontal
buttonsView.spacing = button_spacing
view.addSubview(buttonsView)
buttonsView.alignAbove(view: controlsView,withMargin: SharedLayoutConstants.buttons_bottom_margin).centerX().done()
start.width(button_width).done()
cancel.width(button_width).done()
buttonsView.addArrangedSubview(cancel)
buttonsView.addArrangedSubview(start)
cancel.onClick {
Core.get().calls.forEach { call in
if ([Call.State.OutgoingInit, Call.State.OutgoingRinging, Call.State.OutgoingProgress].contains(call.state)) {
CallManager.instance().terminateCall(call: call.getCobject)
}
}
ConferenceWaitingRoomViewModel.sharedModel.joinInProgress.value = false
PhoneMainView.instance().popView(self.compositeViewDescription())
}
start.onClick {
ConferenceWaitingRoomViewModel.sharedModel.joinInProgress.value = true
self.conferenceUrl.map{ CallManager.instance().startCall(addr: $0, isSas: false, isVideo: ConferenceWaitingRoomViewModel.sharedModel.isVideoEnabled.value!, isConference: true) }
}
ConferenceWaitingRoomViewModel.sharedModel.joinInProgress.readCurrentAndObserve { joining in
self.start.isEnabled = joining != true
//self.localVideo.isHidden = joining == true (UX question as video window goes black by the core, better black or hidden ?)
self.noVideoLabel.isHidden = joining == true
self.layoutPicker?.isHidden = joining == true
if (joining == true) {
self.view.addSubview(self.conferenceJoinSpinner)
self.conferenceJoinSpinner.square(IncomingOutgoingCommonView.spinner_size).center().done()
self.conferenceJoinSpinner.startRotation()
self.controlsView.isHidden = true
} else {
self.conferenceJoinSpinner.stopRotation()
self.conferenceJoinSpinner.removeFromSuperview()
self.controlsView.isHidden = false
}
}
// localVideo view
localVideo.layer.cornerRadius = center_view_corner_radius
localVideo.clipsToBounds = true
localVideo.contentMode = .scaleAspectFill
localVideo.backgroundColor = .black
self.view.addSubview(localVideo)
localVideo.addSubview(switchCamera)
switchCamera.contentMode = .scaleAspectFit
switchCamera.onClick {
Core.get().videoPreviewEnabled = false
Core.get().toggleCamera()
Core.get().nativePreviewWindow = self.localVideo
Core.get().videoPreviewEnabled = true
}
self.view.addSubview(noVideoLabel)
noVideoLabel.center().done()
ConferenceWaitingRoomViewModel.sharedModel.isVideoEnabled.readCurrentAndObserve { videoEnabled in
Core.get().videoPreviewEnabled = videoEnabled == true
self.localVideo.isHidden = videoEnabled != true
self.switchCamera.isHidden = videoEnabled != true
self.noVideoLabel.isHidden = videoEnabled == true
}
// Audio Routes
audioRoutesView = AudioRoutesView()
view.addSubview(audioRoutesView!)
audioRoutesView!.alignBottomWith(otherView: controlsView).done()
ConferenceWaitingRoomViewModel.sharedModel.audioRoutesSelected.readCurrentAndObserve { (audioRoutesSelected) in
self.audioRoutesView!.isHidden = audioRoutesSelected != true
}
audioRoutesView!.alignAbove(view:controlsView,withMargin:SharedLayoutConstants.buttons_bottom_margin).centerX().done()
layoutRotatableElements()
}
func layoutRotatableElements() {
layoutPickerView.removeConstraints().done()
localVideo.removeConstraints().done()
switchCamera.removeConstraints().done()
if ([.landscapeLeft, .landscapeRight].contains( UIDevice.current.orientation)) {
layoutPickerView.alignAbove(view:layoutPicker!,withMargin:button_spacing).alignVerticalCenterWith(layoutPicker!).done()
localVideo.matchParentSideBorders().alignParentBottom().alignParentTop().done()
localVideo.layer.cornerRadius = 0
switchCamera.alignParentTop(withMargin: switch_camera_button_margins).alignParentRight(withMargin: switch_camera_button_margins + (UIDevice.hasNotch() && UIDevice.current.orientation == .landscapeRight ? 30.0 : 0.0)).square(switch_camera_button_size).done()
} else {
layoutPickerView.alignAbove(view:layoutPicker!,withMargin:button_spacing).alignVerticalCenterWith(layoutPicker!).done()
localVideo.matchParentSideBorders(insetedByDx: content_inset).alignAbove(view:buttonsView,withMargin:SharedLayoutConstants.buttons_bottom_margin).alignUnder(view: subject,withMargin: common_margin).done()
localVideo.layer.cornerRadius = center_view_corner_radius
switchCamera.alignParentTop(withMargin: switch_camera_button_margins).alignParentRight(withMargin: switch_camera_button_margins).square(switch_camera_button_size).done()
}
view.sendSubviewToBack(localVideo)
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
super.didRotate(from: fromInterfaceOrientation)
self.layoutRotatableElements()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
ConferenceWaitingRoomViewModel.sharedModel.audioRoutesSelected.value = false
ConferenceWaitingRoomViewModel.sharedModel.reset()
Core.get().nativePreviewWindow = localVideo
Core.get().videoPreviewEnabled = ConferenceWaitingRoomViewModel.sharedModel.isVideoEnabled.value == true
}
override func viewWillDisappear(_ animated: Bool) {
ControlsViewModel.shared.fullScreenMode.value = false
Core.get().nativePreviewWindow = nil
Core.get().videoPreviewEnabled = false
ConferenceWaitingRoomViewModel.sharedModel.joinInProgress.value = false
super.viewWillDisappear(animated)
}
@objc func setDetails(subject:String, url:String) {
self.conferenceSubject.value = subject
self.conferenceUrl = url
}
}
|
gpl-3.0
|
81dd5637b9d87c9bddedabcb68f0d31a
| 42.556017 | 260 | 0.782509 | 4.024923 | false | false | false | false |
back2mach/OAuthSwift
|
Sources/Objc.swift
|
5
|
4357
|
//
// Objc.swift
// OAuthSwift
//
// Created by phimage on 05/11/16.
// Copyright © 2016 Dongri Jin. All rights reserved.
//
import Foundation
extension OAuthSwift {
// swiftlint:disable type_name
public typealias Obj_FailureHandler = (_ error: Error) -> Void
}
extension OAuth1Swift {
open func objc_authorize(withCallbackURL urlString: String, success: @escaping TokenSuccessHandler, failure: Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
guard let url = URL(string: urlString) else {
failure?(OAuthSwiftError.encodingError(urlString: urlString))
return nil
}
return authorize(withCallbackURL: url, success: success, failure: failure)
}
}
extension OAuth2Swift {
open func objc_authorize(withCallbackURL urlString: String, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
guard let url = URL(string: urlString) else {
failure?(OAuthSwiftError.encodingError(urlString: urlString))
return nil
}
return authorize(withCallbackURL: url, scope: scope, state: state, parameters: parameters, headers: headers, success: success, failure: failure)
}
open func objc_renewAccessToken(withRefreshToken refreshToken: String, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
return renewAccessToken(withRefreshToken: refreshToken, headers: headers, success: success, failure: failure)
}
}
extension OAuthSwiftHTTPRequest {
// swiftlint:disable type_name
public typealias Obj_FailureHandler = (_ error: Error) -> Void
}
extension OAuthSwiftClient {
open func objc_request(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
return request(urlString, method: method, parameters: parameters, headers: headers, body: body, checkTokenExpiration: checkTokenExpiration, success: success, failure: failure)
}
open func get(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .GET, parameters: parameters, headers: headers, success: success, failure: failure)
}
open func post(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .POST, parameters: parameters, headers: headers, body: body, success: success, failure: failure)
}
open func put(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .PUT, parameters: parameters, headers: headers, body: body, success: success, failure: failure)
}
open func delete(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .DELETE, parameters: parameters, headers: headers, success: success, failure: failure)
}
open func patch(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.Obj_FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .PATCH, parameters: parameters, headers: headers, success: success, failure: failure)
}
}
|
mit
|
9408e2480b910bcfb49d8bf141f2bba1
| 57.08 | 346 | 0.741506 | 4.84 | false | false | false | false |
irisapp/das-quadrat
|
Source/Shared/Parameters.swift
|
1
|
9974
|
//
// Parameters.swift
// Quadrat
//
// Created by Constantine Fry on 12/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
// swiftlint:disable colon
// swiftlint:disable variable_name
// swiftlint:disable variable_name_min_length
import Foundation
public class Parameter {
// MARK: - PUBLIC
// MARK: Ids
public class var categoryId : String { return __FUNCTION__ }
public class var checkinId : String { return __FUNCTION__ }
public class var commentId : String { return __FUNCTION__ }
public class var contentId : String { return __FUNCTION__ }
public class var eventId : String { return __FUNCTION__ }
public class var itemId : String { return __FUNCTION__ }
public class var offerId : String { return __FUNCTION__ }
public class var pageId : String { return __FUNCTION__ }
public class var participantId : String { return __FUNCTION__ }
public class var photoId : String { return __FUNCTION__ }
public class var postContentId : String { return __FUNCTION__ }
public class var primaryCategoryId : String { return __FUNCTION__ }
public class var providerId : String { return __FUNCTION__ }
public class var storeId : String { return __FUNCTION__ }
public class var tipId : String { return __FUNCTION__ }
public class var userId : String { return __FUNCTION__ }
public class var venueId : String { return __FUNCTION__ }
// MARK: - A
public class var addCategoryIds : String { return __FUNCTION__ }
public class var address : String { return __FUNCTION__ }
public class var afterId : String { return __FUNCTION__ }
public class var afterTimestamp : String { return __FUNCTION__ }
public class var alt : String { return __FUNCTION__ }
public class var altAcc : String { return __FUNCTION__ }
// MARK: - B
public class var beforeId : String { return __FUNCTION__ }
public class var beforeTimestamp : String { return __FUNCTION__ }
public class var broadcast : String { return __FUNCTION__ }
// MARK: - C
public class var city : String { return __FUNCTION__ }
public class var collaborative : String { return __FUNCTION__ }
public class var comment : String { return __FUNCTION__ }
public class var cost : String { return __FUNCTION__ }
public class var count1 : String { return __FUNCTION__ }
public class var crossStreet : String { return __FUNCTION__ }
// MARK: - D
public class var day : String { return __FUNCTION__ }
public class var description : String { return __FUNCTION__ }
public class var domain : String { return __FUNCTION__ }
// MARK: - E
public class var email : String { return __FUNCTION__ }
public class var endAt : String { return __FUNCTION__ }
// MARK: - F
public class var facebookUrl : String { return __FUNCTION__ }
public class var fbid : String { return __FUNCTION__ }
public class var fields : String { return __FUNCTION__ }
public class var finePrint : String { return __FUNCTION__ }
public class var friendVisits : String { return __FUNCTION__ }
// MARK: - G
public class var group : String { return __FUNCTION__ }
// MARK: - H
public class var highWatermark : String { return __FUNCTION__ }
public class var hours : String { return __FUNCTION__ }
// MARK: - I
public class var ignoreDuplicates : String { return __FUNCTION__ }
public class var ignoreDuplicatesKey : String { return __FUNCTION__ }
public class var includeFollowing : String { return __FUNCTION__ }
public class var intent : String { return __FUNCTION__ }
// MARK: - L
public class var lastVenue : String { return __FUNCTION__ }
public class var likes : String { return __FUNCTION__ }
public class var limit : String { return __FUNCTION__ }
public class var linkedId : String { return __FUNCTION__ }
public class var ll : String { return __FUNCTION__ }
public class var llAcc : String { return __FUNCTION__ }
public class var llBounds : String { return __FUNCTION__ }
// MARK: - T
public class var mentions : String { return __FUNCTION__ }
public class var menuUrl : String { return __FUNCTION__ }
public class var message : String { return __FUNCTION__ }
// MARK: - S
public class var name : String { return __FUNCTION__ }
public class var ne : String { return __FUNCTION__ }
public class var near : String { return __FUNCTION__ }
public class var novelty : String { return __FUNCTION__ }
// MARK: - O
public class var offset : String { return __FUNCTION__ }
public class var openNow : String { return __FUNCTION__ }
// MARK: - P
public class var phone : String { return __FUNCTION__ }
public class var postText : String { return __FUNCTION__ }
public class var price : String { return __FUNCTION__ }
public class var problem : String { return __FUNCTION__ }
// MARK: - Q
public class var query : String { return __FUNCTION__ }
// MARK: - R
public class var radius : String { return __FUNCTION__ }
public class var removeCategoryIds : String { return __FUNCTION__ }
public class var role : String { return __FUNCTION__ }
// MARK: - S
public class var saved : String { return __FUNCTION__ }
public class var section : String { return __FUNCTION__ }
public class var set : String { return __FUNCTION__ }
public class var shout : String { return __FUNCTION__ }
public class var signature : String { return __FUNCTION__ }
public class var sort : String { return __FUNCTION__ }
public class var sortByDistance : String { return __FUNCTION__ }
public class var specials : String { return __FUNCTION__ }
public class var startAt : String { return __FUNCTION__ }
public class var state : String { return __FUNCTION__ }
public class var status : String { return __FUNCTION__ }
public class var sw : String { return __FUNCTION__ }
// MARK: - T
public class var text : String { return __FUNCTION__ }
public class var time : String { return __FUNCTION__ }
public class var twitter : String { return __FUNCTION__ }
public class var twitterSource : String { return __FUNCTION__ }
public class var type : String { return __FUNCTION__ }
// MARK: - U
public class var url : String { return __FUNCTION__ }
// MARK: - V
public class var value : String { return __FUNCTION__ }
public class var venuell : String { return __FUNCTION__ }
public class var venuePhotos : String { return __FUNCTION__ }
public class var visible : String { return __FUNCTION__ }
// MARK: - Z
public class var zip : String { return __FUNCTION__ }
// MARK: - INTERNAL
class var client_id : String { return "client_id" }
class var client_secret : String { return "client_secret" }
class var redirect_uri : String { return "redirect_uri" }
class var code : String { return "code" }
class var grant_type : String { return "grant_type" }
class var oauth_token : String { return "oauth_token" }
class var v : String { return "v" }
class var locale : String { return "locale" }
class var response_type : String { return "response_type" }
class var m : String { return "m" }
class var requests : String { return "requests" }
class func URLQuery(parameters: Parameters) -> String {
var result = String()
for (key, value) in parameters {
let parameters = key + "=" + value
if result.characters.count == 0 {
result += parameters
} else {
result += "&" + parameters
}
}
return result
}
class func buildURL(baseURL: NSURL, parameters: Parameters, preformattedQueryString: String? = nil) -> NSURL {
let components = NSURLComponents(URL: baseURL, resolvingAgainstBaseURL: false)!
let query = URLQuery(parameters)
if let componentsQuery = components.query {
components.query = componentsQuery + "&" + query
} else {
components.query = query
}
if let preformatted = preformattedQueryString {
let delimiter = components.query != nil ? "&" : "?"
return NSURL(string: components.URL!.absoluteString + delimiter + preformatted)!
}
return components.URL!
}
}
|
bsd-2-clause
|
98fd63c5ebf8e4ee0322a3ef0fc194dd
| 49.120603 | 114 | 0.533788 | 5.027218 | false | false | false | false |
Elm-Tree-Island/Shower
|
Shower/Carthage/Checkouts/ReactiveSwift/Sources/ValidatingProperty.swift
|
11
|
9957
|
import Result
/// A mutable property that validates mutations before committing them.
///
/// If the property wraps an arbitrary mutable property, changes originated from
/// the inner property are monitored, and would be automatically validated.
/// Note that these would still appear as committed values even if they fail the
/// validation.
///
/// ```
/// let root = MutableProperty("Valid")
/// let outer = ValidatingProperty(root) {
/// $0 == "Valid" ? .valid : .invalid(.outerInvalid)
/// }
///
/// outer.result.value // `.valid("Valid")
///
/// root.value = "🎃"
/// outer.result.value // `.invalid("🎃", .outerInvalid)`
/// ```
public final class ValidatingProperty<Value, ValidationError: Swift.Error>: MutablePropertyProtocol {
private let getter: () -> Value
private let setter: (Value) -> Void
/// The result of the last attempted edit of the root property.
public let result: Property<Result>
/// The current value of the property.
///
/// The value could have failed the validation. Refer to `result` for the
/// latest validation result.
public var value: Value {
get { return getter() }
set { setter(newValue) }
}
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time, then complete when the property has
/// deinitialized.
public let producer: SignalProducer<Value, NoError>
/// A signal that will send the property's changes over time,
/// then complete when the property has deinitialized.
public let signal: Signal<Value, NoError>
/// The lifetime of the property.
public let lifetime: Lifetime
/// Create a `ValidatingProperty` that presents a mutable validating
/// view for an inner mutable property.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - note: `inner` is retained by the created property.
///
/// - parameters:
/// - inner: The inner property which validated values are committed to.
/// - validator: The closure to invoke for any proposed value to `self`.
public init<Inner: ComposableMutablePropertyProtocol>(
_ inner: Inner,
_ validator: @escaping (Value) -> Decision
) where Inner.Value == Value {
getter = { inner.value }
producer = inner.producer
signal = inner.signal
lifetime = inner.lifetime
// This flag temporarily suspends the monitoring on the inner property for
// writebacks that are triggered by successful validations.
var isSettingInnerValue = false
(result, setter) = inner.withValue { initial in
let mutableResult = MutableProperty(Result(initial, validator(initial)))
mutableResult <~ inner.signal
.filter { _ in !isSettingInnerValue }
.map { Result($0, validator($0)) }
return (Property(capturing: mutableResult), { input in
// Acquire the lock of `inner` to ensure no modification happens until
// the validation logic here completes.
inner.withValue { _ in
let writebackValue: Value? = mutableResult.modify { result in
result = Result(input, validator(input))
return result.value
}
if let value = writebackValue {
isSettingInnerValue = true
inner.value = value
isSettingInnerValue = false
}
}
})
}
}
/// Create a `ValidatingProperty` that validates mutations before
/// committing them.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - parameters:
/// - initial: The initial value of the property. It is not required to
/// pass the validation as specified by `validator`.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init(
_ initial: Value,
_ validator: @escaping (Value) -> Decision
) {
self.init(MutableProperty(initial), validator)
}
/// Create a `ValidatingProperty` that presents a mutable validating
/// view for an inner mutable property.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - note: `inner` is retained by the created property.
///
/// - parameters:
/// - inner: The inner property which validated values are committed to.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<Other: PropertyProtocol>(
_ inner: MutableProperty<Value>,
with other: Other,
_ validator: @escaping (Value, Other.Value) -> Decision
) {
// Capture a copy that reflects `other` without influencing the lifetime of
// `other`.
let other = Property(other)
self.init(inner) { input in
return validator(input, other.value)
}
// When `other` pushes out a new value, the resulting property would react
// by revalidating itself with its last attempted value, regardless of
// success or failure.
other.signal
.take(during: lifetime)
.observeValues { [weak self] _ in
guard let s = self else { return }
switch s.result.value {
case let .invalid(value, _):
s.value = value
case let .coerced(_, value, _):
s.value = value
case let .valid(value):
s.value = value
}
}
}
/// Create a `ValidatingProperty` that validates mutations before
/// committing them.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - parameters:
/// - initial: The initial value of the property. It is not required to
/// pass the validation as specified by `validator`.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<Other: PropertyProtocol>(
_ initial: Value,
with other: Other,
_ validator: @escaping (Value, Other.Value) -> Decision
) {
self.init(MutableProperty(initial), with: other, validator)
}
/// Create a `ValidatingProperty` that presents a mutable validating
/// view for an inner mutable property.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - note: `inner` is retained by the created property.
///
/// - parameters:
/// - inner: The inner property which validated values are committed to.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<U, E>(
_ inner: MutableProperty<Value>,
with other: ValidatingProperty<U, E>,
_ validator: @escaping (Value, U) -> Decision
) {
self.init(inner, with: other, validator)
}
/// Create a `ValidatingProperty` that validates mutations before
/// committing them.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - parameters:
/// - initial: The initial value of the property. It is not required to
/// pass the validation as specified by `validator`.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<U, E>(
_ initial: Value,
with other: ValidatingProperty<U, E>,
_ validator: @escaping (Value, U) -> Decision
) {
// Capture only `other.result` but not `other`.
let otherValidations = other.result
self.init(initial) { input in
let otherValue: U
switch otherValidations.value {
case let .valid(value):
otherValue = value
case let .coerced(_, value, _):
otherValue = value
case let .invalid(value, _):
otherValue = value
}
return validator(input, otherValue)
}
// When `other` pushes out a new validation result, the resulting property
// would react by revalidating itself with its last attempted value,
// regardless of success or failure.
otherValidations.signal
.take(during: lifetime)
.observeValues { [weak self] _ in
guard let s = self else { return }
switch s.result.value {
case let .invalid(value, _):
s.value = value
case let .coerced(_, value, _):
s.value = value
case let .valid(value):
s.value = value
}
}
}
/// Represents a decision of a validator of a validating property made on a
/// proposed value.
public enum Decision {
/// The proposed value is valid.
case valid
/// The proposed value is invalid, but the validator coerces it into a
/// replacement which it deems valid.
case coerced(Value, ValidationError?)
/// The proposed value is invalid.
case invalid(ValidationError)
}
/// Represents the result of the validation performed by a validating property.
public enum Result {
/// The proposed value is valid.
case valid(Value)
/// The proposed value is invalid, but the validator was able to coerce it
/// into a replacement which it deemed valid.
case coerced(replacement: Value, proposed: Value, error: ValidationError?)
/// The proposed value is invalid.
case invalid(Value, ValidationError)
/// Whether the value is invalid.
public var isInvalid: Bool {
if case .invalid = self {
return true
} else {
return false
}
}
/// Extract the valid value, or `nil` if the value is invalid.
public var value: Value? {
switch self {
case let .valid(value):
return value
case let .coerced(value, _, _):
return value
case .invalid:
return nil
}
}
/// Extract the error if the value is invalid.
public var error: ValidationError? {
if case let .invalid(_, error) = self {
return error
} else {
return nil
}
}
fileprivate init(_ value: Value, _ decision: Decision) {
switch decision {
case .valid:
self = .valid(value)
case let .coerced(replacement, error):
self = .coerced(replacement: replacement, proposed: value, error: error)
case let .invalid(error):
self = .invalid(value, error)
}
}
}
}
|
gpl-3.0
|
7e2f4e3a5ec266f50a6ea071285c6e35
| 29.431193 | 101 | 0.675008 | 3.814105 | false | false | false | false |
jianwoo/ios-charts
|
Charts/Classes/Renderers/HorizontalBarChartRenderer.swift
|
1
|
16400
|
//
// HorizontalBarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class HorizontalBarChartRenderer: BarChartRenderer
{
private var xOffset: CGFloat = 0.0;
private var yOffset: CGFloat = 0.0;
public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler);
}
internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int)
{
CGContextSaveGState(context);
var barData = delegate!.barChartRendererData(self);
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
calcXBounds(trans);
var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self);
var dataSetOffset = (barData.dataSetCount - 1);
var groupSpace = barData.groupSpace;
var groupSpaceHalf = groupSpace / 2.0;
var barSpace = dataSet.barSpace;
var barSpaceHalf = barSpace / 2.0;
var containsStacks = dataSet.isStacked;
var entries = dataSet.yVals as! [BarChartDataEntry];
var barWidth: CGFloat = 0.5;
var phaseY = _animator.phaseY;
var barRect = CGRect();
var barShadow = CGRect();
var y: Float;
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(j) + groupSpaceHalf;
var vals = e.values;
if (!containsStacks || vals == nil)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = y >= 0.0 ? CGFloat(y) : 0;
var left = y <= 0.0 ? CGFloat(y) : 0;
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (!viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height))
{
continue;
}
if (!viewPortHandler.isInBoundsBottom(barRect.origin.y))
{
break;
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor);
CGContextFillRect(context, barRect);
}
else
{
var all = e.value;
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = y >= 0.0 ? CGFloat(y) : 0.0;
var left = y <= 0.0 ? CGFloat(y) : 0.0;
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// fill the stack
for (var k = 0; k < vals.count; k++)
{
all -= vals[k];
y = vals[k] + all;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = y >= 0.0 ? CGFloat(y) : 0.0;
var left = y <= 0.0 ? CGFloat(y) : 0.0;
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (k == 0 && !viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height))
{
// Skip to next bar
break;
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsBottom(barRect.origin.y))
{
break;
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor);
CGContextFillRect(context, barRect);
}
}
}
CGContextRestoreGState(context);
}
internal override func prepareBarHighlight(#x: CGFloat, y: Float, barspace: CGFloat, from: Float, trans: ChartTransformer, inout rect: CGRect)
{
var barWidth: CGFloat = 0.5;
var spaceHalf = barspace / 2.0;
var top = x - barWidth + spaceHalf;
var bottom = x + barWidth - spaceHalf;
var left = y >= from ? CGFloat(y) : CGFloat(from);
var right = y <= from ? CGFloat(y) : CGFloat(from);
rect.origin.x = left;
rect.origin.y = top;
rect.size.width = right - left;
rect.size.height = bottom - top;
trans.rectValueToPixel(&rect, phaseY: _animator.phaseY);
}
public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY);
}
public override func drawValues(#context: CGContext)
{
// if values are drawn
if (passesCheck())
{
var barData = delegate!.barChartRendererData(self);
var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self);
var dataSets = barData.dataSets;
var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self);
var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self);
// calculate the correct offset depending on the draw position of the value
var negOffset: CGFloat = (drawValueAboveBar ? -5.0 : 5.0);
var posOffset: CGFloat = (drawValueAboveBar ? 5.0 : -5.0);
var textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right;
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
var dataSet = dataSets[i];
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var yOffset = -valueFont.lineHeight / 2.0;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i);
// if only single values are drawn (sum)
if (!drawValuesForWholeStackEnabled)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = entries[j].value;
drawValue(
context: context,
val: val,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
formatter: formatter!,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
else
{
// if each value of a potential stack should be drawn
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
var vals = e.values;
// we still draw stacked bars, but there is one non-stacked in between
if (vals == nil)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = e.value;
drawValue(
context: context,
val: val,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
formatter: formatter!,
font: valueFont,
align: .Left,
color: valueTextColor);
}
else
{
var transformed = [CGPoint]();
var cnt = 0;
var add = e.value;
for (var k = 0; k < vals.count; k++)
{
add -= vals[cnt];
transformed.append(CGPoint(x: (CGFloat(vals[cnt]) + CGFloat(add)) * _animator.phaseY, y: 0.0));
cnt++;
}
trans.pointValuesToPixel(&transformed);
for (var k = 0; k < transformed.count; k++)
{
var x = transformed[k].x + (vals[k] >= 0 ? posOffset : negOffset);
var y = valuePoints[j].y;
if (!viewPortHandler.isInBoundsX(x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue;
}
drawValue(context: context,
val: vals[k],
xPos: x,
yPos: y,
formatter: formatter!,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
var barData = delegate!.barChartRendererData(self);
if (barData === nil)
{
return false;
}
return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY;
}
}
|
apache-2.0
|
25db3925cc2ee949a926d98a68f4cfb5
| 39.596535 | 171 | 0.415732 | 6.471981 | false | false | false | false |
VladislavJevremovic/Exchange-Rates-NBS
|
Widget/TodayViewController.swift
|
1
|
3107
|
//
// TodayViewController.swift
// Widget
//
// Created by Vladislav Jevremovic on 4/4/15.
// Copyright (c) 2015 Vladislav Jevremovic. All rights reserved.
//
import UIKit
import NotificationCenter
import ExchangeRatesKit
class TodayViewController: CurrencyDataSource, NCWidgetProviding {
@IBOutlet weak var labelEURAverageRate: UILabel!
@IBOutlet weak var labelUSDAverageRate: UILabel!
@IBOutlet weak var labelCHFAverageRate: UILabel!
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let singleFingerTap = UITapGestureRecognizer(target: self,
action: #selector(TodayViewController.handleSingleTap(_:)))
containerView.addGestureRecognizer(singleFingerTap)
}
@objc func handleSingleTap(_ recognizer: UITapGestureRecognizer) {
if let url = URL(string: "ExchangeRatesNBS://home") {
self.extensionContext?.open(url, completionHandler: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getCurrencyData({
(error) -> () in
if error == nil {
self.updateData()
}
})
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
getCurrencyData({
(error) -> () in
if error == nil {
self.updateData()
completionHandler(.newData)
} else {
completionHandler(.noData)
}
})
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets(top: defaultMarginInsets.top,
left: defaultMarginInsets.left,
bottom: 0,
right: defaultMarginInsets.right)
}
override func updateData() {
if let currencyDataList = currencyDataList {
let currencyDataEur: CurrencyData? = (currencyDataList.filter() {
$0.code == "eur"
}).first
let currencyDataUsd: CurrencyData? = (currencyDataList.filter() {
$0.code == "usd"
}).first
let currencyDataChf: CurrencyData? = (currencyDataList.filter() {
$0.code == "chf"
}).first
labelEURAverageRate.text = currencyDataEur?.valueAvg?.toString(4)
labelUSDAverageRate.text = currencyDataUsd?.valueAvg?.toString(4)
labelCHFAverageRate.text = currencyDataChf?.valueAvg?.toString(4)
}
}
}
|
mit
|
301e1be36b1bc78823702764070817e1
| 31.364583 | 112 | 0.604442 | 5.085106 | false | false | false | false |
brentdax/swift
|
test/Interpreter/extended_grapheme_cluster_literal.swift
|
5
|
1637
|
// RUN: %target-run-simple-swift
// RUN: %target-build-swift -O %s -o %t/a.out.optimized
// RUN: %target-codesign %t/a.out.optimized
// RUN: %target-run %t/a.out.optimized
// REQUIRES: executable_test
import StdlibUnittest
private let testSuite = TestSuite("extendedGraphemeCluster literals")
private struct Expressible
<T: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral>
: ExpressibleByExtendedGraphemeClusterLiteral {
var value: T
init(extendedGraphemeClusterLiteral value: T) {
self.value = value
}
}
private func string(_ characters: UInt32...) -> String {
return String(characters.map { Character(UnicodeScalar($0)!) })
}
private func expressible<T>(_ literal: Expressible<T>, as type: T.Type)
-> String where T: CustomStringConvertible {
return literal.value.description
}
private let b = string(0x62)
private let 🇦🇺 = string(0x1F1E6, 0x1F1FA)
private let 각 = string(0x1100, 0x1161, 0x11A8)
testSuite.test("String literal type") {
expectEqual(expressible("b", as: String.self), b)
expectEqual(expressible("🇦🇺", as: String.self), 🇦🇺)
expectEqual(expressible("각", as: String.self), 각)
}
testSuite.test("StaticString literal type") {
expectEqual(expressible("b", as: StaticString.self), b)
expectEqual(expressible("🇦🇺", as: StaticString.self), 🇦🇺)
expectEqual(expressible("각", as: StaticString.self), 각)
}
testSuite.test("Character literal type") {
expectEqual(expressible("b", as: Character.self), b)
expectEqual(expressible("🇦🇺", as: Character.self), 🇦🇺)
expectEqual(expressible("각", as: Character.self), 각)
}
runAllTests()
|
apache-2.0
|
b238076676e0e4fbdc6f71d1e3cc5d54
| 30.62 | 71 | 0.72296 | 3.414687 | false | true | false | false |
auth0/Lock.swift
|
Lock/Rule.swift
|
2
|
3583
|
// Rule.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
protocol Rule {
var message: String { get }
func evaluate(on password: String?) -> RuleResult
}
protocol RuleResult {
var message: String { get }
var conditions: [RuleResult] { get }
var valid: Bool { get }
}
func withPassword(lengthInRange range: CountableClosedRange<Int>, message: String) -> Rule {
#if swift(>=3.2)
return SimpleRule(message: message) { range ~= $0.count }
#else
return SimpleRule(message: message) { range ~= $0.characters.count }
#endif
}
func withPassword(havingCharactersIn characterSet: CharacterSet, message: String) -> Rule {
return SimpleRule(message: message) { $0.rangeOfCharacter(from: characterSet) != nil }
}
func withPassword(havingMaxConsecutiveRepeats count: Int, message: String) -> Rule {
return SimpleRule(message: message) {
#if swift(>=3.2)
let repeated = $0.reduce([]) { (partial: [Character], character: Character) in
guard partial.count <= count else { return partial }
guard partial.contains(character) else { return [character] }
return partial + [character]
}
#else
let repeated = $0.characters.reduce([]) { (partial: [Character], character: Character) in
guard partial.count <= count else { return partial }
guard partial.contains(character) else { return [character] }
return partial + [character]
}
#endif
return repeated.count <= count
}
}
struct AtLeastRule: Rule {
let minimum: Int
let rules: [Rule]
let message: String
func evaluate(on password: String?) -> RuleResult {
let results = rules.map { $0.evaluate(on: password) }
let count = results.reduce(0) { $0 + ($1.valid ? 1 : 0) }
return Result(message: message, valid: count >= minimum, conditions: results)
}
struct Result: RuleResult {
let message: String
let valid: Bool
let conditions: [RuleResult]
}
}
struct SimpleRule: Rule {
let message: String
let valid: (String) -> Bool
func evaluate(on password: String?) -> RuleResult {
guard let value = password else { return Result(message: message, valid: false) }
return Result(message: message, valid: self.valid(value))
}
struct Result: RuleResult {
let message: String
let valid: Bool
let conditions: [RuleResult] = []
}
}
|
mit
|
149e41f350f0eafce565eee7b1353b11
| 34.475248 | 97 | 0.670388 | 4.255344 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.