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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
descorp/SwiftPlayground | General.playground/Pages/Math.xcplaygroundpage/Contents.swift | 1 | 1952 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
let nan = Double.nan
let inf = Double.infinity
nan > 10
nan < 10
nan == 10
nan == nan
nan != nan
nan == -nan
nan != -nan
10.0 / 0
-10.0 / 0
10.0 / 1
-10.0 / 1
10.0 / -1
-10.0 / 1
0 / -1
-1 / 0.0
2 / -5
0.0 / 0.0
inf > inf
inf < inf
inf == inf
0 / inf
0 / -inf
5 / inf
-5 / inf
5 / -inf
5.0 / 0
inf / 0
-inf / 0
inf - inf
inf + inf
-inf + -inf
12 % 1
12 % 5
12 % -5
-12 % 5
-12 % -5
5 % 12
5 % -12
-5 % 12
-5 % -12
5 % 5
5 % -5
-5 % 5
-5 % -5
0 % 3
//3 % 0
5 % 2
5.0.remainder(dividingBy: 2.0)
5.0.remainder(dividingBy: -2.0)
-5.0.remainder(dividingBy: -2.0)
5.0.remainder(dividingBy: Double.infinity)
Double.infinity.remainder(dividingBy: Double.infinity)
Double.infinity.remainder(dividingBy: -Double.infinity)
Double.infinity.remainder(dividingBy: 2.0)
0.0.remainder(dividingBy: 0.0)
0.0.remainder(dividingBy: Double.infinity)
0.0.remainder(dividingBy: -Double.infinity)
5.0.remainder(dividingBy: 0.0)
-5.0.remainder(dividingBy: 0.0)
5.0.remainder(dividingBy: 5.0)
5.0.remainder(dividingBy: -5.0)
-5.0.remainder(dividingBy: 5.0)
-5.0.remainder(dividingBy: -5.0)
5.0.remainder(dividingBy: 6.0)
5.0.remainder(dividingBy: -6.0)
-5.0.remainder(dividingBy: 6.0)
-5.0.remainder(dividingBy: -6.0)
0.0.remainder(dividingBy: 5.0)
0.0.remainder(dividingBy: -5.0)
0.0.remainder(dividingBy: 1.0)
0.0.remainder(dividingBy: -1.0)
5.0.remainder(dividingBy: Double.nan)
-0
inf > -inf
inf < -inf
-inf > inf
-inf < inf
inf == -inf
inf - inf
inf + inf
inf * inf
inf / inf
10.0 / inf
inf / 10.0
let a = -5 / inf
a.isZero
a.isFinite
a.isNormal
a.isSubnormal
a == 0
a.magnitude
a.sign
a.description
let b = Double(-0)
let c = Double(-0.0)
c.isZero
c.isFinite
c.isNormal
c.isSubnormal
c == 0
c.magnitude
c.sign
c.description
c.isCanonical
0.0.isCanonical
// Converting
UInt(abs(-42344234))
// Power
pow(5.0, 2.0)
pow(5.0, -2.0)
pow(5.0, 2.0)
| mit | 79879984cd7c9ce30864935b43c432e0 | 11.512821 | 55 | 0.646516 | 2.288394 | false | false | false | false |
taktem/TAKSwiftSupport | TAKSwiftSupport/Core/Extension/UILabel+Attributes.swift | 1 | 4532 | //
// UILabelAttributes.swift
// TAKSwiftSupport
//
// Created by 西村 拓 on 2015/11/11.
// Copyright © 2015年 TakuNishimura. All rights reserved.
//
import UIKit
public extension UILabel {
/**
Fill Color
- parameter color: Fill Color
*/
final class func attributeWithColor(color color: UIColor) -> [String: AnyObject] {
return [NSForegroundColorAttributeName: color]
}
/**
OutLine
- parameter color: Line Color
- parameter width: Line Width
*/
final class func attributeWithOutline(color color: UIColor, width: Int) -> [String: AnyObject] {
return [
NSStrokeColorAttributeName: color,
NSStrokeWidthAttributeName: width
]
}
/**
Font
- parameter fontName: enum FontName
- parameter size: font size
*/
final class func attributeWithFont(fontName fontName: UIFont.FontName, size: CGFloat) -> [String: AnyObject] {
return [
NSFontAttributeName: UIFont(name: fontName, size: size)
]
}
/**
Font
- parameter font: font
*/
final class func attributeWithFont(font font: UIFont) -> [String: AnyObject] {
return [
NSFontAttributeName: font
]
}
/**
Line Height
Text Alignment
- parameter lineHeight: Line Height
- parameter alignment: Text Alignment
*/
final class func attributeWithParagraphStyle(lineHeight lineHeight: Float? = nil, alignment alignment: NSTextAlignment? = nil) -> [String: AnyObject] {
let paragraphStyle = NSMutableParagraphStyle()
if let lineHeight = lineHeight {
paragraphStyle.minimumLineHeight = CGFloat(lineHeight);
paragraphStyle.maximumLineHeight = CGFloat(lineHeight);
}
if let alignment = alignment {
paragraphStyle.alignment = alignment
}
return [NSParagraphStyleAttributeName: paragraphStyle]
}
/**
BaselineOffset
- parameter baseLineOffset: BaselineOffset
*/
final class func attributeWithBaselineOffset(baseLineOffset baseLineOffset: Float) -> [String: AnyObject] {
return [NSBaselineOffsetAttributeName: NSNumber(float: baseLineOffset)]
}
/**
Kerning
- parameter em: Letter Spacing
*/
final class func attributeWithKerning(em em: Float) -> [String: AnyObject] {
return [
NSKernAttributeName: em
]
}
/**
Make AttributeString
- parameter string: String
- parameter attributes: [Attribute]
- returns: NSAttributedString
*/
final class func attributedText(string string: String, attributes: [String: AnyObject]) -> NSAttributedString {
let attrText = NSAttributedString(
string: string,
attributes: attributes
)
return attrText
}
/**
JoinAttributesStrings
- parameter string: String
- returns: [NSAttributedString]
*/
final func joinAttributesStrings(strings strings: [NSAttributedString]) {
let attrStrings = NSMutableAttributedString()
for string in strings {
attrStrings.appendAttributedString(string)
}
self.attributedText = attrStrings
}
/**
OverRide Attributes Setting
*/
final func overrideAttributes(
font font: UIFont? = nil,
color: UIColor? = nil,
borderColor: UIColor? = nil,
borderWidth: Int = 0,
kerning: Float? = nil,
lineHeight: Float? = nil,
alignment: NSTextAlignment? = nil
) {
guard let text = text else {
return
}
var attributes = [String: AnyObject]()
// font
if let font = font {
attributes += UILabel.attributeWithFont(font: font)
}
// color
if let color = color {
attributes += UILabel.attributeWithColor(color: color)
}
// border
if let borderColor = borderColor {
attributes += UILabel.attributeWithOutline(color: borderColor, width: borderWidth)
}
// Kerning
if let kerning = kerning {
attributes += UILabel.attributeWithKerning(em: kerning)
}
// ParagraphStyle
attributes += UILabel.attributeWithParagraphStyle(lineHeight: lineHeight, alignment: alignment)
// set
joinAttributesStrings(
strings: [UILabel.attributedText(
string: text,
attributes: attributes)])
}
/**
Update LabelText and return self
*/
final func setText(text text: String) -> UILabel {
self.text = text
return self
}
}
| mit | ce08c7b280a3ab77d8497f5b74e8756d | 22.557292 | 152 | 0.633208 | 4.677353 | false | false | false | false |
steryokhin/AsciiArtPlayer | src/AsciiArtPlayer/Pods/SwiftyUtils/Sources/Protocols/Then.swift | 3 | 647 | //
// Created by Tom Baranes on 24/04/16.
// Copyright © 2016 Tom Baranes. All rights reserved.
//
// Thanks to devxoul: https://github.com/devxoul/Then
//
import Foundation
public protocol Then {}
extension Then {
/// Makes it available to set properties with closures.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(block: (inout (Self)) -> Void) -> Self {
var copy = self
block(©)
return copy
}
}
extension NSObject: Then {}
| mit | bea03fe59322412b88dbd0a389e7c4df | 21.275862 | 61 | 0.565015 | 3.8 | false | false | false | false |
aiwalle/LiveProject | LiveProject/Base/const.swift | 1 | 733 | //
// const.swift
// LiveProject
//
// Created by liang on 2017/8/2.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
let kNavigationBarHeight : CGFloat = 44
let kStatusBarHeight : CGFloat = 20
let kTabBarHeight : CGFloat = 49
let kDeviceWidth = UIScreen.main.bounds.width
let kDeviceHeight = UIScreen.main.bounds.height
let kAnchorCellSubviewMargin : CGFloat = 8
let kAnchorControllerCellID : String = "kAnchorControllerCellID"
let kPageControllerCellID = "kPageControllerCellID"
let kChatContentCellID = "kChatContentCellID"
let kChatToolsViewMargin : CGFloat = 5
let kEmoticonViewCellID = "kEmoticonViewCellID"
let kEmoticonBtnWidth : CGFloat = 32
let KEmoticonViewHeight : CGFloat = 250
| mit | 2791c8033e55523dc0c1b23a1b613c52 | 17.25 | 64 | 0.767123 | 3.945946 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIComponents/QMUIModalPresentationViewController.swift | 1 | 36226 | //
// QMUIModalPresentationViewController.swift
// QMUI.swift
//
// Created by 黄伯驹 on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
@objc enum QMUIModalPresentationAnimationStyle: Int {
case fade // 渐现渐隐,默认
case popup // 从中心点弹出
case slide // 从下往上升起
}
@objc protocol QMUIModalPresentationContentViewControllerProtocol {
/**
* 当浮层以 UIViewController 的形式展示(而非 UIView),并且使用 modalController 提供的默认布局时,则可通过这个方法告诉 modalController 当前浮层期望的大小
* @param controller 当前的modalController
* @param limitSize 浮层最大的宽高,由当前 modalController 的大小及 `contentViewMargins`、`maximumContentViewWidth` 决定
* @return 返回浮层在 `limitSize` 限定内的大小,如果业务自身不需要限制宽度/高度,则为 width/height 返回 `CGFLOAT_MAX` 即可
*/
@objc optional func preferredContentSize(inModalPresentationViewController controller: QMUIModalPresentationViewController, limitSize: CGSize) -> CGSize
}
@objc protocol QMUIModalPresentationViewControllerDelegate {
/**
* 是否应该隐藏浮层,会在调用`hideWithAnimated:completion:`时,以及点击背景遮罩时被调用。默认为YES。
* @param controller 当前的modalController
* @return 是否允许隐藏,YES表示允许隐藏,NO表示不允许隐藏
*/
@objc optional func shouldHide(modalPresentationViewController controller: QMUIModalPresentationViewController) -> Bool
/**
* modalController 即将隐藏时的回调方法,在调用完这个方法后才开始做一些隐藏前的准备工作,例如恢复 window 的 dimmed 状态等。
* @param controller 当前的modalController
*/
@objc optional func willHide(modalPresentationViewController controller: QMUIModalPresentationViewController)
/**
* modalController隐藏后的回调方法,不管是直接调用`hideWithAnimated:completion:`,还是通过点击遮罩触发的隐藏,都会调用这个方法。
* 如果你想区分这两种方式的隐藏回调,请直接使用hideWithAnimated方法的completion参数,以及`didHideByDimmingViewTappedBlock`属性。
* @param controller 当前的modalController
*/
@objc optional func didHide(modalPresentationViewController controller: QMUIModalPresentationViewController)
@objc optional func requestHideAllModalPresentationViewController()
}
/**
* 一个提供通用的弹出浮层功能的控件,可以将任意`UIView`或`UIViewController`以浮层的形式显示出来并自动布局。
*
* 支持 3 种方式显示浮层:
*
* 1. **推荐** 新起一个 `UIWindow` 盖在当前界面上,将 `QMUIModalPresentationViewController` 以 `rootViewController` 的形式显示出来,可通过 `supportedOrientationMask` 支持横竖屏,不支持在浮层不消失的情况下做界面切换(因为 window 会把背后的 controller 盖住,看不到界面切换)
* @code
* [modalPresentationViewController showWithAnimated:YES completion:nil]
* @endcode
*
* 2. 使用系统接口来显示,支持界面切换,**注意** 使用这种方法必定只能以动画的形式来显示浮层,无法以无动画的形式来显示,并且 `animated` 参数必须为 `NO`。可通过 `supportedOrientationMask` 支持横竖屏。
* @code
* [self presentViewController:modalPresentationViewController animated:NO completion:nil]
* @endcode
*
* 3. 将浮层作为一个 subview 添加到 `superview` 上,从而能够实现在浮层不消失的情况下进行界面切换,但需要 `superview` 自行管理浮层的大小和横竖屏旋转,而且 `QMUIModalPresentationViewController` 不能用局部变量来保存,会在显示后被释放,需要自行 retain。横竖屏跟随当前界面的设置。
* @code
* self.modalPresentationViewController.view.frame = CGRectMake(50, 50, 100, 100)
* [self.view addSubview:self.modalPresentationViewController.view]
* @endcode
*
* 默认的布局会将浮层居中显示,浮层的大小可通过接口控制:
* 1. 如果是用 `contentViewController`,则可通过 `preferredContentSizeInModalPresentationViewController:limitSize:` 来设置
* 2. 如果使用 `contentView`,或者使用 `contentViewController` 但没实现 `preferredContentSizeInModalPresentationViewController:limitSize:`,则调用`contentView`的`sizeThatFits:`方法获取大小。
* 3. 浮层大小会受 `maximumContentViewWidth` 属性的限制,以及 `contentViewMargins` 属性的影响。
*
* 通过`layoutBlock`、`showingAnimation`、`hidingAnimation`可设置自定义的布局、打开及隐藏的动画,并允许你适配键盘升起时的场景。
*
* 默认提供背景遮罩`dimmingView`,你也可以使用自己的遮罩 view。
*
* 默认提供多种显示动画,可通过 `animationStyle` 来设置。
*
* @warning 如果使用者retain了modalPresentationViewController,注意应该在`hideWithAnimated:completion:`里release
*
* @see QMUIAlertController
* @see QMUIDialogViewController
* @see QMUIMoreOperationController
*/
class QMUIModalPresentationViewController: UIViewController {
weak var delegate: QMUIModalPresentationViewControllerDelegate?
/**
* 要被弹出的浮层
* @warning 当设置了`contentView`时,不要再设置`contentViewController`
*/
var contentView: UIView?
/**
* 要被弹出的浮层,适用于浮层以UIViewController的形式来管理的情况。
* @warning 当设置了`contentViewController`时,`contentViewController.view`会被当成`contentView`使用,因此不要再自行设置`contentView`
* @warning 注意`contentViewController`是强引用,容易导致循环引用,使用时请注意
*/
var contentViewController: (UIViewController & QMUIModalPresentationContentViewControllerProtocol)? {
didSet {
contentView = contentViewController?.view
}
}
/**
* 设置`contentView`布局时与外容器的间距,默认为(20, 20, 20, 20)
* @warning 当设置了`layoutBlock`属性时,此属性不生效
*/
@objc dynamic var contentViewMargins = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
/**
* 限制`contentView`布局时的最大宽度,默认为iPhone 6竖屏下的屏幕宽度减去`contentViewMargins`在水平方向的值,也即浮层在iPhone 6 Plus或iPad上的宽度以iPhone 6上的宽度为准。
* @warning 当设置了`layoutBlock`属性时,此属性不生效
*/
var maximumContentViewWidth: CGFloat = QMUIHelper.screenSizeFor47Inch.width - UIEdgeInsets.init(top: 20, left: 20, bottom: 20, right: 20).horizontalValue
/**
* 背景遮罩,默认为一个普通的`UIView`,背景色为`UIColorMask`,可设置为自己的view,注意`dimmingView`的大小将会盖满整个控件。
*
* `QMUIModalPresentationViewController`会自动给自定义的`dimmingView`添加手势以实现点击遮罩隐藏浮层。
*/
private var _dimmingView: UIView?
var dimmingView: UIView? {
get {
return _dimmingView
}
set {
if !isViewLoaded {
_dimmingView = newValue
} else {
if let new = newValue, let old = _dimmingView {
view.insertSubview(new, aboveSubview: old)
}
_dimmingView?.removeFromSuperview()
_dimmingView = newValue
view.setNeedsLayout()
}
addTapGestureRecognizerToDimmingViewIfNeeded()
}
}
/**
* 由于点击遮罩导致浮层被隐藏时的回调(区分于`hideWithAnimated:completion:`里的completion,这里是特地用于点击遮罩的情况)
*/
var didHideByDimmingViewTappedClosure: (() -> Void)?
/**
* 控制当前是否以模态的形式存在。如果以模态的形式存在,则点击空白区域不会隐藏浮层。
*
* 默认为false,也即点击空白区域将会自动隐藏浮层。
*/
var isModal = false
/**
* 标志当前浮层的显示/隐藏状态,默认为false。
*/
var isVisible = false
/**
* 修改当前界面要支持的横竖屏方向,默认为 SupportedOrientationMask。
*/
var supportedOrientationMask: UIInterfaceOrientationMask = SupportedOrientationMask
/**
* 设置要使用的显示/隐藏动画的类型,默认为`QMUIModalPresentationAnimationStyleFade`。
* @warning 当使用了`showingAnimation`和`hidingAnimation`时,该属性无效
*/
@objc dynamic var animationStyle: QMUIModalPresentationAnimationStyle = .fade
/// 是否以 UIWindow 的方式显示,建议在显示之后才使用,否则可能不准确。
private var isShownInWindowMode: Bool {
return containerWindow != nil
}
/// 是否以系统 present 的方式显示,建议在显示之后才使用,否则可能不准确。
private var isShownInPresentedMode: Bool {
return !isShownInWindowMode && presentingViewController != nil && presentingViewController?.presentedViewController == self
}
/// 是否以 addSubview 的方式显示,建议在显示之后才使用,否则可能不准确。
private var isShownInSubviewMode: Bool {
return !isShownInPresentedMode && view.superview != nil
}
private var isShowingPresentedViewController: Bool {
return isShownInPresentedMode && (presentedViewController != nil) && presentedViewController?.presentingViewController == self
}
/**
* 管理自定义的浮层布局,将会在浮层显示前、控件的容器大小发生变化时(例如横竖屏、来电状态栏)被调用
* @arg containerBounds 浮层所在的父容器的大小,也即`self.view.bounds`
* @arg keyboardHeight 键盘在当前界面里的高度,若无键盘,则为0
* @arg contentViewDefaultFrame 不使用自定义布局的情况下的默认布局,会受`contentViewMargins`、`maximumContentViewWidth`、`contentView sizeThatFits:`的影响
*
* @see contentViewMargins
* @see maximumContentViewWidth
*/
var layoutClosure: ((_ containerBounds: CGRect, _ keyboardHeight: CGFloat, _ contentViewDefaultFrame: CGRect) -> Void)?
/**
* 管理自定义的显示动画,需要管理的对象包括`contentView`和`dimmingView`,在`showingAnimation`被调用前,`contentView`已被添加到界面上。若使用了`layoutBlock`,则会先调用`layoutBlock`,再调用`showingAnimation`。在动画结束后,必须调用参数里的`completion` block。
* @arg dimmingView 背景遮罩的View,请自行设置显示遮罩的动画
* @arg containerBounds 浮层所在的父容器的大小,也即`self.view.bounds`
* @arg keyboardHeight 键盘在当前界面里的高度,若无键盘,则为0
* @arg contentViewFrame 动画执行完后`contentView`的最终frame,若使用了`layoutBlock`,则也即`layoutBlock`计算完后的frame
* @arg completion 动画结束后给到modalController的回调,modalController会在这个回调里做一些状态设置,务必调用。
*/
var showingAnimationClosure: ((_ dimmingView: UIView?, _ containerBounds: CGRect, _ keyboardHeight: CGFloat, _ contentViewFrame: CGRect, _ completion: ((Bool) -> Void)?) -> Void)?
/**
* 管理自定义的隐藏动画,需要管理的对象包括`contentView`和`dimmingView`,在动画结束后,必须调用参数里的`completion` block。
* @arg dimmingView 背景遮罩的View,请自行设置隐藏遮罩的动画
* @arg containerBounds 浮层所在的父容器的大小,也即`self.view.bounds`
* @arg keyboardHeight 键盘在当前界面里的高度,若无键盘,则为0
* @arg completion 动画结束后给到modalController的回调,modalController会在这个回调里做一些清理工作,务必调用
*/
var hidingAnimationClosure: ((_ dimmingView: UIView?, _ containerBounds: CGRect, _ keyboardHeight: CGFloat, _ completion: ((Bool) -> Void)?) -> Void)?
private var containerWindow: QMUIModalPresentationWindow?
private weak var previousKeyWindow: UIWindow?
private var appearAnimated = false
private var appearCompletionClosure: ((Bool) -> Void)?
private var disappearAnimated = false
private var disappearCompletionClosure: ((Bool) -> Void)?
/// 标志是否已经走过一次viewWillAppear了,用于hideInView的情况
private var hasAlreadyViewWillDisappear = false
private var dimmingViewTapGestureRecognizer: UITapGestureRecognizer?
private var keyboardHeight: CGFloat = 0
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
didInitialized()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didInitialized()
}
private func didInitialized() {
animationStyle = .fade
contentViewMargins = UIEdgeInsets.init(top: 20, left: 20, bottom: 20, right: 20)
maximumContentViewWidth = QMUIHelper.screenSizeFor47Inch.width - contentViewMargins.horizontalValue
modalTransitionStyle = .crossDissolve
modalPresentationStyle = .custom
initDefaultDimmingViewWithoutAddToView()
}
override func awakeFromNib() {
super.awakeFromNib()
// 在 IB 里设置了 contentViewController 的话,通过这个调用去触发 contentView 的更新
if let contentViewController = self.contentViewController {
self.contentViewController = contentViewController
}
}
deinit {
containerWindow = nil
}
override var shouldAutomaticallyForwardAppearanceMethods: Bool {
// 屏蔽对childViewController的生命周期函数的自动调用,改为手动控制
return false
}
override func viewDidLoad() {
super.viewDidLoad()
if let dimmingView = dimmingView, dimmingView.superview == nil {
view.addSubview(dimmingView)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
dimmingView?.frame = view.bounds
let contentViewFrame = contentViewFrameForShowing
if let layoutClosure = layoutClosure {
layoutClosure(view.bounds, keyboardHeight, contentViewFrame)
} else {
contentView?.frame = contentViewFrame
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
var _animated = animated
if containerWindow != nil {
// 只有使用showWithAnimated:completion:显示出来的浮层,才需要修改之前就记住的animated的值
_animated = appearAnimated
}
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
if contentViewController != nil {
contentViewController!.qmui_modalPresentationViewController = self
contentViewController!.beginAppearanceTransition(true, animated: _animated)
}
// 如果是因为 present 了新的界面再从那边回来,导致走到 viewWillAppear,则后面那些升起浮层的操作都可以不用做了,因为浮层从来没被降下去过
let willAppearByPresentedViewController = isShowingPresentedViewController
if willAppearByPresentedViewController {
return
}
if isShownInWindowMode {
QMUIHelper.dimmedApplicationWindow()
}
let didShownCompletion: (Bool) -> Void = {
self.contentViewController?.endAppearanceTransition()
self.isVisible = true
if let appearCompletionClosure = self.appearCompletionClosure {
appearCompletionClosure($0)
self.appearCompletionClosure = nil
}
self.appearAnimated = false
}
if _animated {
view.addSubview(contentView!)
view.layoutIfNeeded()
var contentViewFrame = contentViewFrameForShowing
if let showingAnimationClosure = showingAnimationClosure {
// 使用自定义的动画
if let layoutClosure = layoutClosure {
layoutClosure(view.bounds, keyboardHeight, contentViewFrame)
contentViewFrame = contentView!.frame
}
showingAnimationClosure(dimmingView, view.bounds, keyboardHeight, contentViewFrame, didShownCompletion)
} else {
contentView?.frame = contentViewFrame
contentView?.setNeedsLayout()
contentView?.layoutIfNeeded()
showingAnimation(didShownCompletion)
}
} else {
let contentViewFrame = contentViewFrameForShowing
contentView?.frame = contentViewFrame
view.addSubview(contentView!)
dimmingView?.alpha = 1
didShownCompletion(true)
}
}
override func viewWillDisappear(_ animated: Bool) {
if hasAlreadyViewWillDisappear {
return
}
super.viewWillDisappear(animated)
var _animated = animated
if isShownInWindowMode {
_animated = disappearAnimated
}
let willDisappearByPresentedViewController = isShowingPresentedViewController
if !willDisappearByPresentedViewController {
delegate?.willHide?(modalPresentationViewController: self)
}
// 在降下键盘前取消对键盘事件的监听,从而避免键盘影响隐藏浮层的动画
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
// 如果是因为 present 了新的界面导致走到 willDisappear,则后面那些降下浮层的操作都可以不用做了
if willDisappearByPresentedViewController {
return
}
if isShownInWindowMode {
QMUIHelper.resetDimmedApplicationWindow()
}
contentViewController?.beginAppearanceTransition(false, animated: _animated)
let didHiddenCompletion: (Bool) -> Void = {_ in
if self.isShownInWindowMode {
// 恢复 keyWindow 之前做一下检查,避免这个问题 https://github.com/QMUI/QMUI_iOS/issues/90
if UIApplication.shared.keyWindow == self.containerWindow {
self.previousKeyWindow?.makeKey()
}
self.containerWindow?.isHidden = true
self.containerWindow?.rootViewController = nil
self.previousKeyWindow = nil
self.endAppearanceTransition()
}
if self.isShownInSubviewMode {
// 这句是给addSubview的形式显示的情况下使用,但会触发第二次viewWillDisappear:,所以要搭配self.hasAlreadyViewWillDisappear使用
self.view.removeFromSuperview()
self.hasAlreadyViewWillDisappear = false
}
self.contentView?.removeFromSuperview()
self.contentViewController?.endAppearanceTransition()
self.isVisible = false
self.delegate?.didHide?(modalPresentationViewController: self)
if let disappearCompletionClosure = self.disappearCompletionClosure {
disappearCompletionClosure(true)
self.disappearCompletionClosure = nil
}
if self.contentViewController != nil {
self.contentViewController!.qmui_modalPresentationViewController = nil
self.contentViewController = nil
}
self.disappearAnimated = false
}
if _animated {
if let hidingAnimationClosure = hidingAnimationClosure {
hidingAnimationClosure(dimmingView, view.bounds, keyboardHeight, didHiddenCompletion)
} else {
hidingAnimation(didHiddenCompletion)
}
} else {
didHiddenCompletion(true)
}
}
private func initDefaultDimmingViewWithoutAddToView() {
guard dimmingView == nil else {
return
}
dimmingView = UIView()
dimmingView!.backgroundColor = UIColorMask
addTapGestureRecognizerToDimmingViewIfNeeded()
if isViewLoaded {
view.addSubview(dimmingView!)
}
}
// 要考虑用户可能创建了自己的dimmingView,则tap手势也要重新添加上去
private func addTapGestureRecognizerToDimmingViewIfNeeded() {
guard let dimmingView = dimmingView else { return }
if dimmingViewTapGestureRecognizer?.view == dimmingView {
return
}
if dimmingViewTapGestureRecognizer == nil {
dimmingViewTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDimmingViewTapGestureRecognizer(_:)))
}
dimmingView.addGestureRecognizer(dimmingViewTapGestureRecognizer!)
dimmingView.isUserInteractionEnabled = true // UIImageView默认userInteractionEnabled为NO,为了兼容UIImageView,这里必须主动设置为YES
}
@objc func handleDimmingViewTapGestureRecognizer(_: UITapGestureRecognizer) {
if isModal {
return
}
if isShownInWindowMode {
hide(true, completion: { [weak self] _ in
self?.didHideByDimmingViewTappedClosure?()
})
} else if isShownInPresentedMode {
dismiss(animated: true) {
self.didHideByDimmingViewTappedClosure?()
}
} else if isShownInSubviewMode {
hide(in: view.superview!, animated: true) { [weak self] _ in
self?.didHideByDimmingViewTappedClosure?()
}
}
}
/**
* 请求重新计算浮层的布局
*/
func updateLayout() {
if isViewLoaded {
view.setNeedsLayout()
}
}
// MARK: - Showing and Hiding
private func showingAnimation(_ completion: ((Bool) -> Void)?) {
if animationStyle == .fade {
dimmingView?.alpha = 0.0
contentView?.alpha = 0.0
UIView.animate(withDuration: 0.2, delay: 0, options: .curveOut, animations: {
self.dimmingView?.alpha = 1.0
self.contentView?.alpha = 1.0
}, completion: completion)
} else if animationStyle == .popup {
dimmingView?.alpha = 0.0
contentView?.transform = CGAffineTransform(scaleX: 0, y: 0)
UIView.animate(withDuration: 0.3, delay: 0, options: .curveOut, animations: {
self.dimmingView?.alpha = 1.0
self.contentView?.transform = CGAffineTransform(scaleX: 1, y: 1)
}, completion: { finished in
self.contentView?.transform = .identity
completion?(finished)
})
} else if animationStyle == .slide {
dimmingView?.alpha = 0.0
contentView?.transform = CGAffineTransform(translationX: 0, y: view.bounds.height - contentView!.frame.minY)
UIView.animate(withDuration: 0.3, delay: 0, options: .curveOut, animations: {
self.dimmingView?.alpha = 1.0
self.contentView?.transform = .identity
}, completion: completion)
}
}
/**
* 将浮层以 UIWindow 的方式显示出来
* @param animated 是否以动画的形式显示
* @param completion 显示动画结束后的回调
*/
func show(_ animated: Bool, completion: ((Bool) -> Void)?) {
// makeKeyAndVisible 导致的 viewWillAppear: 必定 animated 是 NO 的,所以这里用额外的变量保存这个 animated 的值
appearAnimated = animated
appearCompletionClosure = completion
previousKeyWindow = UIApplication.shared.keyWindow
if containerWindow == nil {
containerWindow = QMUIModalPresentationWindow()
containerWindow?.windowLevel = UIWindow.Level(rawValue: UIWindowLevelQMUIAlertView)
containerWindow?.backgroundColor = UIColorClear // 避免横竖屏旋转时出现黑色
}
supportedOrientationMask = QMUIHelper.visibleViewController?.supportedInterfaceOrientations ?? supportedOrientationMask
containerWindow?.rootViewController = self
containerWindow?.makeKeyAndVisible()
}
private func hidingAnimation(_ completion: ((Bool) -> Void)?) {
if animationStyle == .fade {
UIView.animate(withDuration: 0.2, delay: 0, options: .curveOut, animations: {
self.dimmingView?.alpha = 0.0
self.contentView?.alpha = 0.0
}, completion: completion)
} else if animationStyle == .popup {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveOut, animations: {
self.dimmingView?.alpha = 0.0
self.contentView?.transform = CGAffineTransform(scaleX: 0, y: 0)
}, completion: { finished in
if let completion = completion {
self.contentView?.transform = .identity
completion(finished)
}
})
} else if animationStyle == .slide {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveOut, animations: {
self.dimmingView?.alpha = 0.0
self.contentView?.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height - self.contentView!.frame.minY)
}, completion: { finished in
if let completion = completion {
self.contentView?.transform = .identity
completion(finished)
}
})
}
}
/**
* 将浮层隐藏掉
* @param animated 是否以动画的形式隐藏
* @param completion 隐藏动画结束后的回调
* @warning 这里的`completion`只会在你显式调用`hideWithAnimated:completion:`方法来隐藏浮层时会被调用,如果你通过点击`dimmingView`来触发`hideWithAnimated:completion:`,则completion是不会被调用的,那种情况下如果你要在浮层隐藏后做一些事情,请使用`delegate`提供的`didHideModalPresentationViewController:`方法。
*/
func hide(_ animated: Bool, completion: ((Bool) -> Void)?) {
disappearAnimated = animated
disappearCompletionClosure = completion
let shouldHide = delegate?.shouldHide?(modalPresentationViewController: self) ?? true
if !shouldHide {
return
}
// window模式下,通过手动触发viewWillDisappear:来做界面消失的逻辑
if containerWindow != nil {
beginAppearanceTransition(false, animated: animated)
}
}
/**
* 将浮层以 addSubview 的方式显示出来
*
* @param view 要显示到哪个 view 上
* @param animated 是否以动画的形式显示
* @param completion 显示动画结束后的回调
*/
func show(in view: UIView, animated: Bool, completion: ((Bool) -> Void)?) {
appearCompletionClosure = completion
if #available(iOS 9.0, *) {
loadViewIfNeeded()
}
beginAppearanceTransition(true, animated: animated)
view.addSubview(self.view)
endAppearanceTransition()
}
/**
* 将某个 view 上显示的浮层隐藏掉
* @param view 要隐藏哪个 view 上的浮层
* @param animated 是否以动画的形式隐藏
* @param completion 隐藏动画结束后的回调
* @warning 这里的`completion`只会在你显式调用`hideInView:animated:completion:`方法来隐藏浮层时会被调用,如果你通过点击`dimmingView`来触发`hideInView:animated:completion:`,则completion是不会被调用的,那种情况下如果你要在浮层隐藏后做一些事情,请使用`delegate`提供的`didHideModalPresentationViewController:`方法。
*/
func hide(in view: UIView, animated: Bool, completion: ((Bool) -> Void)?) {
disappearCompletionClosure = completion
beginAppearanceTransition(false, animated: animated)
hasAlreadyViewWillDisappear = true
endAppearanceTransition()
}
private var contentViewFrameForShowing: CGRect {
let contentViewContainerSize = CGSize(width: view.bounds.width - contentViewMargins.horizontalValue, height: view.bounds.height - keyboardHeight - contentViewMargins.verticalValue)
let contentViewLimitSize = CGSize(width: min(maximumContentViewWidth, contentViewContainerSize.width), height: contentViewContainerSize.height)
var contentViewSize = CGSize.zero
if let contentViewController = contentViewController {
contentViewSize = contentViewController.preferredContentSize?(inModalPresentationViewController: self, limitSize: contentViewLimitSize) ?? .zero
} else {
contentViewSize = contentView!.sizeThatFits(contentViewLimitSize)
}
contentViewSize.width = min(contentViewLimitSize.width, contentViewSize.width)
contentViewSize.height = min(contentViewLimitSize.height, contentViewSize.height)
var contentViewFrame = CGRect(x: contentViewContainerSize.width.center(contentViewSize.width) + contentViewMargins.left,
y: contentViewContainerSize.height.center(contentViewSize.height) + contentViewMargins.top,
width: contentViewSize.width,
height: contentViewSize.height)
// showingAnimation、hidingAnimation里会通过设置contentView的transform来做动画,所以可能在showing的过程中设置了transform后,系统触发viewDidLayoutSubviews,在viewDidLayoutSubviews里计算的frame又是最终状态的frame,与showing时的transform冲突,导致动画过程中浮层跳动或者位置错误,所以为了保证layout时计算出来的frame与showing/hiding时计算的frame一致,这里给frame应用了transform。但这种处理方法也有局限:如果你在showingAnimation/hidingAnimation里对contentView.frame的更改不是通过修改transform而是直接修改frame来得到结果,那么这里这句CGRectApplyAffineTransform就没用了,viewDidLayoutSubviews里算出来的frame依然会和showingAnimation/hidingAnimation冲突。
contentViewFrame = contentViewFrame.applying(contentView!.transform)
return contentViewFrame
}
// MARK: - Keyboard
@objc func handleKeyboardWillShow(_ notification: Notification) {
let keyboardHeight = QMUIHelper.keyboardHeight(notification, in: view)
if keyboardHeight > 0 {
self.keyboardHeight = keyboardHeight
view.setNeedsLayout()
}
}
@objc func handleKeyboardWillHide(_ notification: NSNotification) {
keyboardHeight = 0
view.setNeedsLayout()
}
// MARK: - 屏幕旋转
override var shouldAutorotate: Bool {
let visibleViewController = QMUIHelper.visibleViewController
if visibleViewController != self {
return visibleViewController?.shouldAutorotate ?? true
}
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
let visibleViewController = QMUIHelper.visibleViewController
if visibleViewController != self {
return visibleViewController?.supportedInterfaceOrientations ?? supportedOrientationMask
}
return supportedOrientationMask
}
// MARK: - 屏幕旋转
override var preferredStatusBarStyle: UIStatusBarStyle {
let style: UIStatusBarStyle = StatusbarStyleLightInitially ? .lightContent : .default
return style
}
}
// MARK: - Manager
extension QMUIModalPresentationViewController {
/**
* 判断当前App里是否有modalViewController正在显示(存在modalViewController但不可见的时候,也视为不存在)
* @return 只要存在正在显示的浮层,则返回true,否则返回false
*/
static var isAnyModalPresentationViewControllerVisible: Bool {
for window in UIApplication.shared.windows {
if window is QMUIModalPresentationWindow && !window.isHidden {
return true
}
}
return false
}
/**
* 把所有正在显示的并且允许被隐藏的modalViewController都隐藏掉
* @return 只要遇到一个正在显示的并且不能被隐藏的浮层,就会返回false,否则都返回true,表示成功隐藏掉所有可视浮层
* @see shouldHideModalPresentationViewController:
*/
static var hideAllVisibleModalPresentationViewControllerIfCan: Bool {
var hideAllFinally = true
for window in UIApplication.shared.windows {
if !(window is QMUIModalPresentationWindow) {
continue
}
// 存在modalViewController,但并没有显示出来,所以不用处理
if window.isHidden {
continue
}
// 存在window,但不存在modalViewController,则直接把这个window移除
if window.rootViewController == nil {
window.isHidden = true
continue
}
let modalViewController = window.rootViewController as? QMUIModalPresentationViewController
let canHide = modalViewController?.delegate?.shouldHide?(modalPresentationViewController: modalViewController!) ?? true
if canHide {
if let delegate = modalViewController?.delegate {
delegate.requestHideAllModalPresentationViewController?()
} else {
modalViewController!.hide(false, completion: nil)
}
} else {
// 只要有一个modalViewController正在显示但却无法被隐藏,就返回NO
hideAllFinally = false
}
}
return hideAllFinally
}
}
/// 专用于QMUIModalPresentationViewController的UIWindow,这样才能在`[[UIApplication sharedApplication] windows]`里方便地区分出来
fileprivate class QMUIModalPresentationWindow: UIWindow {}
extension UIViewController {
private struct Keys {
static var modalPresentationViewController = "ModalPresentationViewController"
}
fileprivate(set) var qmui_modalPresentationViewController: QMUIModalPresentationViewController? {
set {
if let vc = newValue {
objc_setAssociatedObject(self, &Keys.modalPresentationViewController, vc, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
get {
return objc_getAssociatedObject(self, &Keys.modalPresentationViewController) as? QMUIModalPresentationViewController
}
}
}
| mit | a195b4365d860336bcb3bff626c35954 | 39.009067 | 495 | 0.664487 | 4.925371 | false | false | false | false |
quver/Queryable | QueryableTests/QueryableTests.swift | 1 | 3253 | //
// QueryableTests.swift
// QueryableTests
//
// Created by Pawel Bednorz on 02.12.2016.
// Copyright © 2016 Quver.net. All rights reserved.
//
import Quick
import Nimble
import RealmSwift
@testable import Queryable
class TestEntity: Object, Queryable {
typealias Model = TestEntity
dynamic var number = 0
dynamic var text = ""
}
class QueryableTests: QuickSpec {
private let someNumber = 1
private let someString = "Lorem ipsum"
private let otherNumber = 2
private let otherString = "Love Swift"
private func someObject() -> TestEntity {
let object = TestEntity()
object.number = someNumber
object.text = someString
return object
}
private func otherObject() -> TestEntity {
let object = TestEntity()
object.number = otherNumber
object.text = otherString
return object
}
override func spec() {
beforeEach {
QueryManager.removeAll()
}
context("add object") {
it("is containing it") {
let someObject = self.someObject()
someObject.add()
expect(TestEntity.arrayOfObject).to(contain(someObject))
}
it("is not containing other") {
let otherObject = self.otherObject()
let someObject = self.someObject()
someObject.add()
expect(TestEntity.arrayOfObject).notTo(contain(otherObject))
}
it("has only one object") {
let someObject = self.someObject()
someObject.add()
expect(TestEntity.arrayOfObject).to(haveCount(1))
}
}
context("edit object") {
it("change property") {
let someObject = self.someObject()
someObject.add()
someObject.update(transaction: {
someObject.text = self.otherString
}, completion: nil)
expect(TestEntity.arrayOfObject.first!.text).to(equal(self.otherString))
}
it("has only one object") {
let someObject = self.someObject()
someObject.add()
someObject.update(transaction: {
someObject.text = self.otherString
}, completion: nil)
expect(TestEntity.arrayOfObject).to(haveCount(1))
}
}
context("remove object") {
it("one left") {
let someObject = self.someObject()
someObject.add()
let otherObject = self.otherObject()
otherObject.add()
someObject.remove()
expect(TestEntity.arrayOfObject).to(contain(otherObject))
}
}
context("get objects") {
beforeEach {
self.someObject().add()
self.otherObject().add()
}
context("to array") {
it("all objects") {
expect(TestEntity.arrayOfObject).to(haveCount(2))
}
it("with filter") {
let filtered = TestEntity.filtredArray("text == '\(self.otherString)'")
expect(filtered.first!.text).to(equal(self.otherString))
}
}
context("to result") {
it("all objects") {
expect(TestEntity.resultsOfObject).to(haveCount(2))
}
it("with filter") {
let filtered = TestEntity.filtredResults("text == '\(self.otherString)'")
expect(filtered.first!.text).to(equal(self.otherString))
}
}
}
}
}
| mit | 440e81b9732a3b13d865baa281763f84 | 21.427586 | 83 | 0.604244 | 4.516667 | false | true | false | false |
AlphaJian/PaperCalculator | PaperCalculator/PaperCalculator/Views/Review/PopSelectionScoreView.swift | 1 | 2407 | //
// PopSelectionScoreView.swift
// PaperCalculator
//
// Created by Jian Zhang on 9/29/16.
// Copyright © 2016 apple. All rights reserved.
//
import UIKit
class PopSelectionScoreView: UIView {
var btnHandler : ReturnBlock?
func initUI(score : Float){
let bg = UIView(frame: self.bounds)
bg.backgroundColor = UIColor.black
bg.alpha = 0.8
self.addSubview(bg)
let padding = 20
let container = UIScrollView(frame: CGRect(x: padding, y: 0, width: Int(self.width()) - padding * 2, height: Int(self.height()) - 2 * padding))
self.addSubview(container)
var originX = padding
var originY = padding
var width = (Int(container.width()) - padding * 4) / 3
var height = 0
if score < 6 {
originY = 150
} else if score < 9 {
originY = 100
}
if Int(score) % 3 == 0
{
height = (width + padding) * (Int(score) / 3)
}
else
{
height = (width + padding) * (Int(score) / 3 + 1)
}
container.contentSize = CGSize(width: Int(container.width()), height: height)
for i in 0 ... Int(score) {
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: originX, y: originY, width: width, height: width)
btn.backgroundColor = UIColor.white
btn.setTitleColor(lightBlue, for: .normal)
btn.layer.cornerRadius = btn.width() / 2
btn.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: UIFontWeightMedium)
// btn.layer.borderWidth = 2
// btn.layer.borderColor = lightBlue.cgColor
btn.addTarget(self, action: #selector(PopSelectionScoreView.btnTapped(_:)), for: .touchUpInside)
btn.tag = 10 + Int(score) - i
btn.setTitle("\(Int(score) - i)", for: .normal)
container.addSubview(btn)
originX = Int(btn.right()) + padding
if originX + width > Int(container.width())
{
originX = padding
originY = Int(btn.bottom()) + padding
}
}
}
func btnTapped(_ sender : UIButton)
{
if btnHandler != nil
{
btnHandler!(sender.tag - 10 as AnyObject)
}
}
}
| gpl-3.0 | cb56463bf8eda998d917dfa772c98ba0 | 29.455696 | 151 | 0.526185 | 4.281139 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/Markup/Keyboard/KeyboardKey.swift | 1 | 1482 | //
// KeyboardKey.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
/// Represents a single key of a MarkupKeyboard.
public struct MarkupKeyboardKey: Codable, Equatable {
/// The text displayed on the button. If no other optional is used, this will be sent to the bot when pressed.
public var text: String
/// (Optional) If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only.
public var requestContact: Bool = false
// (Optional) If True, the user's current location will be sent when the button is pressed. Available in private chats only.
public var requestLocation: Bool = false
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case text
case requestContact = "request_contact"
case requestLocation = "request_location"
}
init(text: String) {
self.text = text
}
init(withLocationRequest requestLocation: Bool, text: String) {
self.text = text
self.requestLocation = requestLocation
}
init(withContactRequest requestContact: Bool, text: String) {
self.text = text
self.requestContact = requestContact
}
static public func ==(lhs: MarkupKeyboardKey, rhs: MarkupKeyboardKey) -> Bool {
if lhs.text != rhs.text { return false }
if lhs.requestContact != rhs.requestContact { return false }
if lhs.requestLocation != rhs.requestLocation { return false }
return true
}
}
| mit | e6ab3a60d29380eedc8bd9e6483311d3 | 26.962264 | 135 | 0.726046 | 3.941489 | false | false | false | false |
wookay/Look | samples/LookSample/Pods/C4/C4/UI/C4Gradient.swift | 3 | 4543 | // Copyright © 2015 C4
//
// 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
///The C4Gradient class draws a color gradient over its background color, filling the shape of the view (including rounded corners).
public class C4Gradient : C4View {
class GradientView : UIView {
var gradientLayer: C4GradientLayer {
get {
return self.layer as! C4GradientLayer
}
}
override class func layerClass() -> AnyClass {
return C4GradientLayer.self
}
}
///The background layer of the receiver.
public var gradientLayer: C4GradientLayer {
get {
return self.gradientView.gradientLayer
}
}
var gradientView: GradientView {
return self.view as! GradientView
}
///An array of C4Color objects defining the color of each gradient stop. Animatable.
public var colors : [C4Color] {
get {
if let cgcolors = gradientLayer.colors as? [CGColorRef] {
var array = [C4Color]()
for c in cgcolors {
array.append(C4Color(c))
}
return array
}
return [C4Blue,C4Pink]
} set {
assert(newValue.count >= 2, "colors must have at least 2 elements")
var cgcolors = [CGColorRef]()
for c in newValue {
cgcolors.append(c.CGColor)
}
self.gradientLayer.colors = cgcolors
}
}
///An optional array of Double values defining the location of each gradient stop. Animatable.
///
///Defaults to [0,1]
public var locations : [Double] {
get {
return gradientLayer.locations as! [Double]
} set {
var numbers = [NSNumber]()
for n in newValue {
numbers.append(n)
}
gradientLayer.locations = numbers
}
}
///The start point of the gradient when drawn in the layer’s coordinate space. Animatable.
///
///Defaults to the top-left corner of the frame {0.0,0.0}
public var startPoint : C4Point {
get {
return C4Point(gradientLayer.startPoint)
} set {
gradientLayer.startPoint = CGPoint(newValue)
}
}
///The end point of the gradient when drawn in the layer’s coordinate space. Animatable.
///
///Defaults to the top-right corner of the frame {1.0,0.0}
public var endPoint : C4Point {
get {
return C4Point(gradientLayer.endPoint)
} set {
gradientLayer.endPoint = CGPoint(newValue)
}
}
/// Initializes a new C4Gradient.
///
/// - parameter frame: A C4Rect that defines the frame for the gradient's view.
/// - parameter colors: An array of C4Color objects that define the gradient's colors. Defaults to [C4Blue, C4Purple].
/// - parameter locations: An array of Double values that define the location of each gradient stop. Defaults to [0,1]
public convenience init(frame: C4Rect, colors: [C4Color] = [C4Blue, C4Purple], locations: [Double] = [0,1]) {
assert(colors.count == locations.count, "colors and locations need to have the same number of elements")
self.init()
self.view = GradientView(frame: CGRect(frame))
self.colors = colors
self.locations = locations
self.startPoint = C4Point()
self.endPoint = C4Point(1,0)
}
} | mit | be38109e70225061a00bf911a6e15f9e | 37.142857 | 132 | 0.62825 | 4.574597 | false | false | false | false |
slightair/syu | Syu/Entity/SearchIndex.swift | 1 | 423 | import Foundation
import SQLite
struct SearchIndex {
struct Column {
static let id = Expression<Int64>("id")
static let name = Expression<String>("name")
static let type = Expression<Int64>("type")
static let requestKey = Expression<String>("request_key")
}
enum type: Int {
case unknown = 1
}
let name: String
let type: Int64
let requestKey: String
}
| mit | dd05f0cb7e9d6eab33312b7d5e9dc6dd | 21.263158 | 65 | 0.619385 | 4.316327 | false | false | false | false |
youpy/ruby-objc-swift-extension-example | ext/hello/hello_class.swift | 1 | 3256 | typealias RbMethodPointer = CFunctionPointer<(() -> VALUE)>
typealias RbFreePointer = CFunctionPointer<((UnsafeMutablePointer<Void>) -> Void)>
typealias RbMethod0 = @objc_block (VALUE) -> VALUE
typealias RbMethod1 = @objc_block (VALUE, VALUE) -> VALUE
typealias RbMethod2 = @objc_block (VALUE, VALUE, VALUE) -> VALUE
// RbMethod3, RbMethod4...
typealias RbFree = @objc_block (UnsafePointer<mytype>) -> Void
class RbInternal: NSObject {
static func initRb() {
let rb_mHello = rb_define_module("Hello")
let rb_cSwiftObject = rb_define_class("SwiftObject", rb_cObject)
let rb_cWorld = rb_define_class_under(rb_mHello, "World", rb_cSwiftObject)
var pool = [String: Hello]()
let rb_free: RbFree = {
(mytype) in
let description = String.fromCString(mytype.memory.description)
free(unsafeBitCast(mytype, UnsafeMutablePointer<Void>.self))
pool.removeValueForKey(description!)
NSLog("rb_free(): pool count: %d", pool.count)
}
let greeting: RbMethod1 = {
(_self, name) in
let description = String.fromCString(__Data_Get_Struct(_self))
let hello: Hello = pool[description!]!
return self.string2RbString(
hello.greeting(self.rbString2String(name)!)
)
}
let new: RbMethod0 = {
(_self) in
var hello = Hello()
var val:VALUE = __Data_Wrap_Struct(rb_cWorld, (hello.description as NSString).UTF8String, self.convertBlock2RbMethodPointer(rb_free))
pool[hello.description] = hello
return val
}
self.defineMethod(rb_cWorld, name:"greeting", block:greeting)
// TODO: fix arguments
self.defineSingletonMethod(rb_cWorld, name:"new", block:new)
}
static func defineMethod<T>(klass: VALUE, name: String, block: T) {
rb_define_method(klass, "__swift_\(name)", self.convertBlock2RbMethodPointer(block), self.getArgc(block))
}
static func defineSingletonMethod<T>(klass: VALUE, name: String, block: T) {
rb_define_singleton_method(klass, name, self.convertBlock2RbMethodPointer(block), self.getArgc(block))
}
// http://stackoverflow.com/a/29375116
static func convertBlock2RbMethodPointer<T, R>(block: T) -> R {
let imp: COpaquePointer = imp_implementationWithBlock(unsafeBitCast(block, AnyObject.self))
let callback: R = unsafeBitCast(imp, R.self)
return callback
}
static func rbString2String(rbStr: VALUE) -> String? {
return String.fromCString(__rbString2CString(rbStr))
}
static func string2RbString(str: String) -> VALUE {
return rb_str_new_cstr(str)
}
static func getArgc<T>(block: T) -> Int32 {
let argc: Int32
switch block {
case is RbMethod0:
argc = 1
break
case is RbMethod1:
argc = 2
break
case is RbMethod2:
argc = 3
break
default:
argc = 0
}
return argc
}
}
class Hello: NSObject {
func greeting(name: String?) -> String {
return "hello, \(name!)!"
}
}
| mit | 97b28d58e79514ebeae8264a14492c20 | 30.307692 | 145 | 0.604423 | 4.04472 | false | false | false | false |
alexwinston/UIViewprint | UIViewprint/ViewController10.swift | 1 | 4123 | //
// ViewController10.swift
// Blueprint
//
// Created by Alex Winston on 2/11/16.
// Copyright © 2016 Alex Winston. All rights reserved.
//
import Foundation
import UIKit
infix operator < { associativity left }
func input(placeholder placeholder:String, style:UIViewableStyle = UIViewableStyle(), appearance:((UITextField) -> Void)? = nil) -> UIViewable {
var textField:UITextField?
return input(&textField, placeholder:placeholder, style:style, appearance:appearance)
}
func input(inout id:UITextField?, placeholder:String, var style:UIViewableStyle = UIViewableStyle(), appearance:((UITextField) -> Void)? = nil) -> UIViewable {
let textField = UITextField()
textField.placeholder = placeholder
textField.sizeToFit()
if let appearance = appearance {
appearance(textField)
}
if style.display == nil {
style.display = .Flex(.Row)
}
if style.height != -1 {
style.height = textField.frame.height
}
let viewable = UIViewable(style:style)
viewable.addSubview(textField)
id = textField
return div(style, subviews:[viewable])
}
// UIViewableStyle helper functions
func align(align:UIViewableAlign) -> UIViewableStyle {
return UIViewableStyle(align:align)
}
class ViewController10: UIViewableController {
var instructionsLabel:UIViewable?
var emailTextField:UITextField?
var passwordTextField:UITextField?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Example 6"
self.edgesForExtendedLayout = UIRectEdge.None;
// self.view.addSubview(
// div(align(.Middle(.Left)),
// label(&instructionsLabel, text:"Please enter your login credentials.", style:align(.Top(.Center))).display(.Block),
// div(height(10)),
// div(.Flex(.Row),
// div(style(width:100),
// label("Email", style:align(.Top(.Right)))
// ),
// input(&emailTextField, placeholder:"[email protected]", appearance:roundedCorners)
// ),
// div(.Flex(.Row),
// div(style(width:100),
// label("Password", style:align(.Top(.Right)))
// ),
// input(placeholder:"", appearance:roundedCorners)
// ),
// div(height(10)),
// button("Login", display:.Flex(.Row), touch:login)
// )
// )
self.view.addSubview(
div(.Flex(.Column),
div(),
div(style(padding:(0,right:10,0,left:10)),
input(&emailTextField, placeholder:"Email", style:style(padding:(0,0,bottom:5,0)), appearance:largeFontRoundedCorners),
input(placeholder:"Password", appearance:largeFontRoundedCorners)
),
div(),
div(
button("Login", display:.Flex(.Row), align:.Bottom(.Left), height:80, touch:login)
)
)
)
}
func roundedCorners(textField:UITextField) {
textField.borderStyle = .RoundedRect
}
func login(button:UIButton) {
print(emailTextField!.text)
if let instructionsLabel = instructionsLabel?.subviews[0] as? UILabel {
instructionsLabel.text = "This is a test of the emergency broadcast system"
}
// self.view.subviews[0].setNeedsLayout()
if let superview = instructionsLabel?.superview as? UIViewable {
superview.setNeedsLayout()
}
}
func largeFontRoundedCorners(view:UIView) {
if let textField = view as? UITextField {
textField.borderStyle = .RoundedRect
textField.frame.size.height = 54
textField.font = UIFont(name: "HelveticaNeue-Light", size: 26)
textField.returnKeyType = .Done
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.debugSubviews(self.view, indent: "")
}
} | mit | 716a8bee09860a38e673e96d2a2b15c4 | 32.520325 | 159 | 0.584668 | 4.694761 | false | false | false | false |
crazypoo/PTools | Pods/SnapshotKit/SnapshotKit/Classes/UIScrollView+Snapshot.swift | 1 | 3168 | //
// UIScrollView+Snapshot.swift
// SnapshotKit
//
// Created by York on 2018/9/9.
//
import UIKit
extension UIScrollView {
override
public func takeSnapshotOfVisibleContent() -> UIImage? {
// 获取当前可视区域的rect
var visibleRect = self.bounds
visibleRect.origin = self.contentOffset
return self.takeSnapshotOfFullContent(for: visibleRect)
}
override
public func takeSnapshotOfFullContent() -> UIImage? {
let originalFrame = self.frame
let originalOffset = self.contentOffset
self.frame = CGRect.init(origin: originalFrame.origin, size: self.contentSize)
self.contentOffset = .zero
let backgroundColor = self.backgroundColor ?? UIColor.white
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.setFillColor(backgroundColor.cgColor)
context.setStrokeColor(backgroundColor.cgColor)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.frame = originalFrame
self.contentOffset = originalOffset
return image
}
override
public func asyncTakeSnapshotOfFullContent(_ completion: @escaping ((UIImage?) -> Void)) {
// 分页绘制内容到ImageContext
let originalOffset = self.contentOffset
// 当contentSize.height<bounds.height时,保证至少有1页的内容绘制
var pageNum = 1
if self.contentSize.height > self.bounds.height {
pageNum = Int(floorf(Float(self.contentSize.height / self.bounds.height)))
}
let backgroundColor = self.backgroundColor ?? UIColor.white
UIGraphicsBeginImageContextWithOptions(self.contentSize, true, 0)
guard let context = UIGraphicsGetCurrentContext() else {
completion(nil)
return
}
context.setFillColor(backgroundColor.cgColor)
context.setStrokeColor(backgroundColor.cgColor)
self.drawScreenshotOfPageContent(0, maxIndex: pageNum) {
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.contentOffset = originalOffset
completion(image)
}
}
fileprivate func drawScreenshotOfPageContent(_ index: Int, maxIndex: Int, completion: @escaping () -> Void) {
self.setContentOffset(CGPoint(x: 0, y: CGFloat(index) * self.frame.size.height), animated: false)
let pageFrame = CGRect(x: 0, y: CGFloat(index) * self.frame.size.height, width: self.bounds.size.width, height: self.bounds.size.height)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
self.drawHierarchy(in: pageFrame, afterScreenUpdates: true)
if index < maxIndex {
self.drawScreenshotOfPageContent(index + 1, maxIndex: maxIndex, completion: completion)
}else{
completion()
}
}
}
}
| mit | bdee523028c564a4c07d74febefc4ea1 | 32.06383 | 144 | 0.661519 | 5.061889 | false | false | false | false |
crazypoo/PTools | Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift | 2 | 2026 | //
// CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
// Electronic codebook (ECB)
//
public struct ECB: BlockMode {
public let options: BlockModeOption = .paddingRequired
public let customBlockSize: Int? = nil
public init() {
}
public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
ECBModeWorker(blockSize: blockSize, cipherOperation: cipherOperation)
}
}
struct ECBModeWorker: BlockModeWorker {
typealias Element = Array<UInt8>
let cipherOperation: CipherOperationOnBlock
let blockSize: Int
let additionalBufferSize: Int = 0
init(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) {
self.blockSize = blockSize
self.cipherOperation = cipherOperation
}
@inlinable
mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
guard let ciphertext = cipherOperation(plaintext) else {
return Array(plaintext)
}
return ciphertext
}
mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
self.encrypt(block: ciphertext)
}
}
| mit | a9f04c85dded7b5f733ca254883784c6 | 37.207547 | 217 | 0.756049 | 4.612756 | false | false | false | false |
justbaum30/NoteifyMe | NoteifyMeCommons/NoteBusinessService.swift | 1 | 2418 | //
// NoteBusinessService.swift
// NoteifyMe
//
// Created by Justin Baumgartner on 1/5/15.
// Copyright (c) 2015 Justin Baumgartner. All rights reserved.
//
import UIKit
public class NoteBusinessService: NSObject {
private struct Constants {
static let appGroupName = "group.justbaumdev.NoteifyMe"
static let notesKey = "notes"
}
// MARK: Public methods
public class func getNotes() -> [Note] {
let store = sharedDefaults()
if let notesData = store.objectForKey(Constants.notesKey) as? NSData {
return NSKeyedUnarchiver.unarchiveObjectWithData(notesData) as [Note]
}
return []
}
public class func getNote(uuid: String) -> Note? {
let notes = getNotes()
for note in notes {
if note.uuid == uuid {
return note
}
}
return nil
}
public class func saveNotes(notes: [Note]) {
let store = sharedDefaults()
store.setObject(NSKeyedArchiver.archivedDataWithRootObject(notes), forKey: Constants.notesKey)
store.synchronize()
}
public class func saveNote(note: Note) {
var notes = getNotes()
for var index = 0; index < notes.count; ++index {
let oldNote = notes[index]
if oldNote.uuid == note.uuid {
notes[index] = note
break
}
}
saveNotes(notes)
}
public class func addNote(note: Note) {
var notes = getNotes()
notes.append(note)
saveNotes(notes)
}
public class func deleteNote(uuid: String) {
var notes = getNotes()
let noteToDeleteOpt = getNote(uuid)
if let noteToDelete = noteToDeleteOpt {
for var index = 0; index < notes.count; ++index {
if notes[index].uuid == uuid {
notes.removeAtIndex(index)
saveNotes(notes)
return
}
}
}
}
public class func deleteNotes() {
let store = sharedDefaults()
store.removeObjectForKey(Constants.notesKey)
store.synchronize()
}
// MARK: Private helper methods
private class func sharedDefaults() -> NSUserDefaults {
return NSUserDefaults(suiteName: Constants.appGroupName)!
}
}
| mit | ca5e4efda7e052c9129fbcbedfcf5fc1 | 26.168539 | 102 | 0.558726 | 4.70428 | false | false | false | false |
Plopix/PlopixKonamiCodeGesture | PlopixKonamiGesture.swift | 1 | 7345 | /*
* This file is part of the PlopixKonamiGesture package.
*
* (c) Sébastien Morel aka Plopix <[email protected]>
*
* For the full copyright and license information(MIT), please view the LICENSE
* file that was distributed with this source code.
*/
import UIKit
import UIKit.UIGestureRecognizerSubclass
/**
Allow you to track the KomamiTouchCode
Up,up,Down,Down,Left,Right,Left,Right,Tap,Tap
We transform BA by Tap Tap for obvious simple reason
*/
class PlopixKonamiGesture: UIGestureRecognizer {
/**
Take care of the direction vectors
*/
struct Direction {
var up: CGVector
var down: CGVector
var left: CGVector
var right: CGVector
var neutral: CGVector
init() {
neutral = CGVectorMake( 0, 0 )
up = CGVectorMake( 0, -1 )
down = CGVectorMake( 0, 1 )
left = CGVectorMake( -1, 0 )
right = CGVectorMake( 1, 0 )
}
func isUp( vector: CGVector ) -> Bool {
return vector == self.up
}
func isDown( vector: CGVector ) -> Bool {
return vector == self.down
}
func isRight( vector: CGVector ) -> Bool {
return vector == self.right
}
func isLeft( vector: CGVector ) -> Bool {
return vector == self.left
}
func isNeutral( vector: CGVector ) -> Bool {
return vector == self.neutral
}
}
/**
Direction instance
*/
private let direction : Direction
/**
Configuration
*/
private let swipeDistanceTolerance : CGFloat = 50.0
private let swipeMinDistance : CGFloat = 50.0
/**
Store the Konami Code
*/
private var konamiCode: [CGVector] = []
/**
Store the user code
*/
private var currentCode : [CGVector] = []
/**
Store the starting point of the gesture
*/
private var startingPoint: CGPoint = CGPointZero
/**
init
*/
override init(target: AnyObject?, action: Selector) {
self.direction = Direction()
self.konamiCode = [
direction.up,direction.up,
direction.down,direction.down,
direction.left,direction.right,
direction.left,direction.right,
direction.neutral,direction.neutral]
super.init(target: target, action: action)
}
/**
Get the next vector
*/
private func nextVector() -> CGVector? {
let succeedGesture = currentCode.count
if ( succeedGesture == konamiCode.count) {
return nil;
}
return konamiCode[succeedGesture]
}
/**
Cancef if the user deviate
*/
private func isOnHisWay( point: CGPoint ) -> Bool {
let next: CGVector? = self.nextVector()
if (( next) == nil ) {
return true
}
if ( direction.isNeutral( next! ) ) {
return true;
}
let deltaX: CGFloat = point.x - startingPoint.x;
let deltaY: CGFloat = point.y - startingPoint.y;
// check the diversion
if ( direction.isUp( next! ) || direction.isDown( next! ) ) {
// next move in on Y, so we check X
if ( abs( deltaX ) > self.swipeDistanceTolerance ) {
return false;
}
}
if ( direction.isLeft( next! ) || direction.isRight( next! ) ) {
// next move in on X, so we check Y
if ( abs( deltaY ) > self.swipeDistanceTolerance ) {
return false;
}
}
// check the direction
if ( direction.isUp( next! ) ) {
if ( deltaY < 0 ) {
return true;
}
}
if ( direction.isDown( next! ) ) {
if ( deltaY > 0 ) {
return true;
}
}
if ( direction.isLeft( next! ) ) {
if ( deltaX < 0 ) {
return true;
}
}
if ( direction.isRight( next! ) ) {
if ( deltaX > 0 ) {
return true;
}
}
return false;
}
/**
We need at least a minimum distance
*/
private func hasReachMinDistance( point: CGPoint ) -> Bool {
let deltaX: CGFloat = point.x - startingPoint.x;
let deltaY: CGFloat = point.y - startingPoint.y;
let next: CGVector? = self.nextVector()
if (( next) == nil ) {
return true
}
if ( direction.isUp( next! ) || direction.isDown( next! ) ) {
if ( abs( deltaY ) > self.swipeMinDistance ) {
return true
}
}
if ( direction.isLeft( next! ) || direction.isRight( next! ) ) {
if ( abs( deltaX ) > self.swipeMinDistance ) {
return true
}
}
if ( direction.isNeutral( next! ) ) {
return true;
}
return false
}
/**
override method
This gesture doesn't prevent anything
*/
override func canPreventGestureRecognizer(preventedGestureRecognizer: UIGestureRecognizer) -> Bool {
return false;
}
/**
Touches Began
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {
if ( event.touchesForGestureRecognizer(self)?.count > 1 ) {
// give a direct failed when more than touches are detected
self.state = .Failed;
return
}
let touch:UITouch = touches.first!
self.startingPoint = touch.locationInView(self.view)
if ( self.state == .Changed ) {
// do nothing now
//@todo: add time check
return
}
if ( self.state == .Possible ) {
// only the first time
self.state = .Began;
return
}
self.state = .Failed;
}
/**
Touches Moved
*/
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
let touch:UITouch = touches.first!
if ( !self.isOnHisWay(touch.locationInView(self.view)) ) {
self.state = .Failed;
}
}
/**
Touches Ended
*/
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent) {
let touch:UITouch = touches.first as UITouch!
let endPoint:CGPoint = touch.locationInView(self.view)
if ( self.isOnHisWay(endPoint) && self.hasReachMinDistance(endPoint) ) {
//go next or finish
let next: CGVector? = self.nextVector()
if (( next) != nil ) {
self.currentCode.append(next!)
}
if ( self.currentCode == self.konamiCode ) {
self.state = .Ended;
}
return
}
self.state = .Failed;
}
/**
Touches Cancelled
*/
override func touchesCancelled(touches: Set<UITouch>, withEvent event: UIEvent) {
self.reset()
}
/**
Touches Reset
*/
override func reset() {
currentCode = []
self.startingPoint = CGPointZero
super.reset()
}
} | mit | afae2e47784e57582d68b4c5bc379612 | 27.25 | 104 | 0.516612 | 4.59 | false | false | false | false |
ITzTravelInTime/TINU | TINU/Diskutil/EFIPartition.swift | 1 | 4077 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Foundation
import AppKit
import Command
public class EFIPartition: Codable, Equatable, Hashable, RawRepresentable{
public var rawValue: BSDID
required public init?(rawValue: BSDID){
if !EFIPartition.genericCheck(rawValue){
return nil
}
self.rawValue = rawValue
}
public func mount() -> Bool{
log("Try to mount the EFI partition: \(rawValue)")
if !check(){
return false
}
var adminPriv = false
if #available(macOS 10.13.3, *){
adminPriv = true
}
let res = rawValue.mount(useAdminPrivileges: adminPriv) ?? false
if res{
log("EFI partition mounted with success: \(rawValue)")
}else{
log("EFI Partition not mounted !!!")
}
return res
}
public func unmount() -> Bool{
log("Try to unmount the EFI partition: \(rawValue)")
if !check(){
return false
}
let res = rawValue.unmount() ?? false
if res{
log("EFI partition unmounted with success: \(rawValue)")
}else{
log("EFI Partition not unmounted: \(rawValue)")
}
return res
}
private static var partitionsCache: [BSDID]! = nil
private static var isUpdatingPartitionsCache = false
public static func clearPartitionsCache(){
EFIPartition.partitionsCache?.removeAll()
EFIPartition.partitionsCache = nil
}
public static func unmountAllPartitions() -> Bool{
log("Unmounting all EFI partitions")
guard let ps = listPartitions() else {
log("Can't get the EFI partitions list!!")
return false
}
for p in ps{
log(" Unmounting EFI partition \(p.rawValue)")
if !p.unmount(){
log(" Unmounting EFI partition \(p.rawValue) failed!!!")
return false
}
log(" Unmounting EFI partition \(p.rawValue) was successfoul")
}
log("All EFI partitions successfully unmounted")
return true
}
public func check() -> Bool{
return EFIPartition.genericCheck(rawValue)
}
private static func genericCheck( _ id: BSDID) -> Bool{
guard let list = EFIPartition.listIDs() else {
print(" Invalid EFI partition list")
return false
}
if !list.contains(id){
print(" Invalid EFI partition: \(id)")
return false
}
return true
}
private static func listIDs() -> [BSDID]!{
if !(partitionsCache == nil || partitionsCache == []){
return partitionsCache
}
isUpdatingPartitionsCache = true
var usableDrives: [BSDID]! = nil
guard let list = Diskutil.List() else {
isUpdatingPartitionsCache = false
clearPartitionsCache()
return nil
}
for drive in list.allDisksAndPartitions{
guard let efi = drive.getEFIPartition() else {
continue
}
if usableDrives == nil{
usableDrives = []
}
usableDrives.append(efi.DeviceIdentifier)
}
isUpdatingPartitionsCache = false
if usableDrives != nil{
partitionsCache = usableDrives
}
return usableDrives
}
public static func listPartitions() -> [EFIPartition]!{
guard let ids = listIDs() else{
print("Can't get valid partitions list, aborting")
return nil
}
var ret = [EFIPartition]()
for id in ids{
guard let item = EFIPartition(rawValue: id) else{
print("Can't allocate EFI Item for: \(id.rawValue)")
continue
}
ret.append(item)
}
return ret
}
}
| gpl-2.0 | 35a0bcadacb136cc5aeb8051afe7b092 | 21.037838 | 74 | 0.681138 | 3.820993 | false | false | false | false |
TheTekton/Malibu | MalibuTests/Helpers/Mocks.swift | 1 | 1637 | import Foundation
import When
@testable import Malibu
// MARK: - Requests
struct GETRequest: GETRequestable {
var message = Message(resource: "http://hyper.no")
init(parameters: [String: AnyObject] = [:], headers: [String: String] = [:]) {
message.parameters = parameters
message.headers = headers
}
}
struct POSTRequest: POSTRequestable {
var message = Message(resource: "http://hyper.no")
let content: ContentType
var contentType: ContentType {
return content
}
init(parameters: [String: AnyObject] = [:],
headers: [String: String] = [:],
contentType: ContentType = .JSON) {
message.parameters = parameters
message.headers = headers
content = contentType
}
}
struct PUTRequest: PUTRequestable {
var message = Message(resource: "http://hyper.no")
}
struct PATCHRequest: PATCHRequestable {
var message = Message(resource: "http://hyper.no")
}
struct DELETERequest: DELETERequestable {
var message = Message(resource: "http://hyper.no")
}
struct HEADRequest: HEADRequestable {
var message = Message(resource: "http://hyper.no")
}
// MARK: - Tasks
class TestNetworkTask: TaskRunning {
let URLRequest: NSURLRequest
let ride: Ride
let data = "test".dataUsingEncoding(NSUTF32StringEncoding)
let response: NSHTTPURLResponse
// MARK: - Initialization
init() {
URLRequest = try! GETRequest().toURLRequest()
ride = Ride()
response = NSHTTPURLResponse(URL: URLRequest.URL!, statusCode: 200, HTTPVersion: "HTTP/2.0", headerFields: nil)!
}
// MARK: - NetworkTaskRunning
func run() {
process(data, response: response, error: nil)
}
}
| mit | 478a7a3e8260cccee573982f339a043c | 22.385714 | 116 | 0.690898 | 4.041975 | false | false | false | false |
higherdotteam/kidbank | iOS/KidBank/ReviewController.swift | 1 | 4939 | //
// ReviewController.swift
// KidBank
//
// Created by Andrew Arrow on 2/27/17.
// Copyright © 2017 higher.team. All rights reserved.
//
import UIKit
extension Data {
mutating func append(_ string: String) {
if let data = string.data(using: .utf8) {
append(data)
}
}
}
class ReviewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var list: [NSDictionary] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func createBody(with parameters: [String: String]?, boundary: String, lat: String, lon: String) throws -> Data {
var body = Data()
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append("\(value)\r\n")
}
}
let latlon:String = "\(lat)_\(lon)"
let name = "kidbank.jpg"
let filename = self.getDocumentsDirectory().appendingPathComponent("kb_\(latlon).jpg").path
if FileManager.default.fileExists(atPath: filename) == false {
NSLog("zzz")
return body
}
let image = UIImage(contentsOfFile: filename)
let data = UIImageJPEGRepresentation(image!, 90) as Data?
let mimetype = "image/jpg"
let filePathKey = "image"
body.append("--\(boundary)\r\n")
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(name)\"\r\n")
body.append("Content-Type: \(mimetype)\r\n\r\n")
body.append(data!)
body.append("\r\n")
body.append("--\(boundary)--\r\n")
return body
}
func doPost(lat: String, lon: String) {
let URL: NSURL = NSURL(string: "https://kidbank.team/api/v1/atms")!
let request:NSMutableURLRequest = NSMutableURLRequest(url:URL as URL)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var parameters = Dictionary<String,String>()
parameters["lat"] = lat
parameters["lon"] = lon
parameters["ifv"] = UIDevice.current.identifierForVendor?.uuidString
request.httpBody = try? createBody(with: parameters, boundary: boundary, lat: lat, lon: lon)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
});
task.resume()
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
self.list.remove(at: indexPath.row)
self.tableView.reloadData()
}
let share = UITableViewRowAction(style: .normal, title: "Submit") { (action, indexPath) in
let lat = self.list[indexPath.row]["lat"] as! String
let lon = self.list[indexPath.row]["lon"] as! String
self.doPost(lat: lat, lon: lon)
self.list.remove(at: indexPath.row)
self.tableView.reloadData()
}
share.backgroundColor = UIColor.blue
return [delete, share]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
let lat = self.list[indexPath.row]["lat"] as! String
let lon = self.list[indexPath.row]["lon"] as! String
cell.textLabel?.text = "\(lat),\(lon)"
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
| mit | 5a0073f4c92502b64e032b99158491c1 | 32.364865 | 116 | 0.593965 | 4.780252 | false | false | false | false |
stormhouse/SnapDemo | SnapDemo/SemiCircleMenuDemoController.swift | 1 | 3114 | //
// SemiCircleMenuDemoController.swift
// SnapDemo
//
// Created by stormhouse on 4/3/15.
// Copyright (c) 2015 stormhouse. All rights reserved.
//
import UIKit
import Snap
class SemiCircleMenuDemoController: UIViewController, SemiCircleMenuDelegate {
var menu: SemiCircleMenu!
var menuButtonItems: Array<Dictionary<String, String>> = [
["img1": "nav-click.png", "img2": "nav-clicked.png"],
["img1": "nav-click.png", "img2": "nav-clicked.png"],
["img1": "nav-click.png", "img2": "nav-clicked.png"],
["img1": "nav-click.png", "img2": "nav-clicked.png"],
// ["img1": "dropbox.png", "img2": "dropbox.png"],
]
var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
//菜单
menu = SemiCircleMenu(buttonItems: menuButtonItems)
view.addSubview(menu)
menu.delegate = self
// menu.snp_makeConstraints { make in
// make.edges.equalTo(self.view.snp_edges)
// return
// }
menu.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addConstraint(NSLayoutConstraint(
item: menu,
attribute: NSLayoutAttribute.Left,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Left,
multiplier: 1,
constant: 0
))
view.addConstraint(NSLayoutConstraint(
item: menu,
attribute: NSLayoutAttribute.Right,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Right,
multiplier: 1,
constant: 0
))
view.addConstraint(NSLayoutConstraint(
item: menu,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: 50
))
view.addConstraint(NSLayoutConstraint(
item: menu,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0
))
label = UILabel()
label.text = "ll"
view.addSubview(label)
label.snp_makeConstraints { make in
make.center.equalTo(self.view).offset(CGPointMake(-5, 10))
// make.center.equalTo(self.view.snp_center)
// make.centerY.equalTo(self.view.snp_centerY)
return
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
self.menu.updateMenuConstraints()
}
func didTapMenuItem(index: Int){
label.text = "\(index)"
println(UIDevice.currentDevice().orientation.isLandscape)
println(UIScreen.mainScreen().bounds)
}
}
| apache-2.0 | 18abe6925686c63c7ada2cf349529935 | 30.1 | 103 | 0.580064 | 4.829193 | false | false | false | false |
KoCMoHaBTa/MHMessageKit | MHMessageKit/WeakObservers/NotificationCender+WeakObserver.swift | 1 | 2315 | //
// NotificationCender+WeakObserver.swift
// MHMessageKit
//
// Created by Milen Halachev on 4/10/17.
// Copyright © 2017 Milen Halachev. All rights reserved.
//
import Foundation
extension NotificationCenter {
public func addWeakObserver(_ observer: Any, selector: Selector, name: NSNotification.Name?, object: Any?) {
let weakObserver = WeakObserver(observer: observer, selector: selector, name: name, object: object)
weakObserver.associate(with: observer)
}
public func addWeakObserver(forName name: NSNotification.Name?, object: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) -> NSObjectProtocol {
let observer = self.addObserver(forName: name, object: object, queue: queue, using: block)
let weakObserver = WeakBlockObserver(observer: observer)
return weakObserver
}
}
extension NotificationCenter {
fileprivate class WeakObserver: NSObject {
private unowned let observer: AnyObject
private let selector: Selector
private let name: NSNotification.Name?
private weak var object: AnyObject?
private var associatedKey: String = ""
init(observer: Any, selector: Selector, name: NSNotification.Name?, object: Any?) {
self.observer = observer as AnyObject
self.selector = selector
self.name = name
self.object = object as AnyObject
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc dynamic func received(notification: Notification) {
_ = self.observer.perform(self.selector, with: notification)
}
func associate(with observer: Any) {
objc_setAssociatedObject(observer, &self.associatedKey, self, .OBJC_ASSOCIATION_RETAIN)
}
}
}
extension NotificationCenter {
fileprivate class WeakBlockObserver: NSObject {
private let observer: Any
init(observer: Any) {
self.observer = observer
}
deinit {
NotificationCenter.default.removeObserver(self.observer)
}
}
}
| mit | c2d28570b6c3b365257f012d1ccd5743 | 28.666667 | 174 | 0.611063 | 5.283105 | false | false | false | false |
ishitaswarup/RWPickFlavor2 | RWPickFlavor2/FlavorFactory.swift | 21 | 969 | //
// FlavorFactory.swift
// IceCreamShop
//
// Created by Joshua Greene on 2/9/15.
// Copyright (c) 2015 Razeware, LLC. All rights reserved.
//
import Foundation
class FlavorFactory {
func flavorsFromPlistNamed(plistName: String, bundle: NSBundle = NSBundle.mainBundle()) -> [Flavor]? {
let path = bundle.pathForResource(plistName, ofType: "plist")!
let data = NSData(contentsOfFile: path)!
let options = Int(NSPropertyListMutabilityOptions.Immutable.rawValue)
let array = NSPropertyListSerialization.propertyListWithData(data, options: options, format: nil, error: nil) as! [[String: String]]!
return flavorsFromDictionaryArray(array)
}
func flavorsFromDictionaryArray(array: [[String: String]]) -> [Flavor] {
var flavors: [Flavor] = []
for dictionary in array {
if let flavor = Flavor(dictionary: dictionary) {
flavors.append(flavor)
}
}
return flavors
}
}
| mit | 458b764a14795b206aea28048a0c29b2 | 25.189189 | 137 | 0.670795 | 4.384615 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Room/Polls/PollAggregator.swift | 1 | 6523 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
/// PollAggregator errors
public enum PollAggregatorError: Error {
case invalidPollStartEvent
}
public protocol PollAggregatorDelegate: AnyObject {
func pollAggregatorDidStartLoading(_ aggregator: PollAggregator)
func pollAggregatorDidEndLoading(_ aggregator: PollAggregator)
func pollAggregator(_ aggregator: PollAggregator, didFailWithError: Error)
func pollAggregatorDidUpdateData(_ aggregator: PollAggregator)
}
/**
Responsible for building poll models out of the original poll start event and listen to replies.
It will listen for PollResponse and PollEnd events on the live timline and update the built models accordingly.
I will also listen for `mxRoomDidFlushData` and reload all data to avoid gappy sync problems
*/
public class PollAggregator {
private struct Constants {
static let minAnswerOptionCount = 2
}
private let session: MXSession
private let room: MXRoom
private let pollStartEventId: String
private let pollBuilder: PollBuilder
private var pollStartEventContent: MXEventContentPollStart!
private var referenceEventsListener: Any?
private var editEventsListener: Any?
private var events: [MXEvent] = []
private var hasBeenEdited = false
public private(set) var poll: PollProtocol! {
didSet {
delegate?.pollAggregatorDidUpdateData(self)
}
}
public var delegate: PollAggregatorDelegate?
deinit {
if let referenceEventsListener = referenceEventsListener {
room.removeListener(referenceEventsListener)
}
if let editEventsListener = editEventsListener {
session.aggregations.removeListener(editEventsListener)
}
}
public init(session: MXSession, room: MXRoom, pollStartEventId: String) throws {
self.session = session
self.room = room
self.pollStartEventId = pollStartEventId
self.pollBuilder = PollBuilder()
NotificationCenter.default.addObserver(self, selector: #selector(handleRoomDataFlush), name: NSNotification.Name.mxRoomDidFlushData, object: self.room)
editEventsListener = session.aggregations.listenToEditsUpdate(inRoom: self.room.roomId) { [weak self] event in
guard let self = self,
self.pollStartEventId == event.relatesTo.eventId
else {
return
}
do {
try self.buildPollStartContent()
} catch {
self.delegate?.pollAggregator(self, didFailWithError: PollAggregatorError.invalidPollStartEvent)
}
}
try buildPollStartContent()
}
private func buildPollStartContent() throws {
guard let event = session.store.event(withEventId: pollStartEventId, inRoom: room.roomId),
let eventContent = MXEventContentPollStart(fromJSON: event.content),
eventContent.answerOptions.count >= Constants.minAnswerOptionCount
else {
throw PollAggregatorError.invalidPollStartEvent
}
pollStartEventContent = eventContent
hasBeenEdited = (event.unsignedData.relations?.replace != nil)
poll = pollBuilder.build(pollStartEventContent: eventContent,
events: events,
currentUserIdentifier: session.myUserId,
hasBeenEdited: hasBeenEdited)
reloadPollData()
}
@objc private func handleRoomDataFlush(sender: Notification) {
guard let room = sender.object as? MXRoom, room == self.room else {
return
}
reloadPollData()
}
private func reloadPollData() {
delegate?.pollAggregatorDidStartLoading(self)
session.aggregations.referenceEvents(forEvent: pollStartEventId, inRoom: room.roomId, from: nil, limit: -1) { [weak self] response in
guard let self = self else {
return
}
self.events.removeAll()
self.events.append(contentsOf: response.chunk)
let eventTypes = [kMXEventTypeStringPollResponse, kMXEventTypeStringPollResponseMSC3381, kMXEventTypeStringPollEnd, kMXEventTypeStringPollEndMSC3381]
self.referenceEventsListener = self.room.listen(toEventsOfTypes: eventTypes) { [weak self] event, direction, state in
guard let self = self,
let relatedEventId = event.relatesTo?.eventId,
relatedEventId == self.pollStartEventId else {
return
}
self.events.append(event)
self.poll = self.pollBuilder.build(pollStartEventContent: self.pollStartEventContent,
events: self.events,
currentUserIdentifier: self.session.myUserId,
hasBeenEdited: self.hasBeenEdited)
} as Any
self.poll = self.pollBuilder.build(pollStartEventContent: self.pollStartEventContent,
events: self.events,
currentUserIdentifier: self.session.myUserId,
hasBeenEdited: self.hasBeenEdited)
self.delegate?.pollAggregatorDidEndLoading(self)
} failure: { [weak self] error in
guard let self = self else {
return
}
self.delegate?.pollAggregator(self, didFailWithError: error)
}
}
}
| apache-2.0 | 89961ce6476f37f6732e74c81b199343 | 37.370588 | 161 | 0.616587 | 5.72193 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/network/RequestButton.swift | 1 | 2547 | //
// RequestButton.swift
// SjekkUt
//
// Created by Henrik Hartz on 07.03.2017.
// Copyright © 2017 Den Norske Turistforening. All rights reserved.
//
import Foundation
class RequestButton: DntTrackButton
{
var previousTitle: String?
var isObserving = false
static var kObservingStatus = "state"
var activityView: UIActivityIndicatorView?
var finishHandler: (()->Void)?
weak var requestTask: URLSessionTask? {
willSet {
stopObserving()
}
didSet {
startObserving()
}
}
deinit {
stopObserving()
}
func startObserving() {
if !isObserving, let task = requestTask {
task.addObserver(self, forKeyPath: RequestButton.kObservingStatus, options: .initial, context: &RequestButton.kObservingStatus)
isObserving = true
}
}
func stopObserving() {
if isObserving, let task = requestTask {
task.removeObserver(self, forKeyPath: RequestButton.kObservingStatus, context: &RequestButton.kObservingStatus)
isObserving = false
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
switch context.unsafelyUnwrapped {
case &RequestButton.kObservingStatus:
if let task = object as? URLSessionTask {
DispatchQueue.main.async {
self.updateTextFor(task.state)
}
}
default:
break
}
}
func updateTextFor(_ state: URLSessionTask.State) {
switch state {
case .running:
previousTitle = title(for: .normal)
setTitle(NSLocalizedString("Working..", comment: "join/leave in progress"), for: .normal)
activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityView?.hidesWhenStopped = true
activityView?.startAnimating()
addSubview(activityView!)
activityView?.center = CGPoint(x: bounds.size.width/2, y: bounds.size.height/2)
isEnabled = false
default:
setTitle(previousTitle, for: .normal)
activityView?.stopAnimating()
activityView?.removeFromSuperview()
activityView = nil
isEnabled = true
stopObserving()
if let finish = finishHandler {
finish()
}
}
}
}
| mit | b2792abc117c04eea053b0e3b3a04df7 | 30.432099 | 151 | 0.595051 | 5.45182 | false | false | false | false |
JeffESchmitz/RideNiceRide | Pods/Willow/Source/LogMessageWriter.swift | 1 | 5186 | //
// LogMessageWriter.swift
//
// Copyright (c) 2015-2016 Nike, Inc. (https://www.nike.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import os
/// The LogMessageWriter protocol defines a single API for writing a log message. The message can be written in any way
/// the conforming object sees fit. For example, it could write to the console, write to a file, remote log to a third
/// party service, etc.
public protocol LogMessageWriter {
func writeMessage(_ message: String, logLevel: LogLevel, modifiers: [LogMessageModifier]?)
}
// MARK: -
/// The ConsoleWriter class runs all modifiers in the order they were created and prints the resulting message
/// to the console.
open class ConsoleWriter: LogMessageWriter {
/// Used to define whether to use the print or NSLog functions when logging to the console.
///
/// During development, it is recommendeded to use the `.print` case. When deploying to production, the `.nslog`
/// case should be used instead. The main reason for this is that the `print` method does not log to the device
/// console where as the `NSLog` method does.
///
/// - print: Backed by the Swift `print` function.
/// - nslog: Backed by the Objective-C `NSLog` function.
public enum Method {
case print, nslog
}
private let method: Method
/// Initializes a console writer instance.
///
/// - parameter method: The method to use when logging to the console. Defaults to `.print`.
///
/// - returns: A new console writer instance.
public init(method: Method = .print) {
self.method = method
}
/// Writes the message to the console using the global `print` function.
///
/// Each modifier is run over the message in the order they are provided before writing the message to
/// the console.
///
/// - parameter message: The original message to write to the console.
/// - parameter logLevel: The log level associated with the message.
/// - parameter modifiers: The modifier objects to run over the message before writing to the console.
open func writeMessage(_ message: String, logLevel: LogLevel, modifiers: [LogMessageModifier]?) {
var message = message
modifiers?.forEach { message = $0.modifyMessage(message, with: logLevel) }
switch method {
case .print:
print(message)
case .nslog:
NSLog("%@", message)
}
}
}
// MARK: -
#if !os(macOS)
/// The OSLogWriter class runs all modifiers in the order they were created and passes the resulting message
/// off to an OSLog with the specified subsystem and category.
@available(iOS 10.0, OSX 10.12.0, tvOS 10.0, watchOS 3.0, *)
open class OSLogWriter: LogMessageWriter {
open let subsystem: String
open let category: String
private let log: OSLog
public init(subsystem: String, category: String) {
self.subsystem = subsystem
self.category = category
self.log = OSLog(subsystem: subsystem, category: category)
}
/// Writes the message to the `OSLog` using the `os_log` function.
///
/// Each modifier is run over the message in the order they are provided before writing the message to
/// the console.
///
/// - parameter message: The original message to write to the console.
/// - parameter logLevel: The log level associated with the message.
/// - parameter modifiers: The modifier objects to run over the message before writing to the console.
open func writeMessage(_ message: String, logLevel: LogLevel, modifiers: [LogMessageModifier]?) {
var message = message
modifiers?.forEach { message = $0.modifyMessage(message, with: logLevel) }
let logType: OSLogType
switch logLevel {
case LogLevel.debug:
logType = .debug
case LogLevel.info:
logType = .info
case LogLevel.warn, LogLevel.error:
logType = .error
default:
logType = .default
}
os_log("%@", log: log, type: logType, message)
}
}
#endif
| mit | fefbd4eff91f6129b04a5165ea8e0ce8 | 38.587786 | 119 | 0.680679 | 4.474547 | false | false | false | false |
malaonline/iOS | mala-ios/Model/Base/BaseObjectModel.swift | 1 | 2255 | //
// BaseObjectModel.swift
// mala-ios
//
// Created by Elors on 15/12/21.
// Copyright © 2015年 Mala Online. All rights reserved.
//
import UIKit
open class BaseObjectModel: NSObject, NSCoding {
// MARK: - Property
var id: Int = 0
var name: String?
// only for exercise-group
var desc: String?
/// first letter that object name transform in mandarin latin, default is "#".
var firstLetter: String {
get {
return name?.applyingTransform(StringTransform.mandarinToLatin, reverse: false)?
.applyingTransform(StringTransform.stripCombiningMarks, reverse: false)?.subStringToIndex(1) ?? "#"
}
}
// MARK: - Constructed
override init() {
super.init()
}
init(dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
required public init(coder aDecoder: NSCoder) {
self.id = Int(aDecoder.decodeInt32(forKey: "id"))
self.name = aDecoder.decodeObject(forKey: "name") as? String
}
convenience init(id: Int, name: String, desc: String = "") {
self.init()
self.id = id
self.name = name
self.desc = desc
}
// MARK: - Override
open override func setValue(_ value: Any?, forUndefinedKey key: String) {
println("BaseObjectModel - Set for UndefinedKey: \(key)")
}
override open func setValue(_ value: Any?, forKey key: String) {
if key == "title", let string = value as? String {
name = string
return
}
// only for option
if key == "text", let string = value as? String {
name = string
return
}
if key == "description", let string = value as? String {
desc = string
return
}
super.setValue(value, forKey: key)
}
// MARK: - Coding
open func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(name, forKey: "name")
}
// MARK: - Description
override open var description: String {
let keys = ["id", "name"]
return dictionaryWithValues(forKeys: keys).description
}
}
| mit | 9478bc9a0be4cbf3f8204b8e5aa5558f | 24.885057 | 115 | 0.561279 | 4.381323 | false | false | false | false |
SwiftGen/StencilSwiftKit | Sources/StencilSwiftKit/Parameters.swift | 1 | 6676 | //
// StencilSwiftKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
/// Namespace to handle extra context parameters passed as a list of `foo=bar` strings.
/// Typically used when parsing command-line arguments one by one
/// (like `foo=bar pt.x=1 pt.y=2 values=1 values=2 values=3 flag`)
/// to turn them into a dictionary structure
public enum Parameters {
public enum Error: Swift.Error {
case invalidSyntax(value: Any)
case invalidKey(key: String, value: Any)
case invalidStructure(key: String, oldValue: Any, newValue: Any)
}
typealias Parameter = (key: String, value: Any)
/// A string-keyed dictionary
public typealias StringDict = [String: Any]
/// Transforms a list of strings representing structured-key/value pairs, like
/// `["pt.x=1", "pt.y=2", "values=1", "values=2", "values=3", "flag"]`
/// into a structured dictionary.
///
/// - Parameter items: The list of `k=v`-style Strings, each string
/// representing either a `key=value` pair or a
/// single `flag` key with no `=` (which will then
/// be interpreted as a `true` value)
/// - Returns: A structured dictionary matching the list of keys
/// - Throws: `Parameters.Error`
public static func parse(items: [String]) throws -> StringDict {
let parameters: [Parameter] = try items.map(createParameter)
return try parameters.reduce(StringDict()) { result, parameter in
try parse(parameter: parameter, result: result)
}
}
/// Flatten a dictionary into a list of "key.path=value" pairs.
/// This method recursively visits the object to build its flat representation.
///
/// - Parameters:
/// - dictionary: The dictionary to recursively flatten into key pairs
/// - Returns: The list of flatten "key.path=value" pair representations of the object
///
/// - Note: flatten is the counterpart of parse. flatten(parse(x)) == parse(flatten(x)) == x
///
/// - Example:
///
/// flatten(["a":["b":1,"c":[2,3]]])
/// // ["a.b=1","a.c=2","a.c=3"]
public static func flatten(dictionary: StringDict) -> [String] {
flatten(object: dictionary, keyPrefix: "")
}
// MARK: - Private methods
/// Parse a single `key=value` (or `key`) string and inserts it into
/// an existing StringDict dictionary being built.
///
/// - Parameters:
/// - parameter: The parameter/string (key/value pair) to parse
/// - result: The dictionary currently being built and to which to add the value
/// - Returns: The new content of the dictionary being built after inserting the new parsed value
/// - Throws: `Parameters.Error`
private static func parse(parameter: Parameter, result: StringDict) throws -> StringDict {
let parts = parameter.key.components(separatedBy: ".")
let key = parts.first ?? ""
// validate key
guard validate(key: key) else { throw Error.invalidKey(key: parameter.key, value: parameter.value) }
// no sub keys, may need to convert to array if repeat key if possible
if parts.count == 1 {
return try parse(key: key, parameter: parameter, result: result)
}
guard result[key] is StringDict || result[key] == nil else {
throw Error.invalidStructure(key: key, oldValue: result[key] ?? "", newValue: parameter.value)
}
// recurse into sub keys
var result = result
let current = result[key] as? StringDict ?? StringDict()
let sub = (key: parts.suffix(from: 1).joined(separator: "."), value: parameter.value)
result[key] = try parse(parameter: sub, result: current)
return result
}
/// Parse a single `key=value` (or `key`) string and inserts it into
/// an existing StringDict dictionary being built.
///
/// - Parameters:
/// - parameter: The parameter/string (key/value pair) to parse, where key doesn't have sub keys
/// - result: The dictionary currently being built and to which to add the value
/// - Returns: The new content of the dictionary being built after inserting the new parsed value
/// - Throws: `Parameters.Error`
private static func parse(key: String, parameter: Parameter, result: StringDict) throws -> StringDict {
var result = result
if let current = result[key] as? [Any] {
result[key] = current + [parameter.value]
} else if let current = result[key] as? String {
result[key] = [current, parameter.value]
} else if let current = result[key] {
throw Error.invalidStructure(key: key, oldValue: current, newValue: parameter.value)
} else {
result[key] = parameter.value
}
return result
}
// a valid key is not empty and only alphanumerical or dot
private static func validate(key: String) -> Bool {
!key.isEmpty && key.rangeOfCharacter(from: notAlphanumericsAndDot) == nil
}
private static let notAlphanumericsAndDot: CharacterSet = {
var result = CharacterSet.alphanumerics
result.insert(".")
return result.inverted
}()
private static func createParameter(from string: String) throws -> Parameter {
let parts = string.components(separatedBy: "=")
if parts.count >= 2 {
return (key: parts[0], value: parts.dropFirst().joined(separator: "="))
} else if let part = parts.first, parts.count == 1 && validate(key: part) {
return (key: part, value: true)
} else {
throw Error.invalidSyntax(value: string)
}
}
/// Flatten an object (dictionary, array or single object) into a list of keypath-type k=v pairs.
/// This method recursively visits the object to build the flat representation.
///
/// - Parameters:
/// - object: The object to recursively flatten
/// - keyPrefix: The prefix to use when creating keys.
/// This is used to build the keyPath via recusrive calls of this function.
/// You should start the root call of this recursive function with an empty keyPrefix.
/// - Returns: The list of flatten "key.path=value" pair representations of the object
private static func flatten(object: Any, keyPrefix: String = "") -> [String] {
var values: [String] = []
switch object {
case is String, is Int, is Double:
values.append("\(keyPrefix)=\(object)")
case let bool as Bool where bool:
values.append(keyPrefix)
case let dict as [String: Any]:
for (key, value) in dict {
let fullKey = keyPrefix.isEmpty ? key : "\(keyPrefix).\(key)"
values += flatten(object: value, keyPrefix: fullKey)
}
case let array as [Any]:
values += array.flatMap { flatten(object: $0, keyPrefix: keyPrefix) }
default:
break
}
return values
}
}
| mit | 75129340850c21981cfe15dd42c674de | 39.70122 | 105 | 0.656479 | 4.107692 | false | false | false | false |
zitao0322/ShopCar | Shoping_Car/Pods/RxDataSources/Sources/DataSources/CollectionViewSectionedDataSource.swift | 2 | 8585 | //
// CollectionViewSectionedDataSource.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxCocoa
#endif
public class _CollectionViewSectionedDataSource
: NSObject
, UICollectionViewDataSource {
func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 0
}
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return _numberOfSectionsInCollectionView(collectionView)
}
func _rx_collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _rx_collectionView(collectionView, numberOfItemsInSection: section)
}
func _rx_collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return (nil as UICollectionViewCell?)!
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return _rx_collectionView(collectionView, cellForItemAtIndexPath: indexPath)
}
func _rx_collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return (nil as UICollectionReusableView?)!
}
public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return _rx_collectionView(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath)
}
func _rx_collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
public func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return _rx_collectionView(collectionView, canMoveItemAtIndexPath: indexPath)
}
func _rx_collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
}
public func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
_rx_collectionView(collectionView, moveItemAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath)
}
}
public class CollectionViewSectionedDataSource<S: SectionModelType>
: _CollectionViewSectionedDataSource
, SectionedViewDataSourceType {
public typealias I = S.Item
public typealias Section = S
public typealias CellFactory = (CollectionViewSectionedDataSource<S>, UICollectionView, NSIndexPath, I) -> UICollectionViewCell
public typealias SupplementaryViewFactory = (CollectionViewSectionedDataSource<S>, UICollectionView, String, NSIndexPath) -> UICollectionReusableView
#if DEBUG
// If data source has already been bound, then mutating it
// afterwards isn't something desired.
// This simulates immutability after binding
var _dataSourceBound: Bool = false
private func ensureNotMutatedAfterBinding() {
assert(!_dataSourceBound, "Data source is already bound. Please write this line before binding call (`bindTo`, `drive`). Data source must first be completely configured, and then bound after that, otherwise there could be runtime bugs, glitches, or partial malfunctions.")
}
#endif
// This structure exists because model can be mutable
// In that case current state value should be preserved.
// The state that needs to be preserved is ordering of items in section
// and their relationship with section.
// If particular item is mutable, that is irrelevant for this logic to function
// properly.
public typealias SectionModelSnapshot = SectionModel<S, I>
private var _sectionModels: [SectionModelSnapshot] = []
public var sectionModels: [S] {
return _sectionModels.map { Section(original: $0.model, items: $0.items) }
}
public func sectionAtIndex(section: Int) -> S {
let sectionModel = self._sectionModels[section]
return S(original: sectionModel.model, items: sectionModel.items)
}
public func itemAtIndexPath(indexPath: NSIndexPath) -> I {
return self._sectionModels[indexPath.section].items[indexPath.item]
}
public func modelAtIndexPath(indexPath: NSIndexPath) throws -> Any {
return itemAtIndexPath(indexPath)
}
public func setSections(sections: [S]) {
self._sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) }
}
public var configureCell: CellFactory! = nil {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
@available(*, deprecated=0.8.1, renamed="configureCell")
public var cellFactory: CellFactory! {
get {
return self.configureCell
}
set {
self.configureCell = newValue
}
}
public var supplementaryViewFactory: SupplementaryViewFactory {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var moveItem: ((CollectionViewSectionedDataSource<S>, sourceIndexPath:NSIndexPath, destinationIndexPath:NSIndexPath) -> Void)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public var canMoveItemAtIndexPath: ((CollectionViewSectionedDataSource<S>, indexPath:NSIndexPath) -> Bool)? {
didSet {
#if DEBUG
ensureNotMutatedAfterBinding()
#endif
}
}
public override init() {
self.configureCell = {_, _, _, _ in return (nil as UICollectionViewCell?)! }
self.supplementaryViewFactory = {_, _, _, _ in (nil as UICollectionReusableView?)! }
super.init()
self.configureCell = { [weak self] _ in
precondition(false, "There is a minor problem. `cellFactory` property on \(self!) was not set. Please set it manually, or use one of the `rx_bindTo` methods.")
return (nil as UICollectionViewCell!)!
}
self.supplementaryViewFactory = { [weak self] _ in
precondition(false, "There is a minor problem. `supplementaryViewFactory` property on \(self!) was not set.")
return (nil as UICollectionReusableView?)!
}
}
// UICollectionViewDataSource
override func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return _sectionModels.count
}
override func _rx_collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _sectionModels[section].items.count
}
override func _rx_collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
precondition(indexPath.item < _sectionModels[indexPath.section].items.count)
return configureCell(self, collectionView, indexPath, itemAtIndexPath(indexPath))
}
override func _rx_collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return supplementaryViewFactory(self, collectionView, kind, indexPath)
}
override func _rx_collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
guard let canMoveItem = canMoveItemAtIndexPath?(self, indexPath: indexPath) else {
return super._rx_collectionView(collectionView, canMoveItemAtIndexPath: indexPath)
}
return canMoveItem
}
override func _rx_collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
self._sectionModels.moveFromSourceIndexPath(sourceIndexPath, destinationIndexPath: destinationIndexPath)
}
} | mit | 67fad49c900766386296d8279eb8ab61 | 39.880952 | 280 | 0.703868 | 5.973556 | false | false | false | false |
almazrafi/Metatron | Sources/Types/FileStream.swift | 1 | 9506 | //
// FileStream.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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 FileStream: Stream {
// MARK: Instance Properties
private var handle: FileHandle?
public let filePath: String
// MARK:
public private(set) var isReadable: Bool
public private(set) var isWritable: Bool
public var isOpen: Bool {
return (self.handle != nil)
}
// MARK:
public var offset: UInt64 {
if let handle = self.handle {
return handle.offsetInFile
}
return 0
}
public var length: UInt64 {
if let handle = self.handle {
let offset = handle.offsetInFile
let length = handle.seekToEndOfFile()
handle.seek(toFileOffset: offset)
return length
} else {
if let attributes = try? FileManager.default.attributesOfItem(atPath: self.filePath) {
if let length = attributes[FileAttributeKey.size] as? NSNumber {
return length.uint64Value
}
}
return 0
}
}
public var bufferLength: Int
// MARK: Initializers
public init(filePath: String) {
self.filePath = filePath
self.isReadable = false
self.isWritable = false
self.bufferLength = 1024
}
// MARK: Deinitializer
deinit {
if let handle = self.handle {
handle.synchronizeFile()
handle.closeFile()
}
}
// MARK: Instance Methods
@discardableResult
public func openForReading() -> Bool {
guard !self.isOpen else {
return false
}
guard let handle = FileHandle(forReadingAtPath: self.filePath) else {
return false
}
self.handle = handle
self.isReadable = true
self.isWritable = false
return true
}
@discardableResult
public func openForUpdating(truncate: Bool) -> Bool {
guard !self.isOpen else {
return false
}
if !FileManager.default.fileExists(atPath: self.filePath) {
let pathCharacters = [Character](self.filePath.characters)
let directoryPath = String(pathCharacters.prefix(pathCharacters.lastIndex(of: "/") ?? 0))
if !directoryPath.isEmpty {
try? FileManager.default.createDirectory(atPath: directoryPath, withIntermediateDirectories: true)
}
guard FileManager.default.createFile(atPath: self.filePath, contents: nil) else {
return false
}
}
guard let handle = FileHandle(forUpdatingAtPath: self.filePath) else {
return false
}
if truncate {
handle.truncateFile(atOffset: 0)
}
self.handle = handle
self.isReadable = true
self.isWritable = true
return true
}
@discardableResult
public func openForWriting(truncate: Bool) -> Bool {
guard !self.isOpen else {
return false
}
if !FileManager.default.fileExists(atPath: self.filePath) {
let pathCharacters = [Character](self.filePath.characters)
let directoryPath = String(pathCharacters.prefix(pathCharacters.lastIndex(of: "/") ?? 0))
if !directoryPath.isEmpty {
try? FileManager.default.createDirectory(atPath: directoryPath, withIntermediateDirectories: true)
}
guard FileManager.default.createFile(atPath: self.filePath, contents: nil) else {
return false
}
}
guard let handle = FileHandle(forWritingAtPath: self.filePath) else {
return false
}
if truncate {
handle.truncateFile(atOffset: 0)
}
self.handle = handle
self.isReadable = false
self.isWritable = true
return true
}
public func synchronize() {
if let handle = self.handle {
handle.synchronizeFile()
}
}
public func close() {
if let handle = self.handle {
handle.synchronizeFile()
handle.closeFile()
self.handle = nil
self.isReadable = false
self.isWritable = false
}
}
// MARK:
@discardableResult
public func seek(offset: UInt64) -> Bool {
guard let handle = self.handle else {
return false
}
guard offset <= self.length else {
return false
}
handle.seek(toFileOffset: offset)
return true
}
public func read(maxLength: Int) -> [UInt8] {
guard self.isReadable && (maxLength > 0) else {
return []
}
guard let handle = self.handle else {
return []
}
return [UInt8](handle.readData(ofLength: maxLength))
}
@discardableResult
public func write(data: [UInt8]) -> Int {
guard self.isWritable && (data.count > 0) else {
return 0
}
guard let handle = self.handle else {
return 0
}
let offset = handle.offsetInFile
let length = min(UInt64.max - offset, UInt64(data.count))
handle.write(Data(data.prefix(Int(length))))
return Int(handle.offsetInFile - offset)
}
@discardableResult
public func truncate(length: UInt64) -> Bool {
guard self.isWritable else {
return false
}
guard let handle = self.handle else {
return false
}
guard length < self.length else {
return false
}
let offset = min(handle.offsetInFile, length)
handle.truncateFile(atOffset: length)
handle.seek(toFileOffset: offset)
return true
}
@discardableResult
public func insert(data: [UInt8]) -> Bool {
guard self.isReadable && self.isWritable else {
return false
}
guard let handle = self.handle else {
return false
}
guard data.count > 0 else {
return true
}
let maxBufferLength = UInt64(max(self.bufferLength, data.count))
let offset = handle.offsetInFile
let length = self.length
let shift = UInt64(data.count)
var count = length - offset
handle.truncateFile(atOffset: length + shift)
while count > 0 {
let bufferLength = min(count, maxBufferLength)
let bufferOffset = offset + count - bufferLength
handle.seek(toFileOffset: bufferOffset)
let buffer = handle.readData(ofLength: Int(bufferLength))
guard buffer.count == Int(bufferLength) else {
handle.seek(toFileOffset: offset)
return false
}
handle.seek(toFileOffset: bufferOffset + shift)
handle.write(buffer)
count -= bufferLength
}
handle.seek(toFileOffset: offset)
handle.write(Data(data))
return true
}
@discardableResult
public func remove(length: UInt64) -> Bool {
guard self.isReadable && self.isWritable else {
return false
}
guard let handle = self.handle else {
return false
}
guard length > 0 else {
return true
}
let maxBufferLength = UInt64(max(self.bufferLength, 1))
let offset = handle.offsetInFile
let margin = self.length - offset
guard length <= margin else {
return false
}
var count = margin - length
while count > 0 {
let bufferLength = min(count, maxBufferLength)
let bufferOffset = offset + margin - count
handle.seek(toFileOffset: bufferOffset)
let buffer = handle.readData(ofLength: Int(bufferLength))
guard buffer.count == Int(bufferLength) else {
handle.seek(toFileOffset: offset)
return false
}
handle.seek(toFileOffset: bufferOffset - length)
handle.write(buffer)
count -= bufferLength
}
handle.truncateFile(atOffset: handle.offsetInFile)
handle.seek(toFileOffset: offset)
return true
}
}
| mit | 6d6f1f557bc556a2a4193b9657d45008 | 24.349333 | 114 | 0.584052 | 5.037626 | false | false | false | false |
v2panda/DaysofSwift | swift2.3/My-PullRefresh/My-PullRefresh/ViewController.swift | 1 | 6967 | //
// ViewController.swift
// My-PullRefresh
//
// Created by v2panda on 16/3/5.
// Copyright © 2016年 Panda. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var myTableView: UITableView!
var refreshController : UIRefreshControl!
var customView : UIView!
var labelsArray: Array<UILabel> = []
var isAnimating = false
var currentColorIndex = 0
var currentLabelIndex = 0
var timer : NSTimer!
var dataArray : Array<String> = ["😂", "🤗", "😳", "😌", "😊"]
override func viewDidLoad() {
super.viewDidLoad()
myTableView.delegate = self
myTableView.dataSource = self
refreshController = UIRefreshControl()
refreshController.backgroundColor = UIColor.clearColor()
refreshController.tintColor = UIColor.clearColor()
myTableView.addSubview(refreshController)
loadCustomRefreshContents()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cells", forIndexPath: indexPath)
cell.textLabel!.text = dataArray[indexPath.row]
cell.textLabel?.font = UIFont(name: "Apple Color Emoji", size: 40)
cell.textLabel?.textAlignment = NSTextAlignment.Center
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
func loadCustomRefreshContents() {
let refreshContents = NSBundle.mainBundle().loadNibNamed("RefreshContents", owner: self, options: nil)
customView = refreshContents[0] as! UIView
customView.frame = refreshController.bounds
for var i = 0;i < customView.subviews.count; ++i {
labelsArray.append(customView.viewWithTag(i + 1) as! UILabel)
}
refreshController.addSubview(customView)
}
func animateRefreshStep1() {
isAnimating = true
UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.labelsArray[self.currentLabelIndex].transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
self.labelsArray[self.currentLabelIndex].textColor = self.getNextColor()
}, completion: { (finished) -> Void in
UIView.animateWithDuration(0.05, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.labelsArray[self.currentLabelIndex].transform = CGAffineTransformIdentity
self.labelsArray[self.currentLabelIndex].textColor = UIColor.blackColor()
}, completion: { (finished) -> Void in
++self.currentLabelIndex
if self.currentLabelIndex < self.labelsArray.count {
self.animateRefreshStep1()
}
else {
self.animateRefreshStep2()
}
})
})
}
func animateRefreshStep2() {
UIView.animateWithDuration(0.4, delay: 0.0, options: .CurveLinear, animations: { () -> Void in
for label in self.labelsArray {
label.transform = CGAffineTransformMakeScale(1.5, 1.5)
}
}) { (finished) -> Void in
UIView.animateWithDuration(0.25, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.labelsArray[0].transform = CGAffineTransformIdentity
self.labelsArray[1].transform = CGAffineTransformIdentity
self.labelsArray[2].transform = CGAffineTransformIdentity
self.labelsArray[3].transform = CGAffineTransformIdentity
self.labelsArray[4].transform = CGAffineTransformIdentity
self.labelsArray[5].transform = CGAffineTransformIdentity
self.labelsArray[6].transform = CGAffineTransformIdentity
self.labelsArray[7].transform = CGAffineTransformIdentity
self.labelsArray[8].transform = CGAffineTransformIdentity
self.labelsArray[9].transform = CGAffineTransformIdentity
self.labelsArray[10].transform = CGAffineTransformIdentity
self.labelsArray[11].transform = CGAffineTransformIdentity
}, completion: { (finished) -> Void in
if self.refreshController.refreshing {
self.currentLabelIndex = 0
self.animateRefreshStep1()
}
else {
self.isAnimating = false
self.currentLabelIndex = 0
for var i=0; i<self.labelsArray.count; ++i {
self.labelsArray[i].textColor = UIColor.blackColor()
self.labelsArray[i].transform = CGAffineTransformIdentity
}
}
})
}
}
func getNextColor() -> UIColor {
var colorsArray : Array<UIColor> = [UIColor.magentaColor(),UIColor.brownColor(), UIColor.yellowColor(), UIColor.redColor(), UIColor.greenColor(), UIColor.blueColor(), UIColor.orangeColor()]
if currentColorIndex == colorsArray.count {
currentColorIndex = 0
}
let returnColor = colorsArray[currentColorIndex]
++currentColorIndex
return returnColor
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if refreshController.refreshing {
if !isAnimating {
doSomething()
animateRefreshStep1()
}
}
}
func doSomething() {
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "endedOfWork", userInfo: nil, repeats: true)
}
func endedOfWork() {
refreshController.endRefreshing()
timer.invalidate()
timer = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 736d7a051916702abc3db875f6878b35 | 37.392265 | 197 | 0.577781 | 6.074301 | false | false | false | false |
vimeo/VimeoUpload | VimeoUpload/Upload/Operations/Async/VideoOperation.swift | 1 | 3189 | //
// RefreshVideoOperation.swift
// VimeoUpload
//
// Created by Hanssen, Alfie on 12/14/15.
// Copyright © 2015 Vimeo. 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
import VimeoNetworking
@objc public class VideoOperation: ConcurrentOperation
{
private let sessionManager: VimeoSessionManager
private let videoUri: String
private var task: Task?
private(set) var video: VIMVideo?
private(set) var error: NSError?
// MARK: - Initialization
init(sessionManager: VimeoSessionManager, videoUri: String)
{
self.sessionManager = sessionManager
self.videoUri = videoUri
super.init()
}
deinit
{
self.task?.cancel()
}
// MARK: Overrides
@objc override public func main()
{
if self.isCancelled
{
return
}
do
{
self.task = try self.sessionManager.videoDataTask(videoUri: self.videoUri, completionHandler: { [weak self] (video, error) -> Void in
guard let strongSelf = self else
{
return
}
strongSelf.task = nil
if strongSelf.isCancelled
{
return
}
if let error = error
{
strongSelf.error = error.error(byAddingDomain: UploadErrorDomain.VideoOperation.rawValue)
}
else
{
strongSelf.video = video
}
strongSelf.state = .finished
})
self.task?.resume()
}
catch let error as NSError
{
self.error = error.error(byAddingDomain: UploadErrorDomain.VideoOperation.rawValue)
self.state = .finished
}
}
@objc override public func cancel()
{
super.cancel()
self.task?.cancel()
}
}
| mit | 8392b0142bd25fe95692f471b09b9418 | 28.794393 | 145 | 0.583752 | 5.133655 | false | false | false | false |
Fenrikur/ef-app_ios | Shared Kernel/EventBus/EventConsumer.swift | 1 | 1129 | /**
An `EventConsumer` represents a type that consumes events transmitted through
an `EventBus`, acting upon the meaning and representation of the received
`Event`. `Event`s could represent a change in state, timer event, action etc.
*/
public protocol EventConsumer: Equatable {
/// Represents the type of the event this consumer will observe.
associatedtype Event
/**
Tells this consumer to accept and act upon the `Event`.
- parameters:
- event: An `Event` broadcast through an `EventBus`, representing a
change in state, action or other behaviour within your program.
*/
func consume(event: Event)
}
public extension EventConsumer where Self: AnyObject {
/**
Compares two `EventConsumer`s that are reference types.
- parameters:
- lhs: An `EventConsumer` to compare
- rhs: An `EventConsumer` to compare against `lhs`
- returns: `true` if `lhs` and `rhs` both refer to the same `EventConsumer`,
`false` otherwise.
*/
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs === rhs
}
}
| mit | 70ebdd8d8ff7a847da2e0142d347add2 | 28.710526 | 81 | 0.654562 | 4.57085 | false | false | false | false |
xuzhou524/Convenient-Swift | View/BaseTableViewCell.swift | 1 | 2379 | //
// BaseTableViewCell.swift
// Convenient-Swift
//
// Created by gozap on 16/3/16.
// Copyright © 2016年 xuzhou. All rights reserved.
//
import UIKit
class BaseTableViewCell: UITableViewCell {
var titleLabel: UILabel?
var detaileLabel: UILabel?
var rightImage: UIImageView?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.sebView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.sebView()
}
func sebView(){
self.titleLabel = UILabel()
self.titleLabel?.text = "当前版本"
self.titleLabel?.textColor = XZSwiftColor.textColor
self.titleLabel?.font = XZFont2(15)
self.contentView.addSubview(self.titleLabel!)
self.titleLabel!.snp.makeConstraints({ (make) -> Void in
make.left.equalTo(self.contentView).offset(15)
make.centerY.equalTo(self.contentView)
});
self.rightImage = UIImageView()
self.rightImage?.image = UIImage(named: "arrow_right")
self.contentView.addSubview(self.rightImage!)
self.rightImage?.snp.makeConstraints({ (make) in
make.centerY.equalTo(self.contentView)
make.height.equalTo(15)
make.width.equalTo(12)
make.right.equalTo(self.contentView).offset(-10)
});
self.detaileLabel = UILabel()
self.detaileLabel?.text = "v1.0.0"
self.detaileLabel?.textColor = XZSwiftColor.textColor
self.detaileLabel?.font = XZFont2(14)
self.detaileLabel?.textAlignment = .right;
self.contentView.addSubview(self.detaileLabel!)
self.detaileLabel!.snp.makeConstraints({ (make) -> Void in
make.right.equalTo((self.rightImage?.snp.left)!).offset(-5)
make.centerY.equalTo(self.contentView)
});
let linView = UIView()
linView.backgroundColor = XZSwiftColor.xzGlay230
self.contentView.addSubview(linView)
linView.snp.makeConstraints { (make) -> Void in
make.height.equalTo(0.5);
make.right.equalTo(self.contentView)
make.left.equalTo(self.contentView).offset(15)
make.bottom.equalTo(self.contentView)
}
}
}
| mit | 571a5459209e8eeeb26e917f0dc8ae8e | 33.823529 | 79 | 0.628801 | 4.321168 | false | false | false | false |
jaisonv/ActiveCoreData | ActiveCoreData-Example/ViewController.swift | 1 | 3532 | //
// ViewController.swift
// ActiveCoreData-Example
//
// Created by Jaison Vieira on 7/24/16.
// Copyright © 2016 jaisonv. All rights reserved.
//
import UIKit
import ActiveCoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: Create NSManagedObject
func createExample() {
// create animal
let animal = Animal.create()
// set attributes
animal.species = "Dog"
animal.breed = "Chihuahua"
animal.name = "Rex"
animal.color = "Black"
animal.gender = Gender.male.rawValue as NSNumber?
// persist animal
animal.save()
}
// MARK: find all the persisted objects of type 'Animal'
func findAllExample() {
let animals = Animal.findAll() as! [Animal]
for animal in animals {
print("Name: \(animal.name)")
print("Breed: \(animal.breed)")
}
}
// MARK: Find all the persisted objects of type 'Animal' with name attribute 'Rex'
func findAllByAttributeExample() {
let animals = Animal.findAll(attribute: "name", value: "Rex") as! [Animal]
for animal in animals {
print("Name: \(animal.name)")
print("Breed: \(animal.breed)")
}
}
// MARK: Find the first persisted object of type 'Animal'
func findFirstExample() {
if let animal = Animal.findFirst() {
print("Name: \(animal.name)")
print("Breed: \(animal.breed)")
}
}
// MARK: Find the first persisted object of type 'Animal' with name attribute 'Rex'
func findFirstByAttributeExample() {
if let animal = Animal.findFirst(attribute: "name", value: "Rex") {
print("Name: \(animal.name)")
print("Breed: \(animal.breed)")
}
}
// MARK: Find the first persisted object of type 'Animal', update it and save
func findFirstAndUpdateExample() {
if let animal = Animal.findFirst() {
print("Name: \(animal.name)")
print("Breed: \(animal.breed)")
animal.name = "Lucky" // change name
animal.save() // save
print("Name: \(animal.name)")
print("Breed: \(animal.breed)")
}
}
// MARK: Find the first persisted object of type 'Animal' and delete it
func findFirstAndDeleteExample() {
if let animal = Animal.findFirst() {
print("Name: \(animal.name)")
print("Breed: \(animal.breed)")
animal.delete() // delete
}
}
@IBAction func createButtonDidTouch(_ sender: Any) {
createExample()
}
@IBAction func findAllButtonDidTouch(_ sender: Any) {
findAllExample()
}
@IBAction func FindAllByAttributeButtonDidTouch(_ sender: Any) {
findAllByAttributeExample()
}
@IBAction func findFirstButtonDidTouch(_ sender: Any) {
findFirstExample()
}
@IBAction func findFirstByAttributeButtonDidTouch(_ sender: Any) {
findFirstByAttributeExample()
}
@IBAction func findFirstAndUpdateButtonDidTouch(_ sender: Any) {
findFirstAndUpdateExample()
}
@IBAction func findFirstAndDeleteButtonDidTouch(_ sender: Any) {
findFirstAndDeleteExample()
}
}
| mit | 4990482b022dba02f61aafab68b9f75d | 20.271084 | 87 | 0.558199 | 4.830369 | false | false | false | false |
mohssenfathi/MTLImage | MTLImage/Sources/Filters/Vignette.swift | 1 | 2485 | //
// Vignette.swift
// Pods
//
// Created by Mohssen Fathi on 4/8/16.
//
//
import UIKit
struct VignetteUniforms: Uniforms {
var x: Float = 0.0
var y: Float = 0.0
var r: Float = 1.0
var g: Float = 1.0
var b: Float = 1.0
var start: Float = 0.25
var end: Float = 0.7
}
public
class Vignette: Filter {
var uniforms = VignetteUniforms()
@objc public var center: CGPoint = CGPoint(x: 0.5, y: 0.5) {
didSet {
needsUpdate = true
}
}
@objc public var color: UIColor = UIColor.black {
didSet {
needsUpdate = true
}
}
@objc public var start: Float = 0.25 {
didSet {
clamp(&start, low: 0, high: 1)
needsUpdate = true
}
}
@objc public var end: Float = 0.7 {
didSet {
clamp(&end, low: 0, high: 1)
needsUpdate = true
update()
}
}
public override func reset() {
center = CGPoint(x: 0.5, y: 0.5)
color = UIColor.black
start = 0.25
end = 0.7
}
public init() {
super.init(functionName: "vignette")
title = "Vignette"
properties = [Property(key: "center", title: "Center", propertyType: .point),
Property(key: "color" , title: "Color" , propertyType: .color),
Property(key: "start" , title: "Start" ),
Property(key: "end" , title: "End" )]
update()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public var needsUpdate: Bool {
didSet {
if needsUpdate == true { update() }
}
}
override func update() {
if self.input == nil { return }
let components = color.cgColor.components
if color == UIColor.white || color == UIColor.black {
uniforms.r = Float((components?[0])!)
uniforms.g = Float((components?[0])!)
uniforms.b = Float((components?[0])!)
} else {
uniforms.r = Float((components?[0])!)
uniforms.g = Float((components?[1])!)
uniforms.b = Float((components?[2])!)
}
uniforms.x = Float(center.x)
uniforms.y = Float(center.y)
uniforms.start = start
uniforms.end = end
updateUniforms(uniforms: uniforms)
}
}
| mit | 0a6ed61ef1703534eb07e0e795b1ea26 | 23.126214 | 85 | 0.497384 | 4.060458 | false | false | false | false |
joshc89/DeclarativeLayout | DeclarativeLayout/Example Layouts/DetailPageLayout.swift | 1 | 2613 | //
// DetailPageLayout.swift
// DeclarativeLayout
//
// Created by Josh Campion on 19/07/2016.
// Copyright © 2016 Josh Campion. All rights reserved.
//
import UIKit
/// Adds Convenience initialiser for `ParallaxScrollLayout`.
public extension ParallaxScrollLayout {
// MARK: Convenience Initialisers
/**
Convenience initialiser stacking a `TitledLayout` with a given `contentLayout` nested inside a white view as the `foregroundLayout`. This is a common layout for a detail page such as an article.
- parameter backgroundLayout: Set as the `backgroundLayout` property.
- parameter title: Set as the title in the `TitledLayout`.
- parameter subtitle: Set as the subtitle in the `TitledLayout`.
- parameter contentLayout: Stacked below the `TitledLayout`, this is the main point of customisation for this layout.
- parameter scrollContentEdge: The edge the stacked content should be aligned to within the scroll view. Default value is `.ReadableContent`.
- parameter withInsets: Extra inset to align the stacked content with the `scrollContentEdge`. Default value is zero.
*/
public convenience init(backgroundLayout: Layout,
title:String?,
subtitle:String?,
contentLayout: Layout,
scrollContentEdge: UIView.Edge = .readableContent,
withInsets: UIEdgeInsets = .zero) {
let titleLayout = TitledLayout(title: title, subtitle: subtitle)
if title?.isEmpty ?? true && subtitle?.isEmpty ?? true {
titleLayout.textStack.isHidden = true
}
let scrollContent = UIStackView(arrangedLayouts: [titleLayout, contentLayout])
scrollContent.axis = .vertical
scrollContent.spacing = 16.0
scrollContent.translatesAutoresizingMaskIntoConstraints = false
// give the scroll content a white background by nesting in a view.
let scrollContentView = UIView()
scrollContentView.backgroundColor = UIColor.white
scrollContentView.preservesSuperviewLayoutMargins = true
scrollContentView.addSubview(scrollContent)
let contentConstraints = scrollContent.constraintsAligningEdges(to: scrollContentView.anchorsForEdge(scrollContentEdge), withInsets: withInsets)
NSLayoutConstraint.activate(contentConstraints)
// create the layout
self.init(background: backgroundLayout, foreground: scrollContentView)
}
}
| mit | 4b2812da8c45dfef84e0084bba5010cd | 43.271186 | 199 | 0.671899 | 5.60515 | false | false | false | false |
viczy/SwiftForward | Pods/Cartography/Cartography/LayoutProxy.swift | 1 | 1607 | //
// LayoutProxy.swift
// Cartography
//
// Created by Robert Böhnke on 17/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
import Foundation
public class LayoutProxy {
public let width: Dimension
public let height: Dimension
public let size: Size
public let top: Edge
public let right: Edge
public let bottom: Edge
public let left: Edge
public let edges: Edges
public let leading: Edge
public let trailing: Edge
public let centerX: Edge
public let centerY: Edge
public let center: Point
public let baseline: Edge
internal let context: Context
internal let view: View
public var superview: LayoutProxy? {
if let superview = view.superview {
return LayoutProxy(context, superview)
} else {
return nil
}
}
init(_ context: Context, _ view: View) {
self.context = context
self.view = view
width = Dimension.Width(context, view)
height = Dimension.Height(context, view)
size = Size.Size(context, view)
top = Edge.Top(context, view)
right = Edge.Right(context, view)
bottom = Edge.Bottom(context, view)
left = Edge.Left(context, view)
edges = Edges.Edges(context, view)
leading = Edge.Leading(context, view)
trailing = Edge.Trailing(context, view)
centerX = Edge.CenterX(context, view)
centerY = Edge.CenterY(context, view)
center = Point.Center(context, view)
baseline = Edge.Baseline(context, view)
}
}
| apache-2.0 | 5b5f341b53cfb932d6bfae8ebe9cbad0 | 21.928571 | 58 | 0.621807 | 4.291444 | false | false | false | false |
MenloHacks/ios-app | Menlo Hacks/Pods/PushNotifications/Sources/NetworkService.swift | 1 | 8973 | import Foundation
class NetworkService: PushNotificationsNetworkable {
let session: URLSession
let queue = DispatchQueue(label: Constants.DispatchQueue.networkQueue)
init(session: URLSession) {
self.session = session
}
// MARK: PushNotificationsNetworkable
func register(url: URL, deviceToken: Data, instanceId: String, completion: @escaping CompletionHandler<Result<Device, Error>>) {
let deviceTokenString = deviceToken.hexadecimalRepresentation()
let bundleIdentifier = Bundle.main.bundleIdentifier ?? ""
let metadata = Metadata.update()
guard let body = try? Register(token: deviceTokenString, instanceId: instanceId, bundleIdentifier: bundleIdentifier, metadata: metadata).encode() else {
return completion(.error(PushNotificationsError.error("[PushNotifications] - Error while encoding register payload.")))
}
let request = self.setRequest(url: url, httpMethod: .POST, body: body)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value(let response):
guard let device = try? JSONDecoder().decode(Device.self, from: response) else {
return completion(.error(PushNotificationsError.error("[PushNotifications] - Error while encoding device payload.")))
}
completion(.value(device))
case .error(let error):
completion(.error(error))
}
}
}
func subscribe(url: URL, completion: @escaping CompletionHandler<Result<Void, Error>>) {
let request = self.setRequest(url: url, httpMethod: .POST)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
func setSubscriptions(url: URL, interests: [String], completion: @escaping CompletionHandler<Result<Void, Error>>) {
guard let body = try? Interests(interests: interests).encode() else {
return completion(.error(PushNotificationsError.error("[PushNotifications] - Error while encoding the interests payload.")))
}
let request = self.setRequest(url: url, httpMethod: .PUT, body: body)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
func unsubscribe(url: URL, completion: @escaping CompletionHandler<Result<Void, Error>>) {
let request = self.setRequest(url: url, httpMethod: .DELETE)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
func track(url: URL, eventType: ReportEventType, completion: @escaping CompletionHandler<Result<Void, Error>>) {
guard let body = try? eventType.encode() else {
return completion(.error(PushNotificationsError.error("[PushNotifications] - Error while encoding the event type payload.")))
}
let request = self.setRequest(url: url, httpMethod: .POST, body: body)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
func syncMetadata(url: URL, completion: @escaping CompletionHandler<Result<Void, Error>>) {
guard let metadataDictionary = Metadata.load() else {
return completion(.error(PushNotificationsError.error("[PushNotifications] - Error while loading the metadata.")))
}
let metadata = Metadata(propertyListRepresentation: metadataDictionary)
if metadata.hasChanged() {
let updatedMetadataObject = Metadata.update()
guard let body = try? updatedMetadataObject.encode() else {
return completion(.error(PushNotificationsError.error("[PushNotifications] - Error while encoding the metadata payload.")))
}
let request = self.setRequest(url: url, httpMethod: .PUT, body: body)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
}
func setUserId(url: URL, token: String, completion: @escaping CompletionHandler<Result<Void, Error>>) {
var request = self.setRequest(url: url, httpMethod: .PUT)
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
func deleteDevice(url: URL, completion: @escaping CompletionHandler<Result<Void, Error>>) {
let request = self.setRequest(url: url, httpMethod: .DELETE)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
func getDevice(url: URL, completion: @escaping CompletionHandler<Result<Void, Error>>) {
let request = self.setRequest(url: url, httpMethod: .GET)
self.networkRequest(request, session: self.session) { result in
switch result {
case .value:
completion(.value(()))
case .error(let error):
completion(.error(error))
}
}
}
// MARK: Networking Layer
private func networkRequest(_ request: URLRequest, session: URLSession, completion: @escaping (_ result: Result<Data, Error>) -> Void) {
self.queue.async {
self.queue.suspend()
func networkRequestWithExponentialBackoff(numberOfAttempts: Int = 0) {
session.dataTask(with: request, completionHandler: { (data, response, error) in
guard
let data = data,
let httpURLResponse = response as? HTTPURLResponse
else {
Thread.sleep(forTimeInterval: TimeInterval(self.calculateExponentialBackoffMs(attemptCount: numberOfAttempts) / 1000.0))
return networkRequestWithExponentialBackoff(numberOfAttempts: numberOfAttempts + 1)
}
let statusCode = httpURLResponse.statusCode
if 400..<500 ~= statusCode && error == nil {
if let reason = try? JSONDecoder().decode(Reason.self, from: data) {
print("[PushNotifications]: Request failed due to: \(reason.description), skipping it.")
}
} else if statusCode >= 500 && error == nil {
if let reason = try? JSONDecoder().decode(Reason.self, from: data) {
print("[PushNotifications]: \(reason.description)")
}
Thread.sleep(forTimeInterval: TimeInterval(self.calculateExponentialBackoffMs(attemptCount: numberOfAttempts) / 1000.0))
return networkRequestWithExponentialBackoff(numberOfAttempts: numberOfAttempts + 1)
}
self.queue.resume()
completion(.value(data))
}).resume()
}
networkRequestWithExponentialBackoff()
}
}
private let maxExponentialBackoffDelayMs = 32000.0
private let baseExponentialBackoffDelayMs = 200.0
private func calculateExponentialBackoffMs(attemptCount: Int) -> Double {
return min(maxExponentialBackoffDelayMs, baseExponentialBackoffDelayMs * pow(2.0, Double(attemptCount)))
}
private func setRequest(url: URL, httpMethod: HTTPMethod, body: Data? = nil) -> URLRequest {
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("push-notifications-swift \(SDK.version)", forHTTPHeaderField: "X-Pusher-Library")
request.httpMethod = httpMethod.rawValue
request.httpBody = body
return request
}
}
| mit | 55c26f99dfcc60312e4122c9a1b93c69 | 41.933014 | 160 | 0.595453 | 5.322064 | false | false | false | false |
kdawgwilk/vapor | Sources/Vapor/Fixes/FileManager.swift | 1 | 2928 | import Foundation
import libc
/**
A replacement for Foundation's NSFileManager using
implementation from Swift's core libraries.
*/
class FileManager {
enum Error: ErrorProtocol {
case CouldNotOpenFile
case Unreadable
}
static func readBytesFromFile(_ path: String) throws -> [UInt8] {
guard let data = NSData(contentsOfFile: path) else {
throw Error.CouldNotOpenFile
}
return data.byteArray ?? []
}
static func fileAtPath(_ path: String) -> (exists: Bool, isDirectory: Bool) {
var isDirectory = false
var s = stat()
if lstat(path, &s) >= 0 {
if (s.st_mode & S_IFMT) == S_IFLNK {
if stat(path, &s) >= 0 {
isDirectory = (s.st_mode & S_IFMT) == S_IFDIR
} else {
return (false, isDirectory)
}
} else {
isDirectory = (s.st_mode & S_IFMT) == S_IFDIR
}
// don't chase the link for this magic case -- we might be /Net/foo
// which is a symlink to /private/Net/foo which is not yet mounted...
if (s.st_mode & S_IFMT) == S_IFLNK {
if (s.st_mode & S_ISVTX) == S_ISVTX {
return (true, isDirectory)
}
// chase the link; too bad if it is a slink to /Net/foo
let _ = stat(path, &s) >= 0
}
} else {
return (false, isDirectory)
}
return (true, isDirectory)
}
static func expandPath(_ path: String) throws -> String {
let maybeResult = realpath(path, nil)
guard let result = maybeResult else {
throw Error.Unreadable
}
defer { free(result) }
let cstring = String(validatingUTF8: result)
if let expanded = cstring {
return expanded
} else {
throw Error.Unreadable
}
}
static func contentsOfDirectory(_ path: String) throws -> [String] {
var gt = glob_t()
defer { globfree(>) }
let path = try self.expandPath(path).finished(with: "/")
let pattern = strdup(path + "{*,.*}")
switch glob(pattern, GLOB_MARK | GLOB_NOSORT | GLOB_BRACE, nil, >) {
case GLOB_NOMATCH:
return [ ]
case GLOB_ABORTED:
throw Error.Unreadable
default:
break
}
var contents = [String]()
let count: Int
#if os(Linux)
count = Int(gt.gl_pathc)
#else
count = Int(gt.gl_matchc)
#endif
for i in 0..<count {
guard let utf8 = gt.gl_pathv[i] else { continue }
let cstring = String(validatingUTF8: utf8)
if let path = cstring {
contents.append(path)
}
}
return contents
}
}
| mit | b3fdb66c25ee8e3506a5ffc5db900d67 | 27.153846 | 81 | 0.503757 | 4.305882 | false | false | false | false |
megavolt605/CNLDataProvider | CNLDataProvider/CNLDataProviderEditable.swift | 1 | 5989 | //
// CNLDataProviderEditable.swift
// CNLDataProvider
//
// Created by Igor Smirnov on 23/12/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import Foundation
public protocol CNLDataProviderEditable: CNLDataProvider {
var canEdit: Bool { get set }
var instructionsLabel: UILabel! { get set }
var instructionsLabelHeightConstraint: NSLayoutConstraint! { get set }
var visualEffectView: UIView? { get set }
var editBarButtonItem: UIBarButtonItem! { get set }
var editButtonTitle: String { get set }
var doneButtonTitle: String { get set }
func editAction(_ animated: Bool, willStartEditing: () -> Void, willFinishEditing: () -> Void)
func saveAction()
}
public extension CNLDataProviderEditable where Self: CNLCanShowViewAcvtitity,
Self.ModelType.ArrayElement: CNLModelDictionaryKeyStored, Self.ModelType: CNLModelObjectEditable {
fileprivate typealias Lists = (old: [ModelType.ArrayElement], new: [ModelType.ArrayElement])
fileprivate func switchEditing() -> Lists {
var result = Lists(old: self.dataSource.allItems, new: [])
self.dataSource.model.editing = !self.dataSource.model.editing
self.dataSource.model.updateList()
self.dataSource.reset()
self.dataSource.requestCompleted()
result.new = self.dataSource.allItems
return result
}
fileprivate func startEditing(_ animated: Bool) {
dataViewer.allowsMultipleSelection = true
instructionsLabel.frame.size.height = 0.0
instructionsLabel.isHidden = false
if let view = dataViewer as? UIView {
visualEffectView?.frame.size.width = view.frame.width
}
visualEffectView?.frame.size.height = 0.0
visualEffectView?.isHidden = false
UIView.setAnimationsEnabled(animated)
UIView.animate(
withDuration: 0.3,
animations: {
self.dataViewer.setContentOffset(CGPoint(x: 0.0, y: -64.0), animated: false)
self.dataViewer.contentInset = UIEdgeInsets(top: 64.0, left: 0.0, bottom: 0.0, right: 0.0)
self.instructionsLabel.frame.size.height = 64.0
self.visualEffectView?.frame.size.height = 64.0
self.editBarButtonItem.title = self.doneButtonTitle
var items: [IndexPath] = []
self.dataViewer.batchUpdates(
updates: {
let lists = self.switchEditing()
var i = 0
var inserted: [Int] = []
for (index, item) in lists.new.enumerated() {
if (i >= lists.old.count) || (lists.old[i].primaryKey != item.primaryKey) {
inserted.append(index)
} else {
i += 1
}
}
items = inserted.map { return self.dataViewer.createIndexPath(item: $0, section: 0) } // !!! section
self.dataViewer.insertItems(at: items)
self.updateCounts()
},
completion: { _ in
items.forEach {
self.dataViewer.selectItemAtIndexPath($0, animated: false, scrollPosition: .none)
self.dataViewer.notifyDelegateDidSelectItemAtIndexPath($0)
}
}
)
},
completion: { _ in
UIView.setAnimationsEnabled(true)
}
)
}
fileprivate func finishEditing(_ animated: Bool) {
instructionsLabel.frame.size.height = 64.0
visualEffectView?.frame.size.height = 64.0
self.dataViewer.setContentOffset(CGPoint(x: 0, y: self.dataViewer.contentOffset.y), animated: true)
UIView.setAnimationsEnabled(animated)
UIView.animate(
withDuration: 0.3,
animations: {
self.dataViewer.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
self.instructionsLabel.frame.size.height = 0.0
self.visualEffectView?.frame.size.height = 0.0
self.editBarButtonItem.title = self.editButtonTitle
self.dataViewer.batchUpdates(
updates: {
let lists = self.switchEditing()
var i = 0
var removed: [Int] = []
for (index, item) in lists.old.enumerated() {
if (i >= lists.new.count) || (lists.new[i].primaryKey != item.primaryKey) {
removed.append(index)
} else {
i += 1
}
}
let items = removed.map { return self.dataViewer.createIndexPath(item: $0, section: 0) } // !!! section
self.dataViewer.deleteItems(at: items)
self.updateCounts()
}, completion: { _ in
self.dataViewer.allowsMultipleSelection = false
self.saveAction()
}
)
},
completion: { _ in
self.instructionsLabel.isHidden = true
self.visualEffectView?.isHidden = true
UIView.setAnimationsEnabled(true)
}
)
}
func editAction(_ animated: Bool, willStartEditing: () -> Void, willFinishEditing: () -> Void) {
guard canEdit else { return }
if !dataSource.model.editing {
willStartEditing()
startEditing(animated)
} else {
willFinishEditing()
finishEditing(animated)
}
}
}
| mit | b0f19a9c90d8824166d99c26fb17899c | 40.583333 | 127 | 0.5334 | 5.257243 | false | false | false | false |
juergen/_Playgrounds | TideParser1.playground/Sources/Extensions.swift | 1 | 2936 | //
// This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to TideParser1.playground.
//
import Foundation
public extension String {
// func split(separator:String) -> [NSString] {
// return self.componentsSeparatedByString(separator) as [NSString]
// }
func split(separator:String) -> [String] {
return self.componentsSeparatedByString(separator) as [String]
}
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
func parseDate(format:String="yyyy-MM-dd") -> NSDate? {
let dateFmt = NSDateFormatter()
dateFmt.timeZone = NSTimeZone.defaultTimeZone() //NSTimeZone.localTimeZone()
dateFmt.dateFormat = format
if let date = dateFmt.dateFromString(self) {
return date
}
return nil
}
func replaceAll(replaceMe:String, replacement:String) -> String {
return self.stringByReplacingOccurrencesOfString(replaceMe, withString: replacement, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
func toFloat() -> Float? {
if self.isEmpty {
return nil
}
// we need to ignore e.g. "60 - 80" values
if self.trim().rangeOfString(" ") != nil {
return nil
}
let s = self.trim().replaceAll(",", replacement: ".")
return (NSString(string: s).floatValue)
}
func substringBetween(first: String, last: String) -> String? {
if let start = self.rangeOfString(first)?.startIndex {
if let end = self.rangeOfString(last, options:NSStringCompareOptions.BackwardsSearch)?.endIndex {
return self.substringWithRange(start ..< end)
}
}
return nil
}
func substringBetweenExclude(first: String, last: String) -> String? {
if let start = self.rangeOfString(first)?.endIndex {
if let end = self.rangeOfString(last, options:NSStringCompareOptions.BackwardsSearch)?.startIndex {
return self.substringWithRange(start ..< end)
}
}
return nil
}
func substringBefore(before: String) -> String? {
if let end = self.rangeOfString(before, options:NSStringCompareOptions.BackwardsSearch)?.startIndex {
return self.substringWithRange(self.startIndex ..< end)
}
return nil
}
func substringAfter(after: String) -> String? {
if let start = self.rangeOfString(after)?.startIndex {
return self.substringWithRange(start ..< self.endIndex)
}
return nil
}
func leftPad(c:Int, pad:String) -> String {
if c > self.characters.count {
return (pad + self).leftPad(c, pad: pad)
}
return self
}
}
public extension Int {
func leftPad(c:Int, pad:String) -> String {
let intAsString = "\(self)"
if c > intAsString.characters.count {
return (pad + intAsString).leftPad(c, pad: pad)
}
return intAsString
}
} | mit | 0fe190b236454c2109ac61ee3abcb8f7 | 28.969388 | 193 | 0.675068 | 4.356083 | false | false | false | false |
volochaev/firebase-and-facebook | firebase-example/MaterialButton.swift | 1 | 535 | //
// MaterialButton.swift
// firebase-example
//
// Created by Nikolai Volochaev on 02/11/15.
// Copyright © 2015 Nikolai Volochaev. All rights reserved.
//
import UIKit
class MaterialButton: UIButton {
override func awakeFromNib() {
layer.cornerRadius = 2.0
layer.shadowColor = UIColor(red: UI_SHADOW_COLOR, green: UI_SHADOW_COLOR, blue: UI_SHADOW_COLOR, alpha: 0.5).CGColor
layer.shadowOpacity = 0.9
layer.shadowRadius = 5.0
layer.shadowOffset = CGSizeMake(0.0, 1.0)
}
}
| mit | bb0e78705fa361884b17ada487b8140b | 25.7 | 126 | 0.659176 | 3.536424 | false | false | false | false |
icapps/ios-air-rivet | Documentation/FaroPlayground.playground/Pages/1. Data received as an array.xcplaygroundpage/Contents.swift | 3 | 4647 | import UIKit
import Faro
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
/*:
# 1. Data received as an array
Faro has switched to use the native `Decoder` and `Encoder` in Swift 4. We use the playground Apple provide in [WWDC2017 session: Whats new in Foundation](https://developer.apple.com/videos/play/wwdc2017/212/)
## Grocery store example
In a grocery store there are products. They have a name and an optional description.
To fetch them from de service and have a `GroceryProduct` array do:
1. Create `Decodable` model
> *More info in folder /Documentation/Using-JSON-with-Custom-Types.playground provided by Apple.*
2. Create a `Service` object and use the perform function
3. Handle the result
*/
//: First make sure we run stubbed network requests
StubbedFaroURLSession.setup()
//: Create stubbed data that can be returned by the service.
let jsonArray = """
[
{
"name": "Banana",
"points": 200,
"description": "A banana grown in Ecuador."
},
{
"name": "Orange",
"points": 100
}
]
""".data(using: .utf8)!
/*: > For more information about how we stub the session to return the data from 'jsonArray' you should take a look at Stubbing.swift file in sources folder.
Every service object is also linked to a specific *endpoint* example: `<baseURL>/products`. To define an endpoint we use an object called `Call`.
*/
let call = Call(path: "products")
//: A call can be handled by a service object. In your code you are encouraged to created subclasses per call.
let service = Service(call: call)
//: Now we will stub the call with the data from above. We will call 4 times wo me need to stub 3 times.
call.stub(statusCode: 200, data: jsonArray)
call.stub(statusCode: 200, data: jsonArray)
call.stub(statusCode: 200, data: jsonArray)
call.stub(statusCode: 200, data: jsonArray)
/*:
The function `perform` can decode any type of model that implements `Decodable`. Luckaly in most cases to implement decodable you do **nothing**!
The first parameter is the type. In Swift of any type you can pass the type itself as a parameter by using *Type.self*.
*/
service.perform([Product].self) { (done) in
// see explanation below on how to get the product array
}
/*:
## Getting the result via a throwing function
This might seam wierd at first but actually allows you to write condense and descriptive code. In Swift funtions are like variables. You can use them in the same way as you would use an `Int` variable. To get my head around this 2 things helped:
> 1. The syntax is wierd but condense. `var function: () -> Void` means that the type of the variable function is a function 🙃. You can assign any function that takes no arguments `()` and returns nothing `Void`
> 2. Before any function returns a value something can go wrong. To report back to the caller of the function that something went wrong you have 2 options: `return nil` or `throw error`
### `Return` to end execution version `throw`
Both return and throw end the execution of the program at a specific line.
1. code
2. code
3. `return`
4. code // will not be executed
Same goes for throw
1. code
2. code
3. `throw error`
4. code // will not be executed
The main difference is that at line 3 we want to tell the caller of the function what went wrong. This difficult with return nil. The error thrown is more descriptive.
*/
service.perform([Product].self) { (done) in
do {
let products = try done()
products.forEach { print("🚀 We have \($0)")}
}
//: Generic way to catch the error and inspect what is going wrong
catch let error as ServiceError where error.decodingErrorMissingKey != nil {
print("Error with missing key \\\(error.decodingErrorMissingKey!)")
} catch {
// ignore error
}
}
/*:
> !Try to remove the name or points form `jsonArray` an see the error described.
> !! Faro also prints the errors so you should not do this in code !!!
So you can write the above more condense
*/
service.perform([Product].self) { (done) in
(try? done())?.forEach { print("🚀🚀 We have \($0)")}
}
//: Because of swift implicit arguments in closures we can replace `done` with `$0`
service.perform([Product].self) { (try? $0())?.forEach { print("🚀🚀🚀 We have \($0)")} }
/*: In the 2 last result we do not use the error. This is because Faro prints any error. So if you do not show the error to the user you can ignore it by writing `try?` which makes `nil` from the thrown `error`.
---
[Table of Contents](0.%20Table%20of%20Contents) [Previous](@previous) / [Next](@next)
*/
| mit | 577224ed7feb1e8504cf7ac1a0309fb1 | 43.480769 | 245 | 0.710117 | 4.012142 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Requests/Threads/ThreadUnfollowRequest.swift | 1 | 819 | //
// ThreadUnfollowRequest.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 16/04/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
// DOCS: https://rocket.chat/docs/developer-guides/rest-api/chat/unfollowmessage/
import Foundation
import SwiftyJSON
final class ThreadUnfollowRequest: APIRequest {
typealias APIResourceType = ThreadUnfollowResource
let requiredVersion = Version(1, 0, 0)
let method: HTTPMethod = .post
var path = "/api/v1/chat.unfollowMessage"
let mid: String
init(mid: String) {
self.mid = mid
}
func body() -> Data? {
return JSON(["mid": mid]).rawString()?.data(using: .utf8)
}
}
final class ThreadUnfollowResource: APIResource {
var success: Bool? {
return raw?["success"].boolValue
}
}
| mit | dedab680d56ab04d03a0a6488a64152a | 20.526316 | 81 | 0.668704 | 3.752294 | false | false | false | false |
cliqz-oss/browser-ios | Account/SyncAuthState.swift | 10 | 6737 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
import SwiftyJSON
private let CurrentSyncAuthStateCacheVersion = 1
private let log = Logger.syncLogger
public struct SyncAuthStateCache {
let token: TokenServerToken
let forKey: Data
let expiresAt: Timestamp
}
public protocol SyncAuthState {
func invalidate()
func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>>
}
public func syncAuthStateCachefromJSON(_ json: JSON) -> SyncAuthStateCache? {
if let version = json["version"].int {
if version != CurrentSyncAuthStateCacheVersion {
log.warning("Sync Auth State Cache is wrong version; dropping.")
return nil
}
if let
token = TokenServerToken.fromJSON(json["token"]),
let forKey = json["forKey"].string?.hexDecodedData,
let expiresAt = json["expiresAt"].int64 {
return SyncAuthStateCache(token: token, forKey: forKey, expiresAt: Timestamp(expiresAt))
}
}
return nil
}
extension SyncAuthStateCache: JSONLiteralConvertible {
public func asJSON() -> JSON {
return JSON([
"version": CurrentSyncAuthStateCacheVersion,
"token": token.asJSON(),
"forKey": forKey.hexEncodedString,
"expiresAt": NSNumber(value: expiresAt),
] as NSDictionary)
}
}
open class FirefoxAccountSyncAuthState: SyncAuthState {
fileprivate let account: FirefoxAccount
fileprivate let cache: KeychainCache<SyncAuthStateCache>
init(account: FirefoxAccount, cache: KeychainCache<SyncAuthStateCache>) {
self.account = account
self.cache = cache
}
// If a token gives you a 401, invalidate it and request a new one.
open func invalidate() {
log.info("Invalidating cached token server token.")
self.cache.value = nil
}
// Generate an assertion and try to fetch a token server token, retrying at most a fixed number
// of times.
//
// It's tricky to get Swift to recurse into a closure that captures from the environment without
// segfaulting the compiler, so we pass everything around, like barbarians.
fileprivate func generateAssertionAndFetchTokenAt(_ audience: String,
client: TokenServerClient,
clientState: String?,
married: MarriedState,
now: Timestamp,
retryCount: Int) -> Deferred<Maybe<TokenServerToken>> {
let assertion = married.generateAssertionForAudience(audience, now: now)
return client.token(assertion, clientState: clientState).bind { result in
if retryCount > 0 {
if let tokenServerError = result.failureValue as? TokenServerError {
switch tokenServerError {
case let .remote(code, status, remoteTimestamp) where code == 401 && status == "invalid-timestamp":
if let remoteTimestamp = remoteTimestamp {
let skew = Int64(remoteTimestamp) - Int64(now) // Without casts, runtime crash due to overflow.
log.info("Token server responded with 401/invalid-timestamp: retrying with remote timestamp \(remoteTimestamp), which is local timestamp + skew = \(now) + \(skew).")
return self.generateAssertionAndFetchTokenAt(audience, client: client, clientState: clientState, married: married, now: remoteTimestamp, retryCount: retryCount - 1)
}
default:
break
}
}
}
// Fall-through.
return Deferred(value: result)
}
}
open func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> {
if let value = cache.value {
// Give ourselves some room to do work.
let isExpired = value.expiresAt < now + 5 * OneMinuteInMilliseconds
if canBeExpired {
if isExpired {
log.info("Returning cached expired token.")
} else {
log.info("Returning cached token, which should be valid.")
}
return deferMaybe((token: value.token, forKey: value.forKey))
}
if !isExpired {
log.info("Returning cached token, which should be valid.")
return deferMaybe((token: value.token, forKey: value.forKey))
}
}
log.debug("Advancing Account state.")
return account.marriedState().bind { result in
if let married = result.successValue {
log.info("Account is in Married state; generating assertion.")
let tokenServerEndpointURL = self.account.configuration.sync15Configuration.tokenServerEndpointURL
let audience = TokenServerClient.getAudience(forURL: tokenServerEndpointURL)
let client = TokenServerClient(URL: tokenServerEndpointURL)
let clientState = FxAClient10.computeClientState(married.kB)
log.debug("Fetching token server token.")
let deferred = self.generateAssertionAndFetchTokenAt(audience, client: client, clientState: clientState, married: married, now: now, retryCount: 1)
deferred.upon { result in
// This could race to update the cache with multiple token results.
// One racer will win -- that's fine, presumably she has the freshest token.
// If not, that's okay, 'cuz the slightly dated token is still a valid token.
if let token = result.successValue {
let newCache = SyncAuthStateCache(token: token, forKey: married.kB,
expiresAt: now + 1000 * token.durationInSeconds)
log.debug("Fetched token server token! Token expires at \(newCache.expiresAt).")
self.cache.value = newCache
}
}
return chain(deferred, f: { (token: $0, forKey: married.kB) })
}
return deferMaybe(result.failureValue!)
}
}
}
| mpl-2.0 | eb3e1248a9370be6490bfbe8ca5315bb | 45.462069 | 193 | 0.594181 | 5.450647 | false | false | false | false |
reactive-swift/UV | UV/Prepare.swift | 1 | 1907 | //===--- Prepare.swift -------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===-----------------------------------------------------------------------===//
import Foundation
import CUV
import Boilerplate
public typealias uv_prepare_p = UnsafeMutablePointer<uv_prepare_t>
public typealias PrepareCallback = (Prepare) -> Void
public class Prepare : Handle<uv_prepare_p> {
fileprivate let callback:PrepareCallback
public init(loop:Loop, callback:@escaping PrepareCallback) throws {
self.callback = callback
try super.init { handle in
uv_prepare_init(loop.loop, handle.portable)
}
}
open func start() throws {
try doWithHandle { handle in
try ccall(Error.self) {
uv_prepare_start(handle, prepare_cb)
}
}
}
open func stop() throws {
try doWithHandle { handle in
try ccall(Error.self) {
uv_prepare_stop(handle)
}
}
}
}
private func _prepare_cb(_ handle:uv_prepare_p?) {
guard let handle = handle , handle != .null else {
return
}
let prepare:Prepare = Prepare.from(handle: handle)
prepare.callback(prepare)
}
private func prepare_cb(_ handle:uv_prepare_p?) {
_prepare_cb(handle)
}
| apache-2.0 | 6b81cd2aa130a2bc573994ed36bf9c9f | 28.796875 | 83 | 0.605663 | 4.455607 | false | false | false | false |
GongChengKuangShi/DYZB | DouYuTV/DouYuTV/Classes/Home/ViewModel/RecommendViewModel.swift | 1 | 5325 | //
// RecommendViewModel.swift
// DouYuTV
//
// Created by xrh on 2017/9/7.
// Copyright © 2017年 xiangronghua. All rights reserved.
//
import UIKit
class RecommendViewModel {//如果用不到父类的东西,那么可以不继承,这样可以使得项目更加轻量级
lazy var anchorGroup : [AnchorGroup] = [AnchorGroup]()
lazy var bigDataGroup: AnchorGroup = AnchorGroup()//热门
lazy var protyDataGroup: AnchorGroup = AnchorGroup()//颜值
lazy var cycleModel : [CycleModel] = [CycleModel]()//无限轮播
}
// -- 发送网络请求
extension RecommendViewModel {
//请求数据(创建一个闭包,给外界传递数据)
func requestData(finishCallback : @escaping () -> ()) {
//0、定义参数
let paramaters = ["limit" : "4", "offset" : "0", "time" : NSDate.getCurrentTime()]
//Swift 3.0 GCD的常用方法:http://www.jianshu.com/p/be5a277e1f96 或者:http://www.jianshu.com/p/8442576377a8
//------ 创建Group队列---------(当发送异步请求的时候,要保证所有的接口都请求好数据,并且得按顺序添加进入model中,好进行赋值)
let dGroup = DispatchGroup()
//1、请求推荐数据
//------ 加入组中 -----
dGroup.enter()
NetworkTools.requestData(.GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : NSDate.getCurrentTime()]) { (result) in
// print(result)
//1、将result转为字典类型
guard let resultDict = result as? [String : NSObject] else {return}
//2、根据data的key,获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
//3、将数组转成模型对象
//设置组的属性
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
//获取主播的数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.bigDataGroup.anchers.append(anchor)
}
//-------离开组---------
dGroup.leave()
}
//2、颜值数据
//------ 加入组中 -----
dGroup.enter()
NetworkTools.requestData(.GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: paramaters) { (result) in
// print(result)
//1、将result转为字典类型
guard let resultDict = result as? [String : NSObject] else {return}
//2、根据data的key,获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
//3、将数组转成模型对象
//设置组的属性
self.protyDataGroup.tag_name = "颜值"
self.protyDataGroup.icon_name = "home_header_phone"
//获取主播的数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.protyDataGroup.anchers.append(anchor)
}
//-------离开组---------
dGroup.leave()
}
//3、后面部分的游戏数据
//------ 加入组中 -----
dGroup.enter()
NetworkTools.requestData(.GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: paramaters) { (result) in
// print(result)
//1、将result转为字典类型
guard let resultDict = result as? [String : NSObject] else {return}
//2、根据data的key,获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
//3、将数组转成模型对象
for dict in dataArray {
let group = AnchorGroup(dict: dict)
self.anchorGroup.append(group)
}
//-------离开组---------
dGroup.leave()
}
//所有数据都请求到之后进行排序
dGroup.notify(queue: .main) {
self.anchorGroup.insert(self.protyDataGroup, at: 0)
self.anchorGroup.insert(self.bigDataGroup, at: 0)
finishCallback()
}
}
//无限轮播数据请求
func requestCycleData(finishCallback : @escaping () -> ()) {
NetworkTools.requestData(.GET, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in
print(result)
guard let resultDict = result as? [String : NSObject] else {return}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
//字典转模型
for dic in dataArray {
self.cycleModel.append(CycleModel(dict:dic))
}
finishCallback()
}
}
}
| mit | f3d1eef74a33e2c041a3956539b8ce43 | 29.986842 | 160 | 0.502548 | 4.599609 | false | false | false | false |
WXGBridgeQ/SwiftPullToRefresh | SwiftPullToRefresh/UIScrollView+Extensions.swift | 1 | 8243 | //
// ScrollViewExtension.swift
// SwiftPullToRefresh
//
// Created by Leo Zhou on 2017/12/19.
// Copyright © 2017年 Wiredcraft. All rights reserved.
//
import UIKit
private var headerKey: UInt8 = 0
private var footerKey: UInt8 = 0
private var tempFooterKey: UInt8 = 0
extension UIScrollView {
private var spr_header: RefreshView? {
get {
return objc_getAssociatedObject(self, &headerKey) as? RefreshView
}
set {
spr_header?.removeFromSuperview()
objc_setAssociatedObject(self, &headerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
newValue.map { insertSubview($0, at: 0) }
}
}
private var spr_footer: RefreshView? {
get {
return objc_getAssociatedObject(self, &footerKey) as? RefreshView
}
set {
spr_footer?.removeFromSuperview()
objc_setAssociatedObject(self, &footerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
newValue.map { insertSubview($0, at: 0) }
}
}
private var spr_tempFooter: RefreshView? {
get {
return objc_getAssociatedObject(self, &tempFooterKey) as? RefreshView
}
set {
objc_setAssociatedObject(self, &tempFooterKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Indicator header
///
/// - Parameters:
/// - height: refresh view height and also the trigger requirement, default is 60
/// - action: refresh action
public func spr_setIndicatorHeader(height: CGFloat = 60,
action: @escaping () -> Void) {
spr_header = IndicatorView(isHeader: true, height: height, action: action)
}
/// Indicator + Text header
///
/// - Parameters:
/// - refreshText: text display for different states
/// - height: refresh view height and also the trigger requirement, default is 60
/// - action: refresh action
public func spr_setTextHeader(refreshText: RefreshText = headerText,
height: CGFloat = 60,
action: @escaping () -> Void) {
spr_header = TextView(isHeader: true, refreshText: refreshText, height: height, action: action)
}
/// GIF header
///
/// - Parameters:
/// - data: data for the GIF file
/// - isBig: whether the GIF is displayed with full screen width
/// - height: refresh view height and also the trigger requirement
/// - action: refresh action
public func spr_setGIFHeader(data: Data,
isBig: Bool = false,
height: CGFloat = 60,
action: @escaping () -> Void) {
spr_header = GIFHeader(data: data, isBig: isBig, height: height, action: action)
}
/// GIF + Text header
///
/// - Parameters:
/// - data: data for the GIF file
/// - refreshText: text display for different states
/// - height: refresh view height and also the trigger requirement, default is 60
/// - action: refresh action
public func spr_setGIFTextHeader(data: Data,
refreshText: RefreshText = headerText,
height: CGFloat = 60,
action: @escaping () -> Void) {
spr_header = GIFTextHeader(data: data, refreshText: refreshText, height: height, action: action)
}
/// Custom header
/// Inherit from RefreshView
/// Update the presentation in 'didUpdateState(_:)' and 'didUpdateProgress(_:)' methods
///
/// - Parameter header: your custom header inherited from RefreshView
public func spr_setCustomHeader(_ header: RefreshView) {
self.spr_header = header
}
/// Custom footer
/// Inherit from RefreshView
/// Update the presentation in 'didUpdateState(_:)' and 'didUpdateProgress(_:)' methods
///
/// - Parameter footer: your custom footer inherited from RefreshView
public func spr_setCustomFooter(_ footer: RefreshView) {
self.spr_footer = footer
}
/// Begin refreshing with header
public func spr_beginRefreshing() {
spr_header?.beginRefreshing()
}
/// End refreshing with both header and footer
public func spr_endRefreshing() {
spr_header?.endRefreshing()
spr_footer?.endRefreshing()
}
/// End refreshing with footer and remove it
public func spr_endRefreshingWithNoMoreData() {
spr_tempFooter = spr_footer
spr_footer?.endRefreshing { [weak self] in
self?.spr_footer = nil
}
}
/// Reset footer which is set to no more data
public func spr_resetNoMoreData() {
if spr_footer == nil {
spr_footer = spr_tempFooter
}
}
/// Indicator footer
///
/// - Parameters:
/// - height: refresh view height and also the trigger requirement, default is 60
/// - action: refresh action
public func spr_setIndicatorFooter(height: CGFloat = 60,
action: @escaping () -> Void) {
spr_footer = IndicatorView(isHeader: false, height: height, action: action)
}
/// Indicator + Text footer
///
/// - Parameters:
/// - refreshText: text display for different states
/// - height: refresh view height and also the trigger requirement, default is 60
/// - action: refresh action
public func spr_setTextFooter(refreshText: RefreshText = footerText,
height: CGFloat = 60,
action: @escaping () -> Void) {
spr_footer = TextView(isHeader: false, refreshText: refreshText, height: height, action: action)
}
/// Indicator auto refresh footer (auto triggered when scroll down to the bottom of the content)
///
/// - Parameters:
/// - height: refresh view height, default is 60
/// - action: refresh action
public func spr_setIndicatorAutoFooter(height: CGFloat = 60,
action: @escaping () -> Void) {
spr_footer = IndicatorAutoFooter(height: height, action: action)
}
/// Indicator + Text auto refresh footer (auto triggered when scroll down to the bottom of the content)
///
/// - Parameters:
/// - loadingText: text display for refreshing
/// - height: refresh view height, default is 60
/// - action: refresh action
public func spr_setTextAutoFooter(loadingText: String = loadingText,
height: CGFloat = 60,
action: @escaping () -> Void) {
spr_footer = TextAutoFooter(loadingText: loadingText, height: height, action: action)
}
/// Clear the header
public func spr_clearHeader() {
spr_header = nil
}
/// Clear the footer
public func spr_clearFooter() {
spr_footer = nil
}
}
/// Text display for different states
public struct RefreshText {
let loadingText: String
let pullingText: String
let releaseText: String
/// Initialization method
///
/// - Parameters:
/// - loadingText: text display for refreshing
/// - pullingText: text display for dragging when don't reach the trigger
/// - releaseText: text display for dragging when reach the trigger
public init(loadingText: String, pullingText: String, releaseText: String) {
self.loadingText = loadingText
self.pullingText = pullingText
self.releaseText = releaseText
}
}
private let isChinese = Locale.preferredLanguages[0].contains("zh-Han")
public let loadingText = isChinese ? "正在加载..." : "Loading..."
public let headerText = RefreshText(
loadingText: loadingText,
pullingText: isChinese ? "下拉刷新" : "Pull down to refresh",
releaseText: isChinese ? "释放刷新" : "Release to refresh"
)
public let footerText = RefreshText(
loadingText: loadingText,
pullingText: isChinese ? "上拉加载" : "Pull up to load more",
releaseText: isChinese ? "释放加载" : "Release to load more"
)
| mit | 2311cad27ec02eb76b33b314a2c46744 | 34.344828 | 107 | 0.599024 | 4.817861 | false | false | false | false |
xocialize/Kiosk | kiosk/FileSave.swift | 1 | 6589 | import Foundation
public struct FileSave {
public static func saveData(fileData:NSData, directory:NSSearchPathDirectory, path:String, subdirectory:String?) -> Bool
{
// Remove unnecessary slash if need
let newPath = self.stripSlashIfNeeded(path)
var newSubdirectory:String?
if let sub = subdirectory {
newSubdirectory = self.stripSlashIfNeeded(sub)
}
// Create generic beginning to file save path
var savePath = ""
if let direct = self.applicationDirectory(directory),
path = direct.path {
savePath = path + "/"
}
if (newSubdirectory != nil) {
savePath.extend(newSubdirectory!)
self.createSubDirectory(savePath)
savePath += "/"
}
// Add requested save path
savePath += newPath
println(savePath)
// Save the file and see if it was successful
var ok:Bool = NSFileManager.defaultManager().createFileAtPath(savePath,contents:fileData, attributes:nil)
// Return status of file save
return ok
}
public static func saveDataToTemporaryDirectory(fileData:NSData, path:String, subdirectory:String?) -> Bool
{
// Remove unnecessary slash if need
let newPath = stripSlashIfNeeded(path)
var newSubdirectory:String?
if let sub = subdirectory {
newSubdirectory = stripSlashIfNeeded(sub)
}
// Create generic beginning to file save path
var savePath = ""
if let direct = self.applicationTemporaryDirectory(),
path = direct.path {
savePath = path + "/"
}
if let sub = newSubdirectory {
savePath += sub
createSubDirectory(savePath)
savePath += "/"
}
// Add requested save path
savePath += newPath
// Save the file and see if it was successful
let ok:Bool = NSFileManager.defaultManager().createFileAtPath(savePath,contents:fileData, attributes:nil)
// Return status of file save
return ok
}
// string methods
public static func saveString(fileString:String, directory:NSSearchPathDirectory, path:String, subdirectory:String) -> Bool {
// Remove unnecessary slash if need
var newPath = self.stripSlashIfNeeded(path)
var newSubdirectory:String? = self.stripSlashIfNeeded(subdirectory)
// Create generic beginning to file save path
var savePath = ""
if let direct = self.applicationDirectory(directory),
path = direct.path {
savePath = path + "/"
}
if let sub = newSubdirectory {
savePath += sub
createSubDirectory(savePath)
savePath += "/"
}
// Add requested save path
savePath += newPath
var error:NSError?
// Save the file and see if it was successful
var ok:Bool = fileString.writeToFile(savePath, atomically:false, encoding:NSUTF8StringEncoding, error:&error)
if (error != nil) {println(error)}
// Return status of file save
return ok
}
public static func saveStringToTemporaryDirectory(fileString:String, path:String, subdirectory:String) -> Bool {
var newPath = self.stripSlashIfNeeded(path)
var newSubdirectory:String? = self.stripSlashIfNeeded(subdirectory)
// Create generic beginning to file save path
var savePath = ""
if let direct = self.applicationTemporaryDirectory(),
path = direct.path {
savePath = path + "/"
}
if (newSubdirectory != nil) {
savePath.extend(newSubdirectory!)
self.createSubDirectory(savePath)
savePath += "/"
}
// Add requested save path
savePath += newPath
var error:NSError?
// Save the file and see if it was successful
var ok:Bool = fileString.writeToFile(savePath, atomically:false, encoding:NSUTF8StringEncoding, error:&error)
if (error != nil) {
println(error)
}
// Return status of file save
return ok;
}
// private methods
//directories
public static func applicationDirectory(directory:NSSearchPathDirectory) -> NSURL? {
var appDirectory:String?
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(directory, NSSearchPathDomainMask.UserDomainMask, true);
if paths.count > 0 {
if let pathString = paths[0] as? String {
appDirectory = pathString
}
}
if let dD = appDirectory {
return NSURL(string:dD)
}
return nil
}
public static func applicationTemporaryDirectory() -> NSURL? {
if let tD = NSTemporaryDirectory() {
return NSURL(string:tD)
}
return nil
}
//pragma mark - strip slashes
private static func stripSlashIfNeeded(stringWithPossibleSlash:String) -> String {
var stringWithoutSlash:String = stringWithPossibleSlash
// If the file name contains a slash at the beginning then we remove so that we don't end up with two
if stringWithPossibleSlash.hasPrefix("/") {
stringWithoutSlash = stringWithPossibleSlash.substringFromIndex(advance(stringWithoutSlash.startIndex,1))
}
// Return the string with no slash at the beginning
return stringWithoutSlash
}
private static func createSubDirectory(subdirectoryPath:String) -> Bool {
var error:NSError?
var isDir:ObjCBool=false;
var exists:Bool = NSFileManager.defaultManager().fileExistsAtPath(subdirectoryPath, isDirectory:&isDir)
if (exists) {
/* a file of the same name exists, we don't care about this so won't do anything */
if isDir {
/* subdirectory already exists, don't create it again */
return true;
}
}
var success:Bool = NSFileManager.defaultManager().createDirectoryAtPath(subdirectoryPath, withIntermediateDirectories:true, attributes:nil, error:&error)
if (error != nil) { println(error) }
return success;
}
}
| mit | 2e41188e7b6d84dce764a54e9b3fa5b5 | 31.781095 | 161 | 0.590074 | 5.729565 | false | false | false | false |
CombineCommunity/CombineExt | Sources/Operators/Internal/Lock.swift | 1 | 1228 | // swiftlint:disable all
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Darwin
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
typealias Lock = os_unfair_lock_t
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
extension UnsafeMutablePointer where Pointee == os_unfair_lock_s {
internal init() {
let l = UnsafeMutablePointer.allocate(capacity: 1)
l.initialize(to: os_unfair_lock())
self = l
}
internal func cleanupLock() {
deinitialize(count: 1)
deallocate()
}
internal func lock() {
os_unfair_lock_lock(self)
}
internal func tryLock() -> Bool {
let result = os_unfair_lock_trylock(self)
return result
}
internal func unlock() {
os_unfair_lock_unlock(self)
}
}
| mit | 6a7f2e43d857de8491ce2fbe614f9c60 | 26.288889 | 80 | 0.59772 | 4.052805 | false | false | false | false |
n8armstrong/CalendarView | CalendarView/Carthage/Checkouts/SwiftMoment/SwiftMoment/SwiftMoment/TimeUnit.swift | 1 | 353 | //
// TimeUnit.swift
// SwiftMoment
//
// Created by Adrian on 19/01/15.
// Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved.
//
public enum TimeUnit: String {
case Years = "y"
case Quarters = "Q"
case Months = "M"
case Weeks = "w"
case Days = "d"
case Hours = "H"
case Minutes = "m"
case Seconds = "s"
}
| mit | 361014c13e2811381c822c633e428eca | 18.611111 | 64 | 0.586402 | 3.123894 | false | false | false | false |
pmtao/SwiftUtilityFramework | SwiftUtilityFramework/UIKit/URLScheme.swift | 1 | 13964 | //
// URLScheme.swift
// SwiftUtilityFramework
//
// Created by 阿涛 on 18-4-26.
// Copyright © 2019年 SinkingSoul. All rights reserved.
//
import Foundation
import SafariServices
/// 让 app 支持其他应用通过 URLScheme 调用自己,也支持自己通过 URLScheme 调用其他应用。
/// 使用步骤:
/// 1. 初始化 URLScheme 结构体,指定本 app 的 scheme、要允许互相调用的 app bundle 字典、要支持的外部调用本 app 的动作字典
/// 2. 判断外部唤起的来源 app 是否有效
/// 3. 解析外部调用的动作和参数
/// 4. 根据动作和参数执行对应的操作
@available(iOS 10.0, *)
public struct URLScheme {
// MARK: --属性----------------👇
/// 初始定义的可通过 URL Scheme 调用的 App 集合
var XcallBackAppBundleDefaultNames: [String: String] = [
"instager": "com.sinkingsoul.Instager",
"bear": "net.shinyfrog.bear-iOS",
"fantastical": "com.flexibits.fantastical2.iphone",
"things": "com.culturedcode.ThingsiPhone",
"drafts5": "com.agiletortoise.Drafts5",
"evernote": "com.evernote.iPhone.Evernote",
"ulysses": "com.ulyssesapp.ios",
"notes": "com.apple.mobilenotes"
]
/// 用户自定义的可通过 URL Scheme 调用的 App 集合
var XcallBackAppBundleNames: [String: String]
/// 初始定义的 URL Scheme 支持的动作集合
var XcallBackDefaultActions: [String: [String]] = [
"Bear": ["saveToBear", "openBearNote"]
]
/// 用户自定义的 URL Scheme 支持的动作集合
var XcallBackActions: [String: [String]]
/// 当前 app 被调用时的 Scheme
var myScheme: String
/// 当前 app 的基础 url,如:scheme://x-callback-url/
var myBaseURL: String
// MARK: --枚举集合----------------👇
/// 解析 URL Scheme 时发生的错误
public enum ResolveURLSchemeError: Error {
case invalidSourceAppBundle // 不支持的源 app bundle
case badPrefix // 错误的前缀
case noAction // 未指定动作
case noParam // 未指定参数
case invalidAction // 不支持的动作
}
// MARK: --初始化方法----------------👇
/// 初始化 URLScheme 结构体
///
/// - Parameters:
/// - myScheme: 当前 app 使用的 url scheme,如 bear
/// - appBundleNames: 需要支持 XcallBack 操作的 AppBundle 字典,如:["bear": "net.shinyfrog.bear-iOS"]
/// - actions: 需要支持 XcallBack 操作的动作字典,如:["Bear": ["saveToBear", "openBearNote"]]
public init(myScheme: String,
appBundleNames: [String: String] = [:],
actions: [String: [String]] = [:]) {
self.myScheme = myScheme
self.myBaseURL = "\(myScheme)://x-callback-url/"
self.XcallBackAppBundleNames =
URLScheme.combineAppBundles(XcallBackAppBundleDefaultNames,
userAppBundles: appBundleNames)
self.XcallBackActions =
URLScheme.combineActions(XcallBackDefaultActions,
userActions: actions)
}
// MARK: --主方法----------------👇
/// 检查发起 App 的有效性,并返回有效的 App Scheme、Bundle ID。
/// 返回结果为元组,第一个值为确认有效的 App Scheme,无效时为 nil);
/// 第二个值为源 App Bundle ID,始终有值;
/// 第三个值为检查发生错误的类型,无错误时为 nil。
public func checkSourceApp(options: [UIApplication.OpenURLOptionsKey : Any])
-> (String?, String, Error?)
{
// 获取发起 App 的 Bundle ID
let sourceAppBundleID = options[UIApplication.OpenURLOptionsKey.sourceApplication]! as! String
// 判断是否为支持的 App
guard let sourceApp = XcallBackAppBundleNames.first( where: {
$0.value == sourceAppBundleID
}) else {
// 不支持的 App bundle ID
return (nil, sourceAppBundleID, ResolveURLSchemeError.invalidSourceAppBundle)
}
return (sourceApp.key, sourceAppBundleID, nil)
}
/// 解析并执行 URL 动作
///
/// - Parameters:
/// - url: 外部发起调用的 url
/// - sourceApp: 源 app 信息,元组类型,格式:("appName": "appBundleID")
/// - actionHandler: 处理 url 动作的方法,
/// - action: 动作名称
/// - params: 动作附带的参数字典
/// - sourceAppDic: 源 app 字典信息,同 sourceApp。
/// - Throws: 解析 url 过程中的错误,类型:URLScheme.ResolveURLSchemeError
public func handleURL(_ url: URL,
from sourceApp: (String, String),
actionHandler: (_ action: String,
_ params: [String : String],
_ sourceAppDic: (String, String)) -> Void)
throws {
guard let (action, params)
= try resolveURLScheme(url, from: sourceApp.1) else {
return
}
// 让 app 自行处理相应动作
actionHandler(action, params, sourceApp)
}
/// 打开 URL 页面,自动匹配两种方式:Safari 内置网页、通过 URL Scheme 打开其他 App。
public static func openApp(_ url: URL, in vc: UIViewController) {
if url.scheme == "http" || url.scheme == "https" {
print("Not app link: \(url)")
} else {
UIApplication.shared.open(url)
}
}
// MARK: --URL 编解码处理----------------👇
/// 将原始 url 字符串转换为经过编码处理的 URL 字符串
static public func encodeURLString(string:String) -> URL {
let urlwithPercentEscapes = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: urlwithPercentEscapes!)
return url!
}
/// 将经过编码处理的 URL 字符串转换为原始字符串
static public func decodeURLString(string:String) -> String {
return string.removingPercentEncoding!
}
// MARK: --URL 参数解析----------------👇
/// 解析 URL Scheme 参数
///
/// - Parameters:
/// - url: 原始调用的 URL 信息
/// - sourceAppBundleID: 调用方 App Bundle ID
/// - Returns: 动作和参数的元组,第一个是动作,第二个是参数字典。
/// - Throws: 解析错误 ResolveURLSchemeError 类型枚举值
func resolveURLScheme(_ url: URL, from sourceAppBundleID: String)
throws -> (String, [String: String])?
{
var result = ("", [String: String]()) // 最后解析结果
// 解析步骤:
// 1. 先判断已编码的 url 是否包含 instager://x-callback-url/ 前缀,如果包含再进行分割。
// 2. 取分割后的参数字符串,将所有参数分解到数组中。
// 3. 将参数的值进行解码
// 4. 将参数和值的数组,交给 App 专用解析的方法近一步解析。
// 5. 返回 App 接下来要执行的动作和参数值
//获取 url 已编码的字符串
let urlEncodedString = url.absoluteString
if urlEncodedString.hasPrefix(myBaseURL) == false {
throw ResolveURLSchemeError.badPrefix // 前缀不符,抛出错误。
}
// 定义解析后的动作和参数
var action = "" // URL 中的动作
var parameterArray = [String]() // URL 中的参数数组
// 分别获取 URL Scheme 的路径与参数
let pathComponents = url.pathComponents
let querys = url.query
if pathComponents.isEmpty || pathComponents.count == 1 {
throw ResolveURLSchemeError.noAction // 无动作
} else {
action = pathComponents.last!
}
if querys == nil || querys!.isEmpty {
throw ResolveURLSchemeError.noParam // 无参数
} else {
// 分割获得参数数组
parameterArray = querys!.components(separatedBy: "&")
// 去除分割后的空参数
parameterArray = parameterArray.filter {
$0.isEmpty == false
}
}
// 将参数列表转为字典
let parameterDict: [String: String] =
turnParamArrayIntoDecodedDiction(paramArray: parameterArray)
// // 根据不同的 App 处理参数
// switch appBundleID {
// case .bear:
// result = try resolveParamOfBear(parameterDict, with: action)
// case .ulysses:
// result = try resolveParamOfUlysses(parameterDict, with: action)
// default:
// break
// }
result = (action, parameterDict)
return result
}
/// 将参数数组转换为字典,并将参数值进行解码。
func turnParamArrayIntoDecodedDiction(paramArray: [String]) -> [String: String] {
var paramDiction = [String: String]()
for param in paramArray {
let array = param.components(separatedBy: "=")
if array[0].isEmpty == false && array[1].isEmpty == false {
paramDiction[array[0]] = URLScheme.decodeURLString(string: array[1])
}
}
return paramDiction
}
// MARK: --不同 App 参数处理----------------👇
// /// 解析来自 bear 的参数
// public func resolveParamOfBear(_ param: [String: String], with action: String)
// throws -> (String, [String: String])
// {
// // 判断 action 是否有效
// guard Actions.Bear(rawValue: action) != nil else {
// throw ResolveURLSchemeError.invalidAction
// }
// return (action, param)
// }
//
// /// 解析来自 Ulysses 的参数
// public func resolveParamOfUlysses(_ param: [String: String], with action: String)
// throws -> (String, [String: String])
// {
// // 判断 action 是否有效
// guard Actions.Ulysses(rawValue: action) != nil else {
// throw ResolveURLSchemeError.invalidAction
// }
// return (action, param)
// }
// MARK: --便利方法----------------👇
/// 合并用户与默认提供的 appBundles,如果有重复,以用户数据优先。
static func combineAppBundles(_ defaultAppBundles: [String: String],
userAppBundles: [String: String])
-> [String: String] {
return defaultAppBundles.merging(userAppBundles)
{ (_, new) in new }
}
/// 合并用户与默认提供的 actions,如果有重复,以用户数据优先。
static func combineActions(_ defaultActions: [String: [String]],
userActions: [String: [String]])
-> [String: [String]] {
return defaultActions.merging(userActions)
{ (_, new) in new }
}
}
/// 表示 app 调用链接的结构体,可用于内部调用和外部调用。
/// 链接范例:"cr://local/Main/ReadingList/Reading/open?mode=present"
public struct AppLink {
var scheme: String
var host: String
/// url 中的路径部分,如果没有则为空数组
var pathComponents: [String]
/// url 中表示动作的参数,如果没有则为空。
var action: String
/// url 中动作附带的参数,如果没有则为空字典。
var queryDictionary: [String: String]
public init?(_ url: URL) {
// 不支持文件类型的链接
if url.isFileURL {
return nil
}
// scheme 不能为空
if url.scheme == nil {
return nil
}
// host 不能为空
if url.host == nil {
return nil
}
self.scheme = url.scheme!
self.host = url.host!
// 路径和动作需同时获取,默认尾部为动作。如果路径拆分后只有一个元素,则认为它代表动作,路径为空。
var pathComponents = url.pathComponents
/// 去除初步解析时,开头无用的 “/”。
if pathComponents.count > 0 {
if pathComponents.first! == "/" {
pathComponents.removeFirst()
}
}
if pathComponents.isEmpty {
self.action = ""
self.pathComponents = []
} else {
self.action = pathComponents.last!
pathComponents.removeLast()
self.pathComponents = pathComponents
}
// 获取参数字典,标准格式: param1=value1¶m2=value2
let query = url.query
if query == nil || query!.isEmpty {
self.queryDictionary = [:]
} else {
// queryArray 范例:["param1=value1", "param2=value2"]
var queryArray = query!.components(separatedBy: "&")
// 去除首尾的空字符
if queryArray.first! == "" {
queryArray.removeFirst()
}
if queryArray.last! == "" {
queryArray.removeLast()
}
// queryDictionary 范例:["param1": "value1", "param2": "value2"]
var queryDictionary = [String: String]()
for param in queryArray {
let paramArray = param.components(separatedBy: "=")
// 确保解析的参数和值都有,且都不为空。
if paramArray.count == 2 &&
!(paramArray.first!.isEmpty) &&
!(paramArray.last!.isEmpty) {
queryDictionary[paramArray.first!] = paramArray.last!
}
}
self.queryDictionary = queryDictionary
}
}
}
| mit | e08a9c1d978066083f06a5b189c6a3ad | 32.745714 | 105 | 0.550588 | 4.119637 | false | false | false | false |
juanm95/Soundwich | Quaggify/TrackViewController.swift | 1 | 15733 | //
// TrackViewController.swift
// Quaggify
//
// Created by Jonathan Bijos on 05/02/17.
// Copyright © 2017 Quaggie. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
import Flurry_iOS_SDK
class TrackViewController: ViewController, SPTAudioStreamingDelegate, SPTAudioStreamingPlaybackDelegate{
var track: Track? {
didSet {
guard let track = track else {
return
}
DispatchQueue.main.async {
if let name = track.name {
self.titleLabel.text = name
}
if let duration = track.durationMS{
self.playbackSlider.maximumValue = Float(duration/1000)
}
if let artists = track.artists {
let names = artists.map { $0.name ?? "Unknown Artist" }.joined(separator: ", ")
self.subTitleLabel.text = names
self.navigationItem.title = names
}
if let smallerImage = track.album?.images?[safe: 1], let imgUrlString = smallerImage.url, let url = URL(string: imgUrlString) {
self.imageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "placeholder"), options: [.transition(.fade(0.2))])
} else if let smallerImage = track.album?.images?[safe: 0], let imgUrlString = smallerImage.url, let url = URL(string: imgUrlString) {
self.imageView.kf.setImage(with: url, placeholder: #imageLiteral(resourceName: "placeholder"), options: [.transition(.fade(0.2))])
} else {
self.imageView.image = #imageLiteral(resourceName: "placeholder")
}
}
addToPlaylistButton.setImage(UIImage(named: "send_button")?.withRenderingMode(.alwaysOriginal), for: .normal)
self.presentedViewController?.loadView()
if(thePlayer.paused){
self.pauseSong()
}
self.playSong()
}
}
var titleLabel: UILabel = {
let label = UILabel()
label.font = Font.montSerratBold(size: 20)
label.textColor = ColorPalette.white
label.textAlignment = .center
return label
}()
var subTitleLabel: UILabel = {
let label = UILabel()
label.font = Font.montSerratRegular(size: 18)
label.textColor = ColorPalette.lightGray
label.textAlignment = .center
return label
}()
/* Used to Send Song to Friend */
lazy var addToPlaylistButton: UIButton = {
let btn = UIButton(type: .system)
btn.setImage(UIImage(named: "send_button")?.withRenderingMode(.alwaysOriginal), for: .normal)
/* btn.tintColor = ColorPalette.white
btn.titleLabel?.font = Font.montSerratRegular(size: 30)
btn.setTitle("Send to Friend", for: .normal)*/
btn.addTarget(self, action: #selector(addToPlaylist), for: .touchUpInside)
return btn
}()
lazy var pauseSongButton: UIButton = {
let btn = UIButton(type: .system)
let image = UIImage(named: "pausebutton")
btn.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal)
btn.addTarget(self, action: #selector(pauseSong), for: .touchUpInside)
return btn
}()
lazy var nextSongButton: UIButton = {
let btn = UIButton(type: .system)
btn.setImage(UIImage(named: "next")?.withRenderingMode(.alwaysOriginal), for: .normal)
btn.addTarget(self, action: #selector(nextSong), for: .touchUpInside)
return btn
}()
lazy var previousSongButton: UIButton = {
let btn = UIButton(type: .system)
btn.setImage(UIImage(named: "previous")?.withRenderingMode(.alwaysOriginal), for: .normal)
btn.addTarget(self, action: #selector(previousSong), for: .touchUpInside)
return btn
}()
lazy var playbackSlider: UISlider = {
let playbackSlid = UISlider(frame:CGRect(x:10, y:250, width:250, height:10))
playbackSlid.minimumValue = 0
playbackSlid.setThumbImage(UIImage(named: "thumb")!, for: .normal)
playbackSlid.isContinuous = true
playbackSlid.tintColor = UIColor.orange
playbackSlid.addTarget(self, action: #selector(slide(_:)), for: .touchUpInside)
return playbackSlid
}()
@IBAction func slide(_ slider: UISlider) {
if(thePlayer.PP){
let seconds : Int64 = Int64(slider.value)
thePlayer.spotifyPlayer?.seek(to: TimeInterval(seconds), callback: { (error) in
if (error != nil) {
}
})
MPNowPlayingInfoCenter.default().nowPlayingInfo![MPNowPlayingInfoPropertyElapsedPlaybackTime] = TimeInterval(seconds)
}
}
var imageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFit
iv.clipsToBounds = true
return iv
}()
let stackView: UIStackView = {
let sv = UIStackView()
sv.alignment = .fill
sv.axis = .vertical
sv.distribution = .fillEqually
sv.backgroundColor = .clear
sv.spacing = 8
return sv
}()
let containerView: UIView = {
let v = UIView()
v.backgroundColor = .clear
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
let commandCenter = MPRemoteCommandCenter.shared()
if(thePlayer.injected == false){
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.previousTrackCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.isEnabled = true
if(thePlayer.start){
commandCenter.nextTrackCommand.addTarget(thePlayer.nowPlaying!, action:#selector(thePlayer.nowPlaying?.nextSong))
commandCenter.previousTrackCommand.addTarget(thePlayer.nowPlaying!, action:#selector(thePlayer.nowPlaying?.previousSong))
commandCenter.pauseCommand.addTarget(thePlayer.nowPlaying!, action:#selector(thePlayer.nowPlaying?.pauseSong))
commandCenter.playCommand.addTarget(thePlayer.nowPlaying!, action:#selector(thePlayer.nowPlaying?.pauseSong))
if #available(iOS 9.1, *) {
commandCenter.changePlaybackPositionCommand.isEnabled = true
} else {
// Fallback on earlier versions
}
if #available(iOS 9.1, *) {
commandCenter.changePlaybackPositionCommand.addTarget(self, action:#selector(thePlayer.nowPlaying?.onChangePlaybackPositionCommand))
} else {
// Fallback on earlier versions
}
}
}
if(!thePlayer.start){
navigationController?.setViewControllers([thePlayer.nowPlaying!], animated: true)
thePlayer.start = true
}
// fetchTrack()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
switch UIApplication.shared.statusBarOrientation {
case .portrait: fallthrough
case .portraitUpsideDown: fallthrough
case .unknown:
setPortraitLayout()
break
case .landscapeLeft: fallthrough
case .landscapeRight:
setLandscapeLayout()
break
}
view.layoutIfNeeded()
}
override func setupViews() {
super.setupViews()
view.addSubview(stackView)
view.addSubview(imageView)
view.addSubview(containerView)
view.addSubview(titleLabel)
view.addSubview(subTitleLabel)
view.addSubview(playbackSlider)
view.addSubview(addToPlaylistButton)
view.addSubview(pauseSongButton)
view.addSubview(nextSongButton)
view.addSubview(previousSongButton)
view.backgroundColor = ColorPalette.black
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(containerView)
stackView.anchor(topLayoutGuide.bottomAnchor, left: view.leftAnchor, bottom: bottomLayoutGuide.topAnchor, right: view.rightAnchor, topConstant: 8, leftConstant: 8, bottomConstant: 8, rightConstant: 8, widthConstant: 0, heightConstant: 0)
titleLabel.anchor(containerView.topAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 24)
subTitleLabel.anchor(titleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 24)
pauseSongButton.anchor(subTitleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 8, leftConstant: 150, bottomConstant: 0, rightConstant: 150, widthConstant: 64, heightConstant: 64)
nextSongButton.anchor(subTitleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 8, leftConstant: 275, bottomConstant: 0, rightConstant: 25, widthConstant: 64, heightConstant: 64)
previousSongButton.anchor(subTitleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 8, leftConstant: 25, bottomConstant: 0, rightConstant: 275, widthConstant: 64, heightConstant: 64)
addToPlaylistButton.anchor(subTitleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 125, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
playbackSlider.anchor(titleLabel.bottomAnchor, left: containerView.leftAnchor, bottom: nil, right: containerView.rightAnchor, topConstant: 115, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
}
extension TrackViewController {
func setPortraitLayout () {
stackView.axis = .vertical
}
func setLandscapeLayout () {
stackView.axis = .horizontal
}
}
extension TrackViewController {
func addToPlaylist () {
if(thePlayer.PP){
addToPlaylistButton.setImage(UIImage(named: "send_button")?.withRenderingMode(.alwaysOriginal), for: .normal)
let trackOptionsVC = TrackOptionsViewController()
trackOptionsVC.track = track
let trackOptionsNav = NavigationController(rootViewController: trackOptionsVC)
trackOptionsNav.modalPresentationStyle = .overCurrentContext
tabBarController?.present(trackOptionsNav, animated: true, completion: nil)
} else {
addToPlaylistButton.setImage(UIImage(named: "nosong_button")?.withRenderingMode(.alwaysOriginal), for: .normal)
}
}
func onChangePlaybackPositionCommand (_ event: MPChangePlaybackPositionCommandEvent){
thePlayer.spotifyPlayer?.seek(to: event.positionTime, callback: { (error) in
if (error != nil) {
}
})
}
func nextSong(){
if(thePlayer.PP){
thePlayer.indeX += 1
if thePlayer.indeX >= (thePlayer.trackList?.total)! {
thePlayer.indeX = 0
}
self.track = thePlayer.trackList?.items?[safe: thePlayer.indeX]?.track
}
}
func previousSong(){
if(thePlayer.PP){
thePlayer.indeX -= 1
if thePlayer.indeX <= -1 {
thePlayer.indeX = 0
}
self.track = thePlayer.trackList?.items?[safe: thePlayer.indeX]?.track
}
}
func pauseSong(){
if(thePlayer.PP){
MPNowPlayingInfoCenter.default().nowPlayingInfo![MPNowPlayingInfoPropertyElapsedPlaybackTime] = thePlayer.spotifyPlayer?.playbackState.position
if(thePlayer.paused){
thePlayer.paused = false
pauseSongButton.setImage(UIImage(named: "pausebutton")?.withRenderingMode(.alwaysOriginal), for: .normal)
MPNowPlayingInfoCenter.default().nowPlayingInfo![MPNowPlayingInfoPropertyPlaybackRate] = 1
thePlayer.spotifyPlayer?.setIsPlaying(true, callback: { (error) in
if (error != nil) {
// print(error)
}
})
} else {
thePlayer.paused = true
pauseSongButton.setImage(UIImage(named: "play-button")?.withRenderingMode(.alwaysOriginal), for: .normal)
MPNowPlayingInfoCenter.default().nowPlayingInfo![MPNowPlayingInfoPropertyPlaybackRate] = 0
thePlayer.spotifyPlayer?.setIsPlaying(false, callback: { (error) in
if (error != nil) {
// print(error)
}
})
}
}
}
func playSong() {
var trackName = "spotify:track:"
trackName += (track?.id)!
thePlayer.spotifyPlayer?.playSpotifyURI(trackName, startingWith: 0, startingWithPosition: 0, callback: { (error) in
if (error != nil) {
print(error)
}
})
let imageURLString = URL(string: (self.track?.album?.images?[0].url)!)
let songParams = ["Song_Title": self.track?.name!, "Artist": self.track?.artists?[0].name!, "Popularity": self.track?.popularity!, "Duration": self.track?.durationMS ?? 0] as [String: Any]
Flurry.logEvent("Play_Track", withParameters: songParams)
let imageData = try! Data(contentsOf:imageURLString!)
let image2 = UIImage(data:imageData)
let newSize = CGSize(width:(self.track?.album?.images?[0].width)!,height:(self.track?.album?.images?[0].height)!)
if let image = image2 ?? UIImage(named: "No Album Artwork"), #available(iOS 10.0, *) {
let albumArt = MPMediaItemArtwork(boundsSize:newSize, requestHandler: { (size) -> UIImage in return image})
let nowPlayingInfo : [String:Any] = [
MPMediaItemPropertyTitle: self.track?.name! ?? "Unknown Song",
MPMediaItemPropertyArtist: self.track?.artists?[0].name! ?? "Unknown Artist",
MPMediaItemPropertyAlbumTitle: self.track?.album?.name! ?? "Unknown Album",
MPMediaItemPropertyPlaybackDuration: (self.track?.durationMS)!/1000,
MPNowPlayingInfoPropertyPlaybackRate: 1,
MPMediaItemPropertyArtwork: albumArt
]
let infoCenter = MPNowPlayingInfoCenter.default()
infoCenter.nowPlayingInfo = nowPlayingInfo
//infoCenter.nowPlayingInfo.MPMediaItemPropertyArtwork = albumArt
}
}
func fetchTrack () {
API.fetchTrack(track: track) { [weak self] (trackResponse, error) in
guard let strongSelf = self else {
return
}
if let error = error {
print(error)
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let trackResponse = trackResponse {
strongSelf.track = trackResponse
// print("--- FETCHED TRACK ---")
// print(trackResponse)
}
}
}
}
| mit | ac203794dce3cdef5557bf3d2c9f487e | 42.7 | 252 | 0.616959 | 5.219642 | false | false | false | false |
vijaytholpadi/WebViewRender | WebWrapper/ViewController.swift | 1 | 1758 | //
// ViewController.swift
// WebWrapper
//
// Created by Vijay Tholpadi on 5/6/16.
// Copyright © 2016 TheGeekProjekt. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var hostnameTextField: UITextField!
@IBOutlet weak var cookieStringTextView: UITextView!
@IBOutlet weak var webViewTypeSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
setupTextView(cookieStringTextView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupTextView(_ targetTextView: UITextView) {
targetTextView.layer.borderWidth = 1.0;
targetTextView.layer.borderColor = UIColor.black.cgColor
}
@IBAction func renderButtonPressed(_ sender: AnyObject) {
switch webViewTypeSwitch.isOn {
case true:
let wkwebViewRenderController = storyboard?.instantiateViewController(withIdentifier: "WKWebViewRenderController") as! WKWebViewRenderController
wkwebViewRenderController.urlToLoad = hostnameTextField.text
self.navigationController?.pushViewController(wkwebViewRenderController, animated: true);
break
case false:
let uiwebViewRenderController = storyboard?.instantiateViewController(withIdentifier: "UIWebViewRenderController") as! UIWebViewRenderController
uiwebViewRenderController.urlToLoad = hostnameTextField.text
uiwebViewRenderController.cookieStringToLoad = cookieStringTextView.text;
self.navigationController?.pushViewController(uiwebViewRenderController, animated: true);
break
}
}
}
| apache-2.0 | 687b3bd693c9cf261d808b6ac897c502 | 36.382979 | 157 | 0.719408 | 5.63141 | false | false | false | false |
ideafamily/Emonar | Emonar/ArchiveReplayViewController.swift | 1 | 8978 | //
// ArchiveReplayViewController.swift
// Emonar
//
// Created by ZengJintao on 4/5/16.
// Copyright © 2016 ZengJintao. All rights reserved.
//
import UIKit
import LDONavigationSubtitleView
class ArchiveReplayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,EZAudioPlayerDelegate {
@IBOutlet weak var recordTableView: UITableView!
@IBOutlet weak var playingAudioPlot: EZAudioPlotGL!
@IBOutlet weak var playButton: UIButton!
var audioName:String = ""
var isPaused:Bool = false
var playingIndex:Int = 0
var player:EZAudioPlayer!
var timer:Timer?
var recordFiles : [RecordFile]!
var audioData: [URL]!
var emotionData : [EmotionData]!
var cardSize:Int!
var customTitleView:LDONavigationSubtitleView?
var recordFileIndex:Int! {
didSet{
recordFiles = FileManager.sharedInstance.getAllLocalRecordFileFromStorage()
audioData = recordFiles[recordFileIndex].audioArrayToNSURLArray()
emotionData = recordFiles[recordFileIndex].sharedEmotionDataArray
cardSize = emotionData.count
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.player = EZAudioPlayer(delegate: self)
player.pause()
self.navigationController!.navigationBar.barTintColor = UIColor.black
recordTableView.delegate = self
recordTableView.dataSource = self
recordTableView.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI))
playingIndex = 0
self.playingAudioPlot.backgroundColor = UIColor(red: 0.984, green: 0.71, blue: 0.365, alpha: 1)
self.playingAudioPlot.color = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
self.playingAudioPlot.plotType = EZPlotType.rolling
self.playingAudioPlot.shouldFill = true
self.playingAudioPlot.shouldMirror = true
self.playingAudioPlot.gain = 5
customTitleView = LDONavigationSubtitleView(frame: CGRect(x: 0, y: 0, width: 300, height: 44))
customTitleView?.titleColor = UIColor.white
customTitleView!.subtitle = "00:00"
customTitleView!.title = "\(audioName)"
let gRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapTitle(_:)))
customTitleView?.addGestureRecognizer(gRecognizer)
customTitleView?.isUserInteractionEnabled = true
navigationItem.titleView = customTitleView
}
func showChangeFileNameAlert() {
let alertController = UIAlertController(title: "Change file name", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alertController.addTextField { (name:UITextField) -> Void in
name.text = self.customTitleView?.title
}
let saveAction = UIAlertAction(title: "Save", style: .default) { (action:UIAlertAction) -> Void in
let fileName = alertController.textFields![0].text
self.customTitleView?.title = fileName
FileManager.sharedInstance.changeRecordFileName(self.recordFileIndex, name: fileName!)
//TODO: save the file
}
let deleteAction = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) -> Void in
}
alertController.addAction(saveAction)
alertController.addAction(deleteAction)
self.present(alertController, animated: true, completion: nil)
}
func didTapTitle(_ gesture: UIGestureRecognizer) {
showChangeFileNameAlert()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecordTableViewCell", for: indexPath) as! RecordTableViewCell
cell.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
cell.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI));
cell.emotionLabel.text = emotionData[indexPath.row].emotion
cell.descriptionLabel.text = emotionData[indexPath.row].emotionDescription
if indexPath.row == playingIndex {
//MARK: cell is playing
cell.cardView.backgroundColor = UIColor.white
} else {
//MARK: cell is not playing
cell.cardView.backgroundColor = UIColor.lightGray
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cardSize
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var preIndex = playingIndex
if playingIndex == cardSize {
preIndex = cardSize - 1
}
playingIndex = indexPath.row
recordTableView.reloadRows(at: [IndexPath(row: preIndex, section: 0)], with: .automatic)
recordTableView.reloadRows(at: [IndexPath(row: playingIndex, section: 0)], with: .automatic)
if isPaused {
isPaused = false
}
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTime(_:)), userInfo: nil, repeats: true)
playButton.isSelected = true
_ = playFile()
}
func playFile()->Bool{
if audioData.count != 0 && playingIndex != cardSize {
let audioFile: EZAudioFile = EZAudioFile(url:audioData[playingIndex])
self.player.playAudioFile(audioFile)
return true
}
return false
}
func audioPlayer(_ audioPlayer: EZAudioPlayer!, reachedEndOf audioFile: EZAudioFile!) {
print("end of file at index \(self.playingIndex)")
self.playingIndex += 1
DispatchQueue.main.async {
if self.playFile() {
//Go to the next indexpath
self.recordTableView.reloadRows(at: [IndexPath(row: self.playingIndex, section: 0)], with: .automatic)
self.recordTableView.reloadRows(at: [IndexPath(row: self.playingIndex - 1, section: 0)], with: .automatic)
self.recordTableView.scrollToRow(at: IndexPath(row: self.playingIndex, section: 0), at: .middle, animated: true)
} else {
//Audio ends
self.playButton.isSelected = false
self.isPaused = false
self.timer?.invalidate()
}
}
}
@nonobjc func audioPlayer(_ audioPlayer: EZAudioPlayer!, playedAudio buffer: UnsafeMutablePointer<UnsafeMutablePointer<Float>>, withBufferSize bufferSize: UInt32, withNumberOfChannels numberOfChannels: UInt32, in audioFile: EZAudioFile!) {
weak var weakSelf = self
DispatchQueue.main.async(execute: {() -> Void in
weakSelf!.playingAudioPlot.updateBuffer(buffer[0], withBufferSize: bufferSize)
})
}
func updateTime(_ timer:Timer) {
let currentTime = Tool.stringFromTimeInterval(player.currentTime.advanced(by: 1 + Double(playingIndex) * timeSpan))
customTitleView?.subtitle = "\(currentTime)"
}
@IBAction func playButtonPressed(_ sender: UIButton) {
if playButton.isSelected {
//MARK: Pause playing
player.pause()
playButton.isSelected = false
isPaused = true
timer?.invalidate()
} else {
//MARK: Start playing
let currentTime = Tool.stringFromTimeInterval(player.currentTime.advanced(by: 1 + Double(playingIndex) * timeSpan))
customTitleView?.subtitle = "\(currentTime)"
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTime(_:)), userInfo: nil, repeats: true)
if isPaused {
isPaused = false
player.play()
} else {
if playingIndex != 0 {
//when audio has been played to end
customTitleView?.subtitle = "00:00"
playingIndex = 0
recordTableView.reloadRows(at: [IndexPath(row: cardSize - 1, section: 0)], with: .automatic)
recordTableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
recordTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .bottom, animated: true)
}
_ = playFile()
}
playButton.isSelected = true
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer?.invalidate()
player.pause()
}
}
| mit | b6f0d8fe2c0e375ff4203871efe561a1 | 38.030435 | 243 | 0.624485 | 5.201043 | false | false | false | false |
tablexi/AlamofireGenome | AlamofireGenome/AlamofireGenome.swift | 1 | 5888 | //
// AlamofireGenome.swift
// PechaKucha
//
// Created by Daniel Hodos on 11/5/15.
// Copyright © 2015 Table XI. All rights reserved.
//
import Foundation
import Alamofire
import Genome
extension Request {
// MARK: Parsing
enum AlamofireGenomeError: ErrorType {
case JSONError
}
/// Parses the JSON and maps it using Genome.
///
/// Generics:
/// - T: `MappableObject` or `Array<MappableObject>`
/// - U: `JSON` or `Array<JSON>`
private static func parse<T, U>(keyPath: String?, callback: U throws -> T) -> ResponseSerializer<T, NSError> {
return ResponseSerializer { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
guard let value = result.value else { return .Failure(result.error!) }
let JSONToMap: U?
if let keyPath = keyPath {
JSONToMap = value[keyPath] as? U
} else {
JSONToMap = value as? U
}
guard let json = JSONToMap else {
return .Failure(AlamofireGenomeError.JSONError as NSError)
}
do {
let result = try callback(json)
return .Success(result)
} catch {
if let error = error as? CustomErrorConvertible {
return .Failure(error.error)
}
return .Failure(error as NSError)
}
}
}
// MARK: Serialization
/// Creates a response serializer that returns a Genome `MappableObject`
/// constructed from the response data.
///
/// Parameters:
/// - keyPath: The root key of the JSON
///
/// Returns: A Genome `ResponseSerializer`
public static func GenomeSerializer<T: MappableObject>(keyPath: String?) -> ResponseSerializer<T, NSError> {
return parse(keyPath) { try T.mappedInstance($0) }
}
/// Creates a response serializer that returns an array of Genome
/// `MappableObject` constructed from the response data.
///
/// Parameters:
/// - keyPath: The root key of the JSON
///
/// Returns: A Genome `ResponseSerializer`
public static func GenomeSerializer<T: MappableObject>(keyPath: String?) -> ResponseSerializer<[T], NSError> {
return parse(keyPath) { try [T].mappedInstance($0) }
}
// MARK: Object
/// Adds a handler to be called once a request has finished to map the
/// returned JSON to a Genome `MappableObject`
///
/// Parameters:
/// - completionHandler: Closure to be executed once the execution has
/// finished
///
/// Returns: The request
public func responseObject<T: MappableObject>(completionHandler: Response<T, NSError> -> Void) -> Self {
return responseObject(nil, keyPath: nil, completionHandler: completionHandler)
}
/// Adds a handler to be called once a request has finished to map the
/// returned JSON to a Genome `MappableObject`
///
/// Parameters:
/// - keyPath: The root key of the JSON
/// - completionHandler: Closure to be executed once the execution has
/// finished
///
/// Returns: The request
public func responseObject<T: MappableObject>(keyPath: String, completionHandler: Response<T, NSError> -> Void) -> Self {
return responseObject(nil, keyPath: keyPath, completionHandler: completionHandler)
}
/// Adds a handler to be called once a request has finished to map the
/// returned JSON to a Genome `MappableObject`
///
/// Parameters:
/// - queue: The queue on which the completion handler is dispatched
/// - keyPath: The root key of the JSON
/// - completionHandler: Closure to be executed once the execution has
/// finished
///
/// Returns: The request
public func responseObject<T: MappableObject>(queue: dispatch_queue_t?, keyPath: String?, completionHandler: Response<T, NSError> -> Void) -> Self {
return response(queue: queue, responseSerializer: Request.GenomeSerializer(keyPath), completionHandler: completionHandler)
}
// MARK: Array
/// Adds a handler to be called once a request has finished to map the
/// returned JSON to an array of Genome `MappableObject`
///
/// Parameters:
/// - completionHandler: Closure to be executed once the execution has
/// finished
///
/// Returns: The request
public func responseArray<T: MappableObject>(completionHandler: Response<[T], NSError> -> Void) -> Self {
return responseArray(nil, keyPath: nil, completionHandler: completionHandler)
}
/// Adds a handler to be called once a request has finished to map the
/// returned JSON to an array of Genome `MappableObject`
///
/// Parameters:
/// - keyPath: The root key of the JSON
/// - completionHandler: Closure to be executed once the execution has
/// finished
///
/// Returns: The request
public func responseArray<T: MappableObject>(keyPath: String, completionHandler: Response<[T], NSError> -> Void) -> Self {
return responseArray(nil, keyPath: keyPath, completionHandler: completionHandler)
}
/// Adds a handler to be called once a request has finished to map the
/// returned JSON to an array of Genome `MappableObject`
///
/// Parameters:
/// - queue: The queue on which the completion handler is dispatched
/// - keyPath: The root key of the JSON
/// - completionHandler: Closure to be executed once the execution has
/// finished
///
/// Returns: The request
public func responseArray<T: MappableObject>(queue: dispatch_queue_t?, keyPath: String?, completionHandler: Response<[T], NSError> -> Void) -> Self {
return response(queue: queue, responseSerializer: Request.GenomeSerializer(keyPath), completionHandler: completionHandler)
}
} | mit | 2d50800b12dd47c2c6b1fb19be1d35e0 | 35.122699 | 151 | 0.664685 | 4.657437 | false | false | false | false |
spf-iOS/WebJSBridge | WebJSBridge/WebJSBridge.swift | 1 | 9097 | //
// WebJSBridge.swift
// TextJS
//
// Created by song on 2017/3/4.
// Copyright © 2017年 song. All rights reserved.
//
import UIKit
import JavaScriptCore
/*! 回调数据 */
typealias WebJSResponseCallback = (_ responseData:Any?) -> ()
/*! js回调App的block */
typealias WebJBHandler = ( _ data:Any?, _ responseCallback:WebJSResponseCallback) -> ()
/*! webView与JS的初始化回调 */
typealias WebJSInitHandler = ( _ success:Bool, _ error:String) -> ()
/*
* WebJSBridge
*
/// 初始化桥接功能
*init(_ webView:UIWebView,_ jsKey:String,webViewDelegate:UIWebViewDelegate?,handler:WebJSInitHandler?)
*
*
/// js调用App回调
*func registerHandler(handlerName:String,webJBHandler: @escaping WebJBHandler)
*
*
/// 移除回调监听
*func removeHandler(handlerName:String)
*
*
/// 移除所有的监听
*func reset()
*
*
/// App调用js中方法
*func callHandler(handlerName:String,data:Any?,responseCallback:WebJSResponseCallback?)
*
*/
@objc class WebJSBridge: NSObject,WebJSDelegate {
fileprivate var appHandler: WebJSDelegate.JSHandler!
fileprivate var webView:UIWebView
fileprivate var jsContext:JSContext
fileprivate var jsModelDict:[String:WebJSModel] = [String:WebJSModel]()
fileprivate var webViewDelegate:UIWebViewDelegate?
fileprivate var isFinishLoad = false
fileprivate var cacheCallDict:[String:Any?] = [String:Any?]()
/// 初始化桥接功能
///
/// - Parameters:
/// - webView: 需要加载的webView
/// - jsKey: h5中调用iOS方法的对象
/// - webViewDelegate: webView.delegate所在的VC
/// - handler: 是否桥接成功的回调
init(_ webView:UIWebView,_ jsKey:String,webViewDelegate:UIWebViewDelegate?,handler:WebJSInitHandler?) {
self.webView = webView
self.webViewDelegate = webViewDelegate
if let context = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as? JSContext {
jsContext = context
}
else
{
print("无法获取webView的JSContext")
jsContext = JSContext()
if let `handler` = handler {
handler(false,"无法获取webView的JSContext,请检查webView")
}
super.init()
return
}
super.init()
jsContext.setObject(self, forKeyedSubscript: jsKey as (NSCopying & NSObjectProtocol)?)
if let `handler` = handler {
handler(true,"JS与iOS桥接成功")
}
initRegisterHandler()
webView.delegate = self
}
/// js调用App回调
///
/// - Parameters:
/// - handlerName: 双方约定的Key
/// - webJBHandler: 里面的data:给App的数据,responseCallback:App给js的响应结果
func registerHandler(handlerName:String,webJBHandler: @escaping WebJBHandler){
let model = WebJSModel()
model.handlerName = handlerName
model.isCall = false
model.webJBHandler = webJBHandler
let responseCallback:WebJSResponseCallback = {
[weak self] (responseData) in
guard let `self` = self else { return }
if let callName = model.callName, let jsParamsFunc = self.jsContext.objectForKeyedSubscript(callName) {
var arr = [Any]()
if let data = responseData {
arr.append(data)
}
jsParamsFunc.call(withArguments: arr)
}
}
model.responseCallback = responseCallback
jsModelDict[handlerName] = model
}
/// 移除回调监听
///
/// - Parameter handlerName: 双方约定的Key
func removeHandler(handlerName:String){
jsModelDict.removeValue(forKey: handlerName)
}
/// 移除所有的监听
func reset(){
jsModelDict.removeAll()
}
/// App调用js中方法
///
/// - Parameters:
/// - handlerName: handlerName: 双方约定的Key
/// - data: 给js的数据
/// - responseCallback: js给App的响应结果
func callHandler(handlerName:String,data:Any?,responseCallback:WebJSResponseCallback?){
if let _ = responseCallback {
let model = WebJSModel()
model.handlerName = handlerName
model.isCall = true
model.responseCallback = responseCallback
jsModelDict[handlerName] = model
}
if isFinishLoad {
if let jsParamsFunc = jsContext.objectForKeyedSubscript(handlerName) {
var arr = [Any]()
if let callData = data {
arr.append(callData)
}
jsParamsFunc.call(withArguments: arr)
}
}
else
{
cacheCallDict[handlerName] = data
}
}
/*! 真实js回调APP的地方 */
private func initRegisterHandler(){
appHandler = {
[weak self] (handlerName,data,callBack) in
guard let `self` = self else { return }
if let jsModle = self.jsModelDict[handlerName] {
//监听js调App isCall一定等于false
if let webJBHandler = jsModle.webJBHandler{
jsModle.callName = callBack
if let responseCallback = jsModle.responseCallback {
webJBHandler(data,responseCallback)
}
else
{
let responseCallback:WebJSResponseCallback = {
[weak self] (responseData) in
guard let `self` = self else { return }
if let jsParamsFunc = self.jsContext.objectForKeyedSubscript(handlerName) {
var arr = [Any]()
if let data = responseData {
arr.append(data)
}
jsParamsFunc.call(withArguments: arr)
}
}
webJBHandler(data,responseCallback)
}
}
else if let responseCallback = jsModle.responseCallback { //isCall一定等于true
responseCallback(data)
// self.jsModelDict.removeValue(forKey: handlerName)
}
//这里有两种情况会销毁js给App的响应结果 1,call js后 js给App的响应结果 2.call js后 js没有给App响应结果 接下来有了 call App的动作
for (handlerName, jsModel) in self.jsModelDict {
if jsModel.isCall {
self.jsModelDict.removeValue(forKey: handlerName)
}
}
}
}
}
/*! h5加载成功后才能Call到js */
fileprivate func callCache(){
cacheCallDict.forEach {
[weak self](handlerName, data) in
guard let `self` = self else { return }
if let jsParamsFunc = self.jsContext.objectForKeyedSubscript(handlerName) {
var arr = [Any]()
if let callData = data {
arr.append(callData)
}
jsParamsFunc.call(withArguments: arr)
}
}
cacheCallDict.removeAll()
}
}
/*! 这里是为了使用webViewDidFinishLoad 但必须将其回调到所在的VC中 */
extension WebJSBridge:UIWebViewDelegate{
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
if let boo = webViewDelegate?.webView?(webView, shouldStartLoadWith: request, navigationType: navigationType) {
return boo
}
return true
}
func webViewDidStartLoad(_ webView: UIWebView){
isFinishLoad = false
webViewDelegate?.webViewDidStartLoad?(webView)
}
func webViewDidFinishLoad(_ webView: UIWebView) {
isFinishLoad = true
callCache()
webViewDelegate?.webViewDidFinishLoad?(webView)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
webViewDelegate?.webView?(webView, didFailLoadWithError: error)
}
}
/*
*
* 增加属性为了H5中调用
*/
@objc fileprivate protocol WebJSDelegate: JSExport {
/*! js与APP的实际参数 */
typealias JSHandler = (_ handlerName:String,_ data:Any?,_ callBack:String?) -> ()
/*! h5中统一调用该属性*/
var appHandler:JSHandler! { get set }
}
/*
*
* 该对象主要处理WebJSDelegate中registerHandler和方法的对接
*/
fileprivate class WebJSModel: NSObject {
var handlerName:String = ""
var isCall = false //true:App调用js false:js调用APP
var webJBHandler:WebJBHandler?
var responseCallback:WebJSResponseCallback?
var callName:String?
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit | 3bd17f97a6c5c6a0bdc1d53f5be04cd4 | 31.075188 | 129 | 0.580052 | 4.847727 | false | false | false | false |
DavidSkrundz/Lua | Tests/LuaTests/CustomTypeTests.swift | 1 | 4091 | //
// CustomTypeTests.swift
// Lua
//
import Lua
import XCTest
class CustomTypeTests: XCTestCase {
func testTypeCreation() {
do {
let lua = Lua()
_ = try lua.createType(Object.self)
let results = try lua.run("return Object.add(3.5, 8.6)")
AssertEqual(results, [12.1])
} catch let e as LuaError {
XCTFail(e.description)
} catch let e {
XCTFail(e.localizedDescription)
}
}
func testInstanceCreation() {
do {
let lua = Lua()
_ = try lua.createType(Object.self)
_ = try lua.run("obj = Object.new('--suffix')")
let instance: Object = (lua.globals["obj"] as! UserData).toType()
XCTAssertEqual(instance.suffix, "--suffix")
} catch let e as LuaError {
XCTFail(e.description)
} catch let e {
XCTFail(e.localizedDescription)
}
}
func testMethodCall() {
do {
let lua = Lua()
_ = try lua.createType(Object.self)
lua.globals["obj"] = Object(suffix: "swef")
_ = try lua.run("oldSuffix = obj:getSuffix()")
_ = try lua.run("obj:setSuffix('--wapoz')")
let results = try lua.run("return obj:addSuffix(oldSuffix)")
let instance: Object = (lua.globals["obj"] as! UserData).toType()
AssertEqual(results, ["swef--wapoz"])
XCTAssertEqual(instance.suffix, "--wapoz")
} catch let e as LuaError {
XCTFail(e.description)
} catch let e {
XCTFail(e.localizedDescription)
}
}
func testSuccessfulTypeChecking() {
do {
let lua = Lua()
_ = try lua.createType(Object.self)
lua.globals["obj"] = Object(suffix: "suffix")
let results = try lua.run("return Object.getSuffixFrom(obj)")
AssertEqual(results, ["suffix"])
} catch let e as LuaError {
XCTFail(e.description)
} catch let e {
XCTFail(e.localizedDescription)
}
}
func testTypeChecking() {
do {
let lua = Lua()
_ = try lua.createType(Object.self)
_ = try lua.createType(Other.self)
_ = try lua.run("obj = Other.new()")
_ = try lua.run("return Object.getSuffixFrom(obj)")
XCTFail("Expected an Error")
} catch let LuaError.Runtime(message) {
XCTAssertEqual(message, "[string \"return Object.getSuffixFrom(obj)\"]:1: bad argument #1 to 'getSuffixFrom' (Object expected, got Other)")
} catch let e as LuaError {
XCTFail(e.description)
} catch let e {
XCTFail(e.localizedDescription)
}
}
static var allTests = [
("testTypeCreation", testTypeCreation),
("testInstanceCreation", testInstanceCreation),
("testMethodCall", testMethodCall),
("testSuccessfulTypeChecking", testSuccessfulTypeChecking),
("testTypeChecking", testTypeChecking),
]
}
private final class Object: LuaConvertible {
static let typeName: StaticString = "Object"
static let initializer: LuaInitializer? = Lua.wrap([.String]) { (values) -> Object in
return Object(suffix: values[0] as! String)
}
static let functions = [
("add", Lua.wrap([.Number, .Number]) { (values) -> [Value] in
return [Object.add(values[0] as! Number, values[1] as! Number)]
}),
("getSuffixFrom", Lua.wrap([.Custom(Object.self)]) { (values) -> [Value] in
return [(values[0] as! Object).suffix]
}),
]
static let methods = [
("getSuffix", Lua.wrap([]) { (obj: Object, _) -> [Value] in
return [obj.suffix]
}),
("setSuffix", Lua.wrap([.String]) { (obj: Object, values) -> [Value] in
obj.suffix = values[0] as! String
return []
}),
("addSuffix", Lua.wrap([.String]) { (obj: Object, values) -> [Value] in
return [obj.addSuffix(values[0] as! String)]
}),
]
var suffix = ""
var hashValue: Int {
return self.suffix.hashValue
}
init(suffix: String) {
self.suffix = suffix
}
static func add(_ lhs: Number, _ rhs: Number) -> Double {
return lhs.doubleValue + rhs.doubleValue
}
func addSuffix(_ string: String) -> String {
return string + self.suffix
}
}
private final class Other: LuaConvertible {
static let typeName: StaticString = "Other"
static var initializer: LuaInitializer? = Lua.wrap([]) { _ in Other() }
static let functions = [(String, LuaFunction)]()
static let methods = [(String, (Other, Lua) -> [Value])]()
var hashValue: Int {
return 0
}
}
| lgpl-3.0 | d4e905803d84040702b438afaf0ff81f | 25.564935 | 142 | 0.650208 | 3.246825 | false | true | false | false |
iThinkersTeam/Blog | SnapKitLoginScreen/Pods/SnapKit/Source/ConstraintOffsetTarget.swift | 3 | 2170 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol ConstraintOffsetTarget: ConstraintConstantTarget {
}
extension Int: ConstraintOffsetTarget {
}
extension UInt: ConstraintOffsetTarget {
}
extension Float: ConstraintOffsetTarget {
}
extension Double: ConstraintOffsetTarget {
}
extension CGFloat: ConstraintOffsetTarget {
}
extension ConstraintOffsetTarget {
internal var constraintOffsetTargetValue: CGFloat {
let offset: CGFloat
if let amount = self as? Float {
offset = CGFloat(amount)
} else if let amount = self as? Double {
offset = CGFloat(amount)
} else if let amount = self as? CGFloat {
offset = CGFloat(amount)
} else if let amount = self as? Int {
offset = CGFloat(amount)
} else if let amount = self as? UInt {
offset = CGFloat(amount)
} else {
offset = 0.0
}
return offset
}
}
| mit | b9994ec58b05a3d221143ae0f700c854 | 31.38806 | 81 | 0.694931 | 4.492754 | false | false | false | false |
stephentyrone/swift | stdlib/private/SwiftPrivateThreadExtras/ThreadBarriers.swift | 3 | 4833 | //===--- ThreadBarriers.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku)
import Glibc
#elseif os(Windows)
import MSVCRT
import WinSDK
#endif
//
// Implement pthread barriers.
//
// (OS X does not implement them.)
//
public var _stdlib_THREAD_BARRIER_SERIAL_THREAD: CInt {
return 1
}
public struct _stdlib_thread_barrier_t {
#if os(Windows)
var mutex: UnsafeMutablePointer<SRWLOCK>?
var cond: UnsafeMutablePointer<CONDITION_VARIABLE>?
#elseif os(Cygwin) || os(FreeBSD) || os(OpenBSD)
var mutex: UnsafeMutablePointer<pthread_mutex_t?>?
var cond: UnsafeMutablePointer<pthread_cond_t?>?
#else
var mutex: UnsafeMutablePointer<pthread_mutex_t>?
var cond: UnsafeMutablePointer<pthread_cond_t>?
#endif
/// The number of threads to synchronize.
var count: CUnsignedInt = 0
/// The number of threads already waiting on the barrier.
///
/// This shared variable is protected by `mutex`.
var numThreadsWaiting: CUnsignedInt = 0
public init() {}
}
public func _stdlib_thread_barrier_init(
_ barrier: UnsafeMutablePointer<_stdlib_thread_barrier_t>,
_ count: CUnsignedInt
) -> CInt {
barrier.pointee = _stdlib_thread_barrier_t()
if count == 0 {
errno = EINVAL
return -1
}
#if os(Windows)
barrier.pointee.mutex = UnsafeMutablePointer.allocate(capacity: 1)
InitializeSRWLock(barrier.pointee.mutex!)
barrier.pointee.cond = UnsafeMutablePointer.allocate(capacity: 1)
InitializeConditionVariable(barrier.pointee.cond!)
#else
barrier.pointee.mutex = UnsafeMutablePointer.allocate(capacity: 1)
barrier.pointee.cond = UnsafeMutablePointer.allocate(capacity: 1)
guard _stdlib_thread_barrier_mutex_and_cond_init(barrier) == 0 else {
barrier.pointee.mutex!.deinitialize(count: 1)
barrier.pointee.mutex!.deallocate()
barrier.pointee.cond!.deinitialize(count: 1)
barrier.pointee.cond!.deallocate()
return -1
}
#endif
barrier.pointee.count = count
return 0
}
#if !os(Windows)
private func _stdlib_thread_barrier_mutex_and_cond_init(_ barrier: UnsafeMutablePointer<_stdlib_thread_barrier_t>) -> CInt {
guard pthread_mutex_init(barrier.pointee.mutex!, nil) == 0 else {
return -1
}
guard pthread_cond_init(barrier.pointee.cond!, nil) == 0 else {
pthread_mutex_destroy(barrier.pointee.mutex!)
return -1
}
return 0
}
#endif
public func _stdlib_thread_barrier_destroy(
_ barrier: UnsafeMutablePointer<_stdlib_thread_barrier_t>
) {
#if os(Windows)
// Condition Variables do not need to be explicitly destroyed
// Mutexes do not need to be explicitly destroyed
#else
guard pthread_cond_destroy(barrier.pointee.cond!) == 0 &&
pthread_mutex_destroy(barrier.pointee.mutex!) == 0 else {
fatalError("_stdlib_thread_barrier_destroy() failed")
}
#endif
barrier.pointee.cond!.deinitialize(count: 1)
barrier.pointee.cond!.deallocate()
barrier.pointee.mutex!.deinitialize(count: 1)
barrier.pointee.mutex!.deallocate()
return
}
public func _stdlib_thread_barrier_wait(
_ barrier: UnsafeMutablePointer<_stdlib_thread_barrier_t>
) -> CInt {
#if os(Windows)
AcquireSRWLockExclusive(barrier.pointee.mutex!)
#else
if pthread_mutex_lock(barrier.pointee.mutex!) != 0 {
return -1
}
#endif
barrier.pointee.numThreadsWaiting += 1
if barrier.pointee.numThreadsWaiting < barrier.pointee.count {
// Put the thread to sleep.
#if os(Windows)
if !SleepConditionVariableSRW(barrier.pointee.cond!, barrier.pointee.mutex!,
INFINITE, 0) {
return -1
}
ReleaseSRWLockExclusive(barrier.pointee.mutex!)
#else
if pthread_cond_wait(barrier.pointee.cond!, barrier.pointee.mutex!) != 0 {
return -1
}
if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 {
return -1
}
#endif
return 0
} else {
// Reset thread count.
barrier.pointee.numThreadsWaiting = 0
// Wake up all threads.
#if os(Windows)
WakeAllConditionVariable(barrier.pointee.cond!)
ReleaseSRWLockExclusive(barrier.pointee.mutex!)
#else
if pthread_cond_broadcast(barrier.pointee.cond!) != 0 {
return -1
}
if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 {
return -1
}
#endif
return _stdlib_THREAD_BARRIER_SERIAL_THREAD
}
}
| apache-2.0 | 86faf6d34de1e91f8650fa3ef5a183b7 | 28.290909 | 124 | 0.68653 | 3.829635 | false | false | false | false |
wanghdnku/Whisper | Pods/KRProgressHUD/KRProgressHUD/Classes/KRProgressHUDViewController.swift | 5 | 1024 | //
// KRProgressHUDViewController.swift
// KRProgressHUD
//
// Copyright © 2016年 Krimpedance. All rights reserved.
//
import UIKit
class KRProgressHUDViewController: UIViewController {
var statusBarStyle = UIStatusBarStyle.default
var statusBarHidden = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0, alpha: 0.4)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
guard let vc = UIApplication.topViewController() else { return statusBarStyle }
if !vc.isKind(of: KRProgressHUDViewController.self) {
statusBarStyle = vc.preferredStatusBarStyle
}
return statusBarStyle
}
override var prefersStatusBarHidden: Bool {
guard let vc = UIApplication.topViewController() else { return statusBarHidden }
if !vc.isKind(of: KRProgressHUDViewController.self) {
statusBarHidden = vc.prefersStatusBarHidden
}
return statusBarHidden
}
}
| mit | b9674c04ed1327224121b2487c095b92 | 29.029412 | 88 | 0.693438 | 5.489247 | false | false | false | false |
sixoverground/ImagePickerController | Classes/ImageStackView.swift | 1 | 2045 | //
// ImageStackView.swift
// ImagePickerController
//
// Created by Craig Phares on 4/20/16.
// Copyright © 2016 Six Overground. All rights reserved.
//
import UIKit
import Photos
class ImageStackView: UIView {
lazy var imageView: UIImageView = {
let view = UIImageView()
view.layer.cornerRadius = 3
view.contentMode = .ScaleAspectFill
view.clipsToBounds = true
view.layer.borderColor = UIColor.whiteColor().CGColor
view.layer.borderWidth = 1
view.alpha = 0
return view
}()
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
subscribe()
addSubview(imageView)
// imageView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
imageView.translatesAutoresizingMaskIntoConstraints = false
for attribute: NSLayoutAttribute in [.Left, .Top, .Right, .Bottom] {
addConstraint(NSLayoutConstraint(item: imageView, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: attribute, multiplier: 1, constant: 0))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Notifications
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func subscribe() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(selectedAssetDidChange(_:)), name: ImagePickerModel.Notifications.selectedAssetDidChange, object: nil)
}
func selectedAssetDidChange(notification: NSNotification) {
if let sender = notification.object as? ImagePickerModel {
if let asset = sender.selectedAsset {
renderViews(asset)
} else {
self.imageView.image = nil
self.imageView.alpha = 0
}
}
}
// MARK: - Helpers
func renderViews(asset: PHAsset) {
ImagePickerModel.resolveAsset(asset, size: CGSize(width: 58, height: 58)) { (image) in
self.imageView.image = image
self.imageView.alpha = 1
}
}
}
| mit | d11e50ecac9c39aa59ff73f4841a6eff | 25.545455 | 181 | 0.675636 | 4.424242 | false | false | false | false |
rustedivan/tapmap | tapmap/Rendering/RenderPrimitives.swift | 1 | 3019 | //
// RenderPrimitives.swift
// tapmap
//
// Created by Ivan Milles on 2019-07-30.
// Copyright © 2019 Wildbrain. All rights reserved.
//
import Metal
class BaseRenderPrimitive<VertexType> {
let ownerHash: Int
let drawMode: MTLPrimitiveType
let vertexBuffer: MTLBuffer
let elementCounts: [Int]
let indexBuffer: MTLBuffer
let color: Color
let name: String
init(polygons: [[VertexType]],
indices: [[UInt16]],
drawMode mode: MTLPrimitiveType,
device: MTLDevice,
color c: Color,
ownerHash hash: Int, debugName: String) {
color = c
ownerHash = hash
name = debugName
drawMode = mode
guard !indices.isEmpty else {
fatalError("Do not create render primitive for empty meshes")
}
// Concatenate all vertices into one buffer
var allVertices: [VertexType] = []
var allIndices: [UInt32] = []
var polyRanges: [Int] = []
for (p, i) in zip(polygons, indices) {
guard !p.isEmpty else { continue }
allVertices.append(contentsOf: p)
allIndices.append(contentsOf: i.map { UInt32($0) })
polyRanges.append(i.count)
}
elementCounts = polyRanges
let vertexBufLen = MemoryLayout<VertexType>.stride * allVertices.count
let indexBufLen = MemoryLayout<UInt32>.stride * allIndices.count
guard let newVertBuffer = device.makeBuffer(bytes: allVertices, length: vertexBufLen, options: .storageModeShared),
let newIndexBuffer = device.makeBuffer(bytes: allIndices, length: indexBufLen, options: .storageModeShared) else {
fatalError("Could not create buffers for \(debugName)")
}
self.vertexBuffer = newVertBuffer
self.vertexBuffer.label = "\(debugName) vertex buffer"
self.indexBuffer = newIndexBuffer
self.indexBuffer.label = "\(debugName) index buffer"
}
}
typealias RenderPrimitive = BaseRenderPrimitive<Vertex>
typealias FixedScaleRenderPrimitive = BaseRenderPrimitive<ScaleVertex>
typealias TexturedRenderPrimitive = BaseRenderPrimitive<TexturedVertex>
func render<T>(primitive: BaseRenderPrimitive<T>, into encoder: MTLRenderCommandEncoder) {
encoder.setVertexBuffer(primitive.vertexBuffer, offset: 0, index: 0)
var cursor = 0
for range in primitive.elementCounts {
encoder.drawIndexedPrimitives(type: primitive.drawMode,
indexCount: range,
indexType: .uint32,
indexBuffer: primitive.indexBuffer,
indexBufferOffset: cursor)
cursor += range * MemoryLayout<UInt32>.stride
}
}
func renderInstanced<T>(primitive: BaseRenderPrimitive<T>, count: Int, into encoder: MTLRenderCommandEncoder) {
encoder.setVertexBuffer(primitive.vertexBuffer, offset: 0, index: 0)
var cursor = 0
for range in primitive.elementCounts {
encoder.drawIndexedPrimitives(type: primitive.drawMode,
indexCount: range,
indexType: .uint32,
indexBuffer: primitive.indexBuffer,
indexBufferOffset: cursor,
instanceCount: count)
cursor += range * MemoryLayout<UInt32>.stride
}
}
| mit | 36a353de60cd14c9a9770a407c49a182 | 30.113402 | 119 | 0.70941 | 4.013298 | false | false | false | false |
matthewpurcell/firefox-ios | Client/Frontend/Home/BookmarksPanel.swift | 1 | 16528 | /* 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
import Shared
import XCGLogger
private let log = Logger.browserLogger
let BookmarkStatusChangedNotification = "BookmarkStatusChangedNotification"
// MARK: - Placeholder strings for Bug 1232810.
let deleteWarningTitle = NSLocalizedString("This folder isn't empty.", tableName: "BookmarkPanelDeleteConfirm", comment: "Title of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.")
let deleteWarningDescription = NSLocalizedString("Are you sure you want to delete it and its contents?", tableName: "BookmarkPanelDeleteConfirm", comment: "Main body of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.")
let deleteCancelButtonLabel = NSLocalizedString("Cancel", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label to cancel deletion when the user tried to delete a non-empty folder.")
let deleteDeleteButtonLabel = NSLocalizedString("Delete", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label for the button that deletes a folder and all of its children.")
// MARK: - UX constants.
struct BookmarksPanelUX {
private static let BookmarkFolderHeaderViewChevronInset: CGFloat = 10
private static let BookmarkFolderChevronSize: CGFloat = 20
private static let BookmarkFolderChevronLineWidth: CGFloat = 4.0
private static let BookmarkFolderTextColor = UIColor(red: 92/255, green: 92/255, blue: 92/255, alpha: 1.0)
}
class BookmarksPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var source: BookmarksModel?
var parentFolders = [BookmarkFolder]()
var bookmarkFolder: BookmarkFolder?
private let BookmarkFolderCellIdentifier = "BookmarkFolderIdentifier"
private let BookmarkFolderHeaderViewIdentifier = "BookmarkFolderHeaderIdentifier"
private lazy var defaultIcon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
self.tableView.registerClass(BookmarkFolderTableViewCell.self, forCellReuseIdentifier: BookmarkFolderCellIdentifier)
self.tableView.registerClass(BookmarkFolderTableViewHeader.self, forHeaderFooterViewReuseIdentifier: BookmarkFolderHeaderViewIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// if we've not already set a source for this panel fetch a new model
// otherwise just use the existing source to select a folder
guard let source = self.source else {
// Get all the bookmarks split by folders
if let bookmarkFolder = bookmarkFolder {
profile.bookmarks.modelForFolder(bookmarkFolder).upon(onModelFetched)
} else {
profile.bookmarks.modelForFolder(BookmarkRoots.MobileFolderGUID).upon(onModelFetched)
}
return
}
if let bookmarkFolder = bookmarkFolder {
source.selectFolder(bookmarkFolder).upon(onModelFetched)
} else {
source.selectFolder(BookmarkRoots.MobileFolderGUID).upon(onModelFetched)
}
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
self.reloadData()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func onModelFetched(result: Maybe<BookmarksModel>) {
guard let model = result.successValue else {
self.onModelFailure(result.failureValue)
return
}
self.onNewModel(model)
}
private func onNewModel(model: BookmarksModel) {
dispatch_async(dispatch_get_main_queue()) {
self.source = model
self.tableView.reloadData()
}
}
private func onModelFailure(e: Any) {
log.error("Error: failed to get data: \(e)")
}
override func reloadData() {
self.source?.reloadData().upon(onModelFetched)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source?.current.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let source = source, bookmark = source.current[indexPath.row] else { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) }
let cell: UITableViewCell
if let _ = bookmark as? BookmarkFolder {
cell = tableView.dequeueReusableCellWithIdentifier(BookmarkFolderCellIdentifier, forIndexPath: indexPath)
} else {
cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if let url = bookmark.favicon?.url.asURL where url.scheme == "asset" {
cell.imageView?.image = UIImage(named: url.host!)
} else {
cell.imageView?.setIcon(bookmark.favicon, withPlaceholder: self.defaultIcon)
}
}
switch (bookmark) {
case let item as BookmarkItem:
if item.title.isEmpty {
cell.textLabel?.text = item.url
} else {
cell.textLabel?.text = item.title
}
default:
// Bookmark folders don't have a good fallback if there's no title. :(
cell.textLabel?.text = bookmark.title
}
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? BookmarkFolderTableViewCell {
cell.textLabel?.font = DynamicFontHelper.defaultHelper.DefaultMediumFont
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Don't show a header for the root
if source == nil || parentFolders.isEmpty {
return nil
}
guard let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(BookmarkFolderHeaderViewIdentifier) as? BookmarkFolderTableViewHeader else { return nil }
// register as delegate to ensure we get notified when the user interacts with this header
if header.delegate == nil {
header.delegate = self
}
if parentFolders.count == 1 {
header.textLabel?.text = NSLocalizedString("Bookmarks", comment: "Panel accessibility label")
} else if let parentFolder = parentFolders.last {
header.textLabel?.text = parentFolder.title
}
return header
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header.
if source == nil || parentFolders.isEmpty {
return 0
}
return SiteTableViewControllerUX.RowHeight
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? BookmarkFolderTableViewHeader {
// for some reason specifying the font in header view init is being ignored, so setting it here
header.textLabel?.font = DynamicFontHelper.defaultHelper.DefaultMediumFont
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let source = source {
let bookmark = source.current[indexPath.row]
switch (bookmark) {
case let item as BookmarkItem:
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: item.url)!, visitType: VisitType.Bookmark)
break
case let folder as BookmarkFolder:
let nextController = BookmarksPanel()
nextController.parentFolders = parentFolders + [source.current]
nextController.bookmarkFolder = folder
nextController.source = source
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.navigationController?.pushViewController(nextController, animated: true)
break
default:
// Weird.
break // Just here until there's another executable statement (compiler requires one).
}
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if source == nil {
return .None
}
if source!.current.itemIsEditableAtIndex(indexPath.row) ?? false {
return .Delete
}
return .None
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
if source == nil {
return [AnyObject]()
}
let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in
if let bookmark = self.source?.current[indexPath.row] {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the bookmarks API switches to
// Deferred instead of using callbacks.
// TODO: it's now time for this.
self.profile.bookmarks.remove(bookmark).uponQueue(dispatch_get_main_queue()) { res in
if let err = res.failureValue {
self.onModelFailure(err)
return
}
dispatch_async(dispatch_get_main_queue()) {
self.source?.reloadData().upon {
guard let model = $0.successValue else {
self.onModelFailure($0.failureValue)
return
}
dispatch_async(dispatch_get_main_queue()) {
tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.source = model
tableView.endUpdates()
NSNotificationCenter.defaultCenter().postNotificationName(BookmarkStatusChangedNotification, object: bookmark, userInfo:["added":false])
}
}
}
}
}
})
return [delete]
}
}
private protocol BookmarkFolderTableViewHeaderDelegate {
func didSelectHeader()
}
extension BookmarksPanel: BookmarkFolderTableViewHeaderDelegate {
private func didSelectHeader() {
self.navigationController?.popViewControllerAnimated(true)
}
}
class BookmarkFolderTableViewCell: TwoLineTableViewCell {
private let ImageMargin: CGFloat = 12
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor
textLabel?.backgroundColor = UIColor.clearColor()
textLabel?.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
textLabel?.font = DynamicFontHelper.defaultHelper.DefaultMediumFont
imageView?.image = UIImage(named: "bookmarkFolder")
let chevron = ChevronView(direction: .Right)
chevron.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
chevron.frame = CGRectMake(0, 0, BookmarksPanelUX.BookmarkFolderChevronSize, BookmarksPanelUX.BookmarkFolderChevronSize)
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
accessoryView = chevron
separatorInset = UIEdgeInsetsZero
}
override func layoutSubviews() {
super.layoutSubviews()
// doing this here as TwoLineTableViewCell changes the imageView frame in it's layoutSubviews and we have to make sure it is right
if let imageSize = imageView?.image?.size {
imageView?.frame = CGRectMake(ImageMargin, (frame.height - imageSize.width) / 2, imageSize.width, imageSize.height)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class BookmarkFolderTableViewHeader : UITableViewHeaderFooterView {
var delegate: BookmarkFolderTableViewHeaderDelegate?
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = UIConstants.HighlightBlue
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .Left)
chevron.tintColor = UIConstants.HighlightBlue
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
return chevron
}()
lazy var topBorder: UIView = {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}()
lazy var bottomBorder: UIView = {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}()
override var textLabel: UILabel? {
return titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
userInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "viewWasTapped:")
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
addSubview(topBorder)
addSubview(bottomBorder)
contentView.addSubview(chevron)
contentView.addSubview(titleLabel)
chevron.snp_makeConstraints { make in
make.left.equalTo(contentView).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
make.size.equalTo(BookmarksPanelUX.BookmarkFolderChevronSize)
}
titleLabel.snp_makeConstraints { make in
make.left.equalTo(chevron.snp_right).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.right.greaterThanOrEqualTo(contentView).offset(-BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
}
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)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func viewWasTapped(gestureRecognizer: UITapGestureRecognizer) {
delegate?.didSelectHeader()
}
}
| mpl-2.0 | 67252312b93b599ac0c28dfa8ed11ac0 | 40.012407 | 278 | 0.661605 | 5.842347 | false | false | false | false |
robinckanatzar/mcw | my-core-wellness/my-core-wellness/OneVC.swift | 1 | 2488 | //
// OneVC.swift
// my-core-wellness
//
// Created by Robin Kanatzar on 2/22/17.
// Copyright © 2017 Robin Kanatzar. All rights reserved.
//
import Foundation
import UIKit
class OneVC : UIViewController {
@IBOutlet weak var buttonMenu: UIBarButtonItem!
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var meditationLabel: UILabel!
@IBOutlet weak var positiveThoughtsLabel: UILabel!
@IBOutlet weak var meditationBackground: UIView!
@IBOutlet weak var positiveThoughtsBackground: UIView!
override func viewDidLoad() {
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
//navigationController?.setNavigationBarHidden(true, animated: false)
setUpMenuButton()
setUpNavigationBar()
self.view.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0)
// stylize meditation card
meditationBackground.layer.masksToBounds = false
meditationBackground.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
meditationBackground.layer.shadowOffset = CGSize(width: 0, height: 0)
meditationBackground.layer.shadowOpacity = 0.8
meditationBackground.layer.cornerRadius = 3.0
// stylize positive thoughts card
positiveThoughtsBackground.layer.masksToBounds = false
positiveThoughtsBackground.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
positiveThoughtsBackground.layer.shadowOffset = CGSize(width: 0, height: 0)
positiveThoughtsBackground.layer.shadowOpacity = 0.8
positiveThoughtsBackground.layer.cornerRadius = 3.0
}
func setUpMenuButton() {
buttonMenu.target = self.revealViewController()
buttonMenu.action = #selector(SWRevealViewController.revealToggle(_:))
}
func setUpNavigationBar() {
// for navigation bar
navigationBar.topItem?.title = "Mental Wellness"
navigationItem.leftBarButtonItem = buttonMenu
self.navigationItem.title = "Mental Wellness"
}
@IBAction func tapMeditation(_ sender: AnyObject) {
// call segueMeditation
performSegue(withIdentifier: "segueMeditation", sender: nil)
}
@IBAction func tapPositiveThoughts(_ sender: AnyObject) {
performSegue(withIdentifier: "seguePositiveThoughts", sender: nil)
}
}
| apache-2.0 | 440bbac3b50f9b8e9677ec4e57a33e26 | 35.573529 | 106 | 0.693205 | 5.159751 | false | false | false | false |
JuliaNocera/learn | AppNativeCode/swift/playgroundsTreehouse/Conditionals.playground/Contents.swift | 1 | 3446 | //import UIKit
//
//let cards = 1...13
//
//////// IF ELSE IF ELSE \\\\\\
//for card in cards {
// if card == 11 {
// print("Jack")
// } else if card == 12 {
// print("Queen")
// } else if card == 13 {
// print("King")
// } else {
// print(card)
// }
//}
//
//////// SWITCH STATEMENT \\\\\\ ( lets you use ranges )
//for card in cards {
// switch card {
// case 1,2,3,5:
// print("Low Cards")
// case 11...13:
// print("Trump cards")
// default:
// print(card)
// }
//}
//
//var airportCodes = ["LGA", "LHR", "CDG", "SFO", "OAK", "LGW", "JFK", "ORY"]
//
//switch airport {
// case "LGA", "JFK": print("New York") // check for multiple cases
// case "LHR", "LGW": print("London")
// case "CDG", "ORY": print("Paris")
// case "SFO": print("San Fran")
// case "OAK": print("Oaklandish")
// default: print("I don't know which you are talking about")
//}
//
//import Foundation
//
//var randomTemp = Int(arc4random_uniform(UInt32(150)))
//
//switch randomTemp {
// case 0..<32: print("don't leave the house - too cold!") // vals below 32 degrees
// case 32...45: print("Its chilly - grab a jacket")
// case 42..<70: print("a bit chill - wear a light sweater")
// case 70...100: print("Its hot - grab nothing but a tshirt and shorts - head to water now")
// default: print("My face is melting")
//
//}
//
///*
//Operators:
// Comparison
// Logical
//*/
//// Comparison
//1 == 1
//2 != 1
//2 > 1
//1 > 2
//1 >= 1
//2 <= 1
//
//// Logical
//// && AND
//// || OR
//// ! NOT
//
//var distance = 121
//if distance < 5 {
// print("\(distance) miles is near")
//} else if distance >= 5 && distance <= 20 {
// print("\(distance) miles is close")
//} else {
// print("\(distance) miles is far")
//}
//
//var number = 121
//func fizzbuzz(num: Int) {
// if num % 3 == 0 {
// print("buzz")
// } else if num % 5 == 0 {
// print("Buzz")
// } else if num % 5 == 0 && num % 3 == 0 {
// print("FizzBuzz")
// } else {
// print("\(num) is not divisible by 3 or 5")
// }
//}
//
//fizzbuzz(number)
//
//for i in 1...20 {
// if i % 3 == 0 {
// print("Fizz")
// } else if i % 5 == 0 {
// print("Buzz")
// } else if i % 5 == 0 && i % 3 == 0 {
// print("FizzBuzz")
// } else {
// print("\(i) is not divisible by 3 or 5")
// }
//}
//var europeanCapitals: [String] = []
//var asianCapitals: [String] = []
//var otherCapitals: [String] = []
//
//let world = [
// "BEL": "Brussels",
// "LIE": "Vaduz",
// "BGR": "Sofia",
// "USA": "Washington D.C.",
// "MEX": "Mexico City",
// "BRA": "Brasilia",
// "IND": "New Delhi",
// "VNM": "Hanoi"]
//
//for (key, value) in world {
// // Enter your code below
// switch key {
// case "BEL", "LIE", "BGR": europeanCapitals.append(value)
// case "VNM", "IND": asianCapitals.append(value)
// default: otherCapitals.append(value)
// }
// // End code
//}
//print("\(europeanCapitals), \(asianCapitals), \(otherCapitals)")
// given rando num - if 3 : fizz, 5: buzz, 3 & 5 fizzbuzz
func fizzBuzz(n: Int) -> String {
// Enter your code between the two comment markers
if (n % 3 == 0) {
return "Fizz"
} else if (n % 5 == 0) {
return "Buzz"
} else if (n % 5 == 0 && n % 3 == 0) {
return "FizzBuzz"
}
// End code
return "\(n)"
}
fizzBuzz(3)
| mit | 388dc5c5ce08a79f8dc0a8e3fc709ddb | 22.127517 | 96 | 0.499129 | 2.922816 | false | false | false | false |
BrianCorbin/SwiftRangeSlider | Examples/SwiftRangeSliderExample/Pods/SwiftRangeSlider/SwiftRangeSlider/RangeSliderTrackLayer.swift | 1 | 1108 | //
// RangeSliderTrackLayer.swift
// SwiftRangeSlider
//
// Created by Brian Corbin on 5/22/16.
// Copyright © 2016 Caramel Apps. All rights reserved.
//
import UIKit
import QuartzCore
class RangeSliderTrackLayer: CALayer {
weak var rangeSlider: RangeSlider?
override func draw(in ctx: CGContext) {
if let slider = rangeSlider {
// Clip
let cornerRadius = bounds.height * slider.curvaceousness / 2.0
let path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
ctx.addPath(path.cgPath)
// Fill the track
ctx.setFillColor(slider.trackTintColor.cgColor)
ctx.addPath(path.cgPath)
ctx.fillPath()
// Fill the highlighted range
ctx.setFillColor(slider.trackHighlightTintColor.cgColor)
let lowerValuePosition = CGFloat(slider.positionForValue(slider.lowerValue))
let upperValuePosition = CGFloat(slider.positionForValue(slider.upperValue))
let rect = CGRect(x: lowerValuePosition, y: 0.0, width: upperValuePosition - lowerValuePosition, height: bounds.height)
ctx.fill(rect)
}
}
}
| mit | b3e58ccca5f24cf37252b5fbed905e3d | 30.628571 | 125 | 0.704607 | 4.358268 | false | false | false | false |
jasonhenderson/examples-ios | WebServices/Pods/Unbox/Sources/Dictionary+Unbox.swift | 6 | 2434 | /**
* Unbox
* Copyright (c) 2015-2017 John Sundell
* Licensed under the MIT license, see LICENSE file
*/
import Foundation
/// Extension making `Dictionary` an unboxable collection
extension Dictionary: UnboxableCollection {
public typealias UnboxValue = Value
public static func unbox<T: UnboxCollectionElementTransformer>(value: Any, allowInvalidElements: Bool, transformer: T) throws -> Dictionary? where T.UnboxedElement == UnboxValue {
guard let dictionary = value as? [String : T.UnboxRawElement] else {
return nil
}
let keyTransform = try self.makeKeyTransform()
return try dictionary.map(allowInvalidElements: allowInvalidElements) { key, value in
guard let unboxedKey = keyTransform(key) else {
throw UnboxPathError.invalidDictionaryKey(key)
}
guard let unboxedValue = try transformer.unbox(element: value, allowInvalidCollectionElements: allowInvalidElements) else {
throw UnboxPathError.invalidDictionaryValue(value, key)
}
return (unboxedKey, unboxedValue)
}
}
private static func makeKeyTransform() throws -> (String) -> Key? {
if Key.self is String.Type {
return { $0 as? Key }
}
if let keyType = Key.self as? UnboxableKey.Type {
return { keyType.transform(unboxedKey: $0) as? Key }
}
throw UnboxPathError.invalidDictionaryKeyType(Key.self)
}
}
/// Extension making `Dictionary` an unbox path node
extension Dictionary: UnboxPathNode {
func unboxPathValue(forKey key: String) -> Any? {
return self[key as! Key]
}
}
// MARK: - Utilities
private extension Dictionary {
func map<K, V>(allowInvalidElements: Bool, transform: (Key, Value) throws -> (K, V)?) throws -> [K : V]? {
var transformedDictionary = [K : V]()
for (key, value) in self {
do {
guard let transformed = try transform(key, value) else {
if allowInvalidElements {
continue
}
return nil
}
transformedDictionary[transformed.0] = transformed.1
} catch {
if !allowInvalidElements {
throw error
}
}
}
return transformedDictionary
}
}
| gpl-3.0 | 36301be4dea0b7065e543aa63deea97c | 29.810127 | 183 | 0.59696 | 5.00823 | false | false | false | false |
yoichitgy/swipe | core/SwipeTextArea.swift | 2 | 3328 | //
// SwipeTextArea.swift
//
// Created by Pete Stoppani on 6/7/16.
//
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
class SwipeTextArea: SwipeView, UITextViewDelegate {
private var screenDimension = CGSize(width: 0, height: 0)
private var textView: UITextView
init(parent: SwipeNode, info: [String:Any], frame: CGRect, screenDimension: CGSize) {
self.screenDimension = screenDimension
self.textView = UITextView(frame: frame)
super.init(parent: parent, info: info)
self.textView.delegate = self
self.textView.backgroundColor = UIColor.clear
//self.textView.becomeFirstResponder()
self.view = self.textView as UIView
}
override func setText(_ text:String, scale:CGSize, info:[String:Any], dimension:CGSize, layer:CALayer?) -> Bool {
self.textView.text = text
self.textView.textAlignment = NSTextAlignment.center
func processAlignment(_ alignment:String) {
switch(alignment) {
case "center":
self.textView.textAlignment = .center
case "left":
self.textView.textAlignment = .left
case "right":
self.textView.textAlignment = .right
case "justified":
self.textView.textAlignment = .justified
default:
break
}
}
if let alignment = info["textAlign"] as? String {
processAlignment(alignment)
} else if let alignments = info["textAlign"] as? [String] {
for alignment in alignments {
processAlignment(alignment)
}
}
let fontSize:CGFloat = {
var ret = 20.0 / 480.0 * dimension.height // default
if let fontSize = info["fontSize"] as? CGFloat {
ret = fontSize
} else if let fontSize = info["fontSize"] as? String {
ret = SwipeParser.parsePercent(fontSize, full: dimension.height, defaultValue: ret)
}
return round(ret * scale.height)
}()
self.textView.font = UIFont(name: "Helvetica", size: fontSize)
self.textView.textColor = UIColor(cgColor: SwipeParser.parseColor(info["textColor"], defaultColor: UIColor.black.cgColor))
parent!.execute(self, actions: parent!.eventHandler.actionsFor("textChanged"))
return true
}
override func getPropertyValue(_ originator: SwipeNode, property: String) -> Any? {
switch (property) {
case "text":
return self.textView.text
case "text.length":
return self.textView.text?.characters.count
default:
return super.getPropertyValue(originator, property: property)
}
}
override func isFirstResponder() -> Bool {
return view!.isFirstResponder
}
// UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
parent!.execute(self, actions: parent!.eventHandler.actionsFor("textChanged"))
}
func textViewDidBeginEditing(_ textView: UITextView) {
}
func textViewDidEndEditing(_ textView: UITextView) {
parent!.execute(self, actions: parent!.eventHandler.actionsFor("endEdit"))
}
}
| mit | 4e94e52d67ca110ff5590eaf5512e10a | 32.616162 | 130 | 0.605469 | 4.894118 | false | false | false | false |
andrebocchini/SwiftChatty | SwiftChatty/Requests/Threads/GetThreadPostIdsRequest.swift | 1 | 819 | //
// GetThreadPostIdsRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/17/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.//
/// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451666
public struct GetThreadPostIdsRequest: Request {
public let endpoint: ApiEndpoint = .GetThreadPostIds
public var customParameters: [String : Any] = [:]
public init(withThreadIds ids: [Int]) {
if ids.count > 0 {
var concatenatedIds: String = ""
for i in 0...(ids.count - 1) {
if i == 0 {
concatenatedIds += String(ids[i])
} else {
concatenatedIds += ("," + String(ids[i]))
}
}
self.customParameters["id"] = concatenatedIds
}
}
}
| mit | bd2df69a4883bf3a1a3a9bb746a44f13 | 28.214286 | 61 | 0.5489 | 4.131313 | false | false | false | false |
zon/that-bus | ios/That Bus/Unit.swift | 1 | 476 | import Foundation
import UIKit
class Unit {
static let screen = UIScreen.main.bounds
static let status = UIApplication.shared.statusBarFrame.height
static let header = CGFloat(44)
static let menu = CGFloat(60)
static let one = 1 / UIScreen.main.scale
static let m1 = CGFloat(32)
static let m2 = CGFloat(16)
static let m3 = CGFloat(8)
static let corner = CGFloat(2)
static let buttonHeight = CGFloat(48)
}
| gpl-3.0 | e62d3aba067f9e856da36666d5c891ed | 21.666667 | 66 | 0.653361 | 4.175439 | false | false | false | false |
EBGToo/SBVariables | Sources/Domain.swift | 1 | 4499 | //
// Domain.swift
// SBVariables
//
// Created by Ed Gamble on 10/22/15.
// Copyright © 2015 Edward B. Gamble Jr. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import SBBasics
///
public class Domain<Value> {
public func contains (_ value:Value) -> Bool {
return true
}
}
// MARK: Always Domain
///
/// An `AlwaysDomain` is a `Domain` that, ignoring object, is either always `true` or always `false`
///
public final class AlwaysDomain<Value> : Domain<Value> {
/// The fixed result of `contains()`
let result : Bool
/// Ignores value and returns `result`
public override func contains (_ value: Value) -> Bool {
return result
}
///
/// Initialize an instance
///
/// - parameter result: The fixed result to use
///
public init (result: Bool) {
self.result = result;
}
}
// MARK: Singleton Domain
///
/// A `SingletonDomain` is a Domain with a single value in the domain matched with a `test` function.
///
public final class SingletonDomain<Value> : Domain<Value> {
/// The single value
let value : Value
/// The comparison predicate
let test : (Value, Value) -> Bool
public override func contains (_ value: Value) -> Bool {
return test (value, self.value)
}
public init (value: Value, test: @escaping (Value, Value) -> Bool) {
self.value = value
self.test = test
}
}
extension SingletonDomain where Value:Equatable {
public convenience init (value: Value) {
self.init(value: value, test: ==)
}
}
// MARK: Enumerated Domain
///
/// An `EnumeratedDomain` is a `Domain` with an arbitrary number of values in the domain matched
/// with a `test` function. Worst case performance O(N) as the arbitrary values need to be tested
/// one-by-one.
///
public final class EnumeratedDomain<Value> : Domain<Value> {
/// The enumerated values
let values : [Value]
/// the comparison predicate
let test : (Value, Value) -> Bool
public override func contains(_ value: Value) -> Bool {
return values.contains { test(value, $0) }
}
public init (values: [Value], test: @escaping (Value, Value) -> Bool) {
self.values = values
self.test = test
}
}
extension EnumeratedDomain where Value:Equatable {
public convenience init (values: Value...) {
self.init(values: values, test: ==)
}
}
// MARK: Set Domain
///
///The `SetDomain` is a `Domain` with a set of values.
///
public final class SetDomain<Value:Hashable> : Domain<Value> {
/// The `Set` of values constituting the domain
let set : Set<Value>
///
public override func contains(_ value: Value) -> Bool {
return set.contains(value);
}
public init (set: Set<Value>) {
self.set = set
}
public convenience init (values: Value...) {
self.init (set: Set<Value>(values))
}
}
// MARK: Range Domain
///
/// A `RangeDomain` is a `Domain` with values determined by a `Range`
///
public final class RangeDomain<Value:Comparable> : Domain<Value> {
/// The `Range` of the domain
let range : Range<Value>
public override func contains(_ value: Value) -> Bool {
return range.contains (value)
}
public init (range: Range<Value>) {
self.range = range
}
}
// MARK: Complement Domain
///
/// A ComplementDomain is a Domain that complement another domain
///
public final class ComplementDomain<Value> : Domain<Value> {
let domain : Domain<Value>
public override func contains(_ value: Value) -> Bool {
return !domain.contains(value)
}
public init (domain: Domain<Value>) {
self.domain = domain
}
}
// MARK: Compound Domain
///
/// DomainLogic is an Enumeration with .And and .Or and is used with a Compound Domain
///
public enum DomainLogic {
case and
case or
}
///
/// A `CompoundDomain` is a Domain comprised of a arbitary number of (sub)domains combined with
/// the provided DomainLogic
///
public final class CompoundDomain<Value> : Domain<Value> {
/// The domains
let domains : [Domain<Value>]
/// The logic
let logic : DomainLogic
public init (logic: DomainLogic, domains: Domain<Value>...) {
self.logic = logic
self.domains = domains
}
public override func contains(_ value: Value) -> Bool {
switch logic {
case .and: return domains.all { $0.contains (value) }
case .or : return domains.any { $0.contains (value) }
}
}
}
| mit | d195e608bbedb4604d08692773c25d2c | 21.49 | 101 | 0.652068 | 3.754591 | false | true | false | false |
hrscy/TodayNews | News/News/Classes/Mine/View/UserDetailDongTaiCell.swift | 1 | 6695 | //
// UserDetailDongTaiCell.swift
// News
//
// Created by 杨蒙 on 2017/12/7.
// Copyright © 2017年 hrscy. All rights reserved.
//
// 用户动态 cell
//
import UIKit
import IBAnimatable
import Kingfisher
class UserDetailDongTaiCell: UITableViewCell, RegisterCellFromNib {
/// 点击了 用户名
var didSelectDongtaiUserName: ((_ uid: Int)->())?
/// 点击了 话题
var didSelectDongtaiTopic: ((_ cid: Int)->())?
var dongtai = UserDetailDongtai() {
didSet {
avatarImageView.kf.setImage(with: URL(string: dongtai.user.avatar_url))
nameLabel.text = dongtai.user.screen_name
modifyTimeLabel.text = "· " + dongtai.createTime
likeButton.setTitle(dongtai.diggCount, for: .normal)
commentButton.setTitle(dongtai.commentCount, for: .normal)
forwardButton.setTitle(dongtai.forwardCount, for: .normal)
areaLabel.text = dongtai.brand_info + " " + dongtai.position.position
readCountLabel.text = dongtai.readCount + "阅读"
// 点击了用户
contentLabel.userTapped = { [weak self] (userName, range) in
for userContent in self!.dongtai.userContents! {
if userName.contains(userContent.name) {
self!.didSelectDongtaiUserName?(Int(userContent.uid)!)
}
}
}
// 点击了话题
contentLabel.topicTapped = {[weak self] (topic, range) in
for topicContent in self!.dongtai.topicContents! {
if topic.contains(topicContent.name) {
self!.didSelectDongtaiTopic?(Int(topicContent.uid)!)
}
}
}
// 显示 emoji
contentLabel.attributedText = dongtai.attributedContent
contentLabelHeight.constant = dongtai.contentH
allContentLabel.isHidden = dongtai.attributedCntentHeight == 110 ? false : true
/// 防止因为 cell 重用机制,导致数据错乱现象出现
if middleView.contains(postVideoOrArticleView) { postVideoOrArticleView.removeFromSuperview() }
if middleView.contains(collectionView) { collectionView.removeFromSuperview() }
if middleView.contains(originThreadView) { originThreadView.removeFromSuperview() }
switch dongtai.item_type {
case .postVideoOrArticle, .postVideo, .answerQuestion, .proposeQuestion, .forwardArticle, .postContentAndVideo: // 发布了文章或者视频
middleView.addSubview(postVideoOrArticleView)
postVideoOrArticleView.frame = CGRect(x: 15, y: 0, width: screenWidth - 30, height: middleView.height)
if dongtai.group.group_id != 0 { postVideoOrArticleView.group = dongtai.group }
else if dongtai.origin_group.group_id != 0 { postVideoOrArticleView.group = dongtai.origin_group }
case .postContent, .postSmallVideo: // 发布了文字内容
middleView.addSubview(collectionView)
collectionView.frame = CGRect(x: 15, y: 0, width: dongtai.collectionViewW, height: dongtai.collectionViewH)
collectionView.isPostSmallVideo = (dongtai.item_type == .postSmallVideo)
collectionView.thumbImages = dongtai.thumb_image_list
collectionView.largeImages = dongtai.large_image_list
case .commentOrQuoteContent, .commentOrQuoteOthers: // 引用或评论
middleView.addSubview(originThreadView)
originThreadView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: dongtai.origin_thread.height)
originThreadView.originthread = dongtai.origin_thread
}
layoutIfNeeded()
}
}
/// 懒加载 评论或引用
private lazy var originThreadView = DongtaiOriginThreadView.loadViewFromNib()
/// 懒加载 发布视频或者文章
private lazy var postVideoOrArticleView = PostVideoOrArticleView.loadViewFromNib()
/// 懒加载 collectionView
private lazy var collectionView = DongtaiCollectionView.loadViewFromNib()
@IBOutlet weak var separatorView: UIView!
/// 头像
@IBOutlet weak var avatarImageView: AnimatableImageView!
/// 用户名
@IBOutlet weak var nameLabel: UILabel!
/// 修改时间
@IBOutlet weak var modifyTimeLabel: UILabel!
/// 更多按钮
@IBOutlet weak var moreButton: UIButton!
/// 喜欢按钮
@IBOutlet weak var likeButton: UIButton!
/// 评论按钮
@IBOutlet weak var commentButton: UIButton!
/// 转发按钮
@IBOutlet weak var forwardButton: UIButton!
/// 位置,阅读数量
@IBOutlet weak var areaLabel: UILabel!
@IBOutlet weak var readCountLabel: UILabel!
@IBOutlet weak var separatorView2: UIView!
/// 内容
@IBOutlet weak var contentLabel: RichLabel!
@IBOutlet weak var contentLabelHeight: NSLayoutConstraint!
/// 全文
@IBOutlet weak var allContentLabel: UILabel!
/// 中间的 view
@IBOutlet weak var middleView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
separatorView.theme_backgroundColor = "colors.separatorViewColor"
separatorView2.theme_backgroundColor = "colors.separatorViewColor"
theme_backgroundColor = "colors.cellBackgroundColor"
nameLabel.theme_textColor = "colors.grayColor150"
modifyTimeLabel.theme_textColor = "colors.grayColor150"
likeButton.theme_setTitleColor("colors.black", forState: .normal)
commentButton.theme_setTitleColor("colors.black", forState: .normal)
forwardButton.theme_setTitleColor("colors.black", forState: .normal)
likeButton.theme_setImage("images.feed_like_24x24_", forState: .normal)
likeButton.theme_setImage("images.feed_like_press_24x24_", forState: .selected)
commentButton.theme_setImage("images.comment_feed_24x24_", forState: .normal)
moreButton.theme_setImage("images.morebutton_dynamic_14x8_", forState: .normal)
moreButton.theme_setImage("images.morebutton_dynamic_press_14x8_", forState: .highlighted)
forwardButton.theme_setImage("images.feed_share_24x24_", forState: .normal)
contentLabel.theme_textColor = "colors.black"
allContentLabel.theme_backgroundColor = "colors.cellBackgroundColor"
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | e53dc670fb42c2b4729c48f1c61f2bc7 | 44.260563 | 136 | 0.652093 | 4.771344 | false | false | false | false |
GirAppe/Blackhole | Example/Tests/ReceivingPromisesTestCase.swift | 1 | 3390 | import UIKit
import XCTest
import Blackhole
import BrightFutures
class ReceivingPromisesTestCase: BlackholeTestCase {
// MARK: - Basic Tests
func testSimpleSendingReceiveSuccess() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let sendExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
let receiveExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
self.session.emit(TestSession.EmitResult(success: true))
let messegeListener = MessageListener { message -> BlackholeMessage? in
guard let value = message["someKey"], value is String, value as! String == "stringValue" else {
XCTAssert(false)
return nil
}
receiveExpectation.fulfill()
return nil
}
receiver.addListener(messegeListener, forIdentifier: identifier)
emitter.promiseSendMessage(message, withIdentifier: identifier)
.onFailure { error in
XCTAssert(false, "Error sending: \(error)")
}
.onSuccess {
sendExpectation.fulfill()
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
func testTripleSendingReceivedSuccess() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let sendExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
let receiveExpectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
self.session.emit(TestSession.EmitResult(success: true))
self.session.emit(TestSession.EmitResult(success: true))
self.session.emit(TestSession.EmitResult(success: true))
var counter = 3
let messegeListener = MessageListener { message -> BlackholeMessage? in
guard let value = message["someKey"], value is String, value as! String == "stringValue" else {
XCTAssert(false)
return nil
}
counter -= 1
if counter == 0 {
receiveExpectation.fulfill()
}
return nil
}
receiver.addListener(messegeListener, forIdentifier: identifier)
let _ = emitter.promiseSendMessage(message, withIdentifier: identifier)
.flatMap { _ -> Future<Void,BlackholeError> in
return self.emitter.promiseSendMessage(message, withIdentifier: identifier)
}
.flatMap { _ -> Future<Void,BlackholeError> in
return self.emitter.promiseSendMessage(message, withIdentifier: identifier)
}
.onSuccess {
sendExpectation.fulfill()
}
.onFailure { error in
XCTAssert(false, "Error sending: \(error)")
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
}
| mit | 84001e6bb1a7bf73d3ffc895819e1ab4 | 35.847826 | 115 | 0.595575 | 5.441413 | false | true | false | false |
adamnemecek/AudioKit | Tests/AudioKitTests/Node Tests/Player Tests/AudioPlayerTests.swift | 1 | 8355 | import AudioKit
import AVFoundation
import XCTest
class AudioPlayerTests: XCTestCase {
func testBasic() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav"),
let file = try? AVAudioFile(forReading: url) else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
let audio = engine.startTest(totalDuration: 5.0)
player.file = file
player.play()
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testLoop() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav"),
let buffer = try? AVAudioPCMBuffer(url: url) else {
XCTFail("Couldn't create buffer")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
player.isLooping = true
player.buffer = buffer
let audio = engine.startTest(totalDuration: 10.0)
player.play()
audio.append(engine.render(duration: 10.0))
testMD5(audio)
}
func testPlayAfterPause() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav"),
let file = try? AVAudioFile(forReading: url) else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
let audio = engine.startTest(totalDuration: 5.0)
player.file = file
player.play()
audio.append(engine.render(duration: 2.0))
player.pause()
audio.append(engine.render(duration: 1.0))
player.play()
audio.append(engine.render(duration: 2.0))
testMD5(audio)
}
func testEngineRestart() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav"),
let file = try? AVAudioFile(forReading: url) else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
let audio = engine.startTest(totalDuration: 5.0)
player.file = file
player.play()
audio.append(engine.render(duration: 2.0))
player.stop()
engine.stop()
_ = engine.startTest(totalDuration: 2.0)
audio.append(engine.render(duration: 1.0))
player.play()
audio.append(engine.render(duration: 2.0))
testMD5(audio)
}
func testScheduleFile() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav") else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
player.volume = 0.1
engine.output = player
player.isLooping = true
let audio = engine.startTest(totalDuration: 5.0)
do {
try player.load(url: url, buffered: true)
} catch let error as NSError {
Log(error, type: .error)
XCTFail(error.description)
}
player.play()
audio.append(engine.render(duration: 5.0))
engine.stop()
testMD5(audio)
}
func testVolume() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav"),
let file = try? AVAudioFile(forReading: url) else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
player.volume = 0.1
engine.output = player
player.file = file
let audio = engine.startTest(totalDuration: 5.0)
player.play()
audio.append(engine.render(duration: 5.0))
testMD5(audio)
}
func testSeek() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav") else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
player.isLooping = true
let audio = engine.startTest(totalDuration: 4.0)
do {
try player.load(url: url, buffered: true)
} catch let error as NSError {
Log(error, type: .error)
XCTFail(error.description)
}
player.seek(time: 1.0)
player.play()
audio.append(engine.render(duration: 4.0))
testMD5(audio)
}
func testGetCurrentTime() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav") else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
player.isLooping = true
let audio = engine.startTest(totalDuration: 2.0)
do {
try player.load(url: url, buffered: true)
} catch let error as NSError {
Log(error, type: .error)
XCTFail(error.description)
}
player.seek(time: 0.5)
player.play()
audio.append(engine.render(duration: 2.0))
let currentTime = player.getCurrentTime()
XCTAssertEqual(currentTime, 2.5)
testMD5(audio)
}
func testToggleEditTime() {
guard let url = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav") else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
player.isLooping = true
let audio = engine.startTest(totalDuration: 1.0)
do {
try player.load(url: url, buffered: true)
} catch let error as NSError {
Log(error, type: .error)
XCTFail(error.description)
}
player.editStartTime = 0.5
player.editEndTime = 0.6
player.play()
let onStartTime = player.editStartTime
let onEndTime = player.editEndTime
XCTAssertEqual(onStartTime, 0.5)
XCTAssertEqual(onEndTime, 0.6)
player.isEditTimeEnabled = false
let offStartTime = player.editStartTime
let offEndTime = player.editEndTime
XCTAssertEqual(offStartTime, 0)
XCTAssertEqual(offEndTime, player.file?.duration)
player.isEditTimeEnabled = true
let nextOnStartTime = player.editStartTime
let nextOnEndTime = player.editEndTime
XCTAssertEqual(nextOnStartTime, 0.5)
XCTAssertEqual(nextOnEndTime, 0.6)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testSwitchFilesDuringPlayback() {
guard let url1 = Bundle.module.url(forResource: "TestResources/12345", withExtension: "wav") else {
XCTFail("Didn't get test file")
return
}
guard let url2 = Bundle.module.url(forResource: "TestResources/chromaticScale-1", withExtension: "aiff") else {
XCTFail("Didn't get test file")
return
}
let engine = AudioEngine()
let player = AudioPlayer()
engine.output = player
player.isLooping = true
let audio = engine.startTest(totalDuration: 3.0)
do {
try player.load(url: url1)
} catch let error as NSError {
Log(error, type: .error)
XCTFail(error.description)
}
player.play()
do {
try player.load(url: url2)
} catch let error as NSError {
Log(error, type: .error)
XCTFail(error.description)
}
audio.append(engine.render(duration: 3.0))
testMD5(audio)
}
}
| mit | 81aaa10a725919dfd25be3bf412be97d | 29.053957 | 119 | 0.55775 | 4.639089 | false | true | false | false |
johndpope/tensorflow | tensorflow/swift/Sources/GoScope.swift | 1 | 5189 | /*
Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/op/scope.go
*/
import Foundation
/*
*/
// Scope encapsulates common operation properties when building a Graph.
//
// A Scope object (and its derivates, e.g., obtained from Scope.SubScope)
// act as a builder for graphs. They allow common properties (such as
// a name prefix) to be specified for multiple operations being added
// to the graph.
//
// A Scope object and all its derivates (e.g., obtained from Scope.SubScope)
// are not safe for concurrent use by multiple goroutines.
struct Scope {
var graph:Graph
var namemap:Dictionary<String,Int>
var namespace:String = ""
var error:scopeError
}
// scopeErr is used to share errors between all derivatives of a root scope.
struct scopeError {
var error:NSError?
}
// NewScope creates a Scope initialized with an empty Graph.
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/op/scope.go#L47
func NewScope()->Scope {
return Scope(graph: newGraph(), namemap: [String: Int]() , namespace: "", error: scopeError())
}
// NewScopeWithGraph creates a Scope initialized with the Graph thats passed in
func NewScopeWithGraph(g:Graph)-> Scope {
return Scope(graph: g, namemap: [String: Int]() , namespace: "", error: scopeError())
}
// Finalize returns the Graph on which this scope operates on and renders s
// unusable. If there was an error during graph construction, that error is
// returned instead.
extension Scope{
func Finalize()-> (Graph?, NSError?) {
if let error = self.error.error {
return (nil, error)
}
print("Scope has been finalized and is no longer usable")
return (self.graph, nil)
}
}
// AddOperation adds the operation to the Graph managed by s.
//
// If there is a name prefix associated with s (such as if s was created
// by a call to SubScope), then this prefix will be applied to the name
// of the operation being added. See also Graph.AddOperation.
extension Scope{
func AddOperation(_ args:OpSpec) -> GoOperation? {
var args = args
if self.error.error != nil {
return nil
}
if (args.Name == "") {
args.Name = args.OpType
}
if (self.namespace != "") {
args.Name = self.namespace + "/" + args.Name
}
let op:GoOperation?
let error:NSError?
(op, error) = self.graph.AddOperation(args:args)
if let error = error {
self.UpdateError(op: args.OpType, error: error)
}
return op
}
}
// SubScope returns a new Scope which will cause all operations added to the
// graph to be namespaced with 'namespace'. If namespace collides with an
// existing namespace within the scope, then a suffix will be added.
extension Scope{
func SubScope(namespace:String)->Scope {
var namespace = self.uniqueName(namespace)
if self.namespace != "" {
namespace = self.namespace + "/" + namespace
}
// TODO -> make(map[string]int) -> Dictionary<String,Int>? or Dictionary<[String],Int>
return Scope( graph: self.graph, namemap: Dictionary<String,Int>(),namespace: namespace, error:self.error)
}
}
// Err returns the error, if any, encountered during the construction
// of the Graph managed by s.
//
// Once Err returns a non-nil error, all future calls will do the same,
// indicating that the scope should be discarded as the graph could not
// be constructed.
extension Scope{
func Error() -> NSError? {
return self.error.error
}
}
// UpdateErr is used to notify Scope of any graph construction errors
// while creating the operation op.
extension Scope{
func UpdateError(op:String, error: NSError) {
if self.error.error == nil {
let msg = "failed to add operation \(op.description): \(error) (Stacktrace: ))" //\(debug.Stack()
print(msg)
// self.error.error = NSError.newIoError(msg, code: 111)
}
}
}
//https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/op/scope.go#L124
extension Scope{
func uniqueName(_ name:String)-> String {
if let count = self.namemap[name], count > 0{
return"\(name)_\(count)"
}
return name
}
func opName(type:String) -> String {
if self.namespace == "" {
return type
}
return self.namespace + "/" + type
}
}
| apache-2.0 | 1ff8f2a41e47d41bb5f928a844b4069c | 30.259036 | 116 | 0.650414 | 4.124801 | false | false | false | false |
coach-plus/ios | CoachPlus/CoachPlus.swift | 1 | 584 | //
// CoachPlus.swift
// CoachPlus
//
// Created by Breit, Maurice on 23.03.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import Foundation
class CoachPlus {
public static let appUrl = "\(Environment.backendURL)app/"
public static let registerUrl = CoachPlus.appUrl + "register"
public static let forgotUrl = CoachPlus.appUrl + "forgot"
public static let aboutUrl = CoachPlus.appUrl + "about"
public static let termsUrl = CoachPlus.appUrl + "terms"
public static let dataPrivacyUrl = CoachPlus.appUrl + "dataprivacy"
}
| mit | 0fe7ecf1d4b566d367bca20148fde53b | 25.5 | 71 | 0.694683 | 4.076923 | false | false | false | false |
maxim-pervushin/TimeLogger | HyperTimeLogger/Common/Src/Collection View Layouts/HTLGridLayout.swift | 2 | 6207 | //
// Created by Maxim Pervushin on 16/11/15.
// Copyright (c) 2015 Maxim Pervushin. All rights reserved.
//
import UIKit
class HTLGridLayout: ZLBalancedFlowLayout {
private let _columnsCount = CGFloat(2)
private let _rowHeight = CGFloat(50)
override var itemSize: CGSize {
set {
}
get {
if let collectionView = collectionView {
return CGSizeMake(collectionView.bounds.size.width / _columnsCount, _rowHeight)
}
return CGSizeZero
}
}
override var rowHeight: CGFloat {
set {
}
get {
return _rowHeight
}
}
override var enforcesRowHeight: Bool {
set {
}
get {
return true
}
}
override var minimumLineSpacing: CGFloat {
set {
}
get {
return 0
}
}
override var minimumInteritemSpacing: CGFloat {
set {
}
get {
return 0
}
}
}
class HTLTableLayout: UICollectionViewLayout {
private var _maxNumberOfColumns: Int = 2
private var _rowHeight = CGFloat(50)
var maxNumberOfColumns: Int {
set {
_maxNumberOfColumns = newValue < 2 ? 2 : newValue
invalidateLayout()
}
get {
return _maxNumberOfColumns
}
}
var rowHeight: CGFloat {
set {
_rowHeight = newValue
invalidateLayout()
}
get {
return _rowHeight
}
}
private var numberOfSections: Int {
get {
guard let result = collectionView?.dataSource?.numberOfSectionsInCollectionView?(collectionView!) else {
// TODO: Make default number of sections const
return 1
}
return result
}
}
private func numberOfItemsInSection(section: Int) -> Int {
guard let result = collectionView?.dataSource?.collectionView(collectionView!, numberOfItemsInSection: section) else {
return 0
}
return result
}
private func numberOfRowsInSection(section: Int) -> Int {
let numberOfItems = numberOfItemsInSection(section)
return (numberOfItems / _maxNumberOfColumns) + (CGFloat(numberOfItems % _maxNumberOfColumns) > 0 ? 1 : 0)
}
private func sizeForSection(section: Int) -> CGSize {
guard let collectionView = collectionView else {
return CGSizeZero
}
return CGSizeMake(collectionView.frame.size.width, CGFloat(numberOfRowsInSection(section)) * _rowHeight)
}
private func frameForSection(section: Int) -> CGRect {
var horizontalOffset: CGFloat = 0;
var verticalOffset: CGFloat = 0;
for var previousSection = 0; previousSection < section; previousSection++ {
let previousSectionSize = sizeForSection(previousSection)
verticalOffset += previousSectionSize.height
}
let size = sizeForSection(section)
return CGRectMake(horizontalOffset, verticalOffset, size.width, size.height)
}
private func columnForIndexPath(indexPath: NSIndexPath) -> Int {
return indexPath.row % _maxNumberOfColumns
}
private func lineForIndexPath(indexPath: NSIndexPath) -> Int {
return (indexPath.row - columnForIndexPath(indexPath)) / _maxNumberOfColumns
}
private func horizontalOffsetForItemAtIndexPath(indexPath: NSIndexPath) -> CGFloat {
guard let collectionView = collectionView else {
return 0
}
return CGFloat(columnForIndexPath(indexPath)) * collectionView.bounds.size.width / CGFloat(_maxNumberOfColumns)
}
private func verticalOffsetForItemAtIndexPath(indexPath: NSIndexPath) -> CGFloat {
var verticalSectionOffset: CGFloat = 0;
for var section = 0; section < indexPath.section; section++ {
verticalSectionOffset += sizeForSection(section).height
}
verticalSectionOffset += CGFloat(lineForIndexPath(indexPath)) * _rowHeight
return verticalSectionOffset
}
private func frameForItemAtIndexPath(itemIndexPath: NSIndexPath) -> CGRect {
guard let collectionView = collectionView else {
return CGRectZero
}
return CGRectMake(horizontalOffsetForItemAtIndexPath(itemIndexPath), verticalOffsetForItemAtIndexPath(itemIndexPath), collectionView.bounds.size.width / CGFloat(_maxNumberOfColumns), _rowHeight)
}
override func collectionViewContentSize() -> CGSize {
let lastSectionFrame = frameForSection(numberOfSections - 1)
return CGSizeMake(lastSectionFrame.origin.x + lastSectionFrame.size.width, lastSectionFrame.origin.y + lastSectionFrame.size.height)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributesArray = Array<UICollectionViewLayoutAttributes>()
for var section = 0; section < numberOfSections; section++ {
if !CGRectIntersectsRect(frameForSection(section), rect) {
continue
}
for var item = 0; item < numberOfItemsInSection(section); item++ {
let indexPath = NSIndexPath(forItem: item, inSection: section)
let frame = frameForItemAtIndexPath(indexPath)
if !CGRectIntersectsRect(frame, rect) {
continue
}
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = frame
attributesArray.append(attributes)
}
}
return attributesArray
}
override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: itemIndexPath)
attributes.frame = frameForItemAtIndexPath(itemIndexPath)
return attributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
| mit | 51f9e9b299c64b85f861b3acc60cb3fb | 30.190955 | 202 | 0.634284 | 5.833647 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | iOS/Venue/Controllers/ControlPanelViewController.swift | 1 | 4406 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
class ControlPanelViewController: UIViewController {
@IBOutlet weak var offerButton: UIButton!
@IBOutlet weak var weatherButton: UIButton!
@IBOutlet weak var waitTimeButton: UIButton!
@IBOutlet weak var inviteButton: UIButton!
@IBOutlet weak var reminderButton: UIButton!
@IBOutlet weak var badgeButton: UIButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var contentViewWidth: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didPressTutorialButton(sender: AnyObject) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let tutorialViewController = mainStoryboard.instantiateViewControllerWithIdentifier("onboardingViewController")
presentViewController(tutorialViewController, animated: true, completion: {})
}
@IBAction func didPressButton(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension ControlPanelViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("controlCell") as? ControlTableViewCell {
switch indexPath.row {
case 0:
if let image = UIImage(named: "button_offers") {
cell.controlImage.image = image
cell.controlLabel.text = "Context-Driven Offer"
}
break
case 1:
if let image = UIImage(named: "button_weather") {
cell.controlImage.image = image
cell.controlLabel.text = "Inclement Weather Alert"
}
break
case 2:
if let image = UIImage(named: "button_waittime") {
cell.controlImage.image = image
cell.controlLabel.text = "Queue Wait-Time Alert"
}
break
case 3:
if let image = UIImage(named: "button_reminder") {
cell.controlImage.image = image
cell.controlLabel.text = "Planned Event Reminder"
}
break
case 4:
if let image = UIImage(named: "button_badges") {
cell.controlImage.image = image
cell.controlLabel.text = "Gamification Badge Earned"
}
break
case 5:
if let image = UIImage(named: "button_invitation") {
cell.controlImage.image = image
cell.controlLabel.text = "Receive an Invitation"
}
break
default:
break
}
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.view.frame.height/9
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
case 0:
DemoManager.sendOffer()
break
case 1:
DemoManager.weatherAlert()
break
case 2:
DemoManager.waitTimeAlert()
break
case 3:
DemoManager.sendReminder()
break
case 4:
DemoManager.unlockBadge()
break
case 5:
DemoManager.sendInvite()
break
default:
break
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| epl-1.0 | c11813d20975b37e180fe1f7f30cdef6 | 30.464286 | 119 | 0.564132 | 5.928668 | false | false | false | false |
xiaomudegithub/viossvc | viossvc/AppDelegate.swift | 1 | 5310 | //
// AppDelegate.swift
// viossvc
//
// Created by yaowang on 2016/10/29.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
import XCGLogger
import SVProgressHUD
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,GeTuiSdkDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.with([Crashlytics.self])
appearance()
pushMessageRegister()
umapp()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func pushMessageRegister() {
//注册消息推送
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () in
#if true
GeTuiSdk.startSdkWithAppId("d2YVUlrbRU6yF0PFQJfPkA", appKey: "yEIPB4YFxw64Ag9yJpaXT9", appSecret: "TMQWRB2KrG7QAipcBKGEyA", delegate: self)
#endif
let notifySettings = UIUserNotificationSettings.init(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notifySettings)
UIApplication.sharedApplication().registerForRemoteNotifications()
})
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var token = deviceToken.description
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")
token = token.stringByReplacingOccurrencesOfString("<", withString: "")
token = token.stringByReplacingOccurrencesOfString(">", withString: "")
XCGLogger.debug("\(token)")
#if true
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () in
GeTuiSdk.registerDeviceToken(token)
})
#endif
CurrentUserHelper.shared.deviceToken = token
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
}
private func appearance() {
let navigationBar:UINavigationBar = UINavigationBar.appearance() as UINavigationBar;
navigationBar.setBackgroundImage(UIImage(named: "head_bg"), forBarMetrics: .Default)
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()];
navigationBar.translucent = false;
navigationBar.tintColor = UIColor.whiteColor();
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics:.Default);
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent;
UITableView.appearance().backgroundColor = AppConst.Color.C6;
SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.Dark)
// SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Gradient)
SVProgressHUD.setMinimumDismissTimeInterval(2)
}
private func umapp(){
UMAnalyticsConfig.sharedInstance().appKey = AppConst.UMAppkey
UMAnalyticsConfig.sharedInstance().channelId = ""
MobClick.startWithConfigure(UMAnalyticsConfig.sharedInstance())
//version标识
let version: String? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as? String
MobClick.setAppVersion(version)
//日志加密设置
MobClick.setEncryptEnabled(true)
//使用集成测试服务
MobClick.setLogEnabled(true)
//Crash
MobClick.setCrashReportEnabled(false)
}
}
| apache-2.0 | c17a6770e1e4e5ab5856763f390a0d45 | 43.601695 | 285 | 0.719362 | 5.551688 | false | false | false | false |
MartinOSix/DemoKit | dSwift/2048swift/2048swift/GameModel.swift | 1 | 2866 | //
// GameModel.swift
// 2048swift
//
// Created by runo on 17/3/10.
// Copyright © 2017年 com.runo. All rights reserved.
//
import Foundation
protocol GameModelProtocol : class {
func scoreChanged(to score: Int);
func moveOneTitle(form:(Int,Int),to:(Int,Int),value:Int);
func moveTwoTitles(form: ((Int, Int), (Int, Int)), to: (Int, Int), value: Int);
func insertTitle(at location: (Int,Int), withValue value: Int);
}
class GameModel : NSObject {
let dimension : Int
let threshold : Int
unowned let delegate : GameModelProtocol
//存放数字块状态信息
var gameboard: SquareGameboard<TileObject>
var queue: [MoveCommand]
var timer: Timer
let maxCommands = 100
let queueDelay = 0.3
//当前分数
var score : Int = 0 {
didSet {
delegate.scoreChanged(to: score)
}
}
//初始化一个都存empty的squenceGambord
init(dimension d: Int, threshold t: Int, delegate: GameModelProtocol) {
dimension = d;
threshold = t;
self.delegate = delegate
queue = [MoveCommand]()
timer = Timer()
gameboard = SquareGameboard(dimension: d, initialValue: .empty)
super.init()
}
//获取空的区块位置
func getEmptyPosition() -> [(Int, Int)] {
var emptyArrys : [(Int, Int)] = []
for i in 0..<dimension{
for j in 0..<dimension {
if case .empty = gameboard[i,j] {
emptyArrys.append((i, j))
}
}
}
return emptyArrys
}
//随机在空位置上插入
func insertRandomPositionTile(value : Int) {
let emptyArrays = getEmptyPosition()
if emptyArrays.isEmpty {
return
}
let randompos = Int(arc4random_uniform(UInt32(emptyArrays.count-1)))
let (x, y) = emptyArrays[randompos]
gameboard[(x, y)] = .tile(value)
delegate.insertTitle(at: (x, y), withValue: value)
}
class func quiescentTileStillQuiescent(inputPosition: Int, outputLength: Int, originalPosition: Int)-> Bool {
return (inputPosition == outputLength) && (originalPosition == inputPosition)
}
func queueMove(direction: MoveDirection, onCompletion: @escaping (Bool)->()) {
guard queue.count <= maxCommands else {
return
}
queue.append(MoveCommand(direction: direction,completion:onCompletion))
if !timer.isValid {
timerFired(timer)
}
}
func timerFired(_:Timer) {
if queue.count == 0 {
return
}
var changed = false
while queue.count > 0 {
let command = queue[0]
queue.remove(at: 0)
}
}
}
| apache-2.0 | 7466ca2278c2e3c30d2ed62df1b347e7 | 21.844262 | 113 | 0.559742 | 4.190977 | false | false | false | false |
stripe/stripe-ios | StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/Inputs/Card/STPPostalCodeInputTextFieldValidator.swift | 1 | 2395 | //
// STPPostalCodeInputTextFieldValidator.swift
// StripePaymentsUI
//
// Created by Cameron Sabol on 10/30/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
import UIKit
class STPPostalCodeInputTextFieldValidator: STPInputTextFieldValidator {
override var defaultErrorMessage: String? {
if countryCode?.uppercased() == "US" {
return STPLocalizedString(
"Your ZIP is invalid.",
"Error message for when postal code in form is invalid (US only)"
)
} else {
return STPLocalizedString(
"Your postal code is invalid.",
"Error message for when postal code in form is invalid"
)
}
}
override public var inputValue: String? {
didSet {
updateValidationState()
}
}
var countryCode: String? = Locale.autoupdatingCurrent.regionCode {
didSet {
updateValidationState()
}
}
let postalCodeRequirement: STPPostalCodeRequirement
required init(
postalCodeRequirement: STPPostalCodeRequirement
) {
self.postalCodeRequirement = postalCodeRequirement
super.init()
}
private func updateValidationState() {
switch STPPostalCodeValidator.validationState(
forPostalCode: inputValue,
countryCode: countryCode,
with: postalCodeRequirement
)
{
case .valid:
validationState = .valid(message: nil)
case .invalid:
// Note: these don't actually happen (since we don't do offline validation, defaultErrorMessage is
// primarily a backup for missing api error strings)
validationState = .invalid(errorMessage: defaultErrorMessage)
case .incomplete:
var incompleteDescription: String? = nil
if let inputValue = inputValue, !inputValue.isEmpty {
if countryCode?.uppercased() == "US" {
incompleteDescription = String.Localized.your_zip_is_incomplete
} else {
incompleteDescription = String.Localized.your_postal_code_is_incomplete
}
}
validationState = .incomplete(description: incompleteDescription)
}
}
}
| mit | 3cba5c56f80b8525da7db7b954f8adfc | 30.5 | 110 | 0.608187 | 5.541667 | false | false | false | false |
jaderfeijo/SwiftRandom | Tests/SwiftRandomTests/SwiftRandomTests.swift | 1 | 4336 | //
// SwiftRandomTests.swift
// SwiftRandomTests
//
// Created by Jader Feijo on 17/8/17.
//
//
import XCTest
@testable import SwiftRandom
/// Tests above `SwiftRandom` module.
class SwiftRandomTests: XCTestCase {
/// Tests if all static methods are working.
func testStaticMethods() {
XCTAssertNotNil(Randoms.randomInt(10, 20))
XCTAssertNotNil(Randoms.randomPercentageisOver(70))
XCTAssertNotNil(Randoms.randomBool())
XCTAssertNotNil(Randoms.randomDateWithinDaysBeforeToday(5))
XCTAssertNotNil(Randoms.randomDate())
XCTAssertNotNil(Randoms.randomFakeName())
XCTAssertNotNil(Randoms.randomFakeGender())
XCTAssertNotNil(Randoms.randomFakeConversation())
XCTAssertNotNil(Randoms.randomFakeTitle())
XCTAssertNotNil(Randoms.randomFakeTag())
XCTAssertNotNil(Randoms.randomFakeNameAndEnglishHonorific())
XCTAssertNotNil(Randoms.randomNSURL())
}
/// Tests for extensions applied directly above Swift types.
func testTypeExtensions() {
XCTAssertNotNil(Int.random())
XCTAssertNotNil(Date.random())
XCTAssertNotNil(Date.randomWithinDaysBeforeToday(7))
XCTAssertNotNil(Float.random())
XCTAssertNotNil(Double.random())
XCTAssertNotNil(URL.random())
}
/// Tests using SwiftRandom above a `Range` of Int.
func testRandomIntRange() {
for _ in 0...10 {
let randomUntilTen = Int.random(in: 0...10)
XCTAssertGreaterThanOrEqual(randomUntilTen, 0)
XCTAssertLessThanOrEqual(randomUntilTen, 10)
let randomLessTen = Int.random(in: 0..<10)
XCTAssertGreaterThanOrEqual(randomLessTen, 0)
XCTAssertLessThan(randomLessTen, 10)
}
}
/// Tests generating random a `String` of a specified length.
func testRandomStringOfLength() {
let precision = 100
let length = 128
var all: [String] = []
(1...precision).forEach { _ in
let random: String = .random(ofLength: length)
XCTAssertEqual(random.count, length)
if all.contains(random) {
// this is very unlikely to happen with precisions of 100 or over and lengths of 128 or over.
// if this happens, it is likely a bug in the random string generator.
XCTFail("Random string collision")
}
all.append(random)
}
XCTAssertEqual(String.random(ofLength: -1), "")
XCTAssertEqual(String.random(ofLength: 0), "")
}
/// Tests generating a random `String` of variable length.
func testRandomStringOfVariableLength() {
let precision = 100
let minimumLength = 128
let maximumLength = 256
var all: [String] = []
(1...precision).forEach { _ in
let random: String = .random(minimumLength: minimumLength, maximumLength: maximumLength)
XCTAssertLessThanOrEqual(random.count, maximumLength)
XCTAssertGreaterThanOrEqual(random.count, minimumLength)
if all.contains(random) {
// this is very unlikely to happen with precisions of 100 or over and lengths of 128 or over.
// if this happens, it is likely a bug in the random string generator.
XCTFail("Random string collision")
}
all.append(random)
}
XCTAssertEqual(String.random(minimumLength: -1, maximumLength: -2), "")
XCTAssertEqual(String.random(minimumLength: 1, maximumLength: -2), "")
XCTAssertEqual(String.random(minimumLength: -1, maximumLength: 2), "")
XCTAssertEqual(String.random(minimumLength: 0, maximumLength: 0), "")
XCTAssertEqual(String.random(minimumLength: -1, maximumLength: 0), "")
XCTAssertEqual(String.random(minimumLength: 0, maximumLength: -2), "")
XCTAssertEqual(String.random(minimumLength: 10, maximumLength: 5), "")
XCTAssertEqual(String.random(minimumLength: 5, maximumLength: 5).count, 5)
}
/// Tests generating a string with a character set specified
func testRandomStringWithPossibleCharacters() {
let precision = 100
let length = 3
let allowedCharacters = "ab"
(1...precision).forEach { _ in
let random: String = .random(withCharactersInString: "ab", ofLength: length)
for c in random {
XCTAssertTrue(allowedCharacters.contains(c))
}
}
}
}
| mit | cfae423f8d40c604dd6f1e82f506a471 | 33.967742 | 105 | 0.668358 | 4.759605 | false | true | false | false |
obdev/SocketWrapper | SocketWrapper/SocketWrapper/ReceiveSocketType.swift | 1 | 7970 | //
// ReceiveSocketType.swift
// SocketWrapper
//
// Created by Marco Masser on 2016-03-11.
// Copyright © 2016 Objective Development. All rights reserved.
//
import Foundation
/// A `SocketType` that can `receive()`.
protocol ReceiveSocketType: SocketType {
/// Called right before `receive()` will be called on the socket.
/// This is an override point for implementers. The default implementation does nothing.
func willReceive()
/// Called after `receive()` was called on the socket.
/// This is an override point for implementers. The default implementation does nothing.
func didReceive(buffer: UnsafeMutableBufferPointer<Socket.Byte>, bytesReceived: Int)
}
// Basic functionality.
extension ReceiveSocketType {
/// Receives data until `Socket.receive()` returns because no more data is available, or because `buffer` is full.
///
/// - SeeAlso: `Socket.receive(_, flags:, blocking:)`
func receive(buffer: UnsafeMutableBufferPointer<Socket.Byte>, blocking: Bool = false) throws -> Int {
willReceive()
let result = try socket.receive(buffer, blocking: blocking)
didReceive(buffer, bytesReceived: result)
return result
}
func willReceive() {
// Empty default implementation
}
func didReceive(buffer: UnsafeMutableBufferPointer<Socket.Byte>, bytesReceived: Int) {
// Empty default implementation
}
}
/// An answer that various `receive()` methods' handler callback can return.
enum ReceiveSocketMessageHandlerResponse {
/// Continue receiving after the handler callback returns.
case ContinueReceiving
/// Stop receiving after the handler callback returns.
case StopReceiving
}
// Extended functionality that builds upon the basic `receive()` method.
extension ReceiveSocketType {
/// Receives `maxBytes` or or less.
///
/// - Note: This method may be slow because it allocates an `UnsafeBufferPointer`,
/// writes into it and then converts the received bytes into an `Array`.
///
/// - Returns: An `Array` of `Socket.Byte`s whose count is the number of
/// actual bytes received, not `maxBytes`.
///
/// - SeeAlso: `receive(_:, blocking:)`
func receive(maxBytes maxBytes: Int = 1024, blocking: Bool = false) throws -> [Socket.Byte] {
let pointer = UnsafeMutablePointer<Socket.Byte>.alloc(maxBytes)
let buffer = UnsafeMutableBufferPointer(start: pointer, count: maxBytes)
let bytesReceived = try receive(buffer, blocking: blocking)
let result = Array(buffer[0..<bytesReceived])
pointer.destroy(maxBytes)
pointer.dealloc(maxBytes)
return result
}
/// Receives a UTF-8 string that is at most `maxBytes` long. A `NUL` terminator is not required to be sent by the peer.
///
/// - Returns: The `String` received or `nil` if the data is not valid UTF8.
///
/// - SeeAlso: `receive(maxBytes:, blocking:)`
func receiveUTF8String(maxBytes maxBytes: Int = 1024, blocking: Bool = false) throws -> String? {
let buffer = try receive(maxBytes: maxBytes, blocking: blocking)
let string = String(UTF8CodeUnits: buffer)
return string
}
/// Receives an arbitrary amount of bytes that are terminated by a given `terminator`.
///
/// This method allocates an internal `Array<Socket.Byte>` that it appends data to as it receives it.
/// After a call to `receive(_, blocking:)` returns, the received data is searched for the `terminator`
/// sequence of bytes and if it was found, the given `messageHandler` is called with that data.
///
/// - Parameter terminator: A `CollectionType` whose `Element`s are `Socket.Byte`s.
/// - Parameter messageHandler: A callback closure that is called whenever the `terminator` sequence of bytes
/// was found in the received data. The callback's return value determines whether to continue receiving or not.
///
/// - SeeAlso: `receive(_:, blocking:)`
func receive<T: CollectionType where T.Generator.Element == Socket.Byte, T.Index == Int>(terminator terminator: T, blocking: Bool = false, @noescape messageHandler: ArraySlice<Socket.Byte> throws -> ReceiveSocketMessageHandlerResponse) throws {
let terminatorCount = terminator.count
var receivedBytes = Array<Socket.Byte>()
var terminatorEndIndex = 0
let bufferCount = 1024
let pointer = UnsafeMutablePointer<Socket.Byte>.alloc(bufferCount)
let buffer = UnsafeMutableBufferPointer(start: pointer, count: bufferCount)
// pointer.initializeFrom([Socket.Byte](count: bufferCount, repeatedValue: 0))
receiveLoop: while true {
let bytesReceived = try receive(buffer, blocking: blocking)
let firstSearchRangeStartIndex = max(0, receivedBytes.count - terminatorCount)
receivedBytes.appendContentsOf(buffer[0..<bytesReceived])
let lastSearchRangeStartIndex = max(0, receivedBytes.count - terminatorCount)
for i in firstSearchRangeStartIndex...lastSearchRangeStartIndex {
if receivedBytes.suffixFrom(i).startsWith(terminator) {
terminatorEndIndex = i + terminatorCount - 1
let message = receivedBytes[0...terminatorEndIndex]
switch try messageHandler(message) {
case .ContinueReceiving:
receivedBytes.removeFirst(terminatorEndIndex + 1)
continue receiveLoop
case .StopReceiving:
break receiveLoop
}
}
}
}
// pointer.destroy(bufferCount)
pointer.dealloc(bufferCount)
}
/// Receives a UTF-8 string of arbitrary length that is terminated by the `terminator` string.
///
/// - Parameter terminator: A string that represents the end of a message.
/// - Parameter appendNulToTerminator: If `true`, a `NUL`-terminated `terminator` String is expected to be sent by the peer.
///
/// - SeeAlso: `receive(terminator:, blocking:, messageHandler:)`
func receiveUTF8String(terminator terminator: String = "\n", appendNulToTerminator: Bool = false, blocking: Bool = false, @noescape messageHandler: String throws -> ReceiveSocketMessageHandlerResponse) throws {
return try terminator.withUTF8UnsafeBufferPointer(includeNulTerminator: false) { terminatorBuffer in
try receive(terminator: terminatorBuffer, blocking: blocking) { messageBytes in
let message: String = try messageBytes.withUnsafeBufferPointer { buffer in
guard let message = NSString(bytes: buffer.baseAddress, length: buffer.count, encoding: NSUTF8StringEncoding) else {
throw Socket.Error.ReceivedInvalidData
}
return message as String
}
return try messageHandler(message)
}
}
}
}
/// A socket that can receive asynchronously.
protocol ReceiveAsyncSocketType: SocketType {
}
extension ReceiveAsyncSocketType {
/// Creates and returns a `SocketDispatchSource` that calls the given `readyToReceiveHandler`
/// whenever data is available. One of the `receive()` methods can then be called without blocking.
///
/// To stop receiving data asynchronously, call `cancel()` on the returned `SocketDispatchSource`.
/// This also happens automatically in the `SocketDispatchSource.deinit`.
///
/// - Returns: A `SocketDispatchSource` that must be held on to by the caller for as long as callbacks are to be received.
func receiveAsync(queue queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), readyToReceiveHandler: () -> Void) -> SocketDispatchSource {
return SocketDispatchSource(socket: socket, queue: queue, eventHandler: readyToReceiveHandler)
}
}
| mit | 055d099f5d23dc3df0ae40371247fd6d | 42.785714 | 248 | 0.67223 | 4.993108 | false | false | false | false |
MaddTheSane/SpaceEvaders | SpaceEvaders/Options.swift | 3 | 756 | class Options {
class var option: Options {
return _Options
}
var options: [String:Bool]
init(options: [String:Bool]) {
self.options = options
}
func getOptions() -> [String:Bool] {
return self.options
}
func setOptions(options: [String:Bool]) {
self.options = options
}
func get(option: String) -> Bool {
return options[option]!
}
func toggle(option: String) {
if let opt = options[option] {
options[option] = !opt
}
}
func set(option: String, val: Bool) {
options[option] = val
}
}
private let _Options = Options(options:
["premium": false, "sound": true, "music": true, "indicators": false, "follow": true]
)
| mit | 8f338cd9c04dfcd6dbffaac3de0fdf00 | 19.432432 | 85 | 0.560847 | 3.837563 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/Exporters/Persistence/PersistenceMetricExporterDecorator.swift | 1 | 1806 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetrySdk
// a persistence exporter decorator for `Metric`.
// specialization of `PersistenceExporterDecorator` for `MetricExporter`.
public class PersistenceMetricExporterDecorator: MetricExporter {
struct MetricDecoratedExporter: DecoratedExporter {
typealias SignalType = Metric
private let metricExporter: MetricExporter
init(metricExporter: MetricExporter) {
self.metricExporter = metricExporter
}
func export(values: [Metric]) -> DataExportStatus {
let result = metricExporter.export(metrics: values, shouldCancel: nil)
return DataExportStatus(needsRetry: result == .failureRetryable)
}
}
private let persistenceExporter: PersistenceExporterDecorator<MetricDecoratedExporter>
public init(metricExporter: MetricExporter,
storageURL: URL,
exportCondition: @escaping () -> Bool = { true },
performancePreset: PersistencePerformancePreset = .default) throws
{
self.persistenceExporter =
PersistenceExporterDecorator<MetricDecoratedExporter>(
decoratedExporter: MetricDecoratedExporter(metricExporter: metricExporter),
storageURL: storageURL,
exportCondition: exportCondition,
performancePreset: performancePreset)
}
public func export(metrics: [Metric], shouldCancel: (() -> Bool)?) -> MetricExporterResultCode {
do {
try persistenceExporter.export(values: metrics)
return .success
} catch {
return .failureNotRetryable
}
}
}
| apache-2.0 | f477f02935f0dcdfde75bb4c5360ecd6 | 34.411765 | 100 | 0.653378 | 5.980132 | false | false | false | false |
CodePath2017Group4/travel-app | RoadTripPlanner/PhotoViewController.swift | 1 | 2798 | //
// PhotoViewController.swift
// RoadTripPlanner
//
// Created by Nanxi Kang on 10/14/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
class PhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var delegate: AddPhotoDelegate?
static func getVC() -> PhotoViewController {
let storyboard = UIStoryboard(name: "Photo", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "photoVC") as! PhotoViewController
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem?.title = "Cancel"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addPhotoTapped))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addPhotoTapped(_ sender: Any) {
if let delegate = self.delegate {
delegate.addPhoto(image: imageView.image)
}
navigationController?.popViewController(animated: true)
}
@IBAction func takePhotoTapped(_ sender: Any) {
if (!UIImagePickerController.isSourceTypeAvailable(.camera)) {
let alertController = UIAlertController(title: "Unsupported action", message: "Device has no camera", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
self.present(alertController, animated: true)
} else {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .camera
self.present(picker, animated: true)
}
}
@IBAction func pickPhotoTapped(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .photoLibrary
self.present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info["UIImagePickerControllerEditedImage"] as! UIImage
self.imageView.image = image
self.imageView.contentMode = .scaleAspectFit
picker.dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true)
}
}
| mit | 076ecb72c3f9d4d3bf295c56e96b1aad | 34.858974 | 145 | 0.655703 | 5.462891 | false | false | false | false |
yeahdongcn/Persei | Persei/Source/Core/StickyHeaderView.swift | 1 | 8247 | // For License please refer to LICENSE file in the root of Persei project
import Foundation
import UIKit
import QuartzCore
private var ContentOffsetContext = 0
private let DefaultContentHeight: CGFloat = 64
public class StickyHeaderView: UIView {
// MARK: - Init
func commonInit() {
addSubview(backgroundImageView)
addSubview(contentContainer)
contentContainer.addSubview(shadowView)
clipsToBounds = true
}
public override init(frame: CGRect = CGRect(x: 0, y: 0, width: 320, height: DefaultContentHeight)) {
super.init(frame: frame)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - View lifecycle
public override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
scrollView = nil
}
public override func didMoveToSuperview() {
super.didMoveToSuperview()
if superview != nil {
scrollView = superview as? UIScrollView
scrollView.sendSubviewToBack(self)
}
}
private let contentContainer: UIView = {
let view = UIView()
view.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
view.backgroundColor = UIColor.clearColor()
return view
}()
private let shadowView = HeaderShadowView(frame: CGRectZero)
@IBOutlet
public var contentView: UIView? {
didSet {
oldValue?.removeFromSuperview()
if let view = contentView {
view.frame = contentContainer.bounds
view.autoresizingMask = .FlexibleWidth | .FlexibleHeight
contentContainer.addSubview(view)
contentContainer.sendSubviewToBack(view)
}
}
}
// MARK: - Background Image
private let backgroundImageView = UIImageView()
@IBInspectable
public var backgroundImage: UIImage? {
didSet {
backgroundImageView.image = backgroundImage
backgroundImageView.hidden = backgroundImage == nil
}
}
// MARK: - ScrollView
private weak var scrollView: UIScrollView! {
willSet {
self.scrollView?.removeObserver(self, forKeyPath: "contentOffset", context: &ContentOffsetContext)
self.scrollView?.panGestureRecognizer.removeTarget(self, action: "handlePan:")
appliedInsets = UIEdgeInsetsZero
}
didSet {
scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .Initial | .New, context: &ContentOffsetContext)
scrollView?.panGestureRecognizer.addTarget(self, action: "handlePan:")
}
}
// MARK: - KVO
public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &ContentOffsetContext {
didScroll()
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
// MARK: - State
public var revealed: Bool = false {
didSet {
if oldValue != revealed {
if revealed {
self.addInsets()
} else {
self.removeInsets()
}
}
}
}
private func setRevealed(revealed: Bool, animated: Bool, adjustContentOffset adjust: Bool) {
if animated {
UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState | .CurveEaseInOut, animations: {
self.revealed = revealed
}, completion: { completed in
if adjust {
UIView.animateWithDuration(0.2) {
self.scrollView.contentOffset.y = -self.scrollView.contentInset.top
}
}
})
} else {
self.revealed = revealed
if adjust {
self.scrollView.contentOffset.y = -self.scrollView.contentInset.top
}
}
}
public func setRevealed(revealed: Bool, animated: Bool) {
setRevealed(revealed, animated: animated, adjustContentOffset: true)
}
private func fractionRevealed() -> CGFloat {
return min(bounds.height / contentHeight, 1)
}
// MARK: - Applyied Insets
private var appliedInsets: UIEdgeInsets = UIEdgeInsetsZero
private var insetsApplied: Bool {
return appliedInsets != UIEdgeInsetsZero
}
private func applyInsets(insets: UIEdgeInsets) {
let originalInset = scrollView.contentInset - appliedInsets
let targetInset = originalInset + insets
appliedInsets = insets
scrollView.contentInset = targetInset
}
private func addInsets() {
assert(!insetsApplied, "Internal inconsistency")
applyInsets(UIEdgeInsets(top: contentHeight, left: 0, bottom: 0, right: 0))
}
private func removeInsets() {
assert(insetsApplied, "Internal inconsistency")
applyInsets(UIEdgeInsetsZero)
}
// MARK: - ContentHeight
@IBInspectable
public var contentHeight: CGFloat = DefaultContentHeight {
didSet {
if superview != nil {
layoutToFit()
}
}
}
// MARK: - Threshold
@IBInspectable
public var threshold: CGFloat = 0.3
// MARK: - Content Offset Hanlding
private func applyContentContainerTransform(progress: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = -1 / 500
let angle = (1 - progress) * CGFloat(M_PI_2)
transform = CATransform3DRotate(transform, angle, 1, 0, 0)
contentContainer.layer.transform = transform
}
private func didScroll() {
let oldProgress = fractionRevealed()
layoutToFit()
layoutIfNeeded()
let progress = fractionRevealed()
shadowView.alpha = 1 - progress
applyContentContainerTransform(progress)
}
@objc
private func handlePan(recognizer: UIPanGestureRecognizer) {
if recognizer.state == .Ended {
let value = scrollView.normalizedContentOffset.y * (revealed ? 1 : -1)
let triggeringValue = contentHeight * threshold
let velocity = recognizer.velocityInView(scrollView).y
if triggeringValue < value {
let adjust = !revealed || velocity < 0 && -velocity < contentHeight
setRevealed(!revealed, animated: true, adjustContentOffset: adjust)
} else if 0 < bounds.height && bounds.height < contentHeight {
UIView.animateWithDuration(0.3) {
self.scrollView.contentOffset.y = -self.scrollView.contentInset.top
}
}
}
}
// MARK: - Layout
public override func layoutSubviews() {
super.layoutSubviews()
backgroundImageView.frame = bounds
contentContainer.frame = CGRect(
x: 0,
y: min(bounds.height - contentHeight, bounds.midY - contentHeight / 2),
width: bounds.width,
height: contentHeight
)
// shadow should be visible outside of bounds during rotation
shadowView.frame = CGRectInset(contentContainer.bounds, -round(contentContainer.bounds.width / 16), 0)
}
private func layoutToFit() {
var origin = scrollView.contentOffset.y + scrollView.contentInset.top - appliedInsets.top
frame.origin.y = origin
sizeToFit()
}
public override func sizeThatFits(_: CGSize) -> CGSize {
var height: CGFloat = 0
if revealed {
height = appliedInsets.top - scrollView.normalizedContentOffset.y
} else {
height = scrollView.normalizedContentOffset.y * -1
}
let output = CGSize(width: CGRectGetWidth(scrollView.bounds), height: max(height, 0))
return output
}
}
| mit | c1bc9739fb1e5a198900bbdc35725b25 | 30.841699 | 163 | 0.598157 | 5.42923 | false | false | false | false |
depl0y/pixelbits | pixelbits/Parser/UIViewLocation.swift | 1 | 3512 | //
// PBPath.swift
// pixelbits
//
// Created by Wim Haanstra on 12/01/16.
// Copyright © 2016 Wim Haanstra. All rights reserved.
//
import UIKit
/**
The `UIViewLocation` class describes the `location` of a `UIView` within it's parents' views.
This will create a reference which can be used to reference in the stylesheets.
*/
internal class UIViewLocation : Hashable {
var parent: UIViewLocation?
var child: UIViewLocation?
/// Stores the class name of the associated object.
var className: String
/// Stores the style of the associated object.
var style: String?
init(className: String, style: String? = nil, child: UIViewLocation?) {
self.className = className
self.style = style
self.child = child
}
/**
Returns the full path of this `UIViewLocation`. This is used for debugging.
- returns: The full path of this `UIViewLocation`.
*/
func toString() -> String {
var result = ""
if parent != nil {
result = parent!.toString()
}
result += "/" + self.className
if self.style != nil {
result += "." + self.style!
}
return result
}
/// Returns the `className` of this `UIViewLocation`, suffixed with the `style` if specified.
var fullName: String {
get {
var n = self.className
if self.style != nil {
n += "." + self.style!
}
return n
}
}
/// Returns only the `style` property of the `UIViewLocation`, prefixed with a dot if a `style` is specified.
var styleString: String {
get {
if self.style != nil {
return ".\(self.style!)"
}
else {
return ""
}
}
}
/**
Get `UIViewLocation` for the supplied `UIView`.
- parameter view: The `UIView` for which to get the `UIViewLocation`
- parameter child: If the `UIView` has a child `UIViewLocation` they will be linked together to create a valid hierarchy
- returns: The `UIViewLocation` object
*/
static func fromView(view: UIView, child: UIViewLocation? = nil) -> UIViewLocation {
let mirror = Mirror(reflecting: view)
let className: String = "\(mirror.subjectType)"
let location = UIViewLocation(className: className, style: view.style, child: child)
if view.superview != nil {
let parent = UIViewLocation.fromView(view.superview!, child: location)
location.parent = parent
}
else if view.viewController != nil {
let viewController = view.viewController!
let viewControllerMirror = Mirror(reflecting: viewController)
let viewControllerClassName: String = "\(viewControllerMirror.subjectType)"
let parent = UIViewLocation(className: viewControllerClassName, child: location)
location.parent = parent
}
return location
}
/// Needed for the `Hashable` protocol
var hashValue: Int {
get {
return self.toString().hashValue
}
}
}
func ==(lhs: UIViewLocation, rhs: UIViewLocation) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
| mit | 3715629c2d955480536959ca22a0ac3a | 26.865079 | 125 | 0.55967 | 5.081042 | false | false | false | false |
mfebrianto/Budget | budget/ViewController.swift | 1 | 4576 | //
// ViewController.swift
// budget
//
// Created by michael febrianto on 18/07/2016.
// Copyright © 2016 f2mobile. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet var addButton: UIBarButtonItem!
@IBOutlet var categoryTableView: UITableView!
var expenseCategories = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "\"The List\""
categoryTableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
categoryTableView.reloadData()
print ("reloaded")
let ecs = ExpenseCategoryService()
ecs.getAll()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "ExpenseCategory")
//3
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
expenseCategories = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func clickAddButton(sender: UIBarButtonItem) {
print(">>>>clickAddButton")
let alert = UIAlertController(title: "New Name",
message: "Add a new name",
preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save",
style: .Default,
handler: { (action:UIAlertAction) -> Void in
let textField = alert.textFields!.first
self.saveName(textField!.text!)
self.categoryTableView.reloadData()
})
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default) { (action: UIAlertAction) -> Void in
}
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert,
animated: true,
completion: nil)
}
func saveName(name: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let entity = NSEntityDescription.entityForName("ExpenseCategory",
inManagedObjectContext:managedContext)
let expenseCategory = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
//3
expenseCategory.setValue(name, forKey: "name")
//4
do {
try managedContext.save()
//5
expenseCategories.append(expenseCategory)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return expenseCategories.count
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCellWithIdentifier("Cell")
let category = expenseCategories[indexPath.row]
print("table view reload")
cell!.textLabel!.text = category.valueForKey("name") as? String
return cell!
}
}
| apache-2.0 | 1dcc2b113beb8048b48c0ceebd384ab9 | 29.5 | 94 | 0.530055 | 6.45275 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/finalProject/TotalTime/Source/View/HomeViewController.swift | 1 | 4755 | //
// HomeViewController.swift
// TotalTime
//
// Created by Dylan Secreast on 3/1/17.
// Copyright © 2017 Dylan Secreast. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import AVFoundation
class HomeViewController : UIViewController, NSFetchedResultsControllerDelegate {
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var currentJobLabel: UILabel!
@IBOutlet weak var currentTotalTabel: UILabel!
private var jobFetchedResultsController: NSFetchedResultsController<Job>!
private var audioPlayer: AVAudioPlayer!
var jobs: [Job] = []
var timer: Timer = Timer()
var startTime = TimeInterval()
@IBAction func start(_ sender: UIButton) {
// Verify user has entered minimum necessary job info to start
if (jobs.count == 0) {
let alertController = UIAlertController(title: "Wait a Minute!", message: "Please enter Job Title and Hourly Rate under the Job tab to begin.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
return
}
if (timer.isValid) { // Timer already started
let alertController = UIAlertController(title: "On The Clock", message: "Timer has already started. Stop to restart.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
else { // Timer not started
currentJobLabel.text = jobs.last?.title
let audioFilePath = Bundle.main.path(forResource: "train", ofType: "mp3")
if (audioFilePath != nil) {
let audioFileUrl = NSURL.init(fileURLWithPath: audioFilePath!)
do {
try audioPlayer = AVAudioPlayer(contentsOf: audioFileUrl as URL)
audioPlayer.play()
}
catch {
print("Unable to play train.mp3")
}
}
else {
print("Unable to find train.mp3")
}
let aSelector: Selector = #selector(HomeViewController.updateTime)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = Date.timeIntervalSinceReferenceDate
}
}
@IBAction func stop(_ sender: UIButton) {
timer.invalidate()
audioPlayer.stop()
currentJobLabel.text = "Job Complete!"
let alertController = UIAlertController(title: "Get Paid!", message: "Your invoice is ready to view under the Done tab", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
public func updateTime() {
let currentTime = Date.timeIntervalSinceReferenceDate
var elapsedTime: TimeInterval = currentTime - startTime
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
// Play gentle sound notification every 15min
if (minutes % 15 == 0) {
audioPlayer.play()
}
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
timerLabel.text = "\(strMinutes):\(strSeconds)"
calculateTotal(min: minutes, sec: seconds)
}
public func calculateTotal(min: UInt8, sec: UInt8) {
let totalSecondsWorked = Float((min * 60) + sec)
let hourlyRate: Float = (jobs.last?.hourlyRate)!
let commision = hourlyRate * (totalSecondsWorked / 3600)
currentTotalTabel.text = "$" + String(format: "%.2f", commision)
}
func fetchData() {
jobFetchedResultsController = TimeService.shared.jobData()
jobFetchedResultsController.delegate = self
jobs = jobFetchedResultsController.fetchedObjects!
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
currentJobLabel.text = jobs.last?.title
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
fetchData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| gpl-3.0 | 276d8fcc92243132e6f68551afc04541 | 34.744361 | 179 | 0.613589 | 5.161781 | false | false | false | false |
imzyf/99-projects-of-swift | 014-video-splash/014-video-splash/VideoSplashKit/VideoSplashViewController.swift | 1 | 4358 | //
// VideoSplashViewController.swift
// VideoSplash
//
// Created by Toygar Dündaralp on 8/3/15.
// Copyright (c) 2015 Toygar Dündaralp. All rights reserved.
//
import UIKit
import MediaPlayer
import AVKit
public enum ScalingMode {
case resize
case resizeAspect
case resizeAspectFill
}
open class VideoSplashViewController: UIViewController {
private let moviePlayer = AVPlayerViewController()
private var moviePlayerSoundLevel: Float = 1.0
open var videoFrame: CGRect = CGRect()
open var startTime: CGFloat = 0.0
open var duration: CGFloat = 0.0
open var backgroundColor = UIColor.black { didSet { view.backgroundColor = backgroundColor } }
open var contentURL: URL = URL(fileURLWithPath: "") { didSet { setMoviePlayer(url: contentURL) } }
open var sound: Bool = true { didSet { moviePlayerSoundLevel = sound ? 1 : 0 } }
open var alpha: CGFloat = 1 { didSet { moviePlayer.view.alpha = alpha } }
open var alwaysRepeat: Bool = true {
didSet {
if alwaysRepeat {
NotificationCenter.default.addObserver(forName:.AVPlayerItemDidPlayToEndTime, object:nil, queue:nil) { [weak self] (notification) in
self?.playerItemDidReachEnd()
}
return
}
if !alwaysRepeat {
NotificationCenter.default.removeObserver(self, name:.AVPlayerItemDidPlayToEndTime, object: nil)
}
}
}
open var fillMode: ScalingMode = .resizeAspectFill {
didSet {
switch fillMode {
case .resize:
moviePlayer.videoGravity = AVLayerVideoGravity.resize.rawValue
case .resizeAspect:
moviePlayer.videoGravity = AVLayerVideoGravity.resizeAspect.rawValue
case .resizeAspectFill:
moviePlayer.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue
}
}
}
open var restartForeground: Bool = false {
didSet {
if restartForeground {
NotificationCenter.default.addObserver(forName:.UIApplicationWillEnterForeground, object:nil, queue:nil) { [weak self] (notification) in
self?.playerItemDidReachEnd()
}
}
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
moviePlayer.view.frame = videoFrame
moviePlayer.view.backgroundColor = self.backgroundColor;
moviePlayer.showsPlaybackControls = false
moviePlayer.view.isUserInteractionEnabled = false
view.addSubview(moviePlayer.view)
view.sendSubview(toBack: moviePlayer.view)
}
private func setMoviePlayer(url: URL){
let videoCutter = VideoCutter()
videoCutter.cropVideoWithUrl(videoUrl: url, startTime: startTime, duration: duration) { [weak self] (videoPath, error) -> Void in
guard let path = videoPath, let strongSelf = self else { return }
strongSelf.moviePlayer.player = AVPlayer(url: path)
strongSelf.moviePlayer.player?.addObserver(strongSelf, forKeyPath: "status", options: .new, context: nil)
strongSelf.moviePlayer.player?.play()
strongSelf.moviePlayer.player?.volume = strongSelf.moviePlayerSoundLevel
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let player = object as? AVPlayer else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if player.status == .readyToPlay {
movieReadyToPlay()
}
}
deinit{
moviePlayer.player?.removeObserver(self, forKeyPath: "status")
NotificationCenter.default.removeObserver(self)
}
// Override in subclass
open func movieReadyToPlay() { }
func playerItemDidReachEnd() {
moviePlayer.player?.seek(to: kCMTimeZero)
moviePlayer.player?.play()
}
func playVideo() {
moviePlayer.player?.play()
}
func pauseVideo() {
moviePlayer.player?.pause()
}
}
| mit | a9cd09157881d425606aa746b7bde787 | 33.848 | 156 | 0.62787 | 5.404467 | false | false | false | false |
Reblood/iOS-Reblood | Reblood/Reblood/RecentTableViewController.swift | 1 | 3130 | //
// RecentTableViewController.swift
// Reblood
//
// Created by Zulwiyoza Putra on 3/4/17.
// Copyright © 2017 Kibar. All rights reserved.
//
import UIKit
class RecentTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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 | 484dedb33b0f331f0c6c86686a763c34 | 31.936842 | 136 | 0.670821 | 5.285473 | false | false | false | false |
jakub-tucek/fit-checker-2.0 | fit-checker/ViewPlayground.playground/Contents.swift | 1 | 2791 | //: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
/// User login view controller.
class LoginViewController: UIViewController {
struct Layout {
static let spacing: CGFloat = 15
static let inputWidth: CGFloat = 200
static let buttonWidth: CGFloat = 80
static let fieldHeight: CGFloat = 22
}
let usernameField: UITextField = {
let field = UITextField()
field.placeholder = "Username"
return field
}()
let passwordField: UITextField = {
let field = UITextField()
field.placeholder = "Password"
return field
}()
let loginButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Login", for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
configureView()
}
public func login() {
}
private func configureView() {
let views = [usernameField, passwordField, loginButton]
views.forEach { view in
view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(view)
}
let constraints = [
usernameField.topAnchor.constraint(equalTo:
view.topAnchor, constant: Layout.spacing * 5.0),
usernameField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
usernameField.widthAnchor.constraint(equalToConstant:
Layout.inputWidth),
usernameField.heightAnchor.constraint(equalToConstant:
Layout.fieldHeight),
passwordField.topAnchor.constraint(equalTo:
usernameField.bottomAnchor, constant: Layout.spacing),
passwordField.centerXAnchor.constraint(equalTo:
usernameField.centerXAnchor),
passwordField.widthAnchor.constraint(equalTo:
usernameField.widthAnchor),
passwordField.heightAnchor.constraint(equalTo:
usernameField.heightAnchor),
loginButton.topAnchor.constraint(equalTo:
passwordField.bottomAnchor, constant: Layout.spacing),
loginButton.centerXAnchor.constraint(equalTo:
passwordField.centerXAnchor),
loginButton.widthAnchor.constraint(equalToConstant:
Layout.buttonWidth),
loginButton.heightAnchor.constraint(equalTo:
passwordField.heightAnchor)
]
constraints.forEach { $0.isActive = true }
loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
}
}
let controller = LoginViewController()
PlaygroundPage.current.liveView = controller
| mit | 5a95ee20cd79b5091a4b0dd40f024be9 | 29.010753 | 82 | 0.633106 | 5.826722 | false | false | false | false |
zoeyzhong520/InformationTechnology | InformationTechnology/InformationTechnology/Classes/Collection精选/View/CoolPlaySlideCell.swift | 1 | 4790 | //
// CoolPlaySlideCell.swift
// InformationTechnology
//
// Created by qianfeng on 16/11/11.
// Copyright © 2016年 zzj. All rights reserved.
//
import UIKit
class CoolPlaySlideCell: UICollectionViewCell {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var pageCtrl: UIPageControl!
//点击事件
var jumpClosure:RecommendJumpClosure?
//显示数据
var slideArray:Array<CoolPlaySlideCardsInf>? {
didSet {
showData()
}
}
//显示数据
private func showData() {
//遍历添加图片
let cnt = slideArray?.count
if slideArray?.count > 0 {
//滚动视图加约束
//1.创建一个容器视图,作为滚动视图的子视图
let containerView = UIView.createView()
scrollView.addSubview(containerView)
containerView.snp_makeConstraints(closure: {
(make) in
make.edges.equalTo(scrollView)
//一定要设置高度
make.height.equalTo(scrollView)
})
//2.循环设置子视图的约束,子视图是添加到容器视图里面
var lastView: UIView? = nil
for i in 0..<cnt! {
let model = slideArray![i]
//创建图片
let tmpImageView = UIImageView()
if model.image_800_450 != nil {
let url = NSURL(string: model.image_800_450!)
tmpImageView.kf_setImageWithURL(url!, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
containerView.addSubview(tmpImageView)
//添加点击事件
tmpImageView.userInteractionEnabled = true
tmpImageView.tag = 200+i
let g = UITapGestureRecognizer(target: self, action: #selector(tapImage(_:)))
tmpImageView.addGestureRecognizer(g)
//图片的约束
tmpImageView.snp_makeConstraints(closure: {
(make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(scrollView)
if lastView == nil {
make.left.equalTo(containerView)
}else{
make.left.equalTo((lastView?.snp_right)!)
}
})
lastView = tmpImageView
//显示title文字
if model.title != nil {
titleLabel.text = slideArray![pageCtrl.currentPage].title
}
}
//3.修改container的宽度
containerView.snp_makeConstraints(closure: {
(make) in
make.right.equalTo(lastView!)
})
//分页控件
pageCtrl.numberOfPages = cnt!
}
}
func tapImage(g: UIGestureRecognizer) {
let index = (g.view?.tag)! - 200
//获取点击的数据
let item = slideArray![index]
if jumpClosure != nil && item.skip_inf?.video_id != nil {
jumpClosure!((item.skip_inf?.video_id)!)
}
}
//创建cell的方法
class func createHeaderCellFor(collectionView:UICollectionView, atIndexPath indexPath:NSIndexPath, slideArray:Array<CoolPlaySlideCardsInf>?) -> CoolPlaySlideCell {
let cellId = "coolPlaySlideCellId"
var cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as? CoolPlaySlideCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CoolPlaySlideCell", owner: nil, options: nil).last as? CoolPlaySlideCell
}
cell?.slideArray = slideArray
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
//MARK: UIScrollView代理方法
extension CoolPlaySlideCell:UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = scrollView.contentOffset.x/scrollView.bounds.size.width
pageCtrl.currentPage = Int(index)
//显示title文字
titleLabel.text = slideArray![pageCtrl.currentPage].title
}
//点击状态栏返回顶部
func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool {
return false
}
}
| mit | d1db175e9268c6fad39a639dd273ca8e | 27.10559 | 170 | 0.538122 | 5.511571 | false | false | false | false |
stephentyrone/swift | stdlib/public/Darwin/Foundation/IndexPath.swift | 6 | 27773 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
@_implementationOnly import _SwiftFoundationOverlayShims
/**
`IndexPath` represents the path to a specific node in a tree of nested array collections.
Each index in an index path represents the index into an array of children from one node in the tree to another, deeper, node.
*/
public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableCollection, RandomAccessCollection, Comparable, ExpressibleByArrayLiteral {
public typealias ReferenceType = NSIndexPath
public typealias Element = Int
public typealias Index = Array<Int>.Index
public typealias Indices = DefaultIndices<IndexPath>
fileprivate enum Storage : ExpressibleByArrayLiteral {
typealias Element = Int
case empty
case single(Int)
case pair(Int, Int)
case array([Int])
init(arrayLiteral elements: Int...) {
self.init(elements)
}
init(_ elements: [Int]) {
switch elements.count {
case 0:
self = .empty
case 1:
self = .single(elements[0])
case 2:
self = .pair(elements[0], elements[1])
default:
self = .array(elements)
}
}
func dropLast() -> Storage {
switch self {
case .empty:
return .empty
case .single(_):
return .empty
case .pair(let first, _):
return .single(first)
case .array(let indexes):
switch indexes.count {
case 3:
return .pair(indexes[0], indexes[1])
default:
return .array(Array<Int>(indexes.dropLast()))
}
}
}
mutating func append(_ other: Int) {
switch self {
case .empty:
self = .single(other)
case .single(let first):
self = .pair(first, other)
case .pair(let first, let second):
self = .array([first, second, other])
case .array(let indexes):
self = .array(indexes + [other])
}
}
mutating func append(contentsOf other: Storage) {
switch self {
case .empty:
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .single(rhsIndex)
case .pair(let rhsFirst, let rhsSecond):
self = .pair(rhsFirst, rhsSecond)
case .array(let rhsIndexes):
self = .array(rhsIndexes)
}
case .single(let lhsIndex):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .pair(lhsIndex, rhsIndex)
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsIndex, rhsFirst, rhsSecond])
case .array(let rhsIndexes):
self = .array([lhsIndex] + rhsIndexes)
}
case .pair(let lhsFirst, let lhsSecond):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array([lhsFirst, lhsSecond, rhsIndex])
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsFirst, lhsSecond, rhsFirst, rhsSecond])
case .array(let rhsIndexes):
self = .array([lhsFirst, lhsSecond] + rhsIndexes)
}
case .array(let lhsIndexes):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array(lhsIndexes + [rhsIndex])
case .pair(let rhsFirst, let rhsSecond):
self = .array(lhsIndexes + [rhsFirst, rhsSecond])
case .array(let rhsIndexes):
self = .array(lhsIndexes + rhsIndexes)
}
}
}
mutating func append(contentsOf other: __owned [Int]) {
switch self {
case .empty:
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .single(other[0])
case 2:
self = .pair(other[0], other[1])
default:
self = .array(other)
}
case .single(let first):
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .pair(first, other[0])
default:
self = .array([first] + other)
}
case .pair(let first, let second):
switch other.count {
case 0:
// DO NOTHING
break
default:
self = .array([first, second] + other)
}
case .array(let indexes):
self = .array(indexes + other)
}
}
subscript(_ index: Int) -> Int {
get {
switch self {
case .empty:
fatalError("Index \(index) out of bounds of count 0")
case .single(let first):
precondition(index == 0, "Index \(index) out of bounds of count 1")
return first
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "Index \(index) out of bounds of count 2")
return index == 0 ? first : second
case .array(let indexes):
return indexes[index]
}
}
set {
switch self {
case .empty:
fatalError("Index \(index) out of bounds of count 0")
case .single(_):
precondition(index == 0, "Index \(index) out of bounds of count 1")
self = .single(newValue)
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "Index \(index) out of bounds of count 2")
if index == 0 {
self = .pair(newValue, second)
} else {
self = .pair(first, newValue)
}
case .array(let indexes_):
var indexes = indexes_
indexes[index] = newValue
self = .array(indexes)
}
}
}
subscript(range: Range<Index>) -> Storage {
get {
switch self {
case .empty:
switch (range.lowerBound, range.upperBound) {
case (0, 0):
return .empty
default:
fatalError("Range \(range) is out of bounds of count 0")
}
case .single(let index):
switch (range.lowerBound, range.upperBound) {
case (0, 0),
(1, 1):
return .empty
case (0, 1):
return .single(index)
default:
fatalError("Range \(range) is out of bounds of count 1")
}
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0),
(1, 1),
(2, 2):
return .empty
case (0, 1):
return .single(first)
case (1, 2):
return .single(second)
case (0, 2):
return self
default:
fatalError("Range \(range) is out of bounds of count 2")
}
case .array(let indexes):
let slice = indexes[range]
switch slice.count {
case 0:
return .empty
case 1:
return .single(slice.first!)
case 2:
return .pair(slice.first!, slice.last!)
default:
return .array(Array<Int>(slice))
}
}
}
set {
switch self {
case .empty:
precondition(range.lowerBound == 0 && range.upperBound == 0, "Range \(range) is out of bounds of count 0")
self = newValue
case .single(let index):
switch (range.lowerBound, range.upperBound, newValue) {
case (0, 0, .empty),
(1, 1, .empty):
break
case (0, 0, .single(let other)):
self = .pair(other, index)
case (0, 0, .pair(let first, let second)):
self = .array([first, second, index])
case (0, 0, .array(let other)):
self = .array(other + [index])
case (0, 1, .empty),
(0, 1, .single),
(0, 1, .pair),
(0, 1, .array):
self = newValue
case (1, 1, .single(let other)):
self = .pair(index, other)
case (1, 1, .pair(let first, let second)):
self = .array([index, first, second])
case (1, 1, .array(let other)):
self = .array([index] + other)
default:
fatalError("Range \(range) is out of bounds of count 1")
}
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([other, first, second])
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, first, second])
case .array(let other):
self = .array(other + [first, second])
}
case (0, 1):
switch newValue {
case .empty:
self = .single(second)
case .single(let other):
self = .pair(other, second)
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, second])
case .array(let other):
self = .array(other + [second])
}
case (0, 2):
self = newValue
case (1, 2):
switch newValue {
case .empty:
self = .single(first)
case .single(let other):
self = .pair(first, other)
case .pair(let otherFirst, let otherSecond):
self = .array([first, otherFirst, otherSecond])
case .array(let other):
self = .array([first] + other)
}
case (2, 2):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([first, second, other])
case .pair(let otherFirst, let otherSecond):
self = .array([first, second, otherFirst, otherSecond])
case .array(let other):
self = .array([first, second] + other)
}
default:
fatalError("Range \(range) is out of bounds of count 2")
}
case .array(let indexes):
var newIndexes = indexes
newIndexes.removeSubrange(range)
switch newValue {
case .empty:
break
case .single(let index):
newIndexes.insert(index, at: range.lowerBound)
case .pair(let first, let second):
newIndexes.insert(first, at: range.lowerBound)
newIndexes.insert(second, at: range.lowerBound + 1)
case .array(let other):
newIndexes.insert(contentsOf: other, at: range.lowerBound)
}
self = Storage(newIndexes)
}
}
}
var count: Int {
switch self {
case .empty:
return 0
case .single:
return 1
case .pair:
return 2
case .array(let indexes):
return indexes.count
}
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return count
}
var allValues: [Int] {
switch self {
case .empty: return []
case .single(let index): return [index]
case .pair(let first, let second): return [first, second]
case .array(let indexes): return indexes
}
}
func index(before i: Int) -> Int {
return i - 1
}
func index(after i: Int) -> Int {
return i + 1
}
var description: String {
switch self {
case .empty:
return "[]"
case .single(let index):
return "[\(index)]"
case .pair(let first, let second):
return "[\(first), \(second)]"
case .array(let indexes):
return indexes.description
}
}
func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Int>) throws -> R) rethrows -> R {
switch self {
case .empty:
return try body(UnsafeBufferPointer<Int>(start: nil, count: 0))
case .single(let index_):
var index = index_
return try withUnsafePointer(to: &index) { (start) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: start, count: 1))
}
case .pair(let first, let second):
var pair = (first, second)
return try withUnsafeBytes(of: &pair) { (rawBuffer: UnsafeRawBufferPointer) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: rawBuffer.baseAddress?.assumingMemoryBound(to: Int.self), count: 2))
}
case .array(let indexes):
return try indexes.withUnsafeBufferPointer(body)
}
}
var debugDescription: String { return description }
static func +(lhs: Storage, rhs: Storage) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func +(lhs: Storage, rhs: [Int]) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func ==(lhs: Storage, rhs: Storage) -> Bool {
switch (lhs, rhs) {
case (.empty, .empty):
return true
case (.single(let lhsIndex), .single(let rhsIndex)):
return lhsIndex == rhsIndex
case (.pair(let lhsFirst, let lhsSecond), .pair(let rhsFirst, let rhsSecond)):
return lhsFirst == rhsFirst && lhsSecond == rhsSecond
case (.array(let lhsIndexes), .array(let rhsIndexes)):
return lhsIndexes == rhsIndexes
default:
return false
}
}
}
fileprivate var _indexes : Storage
/// Initialize an empty index path.
public init() {
_indexes = []
}
/// Initialize with a sequence of integers.
public init<ElementSequence : Sequence>(indexes: ElementSequence)
where ElementSequence.Iterator.Element == Element {
_indexes = Storage(indexes.map { $0 })
}
/// Initialize with an array literal.
public init(arrayLiteral indexes: Element...) {
_indexes = Storage(indexes)
}
/// Initialize with an array of elements.
public init(indexes: Array<Element>) {
_indexes = Storage(indexes)
}
fileprivate init(storage: Storage) {
_indexes = storage
}
/// Initialize with a single element.
public init(index: Element) {
_indexes = [index]
}
/// Return a new `IndexPath` containing all but the last element.
public func dropLast() -> IndexPath {
return IndexPath(storage: _indexes.dropLast())
}
/// Append an `IndexPath` to `self`.
public mutating func append(_ other: IndexPath) {
_indexes.append(contentsOf: other._indexes)
}
/// Append a single element to `self`.
public mutating func append(_ other: Element) {
_indexes.append(other)
}
/// Append an array of elements to `self`.
public mutating func append(_ other: Array<Element>) {
_indexes.append(contentsOf: other)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Element) -> IndexPath {
var result = _indexes
result.append(other)
return IndexPath(storage: result)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: IndexPath) -> IndexPath {
return IndexPath(storage: _indexes + other._indexes)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Array<Element>) -> IndexPath {
return IndexPath(storage: _indexes + other)
}
public subscript(index: Index) -> Element {
get {
return _indexes[index]
}
set {
_indexes[index] = newValue
}
}
public subscript(range: Range<Index>) -> IndexPath {
get {
return IndexPath(storage: _indexes[range])
}
set {
_indexes[range] = newValue._indexes
}
}
public func makeIterator() -> IndexingIterator<IndexPath> {
return IndexingIterator(_elements: self)
}
public var count: Int {
return _indexes.count
}
public var startIndex: Index {
return _indexes.startIndex
}
public var endIndex: Index {
return _indexes.endIndex
}
public func index(before i: Index) -> Index {
return _indexes.index(before: i)
}
public func index(after i: Index) -> Index {
return _indexes.index(after: i)
}
/// Sorting an array of `IndexPath` using this comparison results in an array representing nodes in depth-first traversal order.
public func compare(_ other: IndexPath) -> ComparisonResult {
let thisLength = count
let otherLength = other.count
let length = Swift.min(thisLength, otherLength)
for idx in 0..<length {
let otherValue = other[idx]
let value = self[idx]
if value < otherValue {
return .orderedAscending
} else if value > otherValue {
return .orderedDescending
}
}
if thisLength > otherLength {
return .orderedDescending
} else if thisLength < otherLength {
return .orderedAscending
}
return .orderedSame
}
public func hash(into hasher: inout Hasher) {
// Note: We compare all indices in ==, so for proper hashing, we must
// also feed them all to the hasher.
//
// To ensure we have unique hash encodings in nested hashing contexts,
// we combine the count of indices as well as the indices themselves.
// (This matches what Array does.)
switch _indexes {
case .empty:
hasher.combine(0)
case let .single(index):
hasher.combine(1)
hasher.combine(index)
case let .pair(first, second):
hasher.combine(2)
hasher.combine(first)
hasher.combine(second)
case let .array(indexes):
hasher.combine(indexes.count)
for index in indexes {
hasher.combine(index)
}
}
}
// MARK: - Bridging Helpers
fileprivate init(nsIndexPath: __shared ReferenceType) {
let count = nsIndexPath.length
if count == 0 {
_indexes = []
} else if count == 1 {
_indexes = .single(nsIndexPath.index(atPosition: 0))
} else if count == 2 {
_indexes = .pair(nsIndexPath.index(atPosition: 0), nsIndexPath.index(atPosition: 1))
} else {
var indexes = Array<Int>(repeating: 0, count: count)
indexes.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer<Int>) -> Void in
nsIndexPath.getIndexes(buffer.baseAddress!, range: NSRange(location: 0, length: count))
}
_indexes = .array(indexes)
}
}
fileprivate func makeReference() -> ReferenceType {
switch _indexes {
case .empty:
return ReferenceType()
case .single(let index):
return ReferenceType(index: index)
case .pair(let first, let second):
return _NSIndexPathCreateFromIndexes(first, second) as! ReferenceType
default:
return _indexes.withUnsafeBufferPointer {
return ReferenceType(indexes: $0.baseAddress, length: $0.count)
}
}
}
public static func ==(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs._indexes == rhs._indexes
}
public static func +(lhs: IndexPath, rhs: IndexPath) -> IndexPath {
return lhs.appending(rhs)
}
public static func +=(lhs: inout IndexPath, rhs: IndexPath) {
lhs.append(rhs)
}
public static func <(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == ComparisonResult.orderedAscending
}
public static func <=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == ComparisonResult.orderedAscending || order == ComparisonResult.orderedSame
}
public static func >(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
public static func >=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == ComparisonResult.orderedDescending || order == ComparisonResult.orderedSame
}
}
extension IndexPath : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return _indexes.description
}
public var debugDescription: String {
return _indexes.debugDescription
}
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self, displayStyle: .collection)
}
}
extension IndexPath : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSIndexPath.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSIndexPath {
return makeReference()
}
public static func _forceBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) {
result = IndexPath(nsIndexPath: x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) -> Bool {
result = IndexPath(nsIndexPath: x)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSIndexPath?) -> IndexPath {
guard let src = source else { return IndexPath() }
return IndexPath(nsIndexPath: src)
}
}
extension NSIndexPath : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as IndexPath)
}
}
extension IndexPath : Codable {
private enum CodingKeys : Int, CodingKey {
case indexes
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var indexesContainer = try container.nestedUnkeyedContainer(forKey: .indexes)
var indexes = [Int]()
if let count = indexesContainer.count {
indexes.reserveCapacity(count)
}
while !indexesContainer.isAtEnd {
let index = try indexesContainer.decode(Int.self)
indexes.append(index)
}
self.init(indexes: indexes)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var indexesContainer = container.nestedUnkeyedContainer(forKey: .indexes)
switch self._indexes {
case .empty:
break
case .single(let index):
try indexesContainer.encode(index)
case .pair(let first, let second):
try indexesContainer.encode(first)
try indexesContainer.encode(second)
case .array(let indexes):
try indexesContainer.encode(contentsOf: indexes)
}
}
}
| apache-2.0 | 56eb1aeeb6816c2d0dd443a4a4a408fa | 35.25718 | 151 | 0.484283 | 5.392816 | false | false | false | false |
Kyoooooo/DouYuZhiBo | DYZB/DYZB/Classes/Main/Controller/BaseAnchorViewController.swift | 1 | 4640 | //
// BaseAnchorViewController.swift
// DYZB
//
// Created by 张起哲 on 2017/9/9.
// Copyright © 2017年 张起哲. All rights reserved.
//
import UIKit
let kItemMargin : CGFloat = 10
let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2
let kNormalItemH = kNormalItemW * 3 / 4
let kPrettyItemH = kNormalItemW * 4 / 3
let kHeaderViewH : CGFloat = 50
private let kHeaderViewID = "kHeaderViewID"
let kNormalCellID = "kNormalCellID"
let kPrettyCellID = "kPrettyCellID"
class BaseAnchorViewController: BaseViewController {
//定义属性
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = {[weak self] in
//1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
//2.创建UICollectionView
let collectionView = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeadView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
//系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//设置UI
extension BaseAnchorViewController {
override func setupUI() {
// 1.给父类中内容View的引用进行赋值
contentView = collectionView
// 2.添加collectionView
view.addSubview(collectionView)
// 3.调用super.setupUI()
super.setupUI()
}
}
//请求数据
extension BaseAnchorViewController {
func loadData() {
}
}
extension BaseAnchorViewController : UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeadView
headView.group = baseVM.anchorGroups[indexPath.section]
return headView
}
}
// MARK:- 遵守UICollectionView的代理协议
extension BaseAnchorViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc()
}
private func presentShowRoomVc() {
// 1.创建ShowRoomVc
let showRoomVc = RoomShowViewController()
// 2.以Modal方式弹出
present(showRoomVc, animated: true, completion: nil)
}
private func pushNormalRoomVc() {
// 1.创建NormalRoomVc
let normalRoomVc = RoomNormalViewController()
// 2.以Push方式弹出
navigationController?.pushViewController(normalRoomVc, animated: true)
}
}
| mit | 06e99d67cd9e172e98df777c48e14c05 | 33.914063 | 184 | 0.695905 | 5.700255 | false | false | false | false |
luanlzsn/EasyPass | EasyPass/Classes/Mine/Controller/MyCourseController.swift | 1 | 7711 | //
// MyCourseController.swift
// EasyPass
//
// Created by luan on 2017/7/3.
// Copyright © 2017年 luan. All rights reserved.
//
import UIKit
import ObjectMapper
class MyCourseController: AntController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var allCourseBtn: UIButton!
@IBOutlet weak var timeBtn: UIButton!
@IBOutlet weak var tableView: UITableView!
var courseArray = [OrderItemModel]()
var coursePage = 1
var classifyModel: ClassifyModel?//选择的专业
var grade = 0//年级
var name = ""
var timeSort = ""
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "search_icon")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), style: .plain, target: self, action: #selector(searchClick))
weak var weakSelf = self
tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
weakSelf?.getMyCourseByPage(pageNo: 1)
})
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
weakSelf?.getMyCourseByPage(pageNo: weakSelf!.coursePage + 1)
})
getMyCourseByPage(pageNo: 1)
}
func searchClick() {
let alert = UIAlertController(title: "提示", message: "输入搜索内容", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "请输入搜索内容"
}
weak var weakSelf = self
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
let textField = alert.textFields?.first
weakSelf?.name = textField!.text!
weakSelf?.getMyCourseByPage(pageNo: 1)
}))
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
func getMyCourseByPage(pageNo: Int) {
weak var weakSelf = self
var params = ["token":AntManage.userModel!.token!, "orderStatus":1, "pageNo":pageNo, "pageSize":20, "name":name] as [String : Any]
if classifyModel != nil {
params["classifyId"] = classifyModel!.id!
}
if grade != 0 {
params["grade"] = grade
}
if !timeSort.isEmpty {
params["timeSort"] = timeSort
}
AntManage.postRequest(path: "order/getOrderList", params:params , successResult: { (response) in
weakSelf?.coursePage = response["pageNo"] as! Int
if weakSelf?.coursePage == 1 {
weakSelf?.courseArray.removeAll()
}
if let list = response["list"] as? [[String : Any]] {
weakSelf?.courseArray += Mapper<OrderItemModel>().mapArray(JSONArray: list)
}
weakSelf?.tableView.mj_header.endRefreshing()
weakSelf?.tableView.mj_footer.endRefreshing()
weakSelf?.tableView.mj_footer.isHidden = (weakSelf!.coursePage >= (response["totalPage"] as! Int))
weakSelf?.tableView.reloadData()
}, failureResult: {
weakSelf?.tableView.mj_header.endRefreshing()
weakSelf?.tableView.mj_footer.endRefreshing()
})
}
@IBAction func allCourseClick(_ sender: UIButton) {
sender.isSelected = true
let courseMenu = UIStoryboard(name: "Home", bundle: Bundle.main).instantiateViewController(withIdentifier: "CourseMenu") as! CourseMenuController
courseMenu.modalPresentationStyle = .overCurrentContext
courseMenu.modalTransitionStyle = .crossDissolve
courseMenu.selectClassify = classifyModel
courseMenu.selectGrade = grade
weak var weakSelf = self
courseMenu.changeSelect = {(response) -> () in
if let dic = response as? [String : Any] {
weakSelf?.classifyModel = dic["Classify"] as? ClassifyModel
weakSelf?.grade = dic["Grade"] as! Int
} else {
weakSelf?.classifyModel = nil
weakSelf?.grade = 0
}
weakSelf?.getMyCourseByPage(pageNo: 1)
}
present(courseMenu, animated: true, completion: nil)
}
@IBAction func updateTimeClick(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
timeSort = sender.isSelected ? "desc" : "asc"
allCourseBtn.isSelected = false
getMyCourseByPage(pageNo: 1)
}
// MARK: - UITableViewDelegate,UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return courseArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: MyCourseCell = tableView.dequeueReusableCell(withIdentifier: "MyCourseCell", for: indexPath) as! MyCourseCell
let order = courseArray[indexPath.section]
cell.courseImage.sd_setImage(with: URL(string: order.photo ?? ""), placeholderImage: UIImage(named: "default_image"))
if order.courseHourId != nil {
cell.courseName.text = order.lessonPeriod! + " " + order.classHourName!
} else {
cell.courseName.text = order.courseName
}
cell.courseCredit.text = "学分\(order.credit!)"
if order.difficulty != nil {
for image in cell.starArray {
if order.difficulty! > image.tag - 100 {
image.image = UIImage(named: "star_select")
} else {
image.image = UIImage(named: "star_unselect")
}
}
} else {
for image in cell.starArray {
image.image = UIImage(named: "star_unselect")
}
}
if order.tag == 0 {
cell.typeImage.image = UIImage(named: "video_course")
} else if order.tag == 1 {
cell.typeImage.image = UIImage(named: "reservation_course")
} else {
cell.typeImage.image = UIImage(named: "study_group")
}
if order.modifyTime != nil {
cell.updateTime.text = "更新时间 \(order.modifyTime!.components(separatedBy: ".").first ?? "")"
} else {
cell.updateTime.text = "更新时间"
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let courseDetail = UIStoryboard(name: "Home", bundle: Bundle.main).instantiateViewController(withIdentifier: "CourseDetail") as! CourseDetailController
courseDetail.courseId = courseArray[indexPath.section].courseId!
navigationController?.pushViewController(courseDetail, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f84e8ec4bf711c8a4e622b1efa6c51bd | 39.189474 | 214 | 0.620089 | 4.839037 | false | false | false | false |
cweatureapps/SwiftScraper | Pods/Observable-Swift/Observable-Swift/Observable.swift | 2 | 1583 | //
// Observable.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 20/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
/// A struct representing information associated with value change event.
public struct ValueChange<T> {
public let oldValue: T
public let newValue: T
public init(_ o: T, _ n: T) {
oldValue = o
newValue = n
}
}
// Implemented as a struct in order to have desired value and mutability sementics.
/// A struct representing an observable value.
public struct Observable<T>: UnownableObservable {
public typealias ValueType = T
public private(set) var beforeChange = EventReference<ValueChange<T>>()
public private(set) var afterChange = EventReference<ValueChange<T>>()
public var value : T {
willSet { beforeChange.notify(ValueChange(value, newValue)) }
didSet { afterChange.notify(ValueChange(oldValue, value)) }
}
public mutating func unshare(removeSubscriptions: Bool) {
if removeSubscriptions {
beforeChange = EventReference<ValueChange<T>>()
afterChange = EventReference<ValueChange<T>>()
} else {
var beforeEvent = beforeChange.event
beforeEvent.unshare()
beforeChange = EventReference<ValueChange<T>>(event: beforeEvent)
var afterEvent = afterChange.event
afterEvent.unshare()
afterChange = EventReference<ValueChange<T>>(event: afterEvent)
}
}
public init(_ v : T) {
value = v
}
}
| mit | e46c66ee85651897b392aa309fa727ce | 29.921569 | 83 | 0.647432 | 4.651917 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Views/List/ListTableHeaderView.swift | 2 | 2010 | /// Renders a table header view with bottom separator, and meant to be used
/// alongside `ListTableViewCell`.
///
/// This is used in Comments and Notifications as part of the Comments
/// Unification project.
///
class ListTableHeaderView: UITableViewHeaderFooterView, NibReusable {
// MARK: IBOutlets
@IBOutlet private weak var separatorsView: SeparatorsView!
@IBOutlet private weak var titleLabel: UILabel!
// MARK: Properties
/// Added to provide objc support, since NibReusable protocol methods aren't accessible from objc.
/// This should be removed when the caller is rewritten in Swift.
@objc static let reuseIdentifier = defaultReuseID
@objc static let estimatedRowHeight = 26
@objc var title: String? {
get {
titleLabel.text
}
set {
titleLabel.text = newValue?.localizedUppercase ?? String()
accessibilityLabel = newValue
}
}
// MARK: Initialization
override func awakeFromNib() {
super.awakeFromNib()
// Hide text label to prevent values being shown due to interaction with
// NSFetchedResultsController. By default, the results controller assigns the
// value of sectionNameKeyPath to UITableHeaderFooterView's textLabel.
textLabel?.isHidden = true
// Set background color.
// Note that we need to set it through `backgroundView`, or Xcode will lash out a warning.
backgroundView = {
let view = UIView(frame: self.bounds)
view.backgroundColor = Style.sectionHeaderBackgroundColor
return view
}()
// configure title label
titleLabel.font = Style.sectionHeaderFont
titleLabel.textColor = Style.sectionHeaderTitleColor
// configure separators view
separatorsView.bottomColor = Style.separatorColor
separatorsView.bottomVisible = true
}
// MARK: Convenience
private typealias Style = WPStyleGuide.List
}
| gpl-2.0 | 2014a13d3192361ed27323c5effda1d0 | 31.95082 | 102 | 0.673632 | 5.646067 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.