repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Henryforce/KRActivityIndicatorView | refs/heads/master | KRActivityIndicatorView/KRActivityIndicatorAnimationOrbit.swift | mit | 1 | //
// KRActivityIndicatorAnimationOrbit.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
class KRActivityIndicatorAnimationOrbit: KRActivityIndicatorAnimationDelegate {
let duration: CFTimeInterval = 1.9
let satelliteCoreRatio: CGFloat = 0.25
let distanceRatio:CGFloat = 1.5 // distance / core size
var coreSize: CGFloat = 0
var satelliteSize: CGFloat = 0
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
coreSize = size.width / (1 + satelliteCoreRatio + distanceRatio)
satelliteSize = coreSize * satelliteCoreRatio
ring1InLayer(layer, size: size, color: color)
ring2InLayer(layer, size: size, color: color)
coreInLayer(layer, size: size, color: color)
satelliteInLayer(layer, size: size, color: color)
}
func ring1InLayer(_ layer: CALayer, size: CGSize, color: NSColor) {
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.45, 0.45, 1]
scaleAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
scaleAnimation.values = [0, 0, 1.3, 2]
scaleAnimation.duration = duration
// Opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
let timingFunction = CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1)
opacityAnimation.keyTimes = [0, 0.45, 1]
scaleAnimation.timingFunctions = [CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear), timingFunction]
opacityAnimation.values = [0.8, 0.8, 0]
opacityAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: coreSize, height: coreSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2,
y: (layer.bounds.size.height - coreSize) / 2,
width: coreSize,
height: coreSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
func ring2InLayer(_ layer: CALayer, size: CGSize, color: NSColor) {
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.55, 0.55, 1]
scaleAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
scaleAnimation.values = [0, 0, 1.3, 2.1]
scaleAnimation.duration = duration
// Opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
let timingFunction = CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1)
opacityAnimation.keyTimes = [0, 0.55, 0.65, 1]
scaleAnimation.timingFunctions = [CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear), timingFunction]
opacityAnimation.values = [0.7, 0.7, 0, 0]
opacityAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: coreSize, height: coreSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2,
y: (layer.bounds.size.height - coreSize) / 2,
width: coreSize,
height: coreSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
func coreInLayer(_ layer: CALayer, size: CGSize, color: NSColor) {
let inTimingFunction = CAMediaTimingFunction(controlPoints: 0.7, 0, 1, 0.5)
let outTimingFunction = CAMediaTimingFunction(controlPoints: 0, 0.7, 0.5, 1)
let standByTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.45, 0.55, 1]
scaleAnimation.timingFunctions = [inTimingFunction, standByTimingFunction, outTimingFunction];
scaleAnimation.values = [1, 1.3, 1.3, 1]
scaleAnimation.duration = duration
scaleAnimation.repeatCount = HUGE
scaleAnimation.isRemovedOnCompletion = false
// Draw circle
let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: coreSize, height: coreSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - coreSize) / 2,
y: (layer.bounds.size.height - coreSize) / 2,
width: coreSize,
height: coreSize)
circle.frame = frame
circle.add(scaleAnimation, forKey: "animation")
layer.addSublayer(circle)
}
func satelliteInLayer(_ layer: CALayer, size: CGSize, color: NSColor) {
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "position")
let arcBezier = NSBezierPath()
arcBezier.appendArc(withCenter: CGPoint(x: layer.bounds.midX, y:layer.bounds.midY), radius: (size.width - satelliteSize) / 2, startAngle: CGFloat(Float.pi) * 1.5, endAngle: CGFloat(Float.pi) * 1.5 + 4 * CGFloat(Float.pi), clockwise: true)
rotateAnimation.path = CGPathFromNSBezierPath(nsPath: arcBezier)
/*rotateAnimation.path = NSBezierPath(arcCenter: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY),
radius: (size.width - satelliteSize) / 2,
startAngle: CGFloat(M_PI) * 1.5,
endAngle: CGFloat(M_PI) * 1.5 + 4 * CGFloat(M_PI),
clockwise: true).cgPath*/
rotateAnimation.duration = duration * 2
rotateAnimation.repeatCount = HUGE
rotateAnimation.isRemovedOnCompletion = false
// Draw circle
let circle = KRActivityIndicatorShape.circle.layerWith(size: CGSize(width: satelliteSize, height: satelliteSize), color: color)
let frame = CGRect(x: 0, y: 0, width: satelliteSize, height: satelliteSize)
circle.frame = frame
circle.add(rotateAnimation, forKey: "animation")
layer.addSublayer(circle)
}
func CGPathFromNSBezierPath(nsPath: NSBezierPath) -> CGPath! {
let path = CGMutablePath()
var points = [CGPoint](repeating: .zero, count: 3)
for i in 0 ..< nsPath.elementCount {
let type = nsPath.element(at: i, associatedPoints: &points)
switch type {
case .moveTo: path.move(to: CGPoint(x: points[0].x, y: points[0].y) )
case .lineTo: path.addLine(to: CGPoint(x: points[0].x, y: points[0].y) )
case .curveTo: path.addCurve( to: CGPoint(x: points[2].x, y: points[2].y),
control1: CGPoint(x: points[0].x, y: points[0].y),
control2: CGPoint(x: points[1].x, y: points[1].y) )
case .closePath: path.closeSubpath()
@unknown default: break
}
}
return path
}
}
| 09a986214ed77cba93a73871d0b63105 | 46.694301 | 246 | 0.630418 | false | false | false | false |
fgengine/quickly | refs/heads/master | Quickly/Compositions/Standart/QTitleDetailShapeComposition.swift | mit | 1 | //
// Quickly
//
open class QTitleDetailShapeComposable : QComposable {
public var titleStyle: QLabelStyleSheet
public var titleSpacing: CGFloat
public var detailStyle: QLabelStyleSheet
public var shapeModel: QShapeView.Model
public var shapeWidth: CGFloat
public var shapeSpacing: CGFloat
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
titleStyle: QLabelStyleSheet,
titleSpacing: CGFloat = 4,
detailStyle: QLabelStyleSheet,
shapeModel: QShapeView.Model,
shapeWidth: CGFloat = 16,
shapeSpacing: CGFloat = 4
) {
self.titleStyle = titleStyle
self.titleSpacing = titleSpacing
self.detailStyle = detailStyle
self.shapeModel = shapeModel
self.shapeWidth = shapeWidth
self.shapeSpacing = shapeSpacing
super.init(edgeInsets: edgeInsets)
}
}
open class QTitleDetailShapeComposition< Composable: QTitleDetailShapeComposable > : QComposition< Composable > {
public private(set) lazy var titleView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(
horizontal: UILayoutPriority(rawValue: 252),
vertical: UILayoutPriority(rawValue: 252)
)
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var detailView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var shapeView: QShapeView = {
let view = QShapeView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _titleSpacing: CGFloat?
private var _shapeWidth: CGFloat?
private var _shapeSpacing: CGFloat?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
private var _shapeConstraints: [NSLayoutConstraint] = [] {
willSet { self.shapeView.removeConstraints(self._shapeConstraints) }
didSet { self.shapeView.addConstraints(self._shapeConstraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right)
let titleTextSize = composable.titleStyle.size(width: availableWidth - (composable.shapeWidth + composable.shapeSpacing))
let detailTextSize = composable.detailStyle.size(width: availableWidth - (composable.shapeWidth + composable.shapeSpacing))
let shapeSize = composable.shapeModel.size
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + max(titleTextSize.height + composable.titleSpacing + detailTextSize.height, shapeSize.height) + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets || self._titleSpacing != composable.titleSpacing || self._shapeSpacing != composable.shapeSpacing {
self._edgeInsets = composable.edgeInsets
self._titleSpacing = composable.titleSpacing
self._shapeSpacing = composable.shapeSpacing
self._constraints = [
self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.titleView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing),
self.detailView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.shapeView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.shapeView.leadingLayout == self.titleView.trailingLayout.offset(composable.shapeSpacing),
self.shapeView.leadingLayout == self.detailView.trailingLayout.offset(composable.shapeSpacing),
self.shapeView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.shapeView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom)
]
}
if self._shapeWidth != composable.shapeWidth {
self._shapeWidth = composable.shapeWidth
self._shapeConstraints = [
self.shapeView.widthLayout == composable.shapeWidth
]
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.titleView.apply(composable.titleStyle)
self.detailView.apply(composable.detailStyle)
self.shapeView.model = composable.shapeModel
}
}
| e2ef633e719519d8113cbd17b13b5aad | 44.652542 | 172 | 0.691108 | false | false | false | false |
levantAJ/ResearchKit | refs/heads/master | TestVoiceActions/UIImage.swift | mit | 1 | //
// UIImage.swift
// TestVoiceActions
//
// Created by Le Tai on 8/30/16.
// Copyright © 2016 Snowball. All rights reserved.
//
import UIKit
extension UIImage {
class func imageFromColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRectMake(0.0, 0.0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func resizeImage(newWidth newWidth: CGFloat) -> UIImage {
let scale = newWidth / size.width
let newHeight = size.height * scale
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
func resizeImage(newHeight newHeight: CGFloat) -> UIImage {
let scale = newHeight / size.height
let newWidth = size.width * scale
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| 2199b5b2d0216c5ace06485d0dcf3a3e | 37.295455 | 91 | 0.691395 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | Habitica Database/Habitica Database/Models/Content/RealmCustomization.swift | gpl-3.0 | 1 | //
// RealmCustomization.swift
// Habitica Database
//
// Created by Phillip Thelen on 20.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmCustomization: Object, CustomizationProtocol {
@objc dynamic var combinedKey: String?
@objc dynamic var key: String?
@objc dynamic var type: String?
@objc dynamic var group: String?
@objc dynamic var price: Float = 0
var set: CustomizationSetProtocol? {
get {
return realmSet
}
set {
if let newSet = newValue as? RealmCustomizationSet {
realmSet = newSet
} else if let newSet = newValue {
realmSet = RealmCustomizationSet(newSet)
}
}
}
@objc dynamic var realmSet: RealmCustomizationSet?
override static func primaryKey() -> String {
return "combinedKey"
}
convenience init(_ customizationProtocol: CustomizationProtocol) {
self.init()
key = customizationProtocol.key
type = customizationProtocol.type
group = customizationProtocol.group
combinedKey = (key ?? "") + (type ?? "") + (group ?? "")
price = customizationProtocol.price
set = customizationProtocol.set
}
}
| c2416b7e7740e1b80f88ed3cfbe936af | 27.934783 | 70 | 0.624343 | false | false | false | false |
hughbe/phone-number-picker | refs/heads/master | src/View/PNPMenuDisabledTextField.swift | mit | 1 | //
// PNPMenuDisabledTextField.swift
// UIComponents
//
// Created by Hugh Bellamy on 05/09/2015.
// Copyright (c) 2015 Hugh Bellamy. All rights reserved.
//
import UIKit
@IBDesignable
internal class PNPMenuDisabledTextField: UITextField {
@IBInspectable private var menuEnabled: Bool = false
@IBInspectable private var canPositionCaretAtStart: Bool = true
@IBInspectable private var editingRectDeltaY: CGFloat = 0
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return menuEnabled
}
override func caretRect(for position: UITextPosition) -> CGRect {
if position == beginningOfDocument && !canPositionCaretAtStart {
return super.caretRect(for: self.position(from: position, offset: 1)!)
}
return super.caretRect(for: position)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 0, dy: editingRectDeltaY)
}
}
| c9643fb3d3a8aa343b7f08946d11cad1 | 31.096774 | 89 | 0.694472 | false | false | false | false |
huangxiangdan/XLPagerTabStrip | refs/heads/master | Example/Example/NavButtonBarExampleViewController.swift | mit | 2 | // NavButtonBarExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XLPagerTabStrip
class NavButtonBarExampleViewController: ButtonBarPagerTabStripViewController {
var isReload = false
override func viewDidLoad() {
// set up style before super view did load is executed
settings.style.buttonBarBackgroundColor = .clearColor()
settings.style.selectedBarBackgroundColor = .orangeColor()
//-
super.viewDidLoad()
buttonBarView.removeFromSuperview()
navigationController?.navigationBar.addSubview(buttonBarView)
changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
guard changeCurrentIndex == true else { return }
oldCell?.label.textColor = UIColor(white: 1, alpha: 0.6)
newCell?.label.textColor = .whiteColor()
if animated {
UIView.animateWithDuration(0.1, animations: { () -> Void in
newCell?.transform = CGAffineTransformMakeScale(1.0, 1.0)
oldCell?.transform = CGAffineTransformMakeScale(0.8, 0.8)
})
}
else {
newCell?.transform = CGAffineTransformMakeScale(1.0, 1.0)
oldCell?.transform = CGAffineTransformMakeScale(0.8, 0.8)
}
}
}
// MARK: - PagerTabStripDataSource
override func viewControllersForPagerTabStrip(pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let child_1 = TableChildExampleViewController(style: .Plain, itemInfo: "Table View")
let child_2 = ChildExampleViewController(itemInfo: "View")
let child_3 = TableChildExampleViewController(style: .Grouped, itemInfo: "Table View 2")
let child_4 = ChildExampleViewController(itemInfo: "View 1")
let child_5 = TableChildExampleViewController(style: .Plain, itemInfo: "Table View 3")
let child_6 = ChildExampleViewController(itemInfo: "View 2")
let child_7 = TableChildExampleViewController(style: .Grouped, itemInfo: "Table View 4")
let child_8 = ChildExampleViewController(itemInfo: "View 3")
guard isReload else {
return [child_1, child_2, child_3, child_4, child_5, child_6, child_7, child_8]
}
var childViewControllers = [child_1, child_2, child_3, child_4, child_6, child_7, child_8]
for (index, _) in childViewControllers.enumerate(){
let nElements = childViewControllers.count - index
let n = (Int(arc4random()) % nElements) + index
if n != index{
swap(&childViewControllers[index], &childViewControllers[n])
}
}
let nItems = 1 + (rand() % 8)
return Array(childViewControllers.prefix(Int(nItems)))
}
override func reloadPagerTabStripView() {
isReload = true
if rand() % 2 == 0 {
pagerBehaviour = .Progressive(skipIntermediateViewControllers: rand() % 2 == 0 , elasticIndicatorLimit: rand() % 2 == 0 )
}
else {
pagerBehaviour = .Common(skipIntermediateViewControllers: rand() % 2 == 0)
}
super.reloadPagerTabStripView()
}
override func configureCell(cell: ButtonBarViewCell, indicatorInfo: IndicatorInfo) {
super.configureCell(cell, indicatorInfo: indicatorInfo)
cell.backgroundColor = .clearColor()
}
}
| ef4a13a356aaa9b4bdf7460c64fb8b05 | 45.259615 | 182 | 0.66348 | false | false | false | false |
seguemodev/Meducated-Ninja | refs/heads/master | iOS/Zippy/CabinetPickerViewController.swift | cc0-1.0 | 1 | //
// CabinetPickerViewController.swift
// Zippy
//
// Created by Geoffrey Bender on 6/19/15.
// Copyright (c) 2015 Segue Technologies, Inc. All rights reserved.
//
import UIKit
class CabinetPickerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
// MARK: - Interface Outlets
@IBOutlet weak var tableView: UITableView!
// MARK: - Variables
let userDefaults = NSUserDefaults.standardUserDefaults()
var cabinetArray = [String]()
var medication: Medication!
var selectedCabinet = ""
// MARK: - Lifecycle Methods
// Each time view appears
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
// For dynamic table row height
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
var leftBarButton = UIBarButtonItem(title:"Cancel", style:UIBarButtonItemStyle.Plain, target:self, action:"cancel")
self.navigationItem.leftBarButtonItem = leftBarButton
var rightBarButton = UIBarButtonItem(title:"Save", style:UIBarButtonItemStyle.Plain, target:self, action:"saveMedicationToCabinet:")
self.navigationItem.rightBarButtonItem = rightBarButton
var normalButtonBackground = UIImage(named:"BlueButtonBackground")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 10, 0, 10))
self.navigationItem.leftBarButtonItem!.setBackgroundImage(normalButtonBackground, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
self.navigationItem.rightBarButtonItem!.setBackgroundImage(normalButtonBackground, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
var pressedButtonBackground = UIImage(named:"GreenButtonBackground")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 10, 0, 10))
self.navigationItem.leftBarButtonItem!.setBackgroundImage(pressedButtonBackground, forState: UIControlState.Highlighted, barMetrics: UIBarMetrics.Default)
self.navigationItem.rightBarButtonItem!.setBackgroundImage(pressedButtonBackground, forState: UIControlState.Highlighted, barMetrics: UIBarMetrics.Default)
if let font = UIFont(name:"RobotoSlab-Bold", size:14.0)
{
self.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal)
self.navigationItem.rightBarButtonItem!.setTitleTextAttributes([NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal)
}
// If we have saved medicine cabinets
if self.userDefaults.valueForKey("cabinetArray") != nil
{
// Set saved cabinets to local array
self.cabinetArray = self.userDefaults.valueForKey("cabinetArray") as! [String]
}
}
// MARK: - Table View Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.cabinetArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cabinetCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = self.cabinetArray[indexPath.row].capitalizedString
if self.cabinetArray[indexPath.row] == self.selectedCabinet
{
cell.accessoryView = UIImageView(image:UIImage(named:"CheckedButton"))
}
else
{
cell.accessoryView = UIImageView(image:UIImage(named:"UncheckedButton"))
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
// Set selected cabinet
self.selectedCabinet = self.cabinetArray[indexPath.row]
// Reload the table with the new cabinet (using this method for proper autoheight calculation on table cells)
self.tableView.reloadSections(NSIndexSet(indexesInRange:NSMakeRange(0, self.tableView.numberOfSections())), withRowAnimation:.None)
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Middle, animated:true)
}
// MARK: - My Methods
// Dismiss view when cancel button is clicked
func cancel()
{
self.navigationController?.popViewControllerAnimated(true)
}
// Show prompt for user to create new medicine cabinet
@IBAction func createNewCabinet(sender: AnyObject)
{
// Create the alert controller
var alert = UIAlertController(title:"Create Medicine Cabinet", message:nil, preferredStyle:.Alert)
// Add the text field
alert.addTextFieldWithConfigurationHandler({(textField) -> Void in
textField.autocapitalizationType = UITextAutocapitalizationType.Words
textField.keyboardAppearance = UIKeyboardAppearance.Dark
textField.text = ""
})
// Add a cancel button
alert.addAction(UIAlertAction(title:"Cancel", style:.Default, handler:nil))
// Add a create button with callback
alert.addAction(UIAlertAction(title:"Create", style:.Default, handler:{(action) -> Void in
// Get text field from alert controller
let textField = alert.textFields![0] as! UITextField
// Complete creating the tag
self.completeCreateNewCabinet(textField.text)
}))
// Present the alert view so user can enter the category name
self.presentViewController(alert, animated:true, completion:nil)
}
// Completion handler for new cabinet creation
func completeCreateNewCabinet(fieldText:String)
{
// Make sure user entered text
if fieldText.isEmpty
{
// Alert user that the cabinet name is required
var foundAlert = UIAlertController(title:"Attention Required", message:"Please enter a cabinet name.", preferredStyle:UIAlertControllerStyle.Alert)
foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil))
self.presentViewController(foundAlert, animated:true, completion:nil)
}
else
{
// Trim string
var cabinet = fieldText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Set variable to track number of duplicates encountered
var duplicates = 0
// Set variable to track highest duplicate label
var highestNumber = 0
// Loop our cabinet array to check for duplicates
for item in self.cabinetArray
{
// Get the cabinet name without the parentheses
let rawStringArray = item.componentsSeparatedByString("(")
// Trim the string to eliminate whitespace
let trimmedRawString = rawStringArray[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// If our entered text matches a cabinet in our array
if cabinet.lowercaseString == trimmedRawString
{
// Increase duplicate count
duplicates++
// If our raw string array has more then one item, then it had parentheses
if rawStringArray.count > 1
{
// Get its number
let labelNumber = rawStringArray[1].componentsSeparatedByString(")")[0].toInt()
// Track the highest label number
if labelNumber > highestNumber
{
highestNumber = labelNumber!
}
}
if highestNumber >= duplicates
{
duplicates = highestNumber + 1
}
}
}
// If we found duplicates
if duplicates > 0
{
// Modify cabinet string
let modifiedCabinet = "\(cabinet.lowercaseString) (\(duplicates))"
// Append the modified string to our array
self.cabinetArray.insert(modifiedCabinet, atIndex:0)
}
else
{
// Append the string to our array
self.cabinetArray.insert(cabinet.lowercaseString, atIndex:0)
}
// Set selected cabinet to newly created cabinet
self.selectedCabinet = self.cabinetArray.first!
// Scroll to first row
self.tableView.setContentOffset(CGPointZero, animated:true)
// Reload the table with the new cabinet (using this method for proper autoheight calculation on table cells)
self.tableView.reloadSections(NSIndexSet(indexesInRange:NSMakeRange(0, self.tableView.numberOfSections())), withRowAnimation:.None)
let medToMove = self.cabinetArray.first
self.cabinetArray.removeAtIndex(0)
self.cabinetArray.append(medToMove!)
// Save medicine cabinet array to persistent store
self.userDefaults.setValue(self.cabinetArray, forKey: "cabinetArray")
// Automatically save the medication to the new cabinet
self.saveMedicationToCabinet(self)
}
}
// Save the medication to the selected medicine cabinet
@IBAction func saveMedicationToCabinet(sender: AnyObject)
{
// Make sure user selected a cabinet
if self.selectedCabinet.isEmpty
{
// Alert user that the cabinet name is required
var foundAlert = UIAlertController(title:"Attention Required", message:"Please choose a cabinet to save to.", preferredStyle:UIAlertControllerStyle.Alert)
foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil))
self.presentViewController(foundAlert, animated:true, completion:nil)
}
else
{
// Set the medication object's medicine cabinet to selected picker row value
self.medication.medicineCabinet = self.selectedCabinet
// Create empty saved medication array
var savedMedications = [Medication]()
// If we have a stored medication array, then load the contents into our empty array
if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey("medicationArray") as? NSData
{
savedMedications = NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as! [Medication]
}
// Add saved medication to our array
savedMedications.append(self.medication)
// Save the modified medication array
let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(savedMedications as NSArray)
self.userDefaults.setObject(archivedObject, forKey:"medicationArray")
self.userDefaults.synchronize()
// Alert user that the medication has been saved
let indexPath = self.tableView.indexPathForSelectedRow()
// Create confirmation
var foundAlert = UIAlertController(title:"Success", message:"You have successfully saved this medication to \(self.selectedCabinet.capitalizedString).", preferredStyle:UIAlertControllerStyle.Alert)
// Create handler for OK button
foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:{(action) -> Void in
// Dismiss the view
self.navigationController?.popViewControllerAnimated(true)
}))
// Show confirmation
self.presentViewController(foundAlert, animated:true, completion:nil)
}
}
}
| 98d908c828b6db8daf462bb09226ae94 | 43.227273 | 209 | 0.63167 | false | false | false | false |
lovehhf/edx-app-ios | refs/heads/master | Source/CourseContentPageViewController.swift | apache-2.0 | 1 | //
// CourseContentPageViewController.swift
// edX
//
// Created by Akiva Leffert on 5/1/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
public protocol CourseContentPageViewControllerDelegate : class {
func courseContentPageViewController(controller : CourseContentPageViewController, enteredItemInGroup blockID : CourseBlockID)
}
// Container for scrolling horizontally between different screens of course content
// TODO: Styles, full vs video mode
public class CourseContentPageViewController : UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, CourseBlockViewController, CourseOutlineModeControllerDelegate, ContainedNavigationController, OpenOnWebControllerDelegate {
public class Environment : NSObject {
private let analytics : OEXAnalytics?
private let dataManager : DataManager
private weak var router : OEXRouter?
private let styles : OEXStyles?
public init(analytics : OEXAnalytics?, dataManager : DataManager, router : OEXRouter, styles : OEXStyles?) {
self.analytics = analytics
self.dataManager = dataManager
self.router = router
self.styles = styles
}
}
private let initialLoadController : LoadStateViewController
private let environment : Environment
private var initialChildID : CourseBlockID?
public private(set) var blockID : CourseBlockID?
public var courseID : String {
return courseQuerier.courseID
}
private var openURLButtonItem : UIBarButtonItem?
private var contentLoader = BackedStream<ListCursor<CourseOutlineQuerier.GroupItem>>()
private let courseQuerier : CourseOutlineQuerier
private let modeController : CourseOutlineModeController
private lazy var webController : OpenOnWebController = OpenOnWebController(delegate: self)
weak var navigationDelegate : CourseContentPageViewControllerDelegate?
///Manages the caching of the viewControllers that have been viewed atleast once.
///Removes the ViewControllers from memory in case of a memory warning
private let cacheManager : BlockViewControllerCacheManager
public init(environment : Environment, courseID : CourseBlockID, rootID : CourseBlockID?, initialChildID: CourseBlockID? = nil) {
self.environment = environment
self.blockID = rootID
self.initialChildID = initialChildID
courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID)
modeController = environment.dataManager.courseDataManager.freshOutlineModeController()
initialLoadController = LoadStateViewController(styles: environment.styles)
cacheManager = BlockViewControllerCacheManager()
super.init(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
self.setViewControllers([initialLoadController], direction: .Forward, animated: false, completion: nil)
modeController.delegate = self
self.dataSource = self
self.delegate = self
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = barButtonFixedSpaceWidth
navigationItem.rightBarButtonItems = [webController.barButtonItem, fixedSpace, modeController.barItem]
addStreamListeners()
}
public required init(coder aDecoder: NSCoder) {
// required by the compiler because UIViewController implements NSCoding,
// but we don't actually want to serialize these things
fatalError("init(coder:) has not been implemented")
}
public override func viewWillAppear(animated : Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(false, animated: animated)
loadIfNecessary()
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setToolbarHidden(true, animated: animated)
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = self.environment.styles?.standardBackgroundColor()
}
private func addStreamListeners() {
contentLoader.listen(self,
success : {[weak self] cursor -> Void in
if let owner = self,
controller = owner.controllerForBlock(cursor.current.block)
{
owner.setViewControllers([controller], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
self?.updateNavigationForEnteredController(controller)
}
else {
self?.initialLoadController.state = LoadState.failed(error: NSError.oex_courseContentLoadError())
self?.updateNavigationBars()
}
return
}, failure : {[weak self] error in
self?.initialLoadController.state = LoadState.failed(error: NSError.oex_courseContentLoadError())
}
)
}
private func loadIfNecessary() {
if !contentLoader.hasBacking {
let stream = courseQuerier.spanningCursorForBlockWithID(blockID, initialChildID: initialChildID, forMode: modeController.currentMode)
contentLoader.backWithStream(stream.firstSuccess())
}
}
private func toolbarItemWithGroupItem(item : CourseOutlineQuerier.GroupItem, adjacentGroup : CourseBlock?, direction : DetailToolbarButton.Direction, enabled : Bool) -> UIBarButtonItem {
let titleText : String
let moveDirection : UIPageViewControllerNavigationDirection
let isGroup = adjacentGroup != nil
switch direction {
case .Next:
titleText = isGroup ? OEXLocalizedString("NEXT_UNIT", nil) : OEXLocalizedString("NEXT", nil)
moveDirection = .Forward
case .Prev:
titleText = isGroup ? OEXLocalizedString("PREVIOUS_UNIT", nil) : OEXLocalizedString("PREVIOUS", nil)
moveDirection = .Reverse
}
let destinationText = adjacentGroup?.name
let view = DetailToolbarButton(direction: direction, titleText: titleText, destinationText: destinationText) {[weak self] in
self?.moveInDirection(moveDirection)
}
view.sizeToFit()
let barButtonItem = UIBarButtonItem(customView: view)
barButtonItem.enabled = enabled
view.button.enabled = enabled
return barButtonItem
}
private func openOnWebInfoForBlock(block : CourseBlock) -> OpenOnWebController.Info {
return OpenOnWebController.Info(courseID: courseID, blockID: block.blockID, supported: block.displayType.isUnknown, URL: block.webURL)
}
private func updateNavigationBars() {
if let cursor = contentLoader.value {
let item = cursor.current
// only animate change if we haven't set a title yet, so the initial set happens without
// animation to make the push transition work right
let actions : () -> Void = {
self.navigationItem.title = item.block.name ?? ""
self.webController.info = self.openOnWebInfoForBlock(item.block)
}
if let navigationBar = navigationController?.navigationBar where navigationItem.title != nil {
let animated = navigationItem.title != nil
UIView.transitionWithView(navigationBar,
duration: 0.3, options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: actions, completion: nil)
}
else {
actions()
}
let prevItem = toolbarItemWithGroupItem(item, adjacentGroup: item.prevGroup, direction: .Prev, enabled: cursor.hasPrev)
let nextItem = toolbarItemWithGroupItem(item, adjacentGroup: item.nextGroup, direction: .Next, enabled: cursor.hasNext)
self.setToolbarItems(
[
prevItem,
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
nextItem
], animated : true)
}
else {
self.toolbarItems = []
}
}
// MARK: Paging
private func siblingWithDirection(direction : UIPageViewControllerNavigationDirection, fromController viewController: UIViewController) -> UIViewController? {
let item : CourseOutlineQuerier.GroupItem?
switch direction {
case .Forward:
item = contentLoader.value?.peekNext()
case .Reverse:
item = contentLoader.value?.peekPrev()
}
return item.flatMap {
controllerForBlock($0.block)
}
}
private func updateNavigationForEnteredController(controller : UIViewController?) {
if let blockController = controller as? CourseBlockViewController,
cursor = contentLoader.value
{
cursor.updateCurrentToItemMatching {
blockController.blockID == $0.block.blockID
}
environment.analytics?.trackViewedComponentForCourseWithID(courseID, blockID: cursor.current.block.blockID)
self.navigationDelegate?.courseContentPageViewController(self, enteredItemInGroup: cursor.current.parent)
}
self.updateNavigationBars()
}
private func moveInDirection(direction : UIPageViewControllerNavigationDirection) {
(viewControllers.first as? UIViewController).flatMap {controller -> UIViewController? in
self.siblingWithDirection(direction, fromController: controller)
}.map { nextController -> Void in
self.setViewControllers([nextController], direction: direction, animated: true, completion: nil)
self.updateNavigationForEnteredController(nextController)
return
}
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
return siblingWithDirection(.Reverse, fromController: viewController)
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
return siblingWithDirection(.Forward, fromController: viewController)
}
public func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [AnyObject], transitionCompleted completed: Bool) {
self.updateNavigationForEnteredController(pageViewController.viewControllers.first as? UIViewController)
}
// MARK: Course Outline Mode
public func courseOutlineModeChanged(courseMode: CourseOutlineMode) {
// If we change mode we want to pop the screen since it may no longer make sense.
// It's easy if we're at the top of the controller stack, but we need to be careful if we're not
if self.navigationController?.topViewController == self {
self.navigationController?.popViewControllerAnimated(true)
}
else {
self.navigationController?.viewControllers = self.navigationController?.viewControllers.filter {
return ($0 as! UIViewController) != self
}
}
}
public func viewControllerForCourseOutlineModeChange() -> UIViewController {
return self
}
func controllerForBlock(block : CourseBlock) -> UIViewController? {
let blockViewController : UIViewController?
if let cachedViewController = self.cacheManager.getCachedViewControllerForBlockID(block.blockID) {
blockViewController = cachedViewController
}
else {
// Instantiate a new VC from the router if not found in cache already
if let viewController = self.environment.router?.controllerForBlock(block, courseID: courseQuerier.courseID) {
cacheManager.addToCache(viewController, blockID: block.blockID)
blockViewController = viewController
}
else {
blockViewController = UIViewController()
assert(false, "Couldn't instantiate viewController for Block \(block)")
}
}
if let viewController = blockViewController {
preloadAdjacentViewControllersFromViewController(viewController)
return viewController
}
else {
assert(false, "Couldn't instantiate viewController for Block \(block)")
return nil
}
}
override public func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle(barStyle : self.navigationController?.navigationBar.barStyle)
}
override public func childViewControllerForStatusBarStyle() -> UIViewController? {
if let controller = viewControllers.last as? ContainedNavigationController as? UIViewController {
return controller
}
else {
return super.childViewControllerForStatusBarStyle()
}
}
override public func childViewControllerForStatusBarHidden() -> UIViewController? {
if let controller = viewControllers.last as? ContainedNavigationController as? UIViewController {
return controller
}
else {
return super.childViewControllerForStatusBarHidden()
}
}
private func preloadBlock(block : CourseBlock) {
if cacheManager.cacheHitForBlockID(block.blockID) {
return
}
if let controller = self.environment.router?.controllerForBlock(block, courseID: courseQuerier.courseID) {
if let preloadable = controller as? PreloadableBlockController {
preloadable.preloadData()
}
cacheManager.addToCache(controller, blockID: block.blockID)
}
}
private func preloadAdjacentViewControllersFromViewController(controller : UIViewController) {
if let block = contentLoader.value?.peekNext()?.block {
preloadBlock(block)
}
if let block = contentLoader.value?.peekPrev()?.block {
preloadBlock(block)
}
}
public func presentationControllerForOpenOnWebController(controller: OpenOnWebController) -> UIViewController {
return self
}
}
// MARK: Testing
extension CourseContentPageViewController {
public func t_blockIDForCurrentViewController() -> Stream<CourseBlockID> {
return contentLoader.flatMap {blocks in
let controller = (self.viewControllers.first as? CourseBlockViewController)
let blockID = controller?.blockID
let result = blockID.toResult()
return result
}
}
public var t_prevButtonEnabled : Bool {
return (self.toolbarItems![0] as! UIBarButtonItem).enabled
}
public var t_nextButtonEnabled : Bool {
return (self.toolbarItems![2] as! UIBarButtonItem).enabled
}
public func t_goForward() {
moveInDirection(.Forward)
}
public func t_goBackward() {
moveInDirection(.Reverse)
}
public var t_isRightBarButtonEnabled : Bool {
return self.webController.barButtonItem.enabled
}
} | 546923da66bbd8f3b802b52ba0da6fd7 | 40.148052 | 255 | 0.66391 | false | false | false | false |
dmitrykurochka/CLTokenInputView-Swift | refs/heads/master | CLTokenInputView-Swift/Classes/CLToken.swift | mit | 1 | //
// CLToken.swift
// CLTokenInputView
//
// Created by Dmitry Kurochka on 23.08.17.
// Copyright © 2017 Prezentor. All rights reserved.
//
import Foundation
struct CLToken {
let displayText: String
let context: AnyObject?
}
extension CLToken: Equatable {
static func == (lhs: CLToken, rhs: CLToken) -> Bool {
if lhs.displayText == rhs.displayText, lhs.context?.isEqual(rhs.context) == true {
return true
}
return false
}
}
| 13a19b403a095642402cf48268d4634b | 18.913043 | 86 | 0.670306 | false | false | false | false |
DarrenKong/firefox-ios | refs/heads/master | Client/Frontend/Browser/Authenticator.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import Deferred
private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Label for Cancel button")
private let LogInButtonTitle = NSLocalizedString("Log in", comment: "Authentication prompt log in button")
private let log = Logger.browserLogger
class Authenticator {
fileprivate static let MaxAuthenticationAttempts = 3
static func handleAuthRequest(_ viewController: UIViewController, challenge: URLAuthenticationChallenge, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> {
// If there have already been too many login attempts, we'll just fail.
if challenge.previousFailureCount >= Authenticator.MaxAuthenticationAttempts {
return deferMaybe(LoginDataError(description: "Too many attempts to open site"))
}
var credential = challenge.proposedCredential
// If we were passed an initial set of credentials from iOS, try and use them.
if let proposed = credential {
if !(proposed.user?.isEmpty ?? true) {
if challenge.previousFailureCount == 0 {
return deferMaybe(Login.createWithCredential(credential!, protectionSpace: challenge.protectionSpace))
}
} else {
credential = nil
}
}
// If we have some credentials, we'll show a prompt with them.
if let credential = credential {
return promptForUsernamePassword(viewController, credentials: credential, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper)
}
// Otherwise, try to look them up and show the prompt.
if let loginsHelper = loginsHelper {
return findMatchingCredentialsForChallenge(challenge, fromLoginsProvider: loginsHelper.logins).bindQueue(.main) { result in
guard let credentials = result.successValue else {
return deferMaybe(result.failureValue ?? LoginDataError(description: "Unknown error when finding credentials"))
}
return self.promptForUsernamePassword(viewController, credentials: credentials, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper)
}
}
// No credentials, so show an empty prompt.
return self.promptForUsernamePassword(viewController, credentials: nil, protectionSpace: challenge.protectionSpace, loginsHelper: nil)
}
static func findMatchingCredentialsForChallenge(_ challenge: URLAuthenticationChallenge, fromLoginsProvider loginsProvider: BrowserLogins) -> Deferred<Maybe<URLCredential?>> {
return loginsProvider.getLoginsForProtectionSpace(challenge.protectionSpace) >>== { cursor in
guard cursor.count >= 1 else {
return deferMaybe(nil)
}
let logins = cursor.asArray()
var credentials: URLCredential? = nil
// It is possible that we might have duplicate entries since we match against host and scheme://host.
// This is a side effect of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
if logins.count > 1 {
credentials = (logins.find { login in
(login.protectionSpace.`protocol` == challenge.protectionSpace.`protocol`) && !login.hasMalformedHostname
})?.credentials
let malformedGUIDs: [GUID] = logins.flatMap { login in
if login.hasMalformedHostname {
return login.guid
}
return nil
}
loginsProvider.removeLoginsWithGUIDs(malformedGUIDs).upon { log.debug("Removed malformed logins. Success :\($0.isSuccess)") }
}
// Found a single entry but the schemes don't match. This is a result of a schemeless entry that we
// saved in a previous iteration of the app so we need to migrate it. We only care about the
// the username/password so we can rewrite the scheme to be correct.
else if logins.count == 1 && logins[0].protectionSpace.`protocol` != challenge.protectionSpace.`protocol` {
let login = logins[0]
credentials = login.credentials
let new = Login(credential: login.credentials, protectionSpace: challenge.protectionSpace)
return loginsProvider.updateLoginByGUID(login.guid, new: new, significant: true)
>>> { deferMaybe(credentials) }
}
// Found a single entry that matches the scheme and host - good to go.
else {
credentials = logins[0].credentials
}
return deferMaybe(credentials)
}
}
fileprivate static func promptForUsernamePassword(_ viewController: UIViewController, credentials: URLCredential?, protectionSpace: URLProtectionSpace, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> {
if protectionSpace.host.isEmpty {
print("Unable to show a password prompt without a hostname")
return deferMaybe(LoginDataError(description: "Unable to show a password prompt without a hostname"))
}
let deferred = Deferred<Maybe<LoginData>>()
let alert: UIAlertController
let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title")
if !(protectionSpace.realm?.isEmpty ?? true) {
let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string")
let formatted = NSString(format: msg as NSString, protectionSpace.host, protectionSpace.realm ?? "") as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: .alert)
} else {
let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site")
let formatted = NSString(format: msg as NSString, protectionSpace.host) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: .alert)
}
// Add a button to log in.
let action = UIAlertAction(title: LogInButtonTitle,
style: .default) { (action) -> Void in
guard let user = alert.textFields?[0].text, let pass = alert.textFields?[1].text else { deferred.fill(Maybe(failure: LoginDataError(description: "Username and Password required"))); return }
let login = Login.createWithCredential(URLCredential(user: user, password: pass, persistence: .forSession), protectionSpace: protectionSpace)
deferred.fill(Maybe(success: login))
loginsHelper?.setCredentials(login)
}
alert.addAction(action)
// Add a cancel button.
let cancel = UIAlertAction(title: CancelButtonTitle, style: .cancel) { (action) -> Void in
deferred.fill(Maybe(failure: LoginDataError(description: "Save password cancelled")))
}
alert.addAction(cancel)
// Add a username textfield.
alert.addTextField { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt")
textfield.text = credentials?.user
}
// Add a password textfield.
alert.addTextField { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt")
textfield.isSecureTextEntry = true
textfield.text = credentials?.password
}
viewController.present(alert, animated: true) { () -> Void in }
return deferred
}
}
| 9a647e41855bb15d764252a4c571bfc7 | 52.509804 | 227 | 0.658117 | false | false | false | false |
jisudong555/swift | refs/heads/master | weibo/weibo/Classes/Main/BaseViewController.swift | mit | 1 | //
// BaseViewController.swift
// weibo
//
// Created by jisudong on 16/4/12.
// Copyright © 2016年 jisudong. All rights reserved.
//
import UIKit
class BaseViewController: UITableViewController, VisitorViewDelegate {
let userLogin = UserAccount.userLogin()
var visitorView: VisitorView?
override func loadView() {
userLogin ? super.loadView() : setupVisitorView()
}
func setupVisitorView()
{
let customView = VisitorView()
view = customView
customView.delegate = self
visitorView = customView
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(registerButtonClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(loginButtonClick))
}
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()
}
// MARK: - VisitorViewDelegate
func loginButtonClick()
{
print(#function)
let oauth = OAuthViewController()
let nav = UINavigationController(rootViewController: oauth)
presentViewController(nav, animated: true, completion: nil)
}
func registerButtonClick()
{
print(#function)
}
}
| abddac6409ad12d1893b0dbc6fb2ce61 | 28 | 160 | 0.661601 | false | false | false | false |
a736220388/TestKitchen_1606 | refs/heads/master | TestKitchen/TestKitchen/classes/community/homePage/CookBookViewController.swift | mit | 1 | //
// CookBookViewController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CookBookViewController: KTCHomeViewController {
var scrollView:UIScrollView?
private var recommendView:CBRecommendView?
private var foodView:CBMaterialView?
private var categoryView:CBMaterialView?
private var segCtrl:KTCSegmentCtrl?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createMyNav()
createHomePageView()
downloadRecommendData()
downloadFoodData()
downloadCategoryData()
}
func downloadCategoryData(){
let params = ["methodName":"CategoryIndex"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = .Category
downloader.postWithUrl(kHostUrl, params: params)
}
func downloadFoodData(){
let dict = ["methodName":"MaterialSubtype"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = KTCDownloaderType.FoodMaterial
downloader.postWithUrl(kHostUrl, params: dict)
}
func createHomePageView(){
automaticallyAdjustsScrollViewInsets = false
//推荐,食材,分类的滚动视图
scrollView = UIScrollView()
view.addSubview(scrollView!)
scrollView!.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 49, 0))
}
let containerView = UIView.createView()
scrollView!.addSubview(containerView)
containerView.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView!)
make.height.equalTo(self!.scrollView!)
}
recommendView = CBRecommendView()
containerView.addSubview(recommendView!)
recommendView?.snp_makeConstraints(closure: {
(make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo(containerView)
})
foodView = CBMaterialView()
foodView?.backgroundColor = UIColor.redColor()
containerView.addSubview(foodView!)
foodView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((recommendView?.snp_right)!)
})
categoryView = CBMaterialView()
categoryView?.backgroundColor = UIColor.yellowColor()
containerView.addSubview(categoryView!)
categoryView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((foodView?.snp_right)!)
})
containerView.snp_makeConstraints { (make) in
make.right.equalTo((categoryView?.snp_right)!)
}
scrollView!.pagingEnabled = true
scrollView!.showsHorizontalScrollIndicator = false
scrollView?.delegate = self
}
func downloadRecommendData(){
let dict = ["methodName":"SceneHome"]
let downloader = KTCDownloader()
downloader.delegate = self
downloader.type = KTCDownloaderType.Recommend
downloader.postWithUrl(kHostUrl, params: dict)
}
func createMyNav(){
segCtrl = KTCSegmentCtrl(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44 ), titleNames: ["推荐","食材","分类"])
segCtrl?.delegate = self
navigationItem.titleView = segCtrl
addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true)
addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false)
}
func scanAction(){
}
func searchAction(){
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//显示首页推荐的数据
func showRecommendData(model:CBRecommendModel){
recommendView?.model = model
recommendView?.clickClosure = {
[weak self]
title,link in
if link.hasPrefix("app://food_course_series") == true{
let id = link.componentsSeparatedByString("#")[1]
/*
let startRange = NSString(string: link).rangeOfString("#")
let endRange = NSString(string: link).rangeOfString("#", options: NSStringCompareOptions.BackwardsSearch, range: NSMakeRange(0, link.characters.count))
let id = NSString(string: link).substringWithRange(NSMakeRange(startRange.location+1, endRange.location-startRange.location-1))
*/
let foodCourseCtrl = FoodCourseViewController()
foodCourseCtrl.seriesId = id
self!.navigationController?.pushViewController(foodCourseCtrl, animated: true)
}
}
}
func gotoFoodCoursePage(seriesId:String){
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension CookBookViewController : KTCDownloaderDelegate{
func downloader(downloader: KTCDownloader, didFailWithError error: NSError) {
print(error)
}
func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) {
if downloader.type == .Recommend{
if let jsonData = data{
let model = CBRecommendModel.parseModel(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.recommendView?.model = model
self?.showRecommendData(model)
})
}
}else if downloader.type == .FoodMaterial{
if let jsonData = data{
let model = CBMaterialModel.parseModelWithData(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.foodView?.model = model
})
}
}else if downloader.type == .Category{
if let jsonData = data{
let model = CBMaterialModel.parseModelWithData(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self?.categoryView?.model = model
})
}
}
}
}
extension CookBookViewController:KTCSegmentCtrlDelegate{
func didSelectSegCtrl(segCtrl: KTCSegmentCtrl, atIndex index: Int) {
scrollView?.setContentOffset(CGPointMake(kScreenWidth*CGFloat(index), 0), animated: true)
}
}
extension CookBookViewController:UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
segCtrl?.selectedIndex = index
}
}
| 2659295a23714cc36147367a06891cf3 | 35.170732 | 167 | 0.618476 | false | false | false | false |
automationWisdri/WISData.JunZheng | refs/heads/master | WISData.JunZheng/View/Operation/OperationView.swift | mit | 1 | //
// OperationView.swift
// WISData.JunZheng
//
// Created by Allen on 16/9/6.
// Copyright © 2016 Wisdri. All rights reserved.
//
import UIKit
import SwiftyJSON
class OperationView: UIView {
@IBOutlet weak var viewTitleLabel: UILabel!
@IBOutlet weak var dataView: UIView!
private var firstColumnView: UIView!
private var scrollView: UIScrollView!
private var firstColumnTableView: DataTableView!
private var columnTableView = [DataTableView]()
private var switchRowCount = [Int]()
private var totalRowCount = 0
private var tableTitleJSON = JSON.null
var tableContentJSON = [JSON]()
var switchContentJSON = [[JSON]]()
var viewHeight: CGFloat = CGFloat(35.0)
override func awakeFromNib() {
super.awakeFromNib()
// Basic setup
self.backgroundColor = UIColor.whiteColor()
self.viewTitleLabel.backgroundColor = UIColor.wisGrayColor().colorWithAlphaComponent(0.3)
}
func initialDrawTable(switchRowCount: [Int], viewHeight: CGFloat) {
self.dataView.removeAllSubviews()
self.switchRowCount = switchRowCount
self.totalRowCount = switchRowCount.reduce(0, combine: + )
// Get table column title
if let path = NSBundle.mainBundle().pathForResource("OperationTitle", ofType: "json") {
let data = NSData(contentsOfFile: path)
tableTitleJSON = JSON(data: data!)
} else {
tableTitleJSON = JSON.null
}
// Define the table dimensions
let dataViewWidth = CURRENT_SCREEN_WIDTH
let dataViewHeight = viewHeight - WISCommon.viewHeaderTitleHeight
// let firstColumnViewWidth: CGFloat = 90
// -2 是因为 KEY "No" 和 "SwitchTimes" 不作为表格列名
let opColumnCount = Operation().propertyNames().count - 2
let switchColumnCount = SwitchTime().propertyNames().count
let totalColumnCount = opColumnCount + switchColumnCount
// Draw view for first column
firstColumnView = UIView(frame: CGRectMake(0, 0, WISCommon.firstColumnViewWidth, dataViewHeight))
firstColumnView.backgroundColor = UIColor.whiteColor()
// headerView.userInteractionEnabled = true
self.dataView.addSubview(firstColumnView)
// Draw first column table
firstColumnTableView = DataTableView(frame: firstColumnView.bounds, style: .Plain, rowInfo: switchRowCount)
firstColumnTableView.dataTableDelegate = self
firstColumnView.addSubview(firstColumnTableView)
// Draw view for data table
scrollView = UIScrollView(frame: CGRectMake (WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, dataViewHeight))
scrollView.contentSize = CGSizeMake(CGFloat(totalColumnCount) * WISCommon.DataTableColumnWidth, DataTableHeaderRowHeight + CGFloat(totalRowCount) * DataTableBaseRowHeight)
scrollView.showsHorizontalScrollIndicator = true
scrollView.showsVerticalScrollIndicator = true
scrollView.bounces = true
scrollView.delegate = self
scrollView.backgroundColor = UIColor.whiteColor()
self.dataView.addSubview(scrollView)
// Draw data table
self.columnTableView.removeAll()
var tableColumnsCount = 0
for p in Operation().propertyNames() {
if p == "No" || p == "SwitchTimes" {
continue
} else {
let tempColumnTableView = DataTableView(frame: CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, dataViewHeight), style: .Plain, rowInfo: switchRowCount)
self.columnTableView.append(tempColumnTableView)
self.columnTableView[tableColumnsCount].dataTableDelegate = self
self.scrollView.addSubview(self.columnTableView[tableColumnsCount])
tableColumnsCount += 1
}
}
for _ in SwitchTime().propertyNames() {
let tempColumnTableView = DataTableView(frame: CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, dataViewHeight), style: .Plain, rowInfo: nil)
self.columnTableView.append(tempColumnTableView)
self.columnTableView[tableColumnsCount].dataTableDelegate = self
self.scrollView.addSubview(self.columnTableView[tableColumnsCount])
tableColumnsCount += 1
}
fillDataTableContent()
}
func arrangeOperationSubView(viewHeight: CGFloat) {
// Define the table dimensions
let dataViewWidth = CURRENT_SCREEN_WIDTH
let dataViewHeight = viewHeight - WISCommon.viewHeaderTitleHeight
guard let scrollView = self.scrollView else {
return
}
scrollView.frame = CGRectMake(WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, dataViewHeight)
/*
* Issue 1 中的 4# 问题,暂未解决
let opColumnCount = Operation().propertyNames().count - 2
let switchColumnCount = SwitchTime().propertyNames().count
let totalColumnCount = opColumnCount + switchColumnCount
if ( dataViewWidth - WISCommon.firstColumnViewWidth ) > CGFloat(totalColumnCount) * WISCommon.DataTableColumnWidth {
// 重绘表格
let dataTableColumnWidth: CGFloat = ( dataViewWidth - WISCommon.firstColumnViewWidth) / CGFloat(totalColumnCount)
let subviews = scrollView.subviews as! [DataTableView]
for subview in subviews {
subview.bounds.size = CGSize(width: dataTableColumnWidth, height: dataViewHeight)
subview.layoutIfNeeded()
}
}
*/
}
private func fillDataTableContent() {
firstColumnTableView.viewModel.headerString = SearchParameter["date"]! + "\n" + getShiftName(SearchParameter["shiftNo"]!)[0]
let firstColumnTitleArray = DJName
firstColumnTableView.viewModel.titleArray = firstColumnTitleArray
self.firstColumnTableView.viewModel.titleArraySubject
.onNext(firstColumnTitleArray)
var tableColumnsCount = 0
for p in Operation().propertyNames() {
if p == "No" || p == "SwitchTimes" {
continue
} else {
// header
let columnTitle: String = self.tableTitleJSON["title"][p].stringValue
self.columnTableView[tableColumnsCount].viewModel.headerString = columnTitle
// content
var contentArray: [String] = []
for j in 0 ..< self.tableContentJSON.count {
let content = self.tableContentJSON[j][p].stringValue.trimNumberFromFractionalPart(2)
contentArray.append(content)
}
self.columnTableView[tableColumnsCount].viewModel.titleArray = contentArray
self.columnTableView[tableColumnsCount].viewModel.titleArraySubject.onNext(contentArray)
self.columnTableView[tableColumnsCount].reloadData()
tableColumnsCount += 1
}
}
for p in SwitchTime().propertyNames() {
// header
let columnTitle: String = self.tableTitleJSON["title"]["SwitchTimes"][p].stringValue
self.columnTableView[tableColumnsCount].viewModel.headerString = columnTitle
// content
var contentArray: [String] = []
for i in 0 ..< self.tableContentJSON.count {
if self.switchContentJSON[i].count == 0 {
contentArray.append(EMPTY_STRING)
} else {
for j in 0 ..< self.switchRowCount[i] {
let content = self.switchContentJSON[i][j][p].stringValue
contentArray.append(content)
}
}
}
self.columnTableView[tableColumnsCount].viewModel.titleArray = contentArray
self.columnTableView[tableColumnsCount].viewModel.titleArraySubject
.onNext(contentArray)
tableColumnsCount += 1
}
}
}
// MARK: - Extension
extension OperationView: DataTableViewDelegate {
func dataTableViewContentOffSet(contentOffSet: CGPoint) {
for subView in scrollView.subviews {
if subView.isKindOfClass(DataTableView) {
(subView as! DataTableView).setTableViewContentOffSet(contentOffSet)
}
}
for subView in firstColumnView.subviews {
(subView as! DataTableView).setTableViewContentOffSet(contentOffSet)
}
}
}
extension OperationView: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
// let p: CGPoint = scrollView.contentOffset
// print(NSStringFromCGPoint(p))
}
}
| ccffa996befa70056ce6229ce3c3ef91 | 40.686364 | 226 | 0.633628 | false | false | false | false |
joemcbride/outlander-osx | refs/heads/master | src/Outlander/ExpUpdateHandler.swift | mit | 1 | //
// ExpUpdateHandler.swift
// Outlander
//
// Created by Joseph McBride on 4/23/15.
// Copyright (c) 2015 Joe McBride. All rights reserved.
//
import Foundation
@objc
class ExpUpdateHandler : NSObject {
class func newInstance() -> ExpUpdateHandler {
return ExpUpdateHandler()
}
static let start_check = "Circle: "
static let end_check = "EXP HELP for more information"
var emitSetting : ((String,String)->Void)?
var emitExp : ((SkillExp)->Void)?
private var parsing = false
private var exp_regex = "(\\w.*?):\\s+(\\d+)\\s(\\d+)%\\s(\\w.*?)\\s+\\(\\d{1,}/34\\)"
func handle(nodes:[Node], text:String, context:GameContext) {
if !self.parsing {
if text.hasPrefix(ExpUpdateHandler.start_check) {
self.parsing = true
return
}
} else {
if text.hasPrefix(ExpUpdateHandler.end_check) {
self.parsing = false
return
}
let groups = text[exp_regex].allGroups()
for group in groups {
let var_name = group[1].replace(" ", withString: "_")
let skill = SkillExp()
skill.name = var_name
skill.mindState = LearningRate.fromDescription(group[4])
skill.ranks = NSDecimalNumber(string: "\(group[2]).\(group[3])")
emitSetting?("\(var_name).Ranks", "\(skill.ranks)")
emitSetting?("\(var_name).LearningRate", "\(skill.mindState.rateId)")
emitSetting?("\(var_name).LearningRateName", "\(skill.mindState.desc)")
emitExp?(skill)
}
}
}
}
| 63d87cbf7126e6af6d6b5f6c5392ed18 | 29.081967 | 90 | 0.497548 | false | false | false | false |
SettlePad/client-iOS | refs/heads/master | SettlePad/NewUOmeViewController.swift | mit | 1 | //
// NewUOmeViewController.swift
// SettlePad
//
// Created by Rob Everhardt on 01/02/15.
// Copyright (c) 2015 SettlePad. All rights reserved.
//
import UIKit
protocol NewUOmeModalDelegate {
func transactionsPosted(controller:NewUOmeViewController)
func transactionsPostCompleted(controller:NewUOmeViewController, error_msg: String?)
}
class NewUOmeViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
let footer = NewUOmeFooterView(frame: CGRectMake(0, 0, 320, 44))
var addressBookFooter = UINib(nibName: "NewUOmeAddressBook", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! NewUOmeAddressBook
var delegate:NewUOmeModalDelegate! = nil
var sortedCurrencies: [Currency] = []
var selectedCurrency: Currency = Currency.EUR
@IBOutlet var newUOmeTableView: UITableView!
@IBAction func closeView(sender: AnyObject) {
if state == .Overview {
//TODO: save draft memos so that they remain after the app is terminated (via Transactions class, in CoreData, see http://www.raywenderlich.com/85578/first-core-data-app-using-swift)
self.dismissViewControllerAnimated(true, completion: nil)
} else {
formTo.text = ""
switchState(.Overview)
}
}
@IBOutlet var sendButton: UIBarButtonItem!
@IBAction func sendUOmes(sender: AnyObject) {
if formTo.text != "" {
saveUOme()
}
if newTransactions.count > 0 {
//Post
activeUser!.transactions.post(newTransactions,
success: {
activeUser!.contacts.updateContacts(
{
self.delegate.transactionsPostCompleted(self, error_msg: nil)
},
failure: {error in
self.delegate.transactionsPostCompleted(self, error_msg: error.errorText)
}
)
},
failure: { error in
self.delegate.transactionsPostCompleted(self, error_msg: error.errorText)
}
)
//Close viewcontroller
delegate.transactionsPosted(self)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
@IBAction func formCurrencyAction(sender: PickerButton) {
sender.becomeFirstResponder()
}
@IBOutlet var formTo: UITextField!
@IBOutlet var formDescription: UITextField!
@IBOutlet var formType: UISegmentedControl!
@IBOutlet var formCurrency: PickerButton!
@IBOutlet var formAmount: UITextField!
@IBOutlet var formSaveButton: UIButton!
@IBOutlet var tableBottomConstraint: NSLayoutConstraint!
var newTransactions = [Transaction]()
enum State {
case Overview //show all new transactions
case NewUOme //show suggestions for email address
}
var matchedContactIdentifiers = [Identifier]() //Name, Identifier
var state: State = .Overview
var actInd: UIActivityIndicatorView = UIActivityIndicatorView()
@IBAction func saveUOme(sender: AnyObject) {
saveUOme()
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if state == .NewUOme {
return false
} else {
return true
}
}
@IBAction func viewTapped(sender: AnyObject) {
self.view.endEditing(true)
}
@IBOutlet var tableSaveContraint: NSLayoutConstraint! //table to Save button
@IBAction func formToEditingChanged(sender: AnyObject) {
validateForm(true, finalCheck: false)
//If not-empty, show suggestions
if formTo.text != "" {
getMatchedContactIdentifiers(formTo.text!)
switchState(.NewUOme)
} else {
switchState(.Overview)
}
}
@IBAction func formToEditingDidEnd(sender: AnyObject) {
validateForm(false, finalCheck: false)
//Hide suggestions
if formTo.text != "" {
switchState(.Overview)
}
}
func switchState(explicitState: State?) {
if let state = explicitState {
self.state = state
} else {
if (self.state == .Overview) {
self.state = .NewUOme
} else {
self.state = .Overview
}
}
if (self.state == .Overview) {
actInd.removeFromSuperview()
formDescription.hidden = false
formType.hidden = false
formCurrency.hidden = false
formAmount.hidden = false
formSaveButton.hidden = false
tableSaveContraint.active = true
sendButton.enabled = true
footer.setNeedsDisplay()
newUOmeTableView.tableFooterView = footer
newUOmeTableView.allowsSelection = false
newUOmeTableView.reloadData()
} else if (self.state == .NewUOme){
actInd.removeFromSuperview()
formDescription.hidden = true
formType.hidden = true
formCurrency.hidden = true
formAmount.hidden = true
formSaveButton.hidden = true
tableSaveContraint.active = false
sendButton.enabled = false
layoutAddressBookFooter()
addressBookFooter.setNeedsDisplay()
newUOmeTableView.tableFooterView = addressBookFooter
newUOmeTableView.allowsSelection = true
newUOmeTableView.reloadData()
}
}
func layoutAddressBookFooter() {
addressBookFooter.frame.size.width = newUOmeTableView.frame.width
addressBookFooter.detailLabel.preferredMaxLayoutWidth = newUOmeTableView.frame.width - 40 //margin of 20 left and right
addressBookFooter.frame.size.height = addressBookFooter.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height //Only works if preferred width is set for the objects that have variable height
}
@IBAction func formDescriptionEditingChanged(sender: AnyObject) {
validateForm(true,finalCheck: false)
}
@IBAction func formAmountEditingChanged(sender: AnyObject) {
validateForm(true, finalCheck: false)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
switchState(.Overview)
addressBookFooter.footerUpdated = {(sender) in
self.addressBookFooter = UINib(nibName: "NewUOmeAddressBook", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! NewUOmeAddressBook
self.layoutAddressBookFooter()
dispatch_async(dispatch_get_main_queue(), {
self.newUOmeTableView.tableFooterView = self.addressBookFooter
})
self.newUOmeTableView.reloadData()
}
//Sort currencies
sortedCurrencies = Currency.allValues.sort({(left: Currency, right: Currency) -> Bool in left.toLongName().localizedCaseInsensitiveCompare(right.toLongName()) == NSComparisonResult.OrderedDescending})
//Link currency picker to delegate and datasource functions below
formCurrency.modInputView.dataSource = self
formCurrency.modInputView.delegate = self
//Set currency picker to user's default currency
let row: Int? = sortedCurrencies.indexOf(activeUser!.defaultCurrency)
if row != nil {
formCurrency.modInputView.selectRow(row!, inComponent: 0, animated: false)
selectedCurrency = activeUser!.defaultCurrency
formCurrency.setTitle(activeUser!.defaultCurrency.rawValue, forState: UIControlState.Normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func validateForm (whileEditing: Bool, finalCheck: Bool) -> Bool {
var isValid = true
var hasGivenFirstResponder = false
/*Could also color the border, with
formTo.layer.borderWidth = 1.0
formTo.layer.borderColor = Colors.danger.textToUIColor().CGColor
*/
if formTo.text!.isEmail() {
formTo.backgroundColor = nil
formTo.textColor = nil
} else {
isValid = false
if finalCheck || (formTo.text != "" && !whileEditing) {
formTo.backgroundColor = Colors.danger.backgroundToUIColor()
formTo.textColor = Colors.danger.textToUIColor()
if (!hasGivenFirstResponder && finalCheck) {
formTo.becomeFirstResponder()
hasGivenFirstResponder = true
}
}
}
if formDescription.text != "" {
formDescription.backgroundColor = nil
formDescription.textColor = nil
} else {
isValid = false
if finalCheck {
formDescription.backgroundColor = Colors.danger.backgroundToUIColor()
formDescription.textColor = Colors.danger.textToUIColor()
if (!hasGivenFirstResponder && finalCheck) {
formDescription.becomeFirstResponder()
hasGivenFirstResponder = true
}
}
}
if formAmount.text!.toDouble() != nil {
formAmount.backgroundColor = nil
formAmount.textColor = nil
} else {
isValid = false
if finalCheck || (formDescription.text != "" && !whileEditing) {
formAmount.backgroundColor = Colors.danger.backgroundToUIColor()
formAmount.textColor = Colors.danger.textToUIColor()
if (!hasGivenFirstResponder && finalCheck) {
formAmount.becomeFirstResponder()
hasGivenFirstResponder = true
}
}
}
return isValid
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.state == .Overview) {
return newTransactions.count
} else {
return matchedContactIdentifiers.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (self.state == .Overview) {
//Show draft UOme's
let cell = tableView.dequeueReusableCellWithIdentifier("TransactionCell", forIndexPath: indexPath) as! TransactionsCell
// Configure the cell...
cell.markup(newTransactions[indexPath.row])
cell.layoutIfNeeded() //to get right layout given dynamic height
return cell
} else {
//show contacts
let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath)
// Configure the cell...
let contactIdentifier = matchedContactIdentifiers[indexPath.row]
cell.textLabel?.text = contactIdentifier.resultingName
cell.detailTextLabel?.text = contactIdentifier.identifierStr
if contactIdentifier.contact != nil {
//Is a uoless user
cell.backgroundColor = Colors.primary.backgroundToUIColor()
} else {
cell.backgroundColor = UIColor.whiteColor()
}
cell.layoutIfNeeded() //to get right layout given dynamic height
return cell
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
//Editable or not
if (self.state == .Overview) {
return true
} else {
return false
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
//function required to have editable rows
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
//return []
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
self.deleteTransaction(indexPath.row)
})
deleteAction.backgroundColor = Colors.danger.textToUIColor()
return [deleteAction]
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if (self.state == .NewUOme) {
//Set value as "to"
let contactIdentifier = matchedContactIdentifiers[indexPath.row]
formTo.text = contactIdentifier.identifierStr
switchState(.Overview)
//goto amount
if formDescription.text == "" {
formDescription.becomeFirstResponder()
} else {
formAmount.becomeFirstResponder()
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//Set cell height to dynamic. Note that it also requires a cell.layoutIfNeeded in cellForRowAtIndexPath!
newUOmeTableView.estimatedRowHeight = 70
newUOmeTableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
formTo.becomeFirstResponder() //If done earlier (eg. at viewWillAppear), the layouting is not done yet and keyboard will pop up before that. As that triggers an animated re-layouting, width-changes can also be seen animated. Can also do a self.view.layoutIfNeeded() before this line
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
//textfields that should trigger this need to have their delegate set to the viewcontroller
if (textField!.restorationIdentifier == "to") {
//goto description
formDescription.becomeFirstResponder()
} else if (textField!.restorationIdentifier == "description") {
//goto amount
formAmount.becomeFirstResponder()
} else if (textField!.restorationIdentifier == "amount") {
saveUOme()
}
return true;
}
func saveUOme() {
if validateForm(false, finalCheck: true) {
var amount: Double
if (formType.selectedSegmentIndex == 0) {
amount = formAmount.text!.toDouble()!
} else {
amount = -1*formAmount.text!.toDouble()!
}
let matchedIdentifier: Identifier? = activeUser!.contacts.getIdentifier(formTo.text!)
var name: String
if matchedIdentifier != nil {
name = matchedIdentifier!.resultingName
} else {
name = formTo.text!
}
let transaction = Transaction(
name: name,
identifier: formTo.text!,
description: formDescription.text!,
currency: selectedCurrency,
amount: amount
)
newTransactions.append(transaction)
//Clean out the form, set focus on recipient
newUOmeTableView.reloadData()
footer.setNeedsDisplay()
newUOmeTableView.tableFooterView = footer
formTo.text = ""
formTo.becomeFirstResponder()
}
}
func deleteTransaction(index:Int){
newTransactions.removeAtIndex(index)
newUOmeTableView.reloadData()
footer.setNeedsDisplay()
newUOmeTableView.tableFooterView = footer
}
func getMatchedContactIdentifiers(needle: String){
matchedContactIdentifiers.removeAll()
//First add those that are registered at Settlepad
for contactIdentifier in activeUser!.contacts.contactIdentifiers where contactIdentifier.contact != nil {
if (contactIdentifier.identifierStr.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.contact?.name.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.contact?.friendlyName.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.localName?.lowercaseString.rangeOfString(needle.lowercaseString) != nil) {
matchedContactIdentifiers.append(contactIdentifier)
}
}
//Then add those from local address book only
for contactIdentifier in activeUser!.contacts.contactIdentifiers where contactIdentifier.contact == nil {
if (contactIdentifier.identifierStr.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.localName?.lowercaseString.rangeOfString(needle.lowercaseString) != nil) {
matchedContactIdentifiers.append(contactIdentifier)
}
}
}
// Currency picker delegate
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
return 1;
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return sortedCurrencies.count;
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return sortedCurrencies[row].toLongName()
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
formCurrency.setTitle(sortedCurrencies[row].rawValue, forState: UIControlState.Normal)
selectedCurrency = sortedCurrencies[row]
}
func donePicker () {
formCurrency.resignFirstResponder()
}
}
class NewUOmeFooterView: UIView {
override init (frame : CGRect) {
super.init(frame : frame)
self.opaque = false //Required for transparent background
}
/*convenience override init () {
self.init(frame:CGRectMake(0, 0, 320, 44)) //By default, make a rect of 320x44
}*/
required init?(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override func drawRect(rect: CGRect) {
//To make sure we are not adding one layer of text onto another
for view in self.subviews {
view.removeFromSuperview()
}
let footerLabel: UILabel = UILabel(frame: rect)
footerLabel.textColor = Colors.gray.textToUIColor()
footerLabel.font = UIFont.boldSystemFontOfSize(11)
footerLabel.textAlignment = NSTextAlignment.Center
footerLabel.text = "Saved memos will be listed here to be all sent at once."
self.addSubview(footerLabel)
}
}
| ea0c9dd10903435b4e996a6d4db879b5 | 34.014679 | 404 | 0.645863 | false | false | false | false |
colemancda/json-swift | refs/heads/master | src/JSValue.swift | mit | 3 | //
// JSON.swift
// JSON
//
// Created by David Owens on 6/20/14.
// Copyright (c) 2014 David Owens II. All rights reserved.
//
/// A convenience type declaration for use with top-level JSON objects.
public typealias JSON = JSValue
/// The error domain for all `JSValue` related errors.
public let JSValueErrorDomain = "com.kiadsoftware.json.error"
/// A representative type for all possible JSON values.
///
/// See http://json.org for a full description.
public struct JSValue : Equatable {
/// The maximum integer that is safely representable in JavaScript.
public static let MaximumSafeInt: Int64 = 9007199254740991
/// The minimum integer that is safely representable in JavaScript.
public static let MinimumSafeInt: Int64 = -9007199254740991
/// The type of the underlying `JSArray`.
public typealias JSArrayType = [JSValue]
/// The type of the underlying `JSObject`.
public typealias JSObjectType = [String:JSValue]
/// The type of the underlying `JSString`.
public typealias JSStringType = String
/// The type of the underlying `JSNumber`.
public typealias JSNumberType = Double
/// The type of the underlying `JSBool`.
public typealias JSBoolType = Bool
/// The underlying value for `JSValue`.
var value: JSBackingValue
/// All of the possible values that a `JSValue` can hold.
enum JSBackingValue {
/*
* Implementation Note:
*
* I do not want consumers to be able to simply do JSValue.JSNumber(123) as I need to perform
* validation on the input. This prevents me from simply using an enum. Thus I have this
* strange nested enum to store the values. I'm not sure I like this approach, but I do not
* see a better one at the moment...
*/
/// Holds an array of JavaScript values that conform to valid `JSValue` types.
case JSArray([JSValue])
/// Holds an unordered set of key/value pairs conforming to valid `JSValue` types.
case JSObject([String : JSValue])
/// Holds the value conforming to JavaScript's String object.
case JSString(String)
/// Holds the value conforming to JavaScript's Number object.
case JSNumber(Double)
/// Holds the value conforming to JavaScript's Boolean wrapper.
case JSBool(Bool)
/// Holds the value that corresponds to `null`.
case JSNull
/// Holds the error information when the `JSValue` could not be made into a valid item.
case Invalid(Error)
}
/// Initializes a new `JSValue` with a `JSArrayType` value.
public init(_ value: JSArrayType) {
self.value = JSBackingValue.JSArray(value)
}
/// Initializes a new `JSValue` with a `JSObjectType` value.
public init(_ value: JSObjectType) {
self.value = JSBackingValue.JSObject(value)
}
/// Initializes a new `JSValue` with a `JSStringType` value.
public init(_ value: JSStringType) {
self.value = JSBackingValue.JSString(value)
}
/// Initializes a new `JSValue` with a `JSNumberType` value.
public init(_ value: JSNumberType) {
self.value = JSBackingValue.JSNumber(value)
}
/// Initializes a new `JSValue` with a `JSBoolType` value.
public init(_ value: JSBoolType) {
self.value = JSBackingValue.JSBool(value)
}
/// Initializes a new `JSValue` with an `Error` value.
init(_ error: Error) {
self.value = JSBackingValue.Invalid(error)
}
/// Initializes a new `JSValue` with a `JSBackingValue` value.
init(_ value: JSBackingValue) {
self.value = value
}
}
// All of the stupid number-type initializers because of the lack of type conversion.
// Grr... convenience initializers not allowed in this context...
// Also... without the labels, Swift cannot seem to actually get the type inference correct (6.1b3)
extension JSValue {
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(int8 value: Int8) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(in16 value: Int16) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(int32 value: Int32) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(int64 value: Int64) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(uint8 value: UInt8) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(uint16 value: UInt16) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(uint32 value: UInt32) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(uint64 value: UInt64) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(int value: Int) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(uint value: UInt) {
self.value = JSBackingValue.JSNumber(Double(value))
}
/// Convenience initializer for a `JSValue` with a non-standard `JSNumberType` value.
public init(float value: Float) {
self.value = JSBackingValue.JSNumber(Double(value))
}
}
extension JSValue : CustomStringConvertible {
/// Attempts to convert the `JSValue` into its string representation.
///
/// - parameter indent: the indent string to use; defaults to " "
///
/// - returns: A `FailableOf<T>` that will contain the `String` value if successful,
/// otherwise, the `Error` information for the conversion.
public func stringify(indent: String = " ") -> String {
return prettyPrint(indent, 0)
}
/// Attempts to convert the `JSValue` into its string representation.
///
/// - parameter indent: the number of spaces to include.
///
/// - returns: A `FailableOf<T>` that will contain the `String` value if successful,
/// otherwise, the `Error` information for the conversion.
public func stringify(indent: Int) -> String {
let padding = (0..<indent).reduce("") { s, i in return s + " " }
return prettyPrint(padding, 0)
}
/// Prints out the description of the JSValue value as pretty-printed JSValue.
public var description: String {
return stringify()
}
}
/// Used to compare two `JSValue` values.
///
/// - returns: `True` when `hasValue` is `true` and the underlying values are the same; `false` otherwise.
public func ==(lhs: JSValue, rhs: JSValue) -> Bool {
switch (lhs.value, rhs.value) {
case (.JSNull, .JSNull):
return true
case let (.JSBool(lhsValue), .JSBool(rhsValue)):
return lhsValue == rhsValue
case let (.JSString(lhsValue), .JSString(rhsValue)):
return lhsValue == rhsValue
case let (.JSNumber(lhsValue), .JSNumber(rhsValue)):
return lhsValue == rhsValue
case let (.JSArray(lhsValue), .JSArray(rhsValue)):
return lhsValue == rhsValue
case let (.JSObject(lhsValue), .JSObject(rhsValue)):
return lhsValue == rhsValue
default:
return false
}
}
extension JSValue {
func prettyPrint(indent: String, _ level: Int) -> String {
let currentIndent = indent == "" ? "" : indent.join((0...level).map({ (item: Int) in "" }))
let nextIndent = currentIndent + indent
let newline = indent == "" ? "" : "\n"
let space = indent == "" ? "" : " "
switch self.value {
case .JSBool(let bool):
return bool ? "true" : "false"
case .JSNumber(let number):
return "\(number)"
case .JSString(let string):
let escaped = string.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
return "\"\(escaped)\""
case .JSArray(let array):
return "[\(newline)" + ",\(newline)".join(array.map({ "\(nextIndent)\($0.prettyPrint(indent, level + 1))" })) + "\(newline)\(currentIndent)]"
case .JSObject(let dict):
return "{\(newline)" + ",\(newline)".join(dict.map({ "\(nextIndent)\"\($0)\":\(space)\($1.prettyPrint(indent, level + 1))"})) + "\(newline)\(currentIndent)}"
case .JSNull:
return "null"
case .Invalid(let error):
return "<Invalid JSON: \(error.description)>"
}
}
}
| 08b84c2117f3f5338a0a8498ec3a7312 | 34.70566 | 169 | 0.626717 | false | false | false | false |
aolan/Cattle | refs/heads/master | CattleKit/UIView+CAFrame.swift | mit | 1 | //
// UIView+CAFrame.swift
// cattle
//
// Created by lawn on 15/11/5.
// Copyright © 2015年 zodiac. All rights reserved.
//
import UIKit
extension UIView{
func ca_minX() -> CGFloat{
return frame.origin.x
}
func ca_minX(x: CGFloat) -> Void{
frame.origin.x = x
}
func ca_minY() -> CGFloat{
return frame.origin.y
}
func ca_minY(y: CGFloat) -> Void{
frame.origin.y = y
}
func ca_maxX() -> CGFloat{
return frame.origin.x + frame.size.width
}
func ca_maxX(x:CGFloat) -> Void{
frame.origin.x = x - frame.size.width
}
func ca_maxY() -> CGFloat{
return frame.origin.y + frame.size.height
}
func ca_maxY(y:CGFloat) -> Void{
frame.origin.y = y - frame.size.height
}
func ca_width() -> CGFloat{
return frame.size.width
}
func ca_width(w:CGFloat) -> Void{
frame.size.width = w
}
func ca_heigth() -> CGFloat{
return frame.size.height
}
func ca_height(h:CGFloat) -> Void{
frame.size.height = h
}
func ca_centerX() -> CGFloat{
return frame.origin.x + frame.size.width/2.0
}
func ca_centerX(x:CGFloat) -> Void{
frame.origin.x = x - frame.size.width/2.0
}
func ca_centerY() -> CGFloat{
return frame.origin.y + frame.size.height/2.0
}
func ca_centerY(y:CGFloat) -> Void{
frame.origin.y = y - frame.size.height/2.0
}
func ca_center() -> CGPoint{
return CGPoint(x: ca_centerX(), y: ca_centerY())
}
func ca_center(p:CGPoint) ->Void{
frame.origin.x = p.x - frame.size.width/2.0
frame.origin.y = p.y - frame.size.height/2.0
}
func ca_size() -> CGSize{
return frame.size
}
func ca_size(size:CGSize) -> Void{
frame.size = size
}
func ca_addX(increment:CGFloat) -> Void{
frame.origin.x += increment
}
func ca_addY(increment:CGFloat) -> Void{
frame.origin.y += increment
}
}
| 199df8b7f0cc9a378482677d9b8a016c | 16.693069 | 50 | 0.630106 | false | false | false | false |
VirgilSecurity/virgil-crypto-ios | refs/heads/master | Source/VirgilCrypto/VirgilCrypto+AuthEncrypt.swift | bsd-3-clause | 1 | //
// Copyright (C) 2015-2021 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
import VirgilCryptoFoundation
extension VirgilCrypto {
/// Signs (with private key) Then Encrypts data (and signature) for passed PublicKeys
///
/// 1. Generates signature depending on KeyType
/// 2. Generates random AES-256 KEY1
/// 3. Encrypts data with KEY1 using AES-256-GCM and generates signature
/// 4. Encrypts signature with KEY1 using AES-256-GCM
/// 5. Generates ephemeral key pair for each recipient
/// 6. Uses Diffie-Hellman to obtain shared secret with each recipient's public key & each ephemeral private key
/// 7. Computes KDF to obtain AES-256 key from shared secret for each recipient
/// 8. Encrypts KEY1 with this key using AES-256-CBC for each recipient
///
/// - Parameters:
/// - data: Data to be signedThenEncrypted
/// - privateKey: Sender private key
/// - recipients: Recipients' public keys
/// - enablePadding: If true, will add padding to plain text before encryption.
/// This is recommended for data for which exposing length can
/// cause security issues (e.g. text messages)
/// - Returns: SignedThenEncrypted data
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authEncrypt(_ data: Data, with privateKey: VirgilPrivateKey,
for recipients: [VirgilPublicKey], enablePadding: Bool = true) throws -> Data {
return try self.encrypt(inputOutput: .data(input: data),
signingOptions: SigningOptions(privateKey: privateKey, mode: .signThenEncrypt),
recipients: recipients,
enablePadding: enablePadding)!
}
/// Decrypts (with private key) data and signature and Verifies signature using any of signers' PublicKeys
///
/// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key
/// 2. Computes KDF to obtain AES-256 KEY2 from shared secret
/// 3. Decrypts KEY1 using AES-256-CBC
/// 4. Decrypts data and signature using KEY1 and AES-256-GCM
/// 5. Finds corresponding PublicKey according to signer id inside data
/// 6. Verifies signature
///
/// - Parameters:
/// - data: Signed Then Encrypted data
/// - privateKey: Receiver's private key
/// - signersPublicKeys: Array of possible signers public keys.
/// WARNING: Data should have signature of ANY public key from array.
/// - Returns: DecryptedThenVerified data
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authDecrypt(_ data: Data, with privateKey: VirgilPrivateKey,
usingOneOf signersPublicKeys: [VirgilPublicKey]) throws -> Data {
return try self.authDecrypt(data,
with: privateKey,
usingOneOf: signersPublicKeys,
allowNotEncryptedSignature: false)
}
/// Decrypts (with private key) data and signature and Verifies signature using any of signers' PublicKeys
///
/// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key
/// 2. Computes KDF to obtain AES-256 KEY2 from shared secret
/// 3. Decrypts KEY1 using AES-256-CBC
/// 4. Decrypts data and signature using KEY1 and AES-256-GCM
/// 5. Finds corresponding PublicKey according to signer id inside data
/// 6. Verifies signature
///
/// - Parameters:
/// - data: Signed Then Encrypted data
/// - privateKey: Receiver's private key
/// - signersPublicKeys: Array of possible signers public keys.
/// WARNING: Data should have signature of ANY public key from array.
/// - allowNotEncryptedSignature: Allows storing signature in plain text
/// for compatibility with deprecated signAndEncrypt
/// - Returns: DecryptedThenVerified data
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authDecrypt(_ data: Data, with privateKey: VirgilPrivateKey,
usingOneOf signersPublicKeys: [VirgilPublicKey],
allowNotEncryptedSignature: Bool) throws -> Data {
let verifyMode: VerifyingMode = allowNotEncryptedSignature ? .any : .decryptThenVerify
return try self.decrypt(inputOutput: .data(input: data),
verifyingOptions: VerifyingOptions(publicKeys: signersPublicKeys,
mode: verifyMode),
privateKey: privateKey)!
}
/// Signs (with private key) Then Encrypts stream (and signature) for passed PublicKeys
///
/// 1. Generates signature depending on KeyType
/// 2. Generates random AES-256 KEY1
/// 3. Encrypts data with KEY1 using AES-256-GCM and generates signature
/// 4. Encrypts signature with KEY1 using AES-256-GCM
/// 5. Generates ephemeral key pair for each recipient
/// 6. Uses Diffie-Hellman to obtain shared secret with each recipient's public key & each ephemeral private key
/// 7. Computes KDF to obtain AES-256 key from shared secret for each recipient
/// 8. Encrypts KEY1 with this key using AES-256-CBC for each recipient
///
/// - Parameters:
/// - stream: Input stream
/// - streamSize: Input stream size
/// - outputStream: Output stream
/// - privateKey: Private key to generate signatures
/// - recipients: Recipients public keys
/// - enablePadding: If true, will add padding to plain text before encryption.
/// This is recommended for data for which exposing length can
/// cause security issues (e.g. text messages)
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authEncrypt(_ stream: InputStream,
streamSize: Int,
to outputStream: OutputStream,
with privateKey: VirgilPrivateKey,
for recipients: [VirgilPublicKey],
enablePadding: Bool = false) throws {
_ = try self.encrypt(inputOutput: .stream(input: stream, streamSize: streamSize, output: outputStream),
signingOptions: SigningOptions(privateKey: privateKey, mode: .signThenEncrypt),
recipients: recipients,
enablePadding: enablePadding)
}
/// Decrypts (using passed PrivateKey) then verifies (using one of public keys) stream
///
/// - Note: Decrypted stream should not be used until decryption
/// of whole InputStream completed due to security reasons
///
/// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key
/// 2. Computes KDF to obtain AES-256 KEY2 from shared secret
/// 3. Decrypts KEY1 using AES-256-CBC
/// 4. Decrypts data and signature using KEY1 and AES-256-GCM
/// 5. Finds corresponding PublicKey according to signer id inside data
/// 6. Verifies signature
///
/// - Parameters:
/// - stream: Stream with encrypted data
/// - outputStream: Stream with decrypted data
/// - privateKey: Recipient's private key
/// - signersPublicKeys: Array of possible signers public keys.
/// WARNING: Stream should have signature of ANY public key from array.
/// - Throws: Rethrows from `RecipientCipher`.
@objc open func authDecrypt(_ stream: InputStream, to outputStream: OutputStream,
with privateKey: VirgilPrivateKey,
usingOneOf signersPublicKeys: [VirgilPublicKey]) throws {
_ = try self.decrypt(inputOutput: .stream(input: stream, streamSize: nil, output: outputStream),
verifyingOptions: VerifyingOptions(publicKeys: signersPublicKeys,
mode: .decryptThenVerify),
privateKey: privateKey)
}
}
| 3d9c236dad62b0ccd2b15a7ec991c767 | 54.165746 | 116 | 0.636855 | false | false | false | false |
jnross/Bluetility | refs/heads/main | Bluetility/Device.swift | mit | 1 | //
// Device.swift
// Bluetility
//
// Created by Joseph Ross on 7/1/20.
// Copyright © 2020 Joseph Ross. All rights reserved.
//
import CoreBluetooth
protocol DeviceDelegate: AnyObject {
func deviceDidConnect(_ device: Device)
func deviceDidDisconnect(_ device: Device)
func deviceDidUpdateName(_ device: Device)
func device(_ device: Device, updated services: [CBService])
func device(_ device: Device, updated characteristics: [CBCharacteristic], for service: CBService)
func device(_ device: Device, updatedValueFor characteristic: CBCharacteristic)
}
class Device : NSObject {
let peripheral: CBPeripheral
unowned var scanner: Scanner
var advertisingData: [String:Any]
var rssi: Int
weak var delegate: DeviceDelegate? = nil
// Transient data
var manufacturerName: String? = nil
var modelName: String? = nil
init(scanner: Scanner, peripheral: CBPeripheral, advertisingData: [String: Any], rssi: Int) {
self.scanner = scanner
self.peripheral = peripheral
self.advertisingData = advertisingData
self.rssi = rssi
super.init()
peripheral.delegate = self
}
deinit {
peripheral.delegate = nil
}
var friendlyName : String {
if let advertisedName = advertisingData[CBAdvertisementDataLocalNameKey] as? String {
return advertisedName
}
if let peripheralName = peripheral.name {
return peripheralName
}
let infoFields = [manufacturerName, modelName].compactMap({$0})
if infoFields.count > 0 {
return infoFields.joined(separator: " ")
}
return "Untitled"
}
var services: [CBService] {
return peripheral.services ?? []
}
func connect() {
scanner.central.connect(self.peripheral, options: [:])
}
func disconnect() {
scanner.central.cancelPeripheralConnection(self.peripheral)
}
func discoverCharacteristics(for service: CBService) {
peripheral.discoverCharacteristics(nil, for: service)
}
func read(characteristic: CBCharacteristic) {
peripheral.readValue(for: characteristic)
}
func write(data: Data, for characteristic: CBCharacteristic, type:CBCharacteristicWriteType) {
peripheral.writeValue(data, for: characteristic, type: type)
}
func setNotify(_ enabled: Bool, for characteristic: CBCharacteristic) {
peripheral.setNotifyValue(enabled, for: characteristic)
}
}
extension Device : CBPeripheralDelegate {
func peripheralDidConnect() {
peripheral.discoverServices(nil)
delegate?.deviceDidConnect(self)
}
func peripheralDidDisconnect(error: Error?) {
delegate?.deviceDidDisconnect(self)
}
func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
delegate?.deviceDidUpdateName(self)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
let services = peripheral.services ?? []
handleSpecialServices(services)
delegate?.device(self, updated: services)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
let characteristics = service.characteristics ?? []
handleSpecialCharacteristics(characteristics)
delegate?.device(self, updated: characteristics, for: service)
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
handleSpecialCharacteristic(characteristic)
delegate?.device(self, updatedValueFor: characteristic)
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
// TODO: report successful write?
}
}
// MARK: Handle Special Characteristics
fileprivate let specialServiceUUIDs = [
CBUUID(string: "180A"), // Device Information Service
]
fileprivate let manufacturerNameUUID = CBUUID(string: "2A29")
fileprivate let modelNumberUUID = CBUUID(string: "2A24")
fileprivate let specialCharacteristicUUIDs = [
manufacturerNameUUID, // Manufacturer Name
modelNumberUUID, // Model Number
]
extension Device {
func handleSpecialServices(_ services: [CBService]) {
for service in services {
if specialServiceUUIDs.contains(service.uuid) {
peripheral.discoverCharacteristics(specialCharacteristicUUIDs, for: service)
}
}
}
func handleSpecialCharacteristics(_ characteristics: [CBCharacteristic]) {
for characteristic in characteristics {
if specialCharacteristicUUIDs.contains(characteristic.uuid) {
peripheral.readValue(for: characteristic)
handleSpecialCharacteristic(characteristic)
}
}
}
func handleSpecialCharacteristic(_ characteristic: CBCharacteristic) {
guard let value = characteristic.value else { return }
if specialCharacteristicUUIDs.contains(characteristic.uuid) {
switch characteristic.uuid {
case manufacturerNameUUID:
manufacturerName = String(bytes: value, encoding: .utf8)
case modelNumberUUID:
modelName = String(bytes: value, encoding: .utf8)
default:
assertionFailure("Forgot to handle one of the UUIDs in specialCharacteristicUUIDs: \(characteristic.uuid)")
}
delegate?.deviceDidUpdateName(self)
}
}
}
| 5198a6ea6b4eb26835ad6a51175ab7b4 | 31.091837 | 123 | 0.647218 | false | false | false | false |
twostraws/HackingWithSwift | refs/heads/main | Classic/project33/Project33/AddCommentsViewController.swift | unlicense | 1 | //
// AddCommentsViewController.swift
// Project33
//
// Created by TwoStraws on 24/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
class AddCommentsViewController: UIViewController, UITextViewDelegate {
var genre: String!
var comments: UITextView!
let placeholder = "If you have any additional comments that might help identify your tune, enter them here."
override func loadView() {
view = UIView()
view.backgroundColor = .white
comments = UITextView()
comments.translatesAutoresizingMaskIntoConstraints = false
comments.delegate = self
comments.font = UIFont.preferredFont(forTextStyle: .body)
view.addSubview(comments)
comments.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
comments.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
comments.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
comments.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Comments"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Submit", style: .plain, target: self, action: #selector(submitTapped))
comments.text = placeholder
}
@objc func submitTapped() {
let vc = SubmitViewController()
vc.genre = genre
if comments.text == placeholder {
vc.comments = ""
} else {
vc.comments = comments.text
}
navigationController?.pushViewController(vc, animated: true)
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text == placeholder {
textView.text = ""
}
}
}
| 3b4ceb8c22efc8077d5e5216954f9d33 | 27.237288 | 132 | 0.748499 | false | false | false | false |
DrGo/LearningSwift | refs/heads/master | PLAYGROUNDS/ExpressionParser/ExpressionParser/TokenParser.swift | gpl-3.0 | 2 | //
// TokenParser.swift
// ExpressionParser
//
// Created by Kyle Oba on 2/6/15.
// Copyright (c) 2015 Pas de Chocolat. All rights reserved.
//
import Foundation
/*---------------------------------------------------------------------/
// Expressions - Can be numbers, references, binary expressions with,
// an operator, or function calls.
//
// This recursive Enum is the Abstract Syntax Tree for our
// spreadsheet expressions.
//
// ExpressionLike is a work around because Swift doesn't currently
// allow recursive Enums.
/---------------------------------------------------------------------*/
public protocol ExpressionLike {
func toExpression() -> Expression
}
public enum Expression {
case Number(Int)
case Reference(String, Int)
case BinaryExpression(String, ExpressionLike, ExpressionLike)
case FunctionCall(String, ExpressionLike)
}
extension Expression: ExpressionLike {
public func toExpression() -> Expression {
return self
}
}
// Computes expression values from a stream of tokens
typealias ExpressionParser = Parser<Token, Expression>
/*---------------------------------------------------------------------/
// optionalTransform - Generates a parser that satisfies a predicate
// or returns nil
/---------------------------------------------------------------------*/
func optionalTransform<A, T>(f: T -> A?) -> Parser<T, A> {
return { f($0)! } </> satisfy { f($0) != nil }
}
/*---------------------------------------------------------------------/
// pNumber - Number parser
/---------------------------------------------------------------------*/
let pNumber: ExpressionParser = optionalTransform {
switch $0 {
case .Number(let number):
return Expression.Number(number)
default:
return nil
}
}
/*---------------------------------------------------------------------/
// pReference - Cell reference parser
/---------------------------------------------------------------------*/
let pReference: ExpressionParser = optionalTransform {
switch $0 {
case .Reference(let column, let row):
return Expression.Reference(column, row)
default:
return nil
}
}
let pNumberOrReference = pNumber <|> pReference
extension Expression : Printable {
public var description: String {
switch (self) {
case Number(let x):
return "\(x)"
case let .Reference(col, row):
return "\(col)\(row)"
case let Expression.BinaryExpression(binaryOp, expLike1, expLike2):
let operand1 = expLike1.toExpression().description
let operand2 = expLike2.toExpression().description
return "\(operand1) \(binaryOp) \(operand2)"
case let .FunctionCall(fn, expLike):
let expr = expLike.toExpression().description
return "\(fn)(\(expr))"
}
}
}
func readExpression(expr: Expression) -> String {
var header = ""
switch (expr) {
case .Number:
header = "Number"
case .Reference:
header = "Reference"
case .BinaryExpression:
header = "Binary Expression"
case .FunctionCall:
header = "Function"
}
return "\(header): \(expr.description)"
}
/*---------------------------------------------------------------------/
// pFunctionName - Function name parser
/---------------------------------------------------------------------*/
let pFunctionName: Parser<Token, String> = optionalTransform {
switch $0 {
case .FunctionName(let name):
return name
default:
return nil
}
}
/*---------------------------------------------------------------------/
// pList - List parser
/---------------------------------------------------------------------*/
func makeList(l: Expression, r: Expression) -> Expression {
return Expression.BinaryExpression(":", l, r)
}
func op(opString: String) -> Parser<Token, String> {
return const(opString) </> token(Token.Operator(opString))
}
let pList: ExpressionParser = curry(makeList) </> pReference <* op(":") <*> pReference
/*---------------------------------------------------------------------/
// parenthesized - Generates Parser for parenthesized expression
/---------------------------------------------------------------------*/
func parenthesized<A>(p: Parser<Token, A>) -> Parser<Token, A> {
return token(Token.Punctuation("(")) *> p <* token(Token.Punctuation(")"))
}
/*---------------------------------------------------------------------/
// pFunctionCall - Put it all together to create function call Parser
/---------------------------------------------------------------------*/
func makeFunctionCall(name: String, arg: Expression) -> Expression {
return Expression.FunctionCall(name, arg)
}
let pFunctionCall = curry(makeFunctionCall) </> pFunctionName <*> parenthesized(pList)
/*---------------------------------------------------------------------/
// Parsers for formula primitives - start with the smallest
/---------------------------------------------------------------------*/
func expression() -> ExpressionParser {
return pSum
}
let pParenthesizedExpression = parenthesized(lazy(expression()))
let pPrimitive = pNumberOrReference <|> pFunctionCall <|> pParenthesizedExpression
/*---------------------------------------------------------------------/
// pMultiplier - Multiplication or Division are equal
/---------------------------------------------------------------------*/
let pMultiplier = curry { ($0, $1) } </> (op("*") <|> op("/")) <*> pPrimitive
/*---------------------------------------------------------------------/
// combineOperands - Build an expression tree from primitive and
// multipier tuples
/---------------------------------------------------------------------*/
func combineOperands(first: Expression, rest: [(String, Expression)]) -> Expression {
return rest.reduce(first, combine: { result, pair in
let (op, exp) = pair
return Expression.BinaryExpression(op, result, exp)
})
}
/*---------------------------------------------------------------------/
// pProduct - Combine tuples from pMultiplier (also handles division)
/---------------------------------------------------------------------*/
let pProduct = curry(combineOperands) </> pPrimitive <*> zeroOrMore(pMultiplier)
/*---------------------------------------------------------------------/
// pSum - Do the same for addition and subtraction
/---------------------------------------------------------------------*/
let pSummand = curry { ($0, $1) } </> (op("-") <|> op("+")) <*> pProduct
let pSum = curry(combineOperands) </> pProduct <*> zeroOrMore(pSummand)
/*---------------------------------------------------------------------/
// parseExpression - Tokenizer combined with Parsers
/---------------------------------------------------------------------*/
func parseExpressionWithoutFlatmap(input: String) -> Expression? {
if let tokens = parse(tokenize(), input) {
return parse(expression(), tokens)
}
return nil
}
// Can also use `flatMap` for this
func flatMap<A, B>(x: A?, f: A -> B?) -> B? {
if let value = x {
return f(value)
}
return nil
}
public func parseExpression(input: String) -> Expression? {
return flatMap(parse(tokenize(), input)) {
parse(expression(), $0)
}
}
| 5add9e3df68b50d236af74dd87e66b17 | 30.382609 | 86 | 0.489194 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Shared/SharePost.swift | gpl-2.0 | 2 | import Foundation
import MobileCoreServices
/// A simple shared model to represent a Site
///
@objc class ShareBlog: NSObject {
@objc static let typeIdentifier = "org.wordpress.share-blog"
}
/// A simple shared model to represent a post
///
/// This is a simplified version of a post used as a base for sharing amongst
/// the app, the Share extension, and other share options.
///
/// It supports NSCoding and can be imported/exported as NSData. It also defines
/// its own UTI data type.
///
@objc class SharePost: NSObject, NSSecureCoding {
@objc static let typeIdentifier = "org.wordpress.share-post"
@objc static let activityType = UIActivity.ActivityType(rawValue: "org.wordpress.WordPressShare")
@objc let title: String?
@objc let summary: String?
@objc let url: URL?
@objc init(title: String?, summary: String?, url: String?) {
self.title = title
self.summary = summary
self.url = url.flatMap(URL.init(string:))
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let title = aDecoder.decodeString(forKey: .title)
let summary = aDecoder.decodeString(forKey: .summary)
let url = aDecoder.decodeString(forKey: .url)
self.init(title: title, summary: summary, url: url)
}
@objc convenience init?(data: Data) {
do {
let decoder = try NSKeyedUnarchiver(forReadingFrom: data)
self.init(coder: decoder)
} catch {
return nil
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: .title)
aCoder.encode(summary, forKey: .summary)
aCoder.encode(url?.absoluteString, forKey: .url)
}
static var supportsSecureCoding: Bool {
return true
}
@objc var content: String {
var content = ""
if let title = title {
content.append("\(title)\n\n")
}
if let url = url {
content.append(url.absoluteString)
}
return content
}
@objc var data: Data {
let encoder = NSKeyedArchiver(requiringSecureCoding: false)
encode(with: encoder)
encoder.finishEncoding()
return encoder.encodedData
}
}
extension SharePost {
private func decode(coder: NSCoder, key: Key) -> String? {
return coder.decodeObject(forKey: key.rawValue) as? String
}
private func encode(coder: NSCoder, string: String?, forKey key: Key) {
guard let string = string else {
return
}
coder.encode(string, forKey: key.rawValue)
}
enum Key: String {
case title
case summary
case url
}
}
private extension NSCoder {
func encode(_ string: String?, forKey key: SharePost.Key) {
guard let string = string else {
return
}
encode(string, forKey: key.rawValue)
}
func decodeString(forKey key: SharePost.Key) -> String? {
return decodeObject(forKey: key.rawValue) as? String
}
}
| 78dc4f52f3f7e62012c69d1564e3a89a | 27.212963 | 101 | 0.621923 | false | false | false | false |
SirArkimedes/WWDC-2015 | refs/heads/master | Andrew Robinson/GameScene.swift | mit | 1 | //
// GameScene.swift
// Andrew Robinson
//
// Created by Andrew Robinson on 4/19/15.
// Copyright (c) 2015 Andrew Robinson. All rights reserved.
//
import UIKit
import SpriteKit
class GameScene: SKScene {
var circles : [SKShapeNode] = [SKShapeNode]()
var xVelocity: CGFloat = 0
var kMaxLeft : CGFloat = 0
var kMaxRight : CGFloat = 0
var kMaxBottom : CGFloat = 0
var kMaxTop : CGFloat = 0
override func didMoveToView(view: SKView) {
let minusSize : CGFloat = 0
// Set variables
kMaxLeft = CGFloat((5/6)*self.frame.size.width) + minusSize
kMaxRight = self.frame.size.width/6 - minusSize
kMaxBottom = self.frame.size.height/8 - minusSize
kMaxTop = CGFloat((7/8)*self.frame.size.height) + minusSize
var circle = self.circle();
self.addChild(circle)
circle.physicsBody?.applyForce(CGVectorMake(50, 50))
circles.append(circle)
// Fade it in
circle.runAction(SKAction.fadeAlphaTo(1, duration: 1.5))
// Create the loop
self.spawnMore();
// No gravity!
self.physicsWorld.gravity = CGVectorMake(0, 0)
self.physicsBody = SKPhysicsBody(edgeLoopFromRect:self.frame)
}
func circle() -> SKShapeNode {
var circleRadius : CGFloat
let randRadius : UInt32 = arc4random_uniform(3)
var color : SKColor
let randColor : UInt32 = arc4random_uniform(3)
switch randRadius {
case 0:
circleRadius = 50
case 1:
circleRadius = 30
case 2:
circleRadius = 20
default:
circleRadius = 10
}
switch randColor {
case 0:
color = SKColor.blueColor()
case 1:
color = SKColor.purpleColor()
case 2:
color = SKColor.redColor()
default:
color = SKColor.blackColor()
}
var circle = SKShapeNode(circleOfRadius:circleRadius) // Size of Circle
circle.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
circle.physicsBody = SKPhysicsBody(circleOfRadius:circleRadius)
circle.physicsBody!.dynamic = true
circle.strokeColor = SKColor.clearColor()
circle.fillColor = color
circle.alpha = 0
return circle;
}
func spawnMore() {
if circles.count < 10 {
delay(1) {
var circle = self.circle();
self.addChild(circle)
circle.physicsBody?.applyForce(CGVectorMake(-500, -500))
self.circles.append(circle)
// Fade it in
circle.runAction(SKAction.fadeAlphaTo(1, duration: 1.5))
self.spawnMore();
}
}
}
// MARK: Update
override func update(currentTime: CFTimeInterval) {
// Move!
for sprite : SKShapeNode in circles {
if sprite.position.x > kMaxLeft {
sprite.physicsBody?.applyImpulse(CGVectorMake(-30, 0))
}
if sprite.position.x < kMaxRight {
sprite.physicsBody?.applyImpulse(CGVectorMake(30, 0))
}
if sprite.position.y < kMaxBottom {
sprite.physicsBody?.applyImpulse(CGVectorMake(0, 30))
}
if sprite.position.y > kMaxTop {
sprite.physicsBody?.applyImpulse(CGVectorMake(0, -30))
}
}
}
// MARK: Delay
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
| 6433f9d98e1d2a56482dfbff6d2661b0 | 25.934641 | 88 | 0.514196 | false | false | false | false |
ryet231ere/DouYuSwift | refs/heads/master | douyu/douyu/Classes/Main/View/PageContentView.swift | mit | 1 | //
// PageContentView.swift
// douyu
//
// Created by 练锦波 on 2017/2/6.
// Copyright © 2017年 练锦波. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class{
func pageContentView(contentView : PageContentView, progress: CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let ContentId = "ContentId"
class PageContentView: UIView {
// MARK: - 定义属性
fileprivate var childVcs : [UIViewController]
fileprivate weak var parentViewController : UIViewController?
fileprivate var startOffsetX : CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
//1. 创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//2. 创建UICollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:ContentId)
return collectionView
}()
// MARK: - 自定义构造函数
init(frame: CGRect, childVcs : [UIViewController], parentViewController : UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension PageContentView{
fileprivate func setupUI() {
//1. 将所有的子控制器添加到父控制器中
for childVc in childVcs{
parentViewController?.addChildViewController(childVc)
}
//2. 添加UICollectionView,用于在Cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1. 创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentId, for: indexPath)
//2. 给cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
// MARK:- 遵守UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 0. 判断是否是点击事件
if isForbidScrollDelegate {
return
}
// 1.定义获取需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
// 2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1.计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2. 计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3. 计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
// 4. 如果完全划过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
} else { // 右滑
// 1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2. 计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3. 计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
// 3.将progress/targetIndex/sourceIndex传递给titleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
// MARK:- 对外暴露的方法
extension PageContentView {
func setCurrentIndex(currentIndex : Int) {
// 1. 记录需要禁止执行代理方法
isForbidScrollDelegate = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| deff87d2c9ca47f3478513c7d762f293 | 31.389222 | 124 | 0.63228 | false | false | false | false |
allbto/iOS-DynamicRegistration | refs/heads/master | Pods/Swiftility/Swiftility/Swiftility/Classes/Types/Dynamic.swift | mit | 1 | //
// Dynamic.swift
// Swiftility
//
// Created by Allan Barbato on 9/9/15.
// Copyright © 2015 Allan Barbato. All rights reserved.
//
import Foundation
public struct Dynamic<T>
{
public typealias Listener = T -> Void
// MARK: - Private
private var _listener: Listener?
// MARK: - Properties
/// Contained value. Changes fire listener if `self.shouldFire == true`
public var value: T {
didSet {
guard shouldFire == true else { return }
self.fire()
}
}
/// Whether value didSet should fire or not
public var shouldFire: Bool = true
/// Whether fire() should call listener on main thread or not
public var fireOnMainThread: Bool = true
// Has a listener
public var isBinded: Bool {
return _listener != nil
}
// MARK: - Life cycle
/// Init with a value
public init(_ v: T)
{
value = v
}
// MARK: - Binding
/**
Bind a listener to value changes
- parameter listener: Closure called when value changes
*/
public mutating func bind(listener: Listener?)
{
_listener = listener
}
/**
Same as `bind` but also fires immediately
- parameter listener: Closure called immediately and when value changes
*/
public mutating func bindAndFire(listener: Listener?)
{
self.bind(listener)
self.fire()
}
// MARK: - Actions
// Fires listener if not nil. Regardless of `self.shouldFire`
public func fire()
{
if fireOnMainThread {
dispatch_async(dispatch_get_main_queue(), {
self._listener?(self.value)
})
} else {
self._listener?(self.value)
}
}
/**
Set value with optional firing. Regardless of `self.shouldFire`
- parameter value: Value to update to
- parameter =true;fire: Should fire changes of value
*/
public mutating func setValue(value: T, fire: Bool = true)
{
let originalShouldFire = shouldFire
shouldFire = fire
self.value = value
shouldFire = originalShouldFire
}
} | 395cd73058a2986fb6ca6f5344ba8cc3 | 21.3 | 76 | 0.571108 | false | false | false | false |
SPECURE/rmbt-ios-client | refs/heads/main | Sources/OperatorsResponse.swift | apache-2.0 | 1 | /*****************************************************************************************************
* Copyright 2016 SPECURE GmbH
*
* 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 ObjectMapper
///
open class OperatorsResponse: BasicResponse {
open class Operator: NSObject, Mappable {
open var isDefault = false
open var title: String = ""
open var subtitle: String = ""
open var idProvider: Int?
open var provider: String?
open var providerForRequest: String {
if let idProvider = self.idProvider {
return String(format: "%d", idProvider)
} else if let provider = provider {
return provider
}
return ""
}
public required init?(map: Map) {
}
open func mapping(map: Map) {
isDefault <- map["default"]
idProvider <- map["id_provider"]
provider <- map["provider"]
title <- map["title"]
subtitle <- map["detail"]
}
}
///
open var operators: [OperatorsResponse.Operator]?
open var title: String = ""
///
override open func mapping(map: Map) {
super.mapping(map: map)
operators <- map["options"]
title <- map["title"]
}
}
| f6d7d03ed89b73fcf89b06e73c14d39f | 30.634921 | 103 | 0.529353 | false | false | false | false |
shajrawi/swift | refs/heads/master | stdlib/public/core/SmallString.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// The code units in _SmallString are always stored in memory in the same order
// that they would be stored in an array. This means that on big-endian
// platforms the order of the bytes in storage is reversed compared to
// _StringObject whereas on little-endian platforms the order is the same.
//
// Memory layout:
//
// |0 1 2 3 4 5 6 7 8 9 A B C D E F| ← hexadecimal offset in bytes
// | _storage.0 | _storage.1 | ← raw bits
// | code units | | ← encoded layout
// ↑ ↑
// first (leftmost) code unit discriminator (incl. count)
//
@_fixed_layout @usableFromInline
internal struct _SmallString {
@usableFromInline
internal typealias RawBitPattern = (UInt64, UInt64)
// Small strings are values; store them raw
@usableFromInline
internal var _storage: RawBitPattern
@inlinable @inline(__always)
internal var rawBits: RawBitPattern { return _storage }
@inlinable
internal var leadingRawBits: UInt64 {
@inline(__always) get { return _storage.0 }
@inline(__always) set { _storage.0 = newValue }
}
@inlinable
internal var trailingRawBits: UInt64 {
@inline(__always) get { return _storage.1 }
@inline(__always) set { _storage.1 = newValue }
}
@inlinable @inline(__always)
internal init(rawUnchecked bits: RawBitPattern) {
self._storage = bits
}
@inlinable @inline(__always)
internal init(raw bits: RawBitPattern) {
self.init(rawUnchecked: bits)
_invariantCheck()
}
@inlinable @inline(__always)
internal init(_ object: _StringObject) {
_internalInvariant(object.isSmall)
// On big-endian platforms the byte order is the reverse of _StringObject.
let leading = object.rawBits.0.littleEndian
let trailing = object.rawBits.1.littleEndian
self.init(raw: (leading, trailing))
}
@inlinable @inline(__always)
internal init() {
self.init(_StringObject(empty:()))
}
}
extension _SmallString {
@inlinable @inline(__always)
internal static var capacity: Int {
#if arch(i386) || arch(arm)
return 10
#else
return 15
#endif
}
// Get an integer equivalent to the _StringObject.discriminatedObjectRawBits
// computed property.
@inlinable @inline(__always)
internal var rawDiscriminatedObject: UInt64 {
// Reverse the bytes on big-endian systems.
return _storage.1.littleEndian
}
@inlinable @inline(__always)
internal var capacity: Int { return _SmallString.capacity }
@inlinable @inline(__always)
internal var count: Int {
return _StringObject.getSmallCount(fromRaw: rawDiscriminatedObject)
}
@inlinable @inline(__always)
internal var unusedCapacity: Int { return capacity &- count }
@inlinable @inline(__always)
internal var isASCII: Bool {
return _StringObject.getSmallIsASCII(fromRaw: rawDiscriminatedObject)
}
// Give raw, nul-terminated code units. This is only for limited internal
// usage: it always clears the discriminator and count (in case it's full)
@inlinable @inline(__always)
internal var zeroTerminatedRawCodeUnits: RawBitPattern {
let smallStringCodeUnitMask = ~UInt64(0xFF).bigEndian // zero last byte
return (self._storage.0, self._storage.1 & smallStringCodeUnitMask)
}
internal func computeIsASCII() -> Bool {
let asciiMask: UInt64 = 0x8080_8080_8080_8080
let raw = zeroTerminatedRawCodeUnits
return (raw.0 | raw.1) & asciiMask == 0
}
}
// Internal invariants
extension _SmallString {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
_internalInvariant(count <= _SmallString.capacity)
_internalInvariant(isASCII == computeIsASCII())
}
#endif // INTERNAL_CHECKS_ENABLED
internal func _dump() {
#if INTERNAL_CHECKS_ENABLED
print("""
smallUTF8: count: \(self.count), codeUnits: \(
self.map { String($0, radix: 16) }.joined()
)
""")
#endif // INTERNAL_CHECKS_ENABLED
}
}
// Provide a RAC interface
extension _SmallString: RandomAccessCollection, MutableCollection {
@usableFromInline
internal typealias Index = Int
@usableFromInline
internal typealias Element = UInt8
@usableFromInline
internal typealias SubSequence = _SmallString
@inlinable @inline(__always)
internal var startIndex: Int { return 0 }
@inlinable @inline(__always)
internal var endIndex: Int { return count }
@inlinable
internal subscript(_ idx: Int) -> UInt8 {
@inline(__always) get {
_internalInvariant(idx >= 0 && idx <= 15)
if idx < 8 {
return leadingRawBits._uncheckedGetByte(at: idx)
} else {
return trailingRawBits._uncheckedGetByte(at: idx &- 8)
}
}
@inline(__always) set {
_internalInvariant(idx >= 0 && idx <= 15)
if idx < 8 {
leadingRawBits._uncheckedSetByte(at: idx, to: newValue)
} else {
trailingRawBits._uncheckedSetByte(at: idx &- 8, to: newValue)
}
}
}
@inlinable @inline(__always)
internal subscript(_ bounds: Range<Index>) -> SubSequence {
// TODO(String performance): In-vector-register operation
return self.withUTF8 { utf8 in
let rebased = UnsafeBufferPointer(rebasing: utf8[bounds])
return _SmallString(rebased)._unsafelyUnwrappedUnchecked
}
}
}
extension _SmallString {
@inlinable @inline(__always)
internal func withUTF8<Result>(
_ f: (UnsafeBufferPointer<UInt8>) throws -> Result
) rethrows -> Result {
var raw = self.zeroTerminatedRawCodeUnits
return try Swift.withUnsafeBytes(of: &raw) { rawBufPtr in
let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked
.assumingMemoryBound(to: UInt8.self)
return try f(UnsafeBufferPointer(start: ptr, count: self.count))
}
}
// Overwrite stored code units, including uninitialized. `f` should return the
// new count.
@inline(__always)
internal mutating func withMutableCapacity(
_ f: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
) rethrows {
let len = try withUnsafeMutableBytes(of: &self._storage) {
(rawBufPtr: UnsafeMutableRawBufferPointer) -> Int in
let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked
.assumingMemoryBound(to: UInt8.self)
return try f(UnsafeMutableBufferPointer(
start: ptr, count: _SmallString.capacity))
}
_internalInvariant(len <= _SmallString.capacity)
let (leading, trailing) = self.zeroTerminatedRawCodeUnits
self = _SmallString(leading: leading, trailing: trailing, count: len)
}
}
// Creation
extension _SmallString {
@inlinable @inline(__always)
internal init(leading: UInt64, trailing: UInt64, count: Int) {
_internalInvariant(count <= _SmallString.capacity)
let isASCII = (leading | trailing) & 0x8080_8080_8080_8080 == 0
let discriminator = _StringObject.Nibbles
.small(withCount: count, isASCII: isASCII)
.littleEndian // reversed byte order on big-endian platforms
_internalInvariant(trailing & discriminator == 0)
self.init(raw: (leading, trailing | discriminator))
_internalInvariant(self.count == count)
}
// Direct from UTF-8
@inlinable @inline(__always)
internal init?(_ input: UnsafeBufferPointer<UInt8>) {
if input.isEmpty {
self.init()
return
}
let count = input.count
guard count <= _SmallString.capacity else { return nil }
// TODO(SIMD): The below can be replaced with just be a masked unaligned
// vector load
let ptr = input.baseAddress._unsafelyUnwrappedUnchecked
let leading = _bytesToUInt64(ptr, Swift.min(input.count, 8))
let trailing = count > 8 ? _bytesToUInt64(ptr + 8, count &- 8) : 0
self.init(leading: leading, trailing: trailing, count: count)
}
@usableFromInline // @testable
internal init?(_ base: _SmallString, appending other: _SmallString) {
let totalCount = base.count + other.count
guard totalCount <= _SmallString.capacity else { return nil }
// TODO(SIMD): The below can be replaced with just be a couple vector ops
var result = base
var writeIdx = base.count
for readIdx in 0..<other.count {
result[writeIdx] = other[readIdx]
writeIdx &+= 1
}
_internalInvariant(writeIdx == totalCount)
let (leading, trailing) = result.zeroTerminatedRawCodeUnits
self.init(leading: leading, trailing: trailing, count: totalCount)
}
}
#if _runtime(_ObjC) && !(arch(i386) || arch(arm))
// Cocoa interop
extension _SmallString {
// Resiliently create from a tagged cocoa string
//
@_effects(readonly) // @opaque
@usableFromInline // testable
internal init(taggedCocoa cocoa: AnyObject) {
self.init()
self.withMutableCapacity {
let len = _bridgeTagged(cocoa, intoUTF8: $0)
_internalInvariant(len != nil && len! < _SmallString.capacity,
"Internal invariant violated: large tagged NSStrings")
return len._unsafelyUnwrappedUnchecked
}
self._invariantCheck()
}
}
#endif
extension UInt64 {
// Fetches the `i`th byte in memory order. On little-endian systems the byte
// at i=0 is the least significant byte (LSB) while on big-endian systems the
// byte at i=7 is the LSB.
@inlinable @inline(__always)
internal func _uncheckedGetByte(at i: Int) -> UInt8 {
_internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride)
#if _endian(big)
let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8
#else
let shift = UInt64(truncatingIfNeeded: i) &* 8
#endif
return UInt8(truncatingIfNeeded: (self &>> shift))
}
// Sets the `i`th byte in memory order. On little-endian systems the byte
// at i=0 is the least significant byte (LSB) while on big-endian systems the
// byte at i=7 is the LSB.
@inlinable @inline(__always)
internal mutating func _uncheckedSetByte(at i: Int, to value: UInt8) {
_internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride)
#if _endian(big)
let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8
#else
let shift = UInt64(truncatingIfNeeded: i) &* 8
#endif
let valueMask: UInt64 = 0xFF &<< shift
self = (self & ~valueMask) | (UInt64(truncatingIfNeeded: value) &<< shift)
}
}
@inlinable @inline(__always)
internal func _bytesToUInt64(
_ input: UnsafePointer<UInt8>,
_ c: Int
) -> UInt64 {
// FIXME: This should be unified with _loadPartialUnalignedUInt64LE.
// Unfortunately that causes regressions in literal concatenation tests. (Some
// owned to guaranteed specializations don't get inlined.)
var r: UInt64 = 0
var shift: Int = 0
for idx in 0..<c {
r = r | (UInt64(input[idx]) &<< shift)
shift = shift &+ 8
}
// Convert from little-endian to host byte order.
return r.littleEndian
}
| c450d40efce91ce265b16fefa1ac51ae | 31.14245 | 80 | 0.673994 | false | false | false | false |
eBardX/XestiMonitors | refs/heads/master | Sources/Core/CoreLocation/BeaconRangingMonitor.swift | mit | 1 | //
// BeaconRangingMonitor.swift
// XestiMonitors
//
// Created by J. G. Pusey on 2018-03-21.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
#if os(iOS)
import CoreLocation
///
/// A `BeaconRangingMonitor` instance monitors a region for changes to the
/// ranges (*i.e.,* the relative proximity) to the Bluetooth low-energy beacons
/// within.
///
public class BeaconRangingMonitor: BaseMonitor {
///
/// Encapsulates changes to the beacon ranges within a region.
///
public enum Event {
///
/// The beacon ranges have been updated.
///
case didUpdate(Info)
}
///
/// Encapsulates information associated with a beacon ranging monitor
/// event.
///
public enum Info {
///
/// The current beacon ranges.
///
case beacons([CLBeacon], CLBeaconRegion)
///
/// The error encountered in attempting to determine the beacon ranges
/// within the region.
///
case error(Error, CLBeaconRegion)
}
///
/// Initializes a new `BeaconRangingMonitor`.
///
/// - Parameters:
/// - region: The beacon region to monitor.
/// - queue: The operation queue on which the handler executes.
/// - handler: The handler to call when a beacon range change is
/// detected.
///
public init(region: CLBeaconRegion,
queue: OperationQueue,
handler: @escaping (Event) -> Void) {
self.adapter = .init()
self.handler = handler
self.locationManager = LocationManagerInjector.inject()
self.queue = queue
self.region = region
super.init()
self.adapter.didFail = handleDidFail
self.adapter.didRangeBeacons = handleDidRangeBeacons
self.adapter.rangingBeaconsDidFail = handleRangingBeaconsDidFail
self.locationManager.delegate = self.adapter
}
///
/// The beacon region being monitored.
///
public let region: CLBeaconRegion
///
/// A Boolean value indicating whether the region is actively being tracked
/// using ranging. There is a system-imposed, per-app limit to how many
/// regions can be actively ranged.
///
public var isActivelyRanged: Bool {
return isMonitoring
&& locationManager.rangedRegions.contains(region)
}
///
/// A Boolean value indicating whether the device supports the ranging of
/// Bluetooth beacons.
///
public var isAvailable: Bool {
return type(of: locationManager).isRangingAvailable()
}
private let adapter: LocationManagerDelegateAdapter
private let handler: (Event) -> Void
private let locationManager: LocationManagerProtocol
private let queue: OperationQueue
private func handleDidFail(_ error: Error) {
handler(.didUpdate(.error(error, region)))
}
private func handleDidRangeBeacons(_ region: CLBeaconRegion,
_ beacons: [CLBeacon]) {
if self.region == region {
self.handler(.didUpdate(.beacons(beacons, region)))
}
}
private func handleRangingBeaconsDidFail(_ region: CLBeaconRegion,
_ error: Error) {
if self.region == region {
self.handler(.didUpdate(.error(error, region)))
}
}
override public func cleanupMonitor() {
locationManager.stopRangingBeacons(in: region)
super.cleanupMonitor()
}
override public func configureMonitor() {
super.configureMonitor()
locationManager.startRangingBeacons(in: region)
}
}
#endif
| eae718b2739a1074b1ebf62fc5679a05 | 26.864662 | 79 | 0.607933 | false | false | false | false |
Authman2/AUNavigationMenuController | refs/heads/master | AUNavigationMenuController/Classes/NavigationMenuItem.swift | gpl-3.0 | 2 | //
// NavigationMenuItem.swift
// TestingAUNavMenuCont
//
// Created by Adeola Uthman on 11/25/16.
// Copyright © 2016 Adeola Uthman. All rights reserved.
//
import Foundation
import UIKit
public class NavigationMenuItem: NSObject {
// The name of the menu item.
public var name: String!;
// The iamge that goes along with the menu item.
public var image: UIImage?;
// The destination view controller for when this menu item is tapped.
public var destination: UIViewController!;
// The overall navigation controller.
let navCont: AUNavigationMenuController!;
// The completion method.
var completion: (() -> Void)?;
/////////////////////////
//
// Methods
//
/////////////////////////
init(name: String, image: UIImage?, navCont: AUNavigationMenuController, destination: UIViewController, completion: (() -> Void)?) {
self.name = name;
self.image = image;
self.destination = destination;
self.navCont = navCont;
self.completion = completion;
navCont.navigationItem.hidesBackButton = true;
}
/* Goes to the destination view controller.
*/
public func goToDestination(toggle: Bool) {
if navCont.topViewController != destination {
navCont.popToRootViewController(animated: false);
navCont.pushViewController(destination, animated: false);
destination.navigationItem.hidesBackButton = true;
if(toggle) {
navCont.togglePulldownMenu();
}
} else {
navCont.togglePulldownMenu();
}
if let comp = completion {
comp();
}
}
}
| 204f361a579b43a6fd245f7413c2baa2 | 22.818182 | 136 | 0.56434 | false | false | false | false |
WestlakeAPC/game-off-2016 | refs/heads/master | external/Fiber2D/Fiber2D/Scheduler.swift | apache-2.0 | 1 | //
// Scheduler.swift
// Fiber2D
//
// Created by Andrey Volodin on 28.08.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
private class MockNode: Node {
override var priority: Int {
get { return Int.min }
set { }
}
}
internal struct UnownedContainer<T> where T: AnyObject {
unowned var value : T
init(_ value: T) {
self.value = value
}
}
/**
Scheduler is responsible for triggering scheduled callbacks. All scheduled and timed events should use this class, rather than NSTimer.
Generally, you interface with the scheduler by using the "schedule"/"scheduleBlock" methods in Node. You may need to aess Scheduler
in order to aess read-only time properties or to adjust the time scale.
*/
public final class Scheduler {
/** Modifies the time of all scheduled callbacks.
You can use this property to create a 'slow motion' or 'fast forward' effect.
Default is 1.0. To create a 'slow motion' effect, use values below 1.0.
To create a 'fast forward' effect, use values higher than 1.0.
@warning It will affect EVERY scheduled selector / action.
*/
public var timeScale: Time = 1.0
/**
Current time the scheduler is calling a block for.
*/
internal(set) var currentTime: Time = 0.0
/**
Time of the most recent update: calls.
*/
internal(set) var lastUpdateTime: Time = 0.0
/**
Time of the most recent fixedUpdate: calls.
*/
private(set) var lastFixedUpdateTime: Time = 0.0
/**
Maximum allowed time step.
If the CPU can't keep up with the game, time will slow down.
*/
var maxTimeStep: Time = 1.0 / 10.0
/**
The time between fixedUpdate: calls.
*/
var fixedUpdateInterval: Time {
get {
return fixedUpdateTimer.repeatInterval
}
set {
fixedUpdateTimer.repeatInterval = newValue
}
}
internal var heap = [Timer]()
var scheduledTargets = [ScheduledTarget]()
var updatableTargets = [Updatable & Pausable]()
var fixedUpdatableTargets = [FixedUpdatable & Pausable]()
var actionTargets = [UnownedContainer<ScheduledTarget>]()
internal var updatableTargetsNeedSorting = true
internal var fixedUpdatableTargetsNeedSorting = true
var fixedUpdateTimer: Timer!
private let mock = MockNode()
public var actionsRunInFixedMode = false
init() {
fixedUpdateTimer = schedule(block: { [unowned self](timer:Timer) in
if timer.invokeTime > 0.0 {
if self.fixedUpdatableTargetsNeedSorting {
self.fixedUpdatableTargets.sort { $0.priority < $1.priority }
self.fixedUpdatableTargetsNeedSorting = false
}
for t in self.fixedUpdatableTargets {
t.fixedUpdate(delta: timer.repeatInterval)
}
if self.actionsRunInFixedMode {
self.updateActions(timer.repeatInterval)
}
self.lastFixedUpdateTime = timer.invokeTime
}
}, for: mock, withDelay: 0)
fixedUpdateTimer.repeatCount = TIMER_REPEAT_COUNT_FOREVER
fixedUpdateTimer.repeatInterval = Time(Setup.shared.fixedUpdateInterval)
}
}
// MARK: Update
extension Scheduler {
internal func schedule(timer: Timer) {
heap.append(timer)
timer.scheduled = true
}
internal func update(to targetTime: Time) {
assert(targetTime >= currentTime, "Cannot step to a time in the past")
heap.sort()
while heap.count > 0 {
let timer = heap.first!
let invokeTime = timer.invokeTimeInternal
if invokeTime > targetTime {
break;
} else {
heap.removeFirst()
timer.scheduled = false
}
currentTime = invokeTime
guard !timer.paused else {
continue
}
if timer.requiresDelay {
timer.apply(pauseDelay: currentTime)
schedule(timer: timer)
} else {
timer.block?(timer)
if timer.repeatCount > 0 {
if timer.repeatCount < TIMER_REPEAT_COUNT_FOREVER {
timer.repeatCount -= 1
}
timer.deltaTime = timer.repeatInterval
let delay = timer.deltaTime
timer.invokeTimeInternal += delay
assert(delay > 0.0, "Rescheduling a timer with a repeat interval of 0 will cause an infinite loop.")
self.schedule(timer: timer)
} else {
guard let scheduledTarget = timer.scheduledTarget else {
continue
}
scheduledTarget.remove(timer: timer)
if scheduledTarget.empty {
scheduledTargets.removeObject(scheduledTarget)
}
timer.invalidate()
}
}
}
currentTime = targetTime
}
internal func update(_ dt: Time) {
let clampedDelta = min(dt*timeScale, maxTimeStep)
update(to: currentTime + clampedDelta)
if self.updatableTargetsNeedSorting {
self.updatableTargets.sort { $0.priority < $1.priority }
self.updatableTargetsNeedSorting = false
}
for t in updatableTargets {
if !t.paused {
t.update(delta: clampedDelta)
}
}
if !self.actionsRunInFixedMode {
updateActions(dt)
}
lastUpdateTime = currentTime
}
internal func updateActions(_ dt: Time) {
actionTargets = actionTargets.filter {
let st = $0.value
guard !st.paused else {
return st.hasActions
}
for i in 0..<st.actions.count {
st.actions[i].step(dt: dt)
if st.actions[i].isDone {
st.actions[i].stop()
}
}
st.actions = st.actions.filter {
return !$0.isDone
}
return st.hasActions
}
}
}
// MARK: Getters
extension Scheduler {
func scheduledTarget(for target: Node, insert: Bool) -> ScheduledTarget? {
var scheduledTarget = scheduledTargets.first {
$0.target === target
}
if scheduledTarget == nil && insert {
scheduledTarget = ScheduledTarget(target: target)
scheduledTargets.append(scheduledTarget!)
// New targets are implicitly paused.
scheduledTarget!.paused = true
}
return scheduledTarget
}
func schedule(block: @escaping TimerBlock, for target: Node, withDelay delay: Time) -> Timer {
let scheduledTarget = self.scheduledTarget(for: target, insert: true)!
let timer = Timer(delay: delay, scheduler: self, scheduledTarget: scheduledTarget, block: block)
self.schedule(timer: timer)
timer.next = scheduledTarget.timers
scheduledTarget.timers = timer
return timer
}
func schedule(target: Node) {
let scheduledTarget = self.scheduledTarget(for: target, insert: true)!
// Don't schedule something more than once.
if !scheduledTarget.enableUpdates {
scheduledTarget.enableUpdates = true
if target.updatableComponents.count > 0 {
schedule(updatable: target)
}
if target.fixedUpdatableComponents.count > 0 {
schedule(fixedUpdatable: target)
}
}
}
func unscheduleUpdates(from target: Node) {
guard let scheduledTarget = self.scheduledTarget(for: target, insert: false) else {
return
}
scheduledTarget.enableUpdates = false
let target = scheduledTarget.target!
if target.updatableComponents.count > 0 {
unschedule(updatable: target)
}
if target.fixedUpdatableComponents.count > 0 {
unschedule(fixedUpdatable: target)
}
}
func unschedule(target: Node) {
if let scheduledTarget = self.scheduledTarget(for: target, insert: false) {
// Remove the update methods if they are scheduled
if scheduledTarget.enableUpdates {
unschedule(updatable: scheduledTarget.target!)
unschedule(fixedUpdatable: scheduledTarget.target!)
}
if scheduledTarget.hasActions {
actionTargets.remove(at: actionTargets.index { $0.value === scheduledTarget }!)
}
scheduledTarget.invalidateTimers()
scheduledTargets.removeObject(scheduledTarget)
}
}
func isTargetScheduled(target: Node) -> Bool {
return self.scheduledTarget(for: target, insert: false) != nil
}
func setPaused(paused: Bool, target: Node) {
let scheduledTarget = self.scheduledTarget(for: target, insert: false)!
scheduledTarget.paused = paused
}
func isTargetPaused(target: Node) -> Bool {
let scheduledTarget = self.scheduledTarget(for: target, insert: false)!
return scheduledTarget.paused
}
func timersForTarget(target: Node) -> [Timer] {
guard let scheduledTarget = self.scheduledTarget(for: target, insert: false) else {
return []
}
var arr = [Timer]()
var timer = scheduledTarget.timers
while timer != nil {
if !timer!.invalid {
arr.append(timer!)
}
timer = timer!.next
}
return arr
}
}
// MARK: Scheduling Actions
extension Scheduler {
func add(action: ActionContainer, target: Node, paused: Bool) {
let scheduledTarget = self.scheduledTarget(for: target, insert: true)!
scheduledTarget.paused = paused
if scheduledTarget.hasActions {
//assert(!scheduledTarget.actions.contains(action), "Action already running on this target.")
} else {
// This is the first action that has been scheduled for this target.
// It needs to be added to the list of targets with actions.
actionTargets.append(UnownedContainer(scheduledTarget))
}
scheduledTarget.add(action: action)
scheduledTarget.actions[scheduledTarget.actions.count - 1].start(with: target)
}
func removeAllActions(from target: Node) {
let scheduledTarget = self.scheduledTarget(for: target, insert: true)!
scheduledTarget.actions = []
if let idx = actionTargets.index(where: { $0.value === scheduledTarget }) {
actionTargets.remove(at: idx)
}
}
func removeAction(by tag: Int, target: Node) {
let scheduledTarget = self.scheduledTarget(for: target, insert: true)!
scheduledTarget.actions = scheduledTarget.actions.filter {
return $0.tag != tag
}
guard scheduledTarget.hasActions else {
return
}
actionTargets.remove(at: actionTargets.index { $0.value === scheduledTarget }!)
}
func getAction(by tag: Int, target: Node) -> ActionContainer? {
let scheduledTarget = self.scheduledTarget(for: target, insert: true)!
for action: ActionContainer in scheduledTarget.actions {
if (action.tag == tag) {
return action
}
}
return nil
}
func actions(for target: Node) -> [ActionContainer] {
let scheduledTarget = self.scheduledTarget(for: target, insert: true)!
return scheduledTarget.actions
}
}
public extension Scheduler {
public func schedule(updatable: Updatable & Pausable) {
updatableTargets.append(updatable)
updatableTargetsNeedSorting = true
}
public func unschedule(updatable: Updatable & Pausable) {
updatableTargets.removeObject(updatable)
}
public func schedule(fixedUpdatable: FixedUpdatable & Pausable) {
fixedUpdatableTargets.append(fixedUpdatable)
fixedUpdatableTargetsNeedSorting = true
}
public func unschedule(fixedUpdatable: FixedUpdatable & Pausable) {
fixedUpdatableTargets.removeObject(fixedUpdatable)
}
}
| a77e5cbc2a5c175e28e4e275f84ff9c9 | 32.269923 | 136 | 0.571936 | false | false | false | false |
uias/Pageboy | refs/heads/main | Sources/Pageboy/Utilities/WeakContainer.swift | mit | 1 | //
// WeakContainer.swift
// Pageboy iOS
//
// Created by Merrick Sapsford on 02/03/2019.
// Copyright © 2019 UI At Six. All rights reserved.
//
import Foundation
internal final class WeakWrapper<T: AnyObject> {
private(set) weak var object: T?
init(_ object: T) {
self.object = object
}
}
extension WeakWrapper: Equatable {
static func == (lhs: WeakWrapper, rhs: WeakWrapper) -> Bool {
return lhs.object === rhs.object
}
}
| 1b2728f3bd7bac48b6d841475e2ac69e | 18.28 | 65 | 0.622407 | false | false | false | false |
Speicher210/wingu-sdk-ios-demoapp | refs/heads/master | Example/winguSDK-iOS/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// winguSDK-iOS
//
// Created by Jakub Mazur on 08/16/2017.
// Copyright (c) 2017 wingu AG. All rights reserved.
//
import UIKit
import winguSDK
class ViewController: UIViewController {
let winguSegueIdentifier = "loadWinguSegue"
@IBOutlet weak var tableView: UITableView!
var beaconsLocationManger : WinguLocations!
var channels : [Channel] = [Channel]() {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.beaconsLocationManger = WinguLocations.sharedInstance
self.beaconsLocationManger.delegate = self
self.beaconsLocationManger.startBeaconsRanging()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == winguSegueIdentifier {
let gp = sender as? Channel
let destVC = (segue.destination as! WinguDeckViewController)
destVC.content = gp?.content!
destVC.channelId = gp?.uID
}
}
}
// MARK: - BeaconsLocationManagerDelegate
extension ViewController : WinguLocationsDelegate {
func winguRangedChannels(_ channels: [Channel]) {
self.channels = channels
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension ViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell=UITableViewCell(style: .subtitle, reuseIdentifier: "winguDemoCell")
let guidepost : Channel = self.channels[indexPath.row]
cell.textLabel?.text = guidepost.name
cell.detailTextLabel?.text = guidepost.uID
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.channels.count
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: winguSegueIdentifier, sender: self.channels[indexPath.row])
}
}
| 7fbb71f9f8412e63639973e1ce3ec3ee | 31.846154 | 101 | 0.684309 | false | false | false | false |
jgainfort/FRPlayer | refs/heads/master | FRPlayer/PlayerReducer.swift | mit | 1 | //
// PlayerReducer.swift
// FRPlayer
//
// Created by John Gainfort Jr on 3/31/17.
// Copyright © 2017 John Gainfort Jr. All rights reserved.
//
import AVFoundation
import ReSwift
func playerReducer(state: PlayerState?, action: Action) -> PlayerState {
var state = state ?? initialPlayerState()
switch action {
case _ as ReSwiftInit:
break
case let action as UpdatePlayerStatus:
state.status = action.status
case let action as UpdateTimeControlStatus:
state.timeControlStatus = action.status
case let action as UpdatePlayerItemStatus:
state.itemStatus = action.status
case let action as UpdatePlayerItem:
state.currentItem = action.item
case let action as UpdatePlayerCurrentTime:
state.currentTime = action.currentTime
default:
break
}
return state
}
func initialPlayerState() -> PlayerState {
let url = URL(string: "nil")!
let item = AVPlayerItem(url: url)
return PlayerState(status: .unknown, timeControlStatus: .waitingToPlayAtSpecifiedRate, itemStatus: .unknown, currentItem: item, currentTime: -1)
}
| edb0adafbbb3de977d75394fba8a15da | 28.128205 | 148 | 0.695423 | false | false | false | false |
josmas/swiftFizzBuzz | refs/heads/master | FizzBuzzTests/BrainTests.swift | mit | 1 | //
// BrainTests.swift
// FizzBuzz
//
// Created by Jose Dominguez on 15/01/2016.
// Copyright © 2016 Jos. All rights reserved.
//
import XCTest
@testable import FizzBuzz
class BrainTests: XCTestCase {
let brain = Brain()
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testIsDivisibleByThree(){
let result = brain.isDivisibleByThree(3);
XCTAssertEqual(result, true)
let result2 = brain.isDivisibleByThree(1);
XCTAssertEqual(result2, false)
}
func testIsDivisibleByFive(){
let result = brain.isDivisibleByFive(5);
XCTAssertEqual(result, true)
let result2 = brain.isDivisibleByFive(3);
XCTAssertEqual(result2, false)
}
func testIsDivisibleByFifteen(){
let result = brain.isDivisibleByFive(30);
XCTAssertEqual(result, true)
let result2 = brain.isDivisibleByFive(51);
XCTAssertEqual(result2, false)
}
func testSayFizz(){
XCTAssertEqual(brain.check(3), Move.Fizz)
}
func testSayBuzz(){
XCTAssertEqual(brain.check(5), Move.Buzz)
}
func testSayFizzBuzz(){
XCTAssertEqual(brain.check(30), Move.FizzBuzz)
}
func testSayNumber(){
XCTAssertEqual(brain.check(1), Move.Number)
}
}
| 8da15e81a890ff8f69e10fce50673f05 | 19.815385 | 54 | 0.630451 | false | true | false | false |
mmisesin/github_client | refs/heads/master | Github Client/LoginViewController.swift | mit | 1 | //
// ViewController.swift
// Github Client
//
// Created by Artem Misesin on 3/16/17.
// Copyright © 2017 Artem Misesin. All rights reserved.
//
import UIKit
import OAuthSwift
import SwiftyJSON
class SingleOAuth{
static let shared = SingleOAuth()
var oAuthSwift: OAuthSwift?
var owner: String?
}
class LoginViewController: OAuthViewController {
var oAuthSwift: OAuthSwift?
@IBOutlet weak var mainTableView: UITableView!
var repos: [(name: String, language: String)] = []
var reposInfo: JSON?
var spinner: UIActivityIndicatorView = UIActivityIndicatorView()
@IBOutlet weak var logOutItem: UIBarButtonItem!
@IBOutlet weak var signInItem: UIBarButtonItem!
lazy var internalWebViewController: WebViewController = {
let controller = WebViewController()
controller.view = UIView(frame: UIScreen.main.bounds) // needed if no nib or not loaded from storyboard
controller.delegate = self
controller.viewDidLoad()// allow WebViewController to use this ViewController as parent to be presented
return controller
}()
override func viewDidLoad() {
super.viewDidLoad()
logOutItem.isEnabled = false
spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.frame = CGRect(x: self.view.bounds.midX - 10, y: self.view.bounds.midY - 10, width: 20.0, height: 20.0) // (or wherever you want it in the button)
self.view.addSubview(spinner)
doOAuthGithub()
// Do any additional setup after loading the view, typically from a nib.
let backItem = UIBarButtonItem()
backItem.title = "Back"
navigationItem.backBarButtonItem = backItem
}
@IBAction func signIn(_ sender: UIBarButtonItem) {
doOAuthGithub()
//self.test(SingleOAuth.shared.oAuthSwift as! OAuth2Swift)
}
@IBAction func logOut(_ sender: UIBarButtonItem) {
let token = self.oAuthSwift?.client.credential.oauthToken
let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
self.oAuthSwift?.cancel()
//doOAuthGithub()
repos.removeAll()
self.mainTableView.reloadData()
signInItem.isEnabled = true
logOutItem.isEnabled = false
}
func doOAuthGithub(){
let oauthswift = OAuth2Swift(
consumerKey: "dc77c40af509089c9af0",
consumerSecret: "b0d78d5401b2324db779aaf0029c793400935487",
authorizeUrl: "https://github.com/login/oauth/authorize",
accessTokenUrl: "https://github.com/login/oauth/access_token",
responseType: "code"
)
self.oAuthSwift = oauthswift
SingleOAuth.shared.oAuthSwift = oauthswift
oauthswift.authorizeURLHandler = getURLHandler()
let state = generateState(withLength: 20)
let _ = oauthswift.authorize(
withCallbackURL: URL(string: "http://oauthswift.herokuapp.com/callback/github_client")!, scope: "user,repo", state: state,
success: { credential, response, parameters in
self.spinner.startAnimating()
self.spinner.alpha = 1.0
self.mainTableView.isHidden = true
self.signInItem.isEnabled = false
self.logOutItem.isEnabled = true
self.test(oauthswift)
},
failure: { error in
print(error.description)
}
)
}
func test(_ oauthswift: OAuth2Swift) {
let url :String = "https://api.github.com/user/repos"
let parameters :Dictionary = Dictionary<String, AnyObject>()
let _ = oauthswift.client.get(
url, parameters: parameters,
success: { response in
let jsonDict = try? JSON(response.jsonObject())
if let arrayNames = jsonDict?.arrayValue.map({$0["name"].stringValue}){
if let arrayLanguages = jsonDict?.arrayValue.map({$0["language"].stringValue}){
for i in 0..<arrayNames.count{
self.repos.append((arrayNames[i], arrayLanguages[i]))
}
}
}
//print(jsonDict)
self.spinner.stopAnimating()
self.spinner.alpha = 0.0
self.mainTableView.isHidden = false
self.reposInfo = jsonDict
self.mainTableView.reloadData()
},
failure: { error in
self.showAlertView(title: "Error", message: error.localizedDescription)
}
)
}
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController!, ontoPrimaryViewController primaryViewController: UIViewController!) -> Bool{
return true
}
}
extension LoginViewController: OAuthWebViewControllerDelegate {
func oauthWebViewControllerDidPresent() {
}
func oauthWebViewControllerDidDismiss() {
}
func oauthWebViewControllerWillAppear() {
}
func oauthWebViewControllerDidAppear() {
}
func oauthWebViewControllerWillDisappear() {
}
func oauthWebViewControllerDidDisappear() {
// Ensure all listeners are removed if presented web view close
oAuthSwift?.cancel()
}
}
extension LoginViewController{
func showAlertView(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func showTokenAlert(name: String?, credential: OAuthSwiftCredential) {
var message = "oauth_token:\(credential.oauthToken)"
if !credential.oauthTokenSecret.isEmpty {
message += "\n\noauth_token_secret:\(credential.oauthTokenSecret)"
}
self.showAlertView(title: "Service", message: message)
}
// MARK: handler
func getURLHandler() -> OAuthSwiftURLHandlerType {
if internalWebViewController.parent == nil {
self.addChildViewController(internalWebViewController)
}
return internalWebViewController
}
// override func prepare(for segue: OAuthStoryboardSegue, sender: Any?) {
// if segue.identifier == Storyboards.Main.FormSegue {
// #if os(OSX)
// let controller = segue.destinationController as? FormViewController
// #else
// let controller = segue.destination as? FormViewController
// #endif
// // Fill the controller
// if let controller = controller {
// controller.delegate = self
// }
// }
//
// super.prepare(for: segue, sender: sender)
// }
}
extension LoginViewController: UITableViewDelegate, UITableViewDataSource {
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell")
cell.textLabel?.text = repos[indexPath.row].name
cell.detailTextLabel?.text = repos[indexPath.row].language
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = self.parent?.parent as? GlobalSplitViewController{
vc.collapseDVC = false
performSegue(withIdentifier: "showDetail", sender: tableView.cellForRow(at: indexPath))
mainTableView.deselectRow(at: indexPath, animated: false)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.mainTableView.indexPathForSelectedRow {
let repoInfoVC = (segue.destination as! UINavigationController).topViewController as! MainViewController
repoInfoVC.title = repos[indexPath.row].name
let arrayAuthor = reposInfo?.arrayValue.map({$0["owner"].dictionaryValue}).map({$0["login"]?.stringValue})
repoInfoVC.authorString = arrayAuthor![indexPath.row]!
let arrayImage = reposInfo?.arrayValue.map({$0["owner"].dictionaryValue}).map({$0["avatar_url"]?.stringValue})
repoInfoVC.imageURLString = arrayImage![indexPath.row]!
let arrayForks = reposInfo?.arrayValue.map({$0["forks"].stringValue})
repoInfoVC.forksNumber = Int(arrayForks![indexPath.row])!
let arrayWatchers = reposInfo?.arrayValue.map({$0["watchers_count"].stringValue})
repoInfoVC.watchersNumber = Int(arrayWatchers![indexPath.row])!
let arrayDescription = reposInfo?.arrayValue.map({$0["description"].stringValue})
repoInfoVC.descriptionString = arrayDescription![indexPath.row]
}
}
}
}
| ba8ab13ce8d5dce49f5e37fb8df12ac5 | 37 | 225 | 0.624794 | false | false | false | false |
m-alani/contests | refs/heads/master | leetcode/letterCombinationsOfAPhoneNumber.swift | mit | 1 | //
// letterCombinationsOfAPhoneNumber.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/letter-combinations-of-a-phone-number/
// Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code
//
class Solution {
var mapping: [[Character]] = [[" "],
[],
["a","b","c"],
["d","e","f"],
["g","h","i"],
["j","k","l"],
["m","n","o"],
["p","q","r","s"],
["t","u","v"],
["w","x","y","z"]
]
var output = [String]()
func letterCombinations(_ digits: String) -> [String] {
let input = [Character](digits.characters)
if (input.count > 0) {
recursiveSolution(input, [Character]())
}
return output
}
func recursiveSolution(_ digits: [Character], _ word: [Character]) {
if digits.count == 0 {
output.append(String(word))
return
}
let digit = Int(String(digits[0]).utf8.first!) - 48
var newDigits = digits
newDigits.removeFirst()
for char in mapping[digit] {
var newWord = word
newWord.append(char)
recursiveSolution(newDigits, newWord)
}
}
}
| 58405c405b8c6a50e9475d636c4c36db | 31.543478 | 123 | 0.469606 | false | false | false | false |
andrebocchini/SwiftChatty | refs/heads/master | Example/Pods/Alamofire/Source/ResponseSerialization.swift | mit | 2 | //
// ResponseSerialization.swift
//
// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The type in which all data response serializers must conform to in order to serialize a response.
public protocol DataResponseSerializerProtocol {
/// The type of serialized object to be created by this `DataResponseSerializerType`.
associatedtype SerializedObject
/// A closure used by response handlers that takes a request, response, data and error and returns a result.
var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<SerializedObject> { get }
}
// MARK: -
/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object.
public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol {
/// The type of serialized object to be created by this `DataResponseSerializer`.
public typealias SerializedObject = Value
/// A closure used by response handlers that takes a request, response, data and error and returns a result.
public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>
/// Initializes the `ResponseSerializer` instance with the given serialize response closure.
///
/// - parameter serializeResponse: The closure used to serialize the response.
///
/// - returns: The new generic response serializer instance.
public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) {
self.serializeResponse = serializeResponse
}
}
// MARK: -
/// The type in which all download response serializers must conform to in order to serialize a response.
public protocol DownloadResponseSerializerProtocol {
/// The type of serialized object to be created by this `DownloadResponseSerializerType`.
associatedtype SerializedObject
/// A closure used by response handlers that takes a request, response, url and error and returns a result.
var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<SerializedObject> { get }
}
// MARK: -
/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object.
public struct DownloadResponseSerializer<Value>: DownloadResponseSerializerProtocol {
/// The type of serialized object to be created by this `DownloadResponseSerializer`.
public typealias SerializedObject = Value
/// A closure used by response handlers that takes a request, response, url and error and returns a result.
public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>
/// Initializes the `ResponseSerializer` instance with the given serialize response closure.
///
/// - parameter serializeResponse: The closure used to serialize the response.
///
/// - returns: The new generic response serializer instance.
public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Timeline
extension Request {
var timeline: Timeline {
let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent()
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
return Timeline(
requestStartTime: requestStartTime,
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
}
}
// MARK: - Default
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self {
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
var dataResponse = DefaultDataResponse(
request: self.request,
response: self.response,
data: self.delegate.data,
error: self.delegate.error,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
completionHandler(dataResponse)
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
/// and data.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response<T: DataResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
var dataResponse = DataResponse<T.SerializedObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
(queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }
}
return self
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DefaultDownloadResponse) -> Void)
-> Self
{
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
var downloadResponse = DefaultDownloadResponse(
request: self.request,
response: self.response,
temporaryURL: self.downloadDelegate.temporaryURL,
destinationURL: self.downloadDelegate.destinationURL,
resumeData: self.downloadDelegate.resumeData,
error: self.downloadDelegate.error,
timeline: self.timeline
)
downloadResponse.add(self.delegate.metrics)
completionHandler(downloadResponse)
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
/// and data contained in the destination url.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response<T: DownloadResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.downloadDelegate.fileURL,
self.downloadDelegate.error
)
var downloadResponse = DownloadResponse<T.SerializedObject>(
request: self.request,
response: self.response,
temporaryURL: self.downloadDelegate.temporaryURL,
destinationURL: self.downloadDelegate.destinationURL,
resumeData: self.downloadDelegate.resumeData,
result: result,
timeline: self.timeline
)
downloadResponse.add(self.delegate.metrics)
(queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) }
}
return self
}
}
// MARK: - Data
extension Request {
/// Returns a result data type that contains the response data as-is.
///
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> {
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) }
guard let validData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
return .success(validData)
}
}
extension DataRequest {
/// Creates a response serializer that returns the associated data as-is.
///
/// - returns: A data response serializer.
public static func dataResponseSerializer() -> DataResponseSerializer<Data> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseData(response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseData(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<Data>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.dataResponseSerializer(),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns the associated data as-is.
///
/// - returns: A data response serializer.
public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> {
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseData(response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseData(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DownloadResponse<Data>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.dataResponseSerializer(),
completionHandler: completionHandler
)
}
}
// MARK: - String
extension Request {
/// Returns a result string type initialized from the response data with the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseString(
encoding: String.Encoding?,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<String>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") }
guard let validData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil {
convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName))
)
}
let actualEncoding = convertedEncoding ?? .isoLatin1
if let string = String(data: validData, encoding: actualEncoding) {
return .success(string)
} else {
return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
///
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
/// server response, falling back to the default HTTP default character set,
/// ISO-8859-1.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DataResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
///
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> {
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
/// server response, falling back to the default HTTP default character set,
/// ISO-8859-1.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DownloadResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization`
/// with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseJSON(
options: JSONSerialization.ReadingOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<Any>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
let json = try JSONSerialization.jsonObject(with: validData, options: options)
return .success(json)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns a JSON object result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A JSON object response serializer.
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DataResponseSerializer<Any>
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns a JSON object result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A JSON object response serializer.
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DownloadResponseSerializer<Any>
{
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DownloadResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/// Returns a plist object contained in a result type constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponsePropertyList(
options: PropertyListSerialization.ReadOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<Any>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
return .success(plist)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns an object constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
///
/// - returns: A property list object response serializer.
public static func propertyListResponseSerializer(
options: PropertyListSerialization.ReadOptions = [])
-> DataResponseSerializer<Any>
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responsePropertyList(
queue: DispatchQueue? = nil,
options: PropertyListSerialization.ReadOptions = [],
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns an object constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
///
/// - returns: A property list object response serializer.
public static func propertyListResponseSerializer(
options: PropertyListSerialization.ReadOptions = [])
-> DownloadResponseSerializer<Any>
{
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responsePropertyList(
queue: DispatchQueue? = nil,
options: PropertyListSerialization.ReadOptions = [],
completionHandler: @escaping (DownloadResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
/// A set of HTTP response status code that do not contain response data.
private let emptyDataStatusCodes: Set<Int> = [204, 205]
| 3f5b873c6c97195421bf35b927d97cc5 | 39.728671 | 126 | 0.649806 | false | false | false | false |
priya273/stockAnalyzer | refs/heads/master | Stock Analyzer/Stock Analyzer/UserProvider.swift | apache-2.0 | 1 | //
// UserTrackServices.swift
// Stock Analyzer
//
// Created by Naga sarath Thodime on 3/14/16.
// Copyright © 2016 Priyadarshini Ragupathy. All rights reserved.
//
import Foundation
import Alamofire
import UIKit
protocol UserCreationDelegate
{
func UserCreationSuccess()
func UserCreationFailed()
}
class UserProvider
{
let UserStatusCodeAlreadyExists = 200;
let UserCreatedStatusCode = 201
let BadRequest = 400
var Delegate : UserCreationDelegate!
func PostNewUserRecord(user : UserContract)
{
let url = NSURL(string: "http://stockanalyzer.azurewebsites.net/api/user");
let req = NSMutableURLRequest(URL : url!)
req.HTTPMethod = "POST"
let dict: [String : String] = [ "id" : user.id!,
"Email": user.Email!
]
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
do
{
req.HTTPBody = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions())
}
catch
{
print("Exception Converting to jason.")
}
Alamofire.request(req).responseJSON
{
Response in
print(Response.response?.statusCode);
if(Response.response?.statusCode == 400 || Response.response?.statusCode == 500)
{
self.Delegate?.UserCreationFailed()
}
else
{
self.Delegate?.UserCreationSuccess()
}
}
}
} | 6caa1783d6f3f3c7fb2f330e016498c1 | 22.32 | 108 | 0.522883 | false | false | false | false |
brendancboyle/SecTalk-iOS | refs/heads/master | SecTalk/SecTalk Framework/STConnection.swift | mit | 1 | //
// STConnection.swift
// SecTalk
//
// Created by Brendan Boyle on 5/29/15.
// Copyright (c) 2015 DBZ Technology. All rights reserved.
//
import UIKit
import AFNetworking
import SwiftyJSON
import CryptoSwift
class STConnection: NSObject {
static let TOTPSecret:String = "JBSWY3DPEHPK3PXP"
static var APNSToken:String = ""
class func getTOTPCode() -> String {
let secretData:NSData = NSData(base32String: STConnection.TOTPSecret)
var now:NSDate = NSDate()
var generator:TOTPGenerator = TOTPGenerator(secret: secretData, algorithm: kOTPGeneratorSHA512Algorithm, digits: 6, period: 30)
let pin: String = generator.generateOTPForDate(now)
//println("Pin:"+pin)
//let data = pin.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
//let encryptedData = pin.sha512()
return pin
}
/*
HTTP GET request. Returns HTML as a string value
url (String): URL of the data resource
callback (JSON): Callback method to update local data source (Requires SwiftyJSON)
*/
class func getHTML(url:String, callback: (String) -> Void, verbose: Bool) {
//Allocate an AFHTTP Request object
var manager = AFHTTPRequestOperationManager();
manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token")
manager.responseSerializer = AFHTTPResponseSerializer();
//Query using the GET method. If successful, pass the JSON object to the callback function
manager.GET( url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
let text = NSString(data: responseObject as! NSData, encoding: NSUTF8StringEncoding)
if verbose {
println(String(format: "HTML: %@", text!))
}
/*
Build a SwiftyJSON object from the JSON object
let dataFromString = text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var jsonResponse = JSON(data: dataFromString!)
*/
//Invoke the callback method
callback(text as! String)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error ("+url+"): " + error.localizedDescription)
})
}
/*
HTTP GET request. Returns JSON as a SwiftyJSON object
url (String): URL of the data resource
callback (JSON): Callback method to update local data source (Requires SwiftyJSON)
*/
class func getJSON(url:String, callback: (JSON) -> Void, verbose: Bool) {
//Allocate an AFHTTP Request object
var manager = AFHTTPRequestOperationManager();
manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token")
//Query using the GET method. If successful, pass the JSON object to the callback function
manager.GET( url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
if verbose {
println("JSON: " + responseObject.description)
}
//Build a SwiftyJSON object from the JSON object
let jsonResponse = JSON(responseObject)
//Invoke the callback method
callback(jsonResponse)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error ("+url+"): " + error.localizedDescription)
})
}
/*
HTTP PUT request. Returns JSON as a SwiftyJSON object
url (String): URL of the data resource
parameters (NSDictionary): POST parameters
callback (JSON): Callback method to update local data source (Requires SwiftyJSON)
verbose (boolean): Print query result to the console
*/
class func put(url:String, parameters: NSDictionary, callback: (JSON) -> Void, verbose: Bool) {
//Allocate an AFHTTP Request object
var manager = AFHTTPRequestOperationManager();
manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token")
//Query using the PUT method. If successful, pass the JSON object to the callback function
manager.PUT( url,
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
if verbose {
println("JSON: " + responseObject.description)
}
//Build a SwiftyJSON object from the JSON object
let jsonResponse = JSON(responseObject)
//Invoke the callback method
callback(jsonResponse)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error ("+url+"): " + error.localizedDescription)
})
}
/*
HTTP POST request. Returns JSON as a SwiftyJSON object
url (String): URL of the data resource
parameters (NSDictionary): POST parameters
callback (JSON): Callback method to update local data source (Requires SwiftyJSON)
verbose (boolean): Print query result to the console
*/
class func post(url:String, parameters: NSDictionary, callback: (JSON) -> Void, verbose: Bool) {
//Allocate an AFHTTP Request object
var manager = AFHTTPRequestOperationManager();
manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token")
//Query using the POST method. If successful, pass the JSON object to the callback function
manager.POST( url,
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
if verbose {
println("JSON: " + responseObject.description)
}
//Build a SwiftyJSON object from the JSON object
let jsonResponse = JSON(responseObject)
//Invoke the callback method
callback(jsonResponse)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error ("+url+"): " + error.localizedDescription)
})
}
/*
HTTP DELETE request. Returns JSON as a SwiftyJSON object
url (String): URL of the data resource
parameters (NSDictionary): POST parameters
callback (JSON): Callback method to update local data source (Requires SwiftyJSON)
verbose (boolean): Print query result to the console
*/
class func delete(url:String, parameters: NSDictionary, callback: (JSON) -> Void, verbose: Bool) {
//Allocate an AFHTTP Request object
var manager = AFHTTPRequestOperationManager();
manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token")
//Query using the DELETE method. If successful, pass the JSON object to the callback function
manager.DELETE( url,
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
if verbose {
println("JSON: " + responseObject.description)
}
//Build a SwiftyJSON object from the JSON object
let jsonResponse = JSON(responseObject)
//Invoke the callback method
callback(jsonResponse)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error ("+url+"): " + error.localizedDescription)
})
}
}
| 62dc774261df383ba2b05782402cf3cd | 34.847107 | 135 | 0.566686 | false | false | false | false |
mhergon/AVPlayerViewController-Subtitles | refs/heads/master | Example/Shared/ContentView.swift | apache-2.0 | 1 | //
// ContentView.swift
// Shared
//
// Created by TungLim on 21/6/2022.
// Copyright © 2022 Marc Hervera. All rights reserved.
//
import SwiftUI
import AVKit
import Combine
struct ContentView: View {
@State private var currentTime: TimeInterval = 0
@State private var currentText = ""
private let timeObserver: PlayerTimeObserver
private let avplayer: AVPlayer
private let parser: Subtitles?
init() {
avplayer = AVPlayer(url: Bundle.main.url(forResource: "trailer_720p", withExtension: "mov")!)
parser = try? Subtitles(file: URL(fileURLWithPath: Bundle.main.path(forResource: "trailer_720p", ofType: "srt")!), encoding: .utf8)
timeObserver = PlayerTimeObserver(player: avplayer)
}
var body: some View {
VideoPlayer(player: avplayer) {
VStack {
Spacer()
Text(currentText)
.foregroundColor(.white)
.font(.subheadline)
.multilineTextAlignment(.center)
.padding()
.onReceive(timeObserver.publisher) { time in
currentText = parser?.searchSubtitles(at: time) ?? ""
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
class PlayerTimeObserver {
let publisher = PassthroughSubject<TimeInterval, Never>()
private var timeObservation: Any?
init(player: AVPlayer) {
// Periodically observe the player's current time, whilst playing
timeObservation = player.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 60), queue: nil) { [weak self] time in
guard let self = self else { return }
// Publish the new player time
self.publisher.send(time.seconds)
}
}
}
| b898ed206a68d658c5fbe52342accf14 | 28.424242 | 139 | 0.6138 | false | false | false | false |
radhakrishnapai/Gallery-App-Swift | refs/heads/master | Gallery App Swift/Gallery App Swift/CollectionListTableViewController.swift | mit | 1 | //
// CollectionListTableViewController.swift
// Gallery App Swift
//
// Created by Pai on 21/03/16.
// Copyright © 2016 Pai. All rights reserved.
//
import UIKit
import Photos
class CollectionListTableViewController : UITableViewController {
var albumFetchResult:PHFetchResult = PHFetchResult()
override func viewDidLoad() {
self.albumFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.AlbumRegular, options: nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.albumFetchResult.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:AlbumListCell = tableView.dequeueReusableCellWithIdentifier("AlbumListCell", forIndexPath: indexPath) as! AlbumListCell
let collection:PHAssetCollection = self.albumFetchResult[indexPath.row] as! PHAssetCollection
cell.albumTitle.text = collection.localizedTitle
cell.albumCount.text = "\(collection.estimatedAssetCount)"
return cell
}
}
| a4440ff81297ede471b096963669f650 | 32.125 | 170 | 0.727547 | false | false | false | false |
adis300/Swift-Learn | refs/heads/master | SwiftLearn/Source/Random.swift | apache-2.0 | 1 | //
// Random.swift
// Swift-Learn
//
// Created by Innovation on 11/12/16.
// Copyright © 2016 Votebin. All rights reserved.
//
import Foundation
class Random{
static func randMinus1To1(length: Int) -> [Double]{
return (0..<length).map{_ in Double(arc4random())/Double(INT32_MAX) - 1}
}
static func randMinus1To1() -> Double{
return Double(arc4random())/Double(INT32_MAX) - 1
}
static func randN(n:Int) -> Int{
return Int(arc4random_uniform(UInt32(n)))
}
static func rand0To1() -> Double{
return Double(arc4random()) / Double(UINT32_MAX)
}
static var y2 = 0.0
static var use_last = false
/// static Function to get a random value for a given distribution
// static func gaussianRandom(_ mean : Double, standardDeviation : Double) -> Double
static func normalRandom() -> Double
{
var y1 : Double
if (use_last) /* use value from previous call */
{
y1 = y2
use_last = false
}
else
{
var w = 1.0
var x1 = 0.0
var x2 = 0.0
repeat {
x1 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0
x2 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0
w = x1 * x1 + x2 * x2
} while ( w >= 1.0 )
w = sqrt( (-2.0 * log( w ) ) / w )
y1 = x1 * w
y2 = x2 * w
use_last = true
}
return( y1 * 1 )
}
/*
static func normalDistribution(μ:Double, σ:Double, x:Double) -> Double {
let a = exp( -1 * pow(x-μ, 2) / ( 2 * pow(σ,2) ) )
let b = σ * sqrt( 2 * M_PI )
return a / b
}
static func standardNormalDistribution(_ x:Double) -> Double {
return exp( -1 * pow(x, 2) / 2 ) / sqrt( 2 * M_PI )
}*/
}
| b139ccb535fb0d6730359d80ac5f3c15 | 25.093333 | 88 | 0.485437 | false | false | false | false |
themungapp/themungapp | refs/heads/master | Mung/ViewController.swift | bsd-3-clause | 1 | //
// ViewController.swift
// Mung
//
// Created by Chike Chiejine on 30/09/2016.
// Copyright © 2016 Color & Space. All rights reserved.
//
import UIKit
import MXParallaxHeader
class ViewController: UIViewController, SimpleTabsDelegate {
//Tab View
// @IBOutlet weak var containerView: UIView!
// @IBOutlet weak var profileImage: UIImageView!
//
//
//
//
//
// @IBOutlet weak var discoverFeed: UIView!
// @IBOutlet weak var newFeed: UIView!
// @IBOutlet weak var anotherFeed: UIView!
var scrollView: MXScrollView!
var vc:SimpleTabsViewController!
var containerView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var frame = view.frame
let customview = Bundle.main.loadNibNamed("customView", owner: nil, options: nil)![0] as! customView
let tabContainerView = customview.tabContainerView
print("CUSTOM CORNER RADIUS")
print(customview.cornerRadius)
customview.cornerRadius = 20
scrollView = MXScrollView()
scrollView.parallaxHeader.view = Bundle.main.loadNibNamed("customView", owner: nil, options: nil)![0] as! customView
scrollView.parallaxHeader.height = 300
scrollView.parallaxHeader.mode = MXParallaxHeaderMode.fill
scrollView.parallaxHeader.minimumHeight = 10
view.addSubview(scrollView)
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: frame.size.height - 8)
containerView.backgroundColor = UIColor.white
view.addSubview(containerView)
let controller = storyboard?.instantiateViewController(withIdentifier: "ViewController1")
addChildViewController(controller!)
controller?.view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview((controller?.view)!)
controller?.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: frame.size.height - 8)
scrollView.addSubview(containerView)
let scrollHeight = frame.size.height
let scrollWidth = frame.size.width
// NSLayoutConstraint.activate([
// containerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: scrollWidth),
// containerView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: scrollHeight),
// containerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
// containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
// ])
controller?.didMove(toParentViewController: self)
//Tabs Confiigure
let tab1 = SimpleTabItem(title:"DISCOVER", count: 3)
let tab2 = SimpleTabItem(title:"NEWS FEED", count: 2)
let tab3 = SimpleTabItem(title:"ANOTHER FEED", count: 0)
vc = SimpleTabsViewController.create(self, baseView: tabContainerView, delegate: self, items: [tab1,tab2,tab3])
vc.setTabTitleColor(UIColor(red:0.54, green:0.54, blue:0.54, alpha:1.0))
vc.setNumberColor(UIColor.black)
vc.setNumberBackgroundColor(UIColor.yellow)
vc.setMarkerColor(UIColor(red:0.01, green:0.68, blue:0.88, alpha:1.0))
vc.setTabTitleFont(UIFont.systemFont(ofSize: 10))
vc.setNumberFont(UIFont.systemFont(ofSize: 14))
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var frame = view.frame
scrollView.frame = frame
scrollView.contentSize.height = frame.size.height + 20
scrollView.contentSize.width = frame.size.width
// frame.size.height -= scrollView.parallaxHeader.minimumHeight
scrollView.frame = frame
//
//
// let bottomConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
// let horizConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
// let widthConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: scrollWidth)
// let heightConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: scrollHeight)
//
// NSLayoutConstraint.activate([bottomConstraint, horizConstraint, widthConstraint, heightConstraint])
//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK : - SimpleTabsDelegate
func tabSelected(_ tabIndex:Int){
// if tabIndex == 0 {
//
// UIView.animate(withDuration: 0.5, animations: {
//
//
// self.discoverFeed.alpha = 1
// self.newFeed.alpha = 0
// self.anotherFeed.alpha = 0
//
// })
// } else if tabIndex == 1 {
//
// UIView.animate(withDuration: 0.5, animations: {
//
// self.discoverFeed.alpha = 0
// self.newFeed.alpha = 1
// self.anotherFeed.alpha = 0
//
// })
//
// } else {
//
// UIView.animate(withDuration: 0.5, animations: {
//
// self.discoverFeed.alpha = 0
// self.newFeed.alpha = 0
// self.anotherFeed.alpha = 1
//
// })
//
// }
//
var indexInfo = "Index selected: \(tabIndex)"
print(indexInfo)
}
}
| f37ad3898d147b33c3a15f117a4a5214 | 33.795699 | 241 | 0.617429 | false | false | false | false |
smockle/TorToggle | refs/heads/master | TorToggle/AppDelegate.swift | isc | 1 | //
// AppDelegate.swift
// TorToggle
//
// Created by Clay Miller on 4/3/15.
// Copyright (c) 2015 Clay Miller. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
func updateStatusMenuState() {
let isDisabled = SOCKSIsDisabled();
/* Show disabled icon variant if the SOCKS proxy is disabled */
statusItem.button?.appearsDisabled = isDisabled
/* Modify menu item text if the SOCKS proxy is disabled */
if (isDisabled) {
(statusMenu.itemArray[0] as! NSMenuItem).title = "Enable Tor"
} else {
(statusMenu.itemArray[0] as! NSMenuItem).title = "Disable Tor"
}
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
let icon = NSImage(named: "statusIcon")
icon?.setTemplate(true)
statusItem.image = icon
statusItem.menu = statusMenu
updateStatusMenuState()
}
func SOCKSIsDisabled() -> Bool {
/* Check whether Tor is already enabled */
let task = NSTask()
let pipe = NSPipe()
task.launchPath = "/usr/sbin/networksetup"
task.arguments = ["-getsocksfirewallproxy", "Wi-Fi"]
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let string = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
let array = string.componentsSeparatedByString("\n").filter { ($0 as NSString).containsString("Enabled:") && !($0 as NSString).containsString(" Enabled:") }
return array[0].lowercaseString == "enabled: no"
}
/* Toggle Tor launchctl */
func toggleTor(command: String) {
let task = NSTask()
task.launchPath = "/bin/launchctl"
task.arguments = [command, "/usr/local/opt/tor/homebrew.mxcl.tor.plist"]
task.launch()
task.waitUntilExit()
}
/* Toggle SOCKS proxy */
func toggleSOCKS(command: String) {
let task = NSTask()
task.launchPath = "/usr/sbin/networksetup"
task.arguments = ["-setsocksfirewallproxystate", "Wi-Fi", command]
task.launch()
task.waitUntilExit()
}
@IBAction func menuClicked(sender: NSMenuItem) {
if (sender.title == "Disable Tor") {
toggleSOCKS("off")
if (SOCKSIsDisabled()) {
toggleTor("unload")
}
} else {
toggleSOCKS("on")
if (!SOCKSIsDisabled()) {
toggleTor("load")
}
}
updateStatusMenuState()
}
@IBAction func terminateApplication(sender: AnyObject) {
if (!SOCKSIsDisabled()) {
toggleSOCKS("off")
if (SOCKSIsDisabled()) {
toggleTor("unload")
}
}
NSApplication.sharedApplication().terminate(self)
}
}
| 69eab61f8b9ef5b5f45a79924c221712 | 29.911765 | 164 | 0.587377 | false | false | false | false |
jrmgx/swift | refs/heads/master | jrmgx/Classes/Extension/UIImage.swift | mit | 1 |
import UIKit
public extension UIImage {
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public func jrmgx_writeJPEGToFile(_ filePath: URL, quality: CGFloat = 0.7) {
try? UIImageJPEGRepresentation(self, quality)?.write(to: filePath, options: [.atomic])
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public func jrmgx_CropToSquare() -> UIImage {
let imageSize = size
let width = imageSize.width
let height = imageSize.height
guard width != height else {
return self
}
let newDimension = min(width, height)
let widthOffset = (width - newDimension) / 2
let heightOffset = (height - newDimension) / 2
UIGraphicsBeginImageContextWithOptions(CGSize(width: newDimension, height: newDimension), false, 0)
draw(at: CGPoint(x: -widthOffset, y: -heightOffset), blendMode: CGBlendMode.copy, alpha: 1.0)
let destImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return destImage!
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public func jrmgx_resize(_ to: CGSize) -> UIImage {
let imageSize = size
let ratio = imageSize.width / imageSize.height
var scale: CGFloat = 1
if ratio > 0 {
scale = to.height / imageSize.height
}
else {
scale = to.width / imageSize.width
}
let finalSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
UIGraphicsBeginImageContextWithOptions(finalSize, false, 0)
draw(in: CGRect(origin: CGPoint.zero, size: finalSize))
let destImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return destImage!
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public static func Jrmgx_ImageWithColor(_ color: UIColor) -> UIImage {
return UIImage.Jrmgx_ImageWithColor(color, andSize: CGRect(x: 0, y: 0, width: 1, height: 1))
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public static func Jrmgx_ImageWithColor(_ color: UIColor, andSize rect: CGRect) -> UIImage {
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| 82c7df8dc41789a85892ca40bf8c8d1a | 25.883495 | 107 | 0.591188 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Source/E2EE/APSSignalingKeysStore.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireTransport
import WireUtilities
public struct SignalingKeys {
let verificationKey: Data
let decryptionKey: Data
init(verificationKey: Data? = nil, decryptionKey: Data? = nil) {
self.verificationKey = verificationKey ?? NSData.secureRandomData(ofLength: APSSignalingKeysStore.defaultKeyLengthBytes)
self.decryptionKey = decryptionKey ?? NSData.secureRandomData(ofLength: APSSignalingKeysStore.defaultKeyLengthBytes)
}
}
@objcMembers
public final class APSSignalingKeysStore: NSObject {
public var apsDecoder: ZMAPSMessageDecoder!
internal var verificationKey: Data!
internal var decryptionKey: Data!
internal static let verificationKeyAccountName = "APSVerificationKey"
internal static let decryptionKeyAccountName = "APSDecryptionKey"
internal static let defaultKeyLengthBytes: UInt = 256 / 8
public init?(userClient: UserClient) {
super.init()
if let verificationKey = userClient.apsVerificationKey, let decryptionKey = userClient.apsDecryptionKey {
self.verificationKey = verificationKey
self.decryptionKey = decryptionKey
self.apsDecoder = ZMAPSMessageDecoder(encryptionKey: decryptionKey, macKey: verificationKey)
} else {
return nil
}
}
/// use this method to create new keys, e.g. for client registration or update
static func createKeys() -> SignalingKeys {
return SignalingKeys()
}
/// we previously stored keys in the key chain. use this method to retreive the previously stored values to move them into the selfClient
static func keysStoredInKeyChain() -> SignalingKeys? {
guard let verificationKey = ZMKeychain.data(forAccount: self.verificationKeyAccountName),
let decryptionKey = ZMKeychain.data(forAccount: self.decryptionKeyAccountName)
else { return nil }
return SignalingKeys(verificationKey: verificationKey, decryptionKey: decryptionKey)
}
static func clearSignalingKeysInKeyChain() {
ZMKeychain.deleteAllKeychainItems(withAccountName: self.verificationKeyAccountName)
ZMKeychain.deleteAllKeychainItems(withAccountName: self.decryptionKeyAccountName)
}
public func decryptDataDictionary(_ payload: [AnyHashable: Any]!) -> [AnyHashable: Any]! {
return self.apsDecoder.decodeAPSPayload(payload)
}
}
| 0ddfd1629469c46c5a16e2eab7b0d901 | 39.868421 | 141 | 0.735673 | false | false | false | false |
glentregoning/BotTest | refs/heads/master | BotTest/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// BotTest
//
// Created by Glen Tregoning on 7/18/15.
// Copyright © 2015 Glen Tregoning. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "info.gtbox.BotTest" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("BotTest", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 3a4b836dbfe4264c183c34414a7f5643 | 53.882883 | 291 | 0.719468 | false | false | false | false |
arvedviehweger/swift | refs/heads/master | stdlib/public/core/StaticString.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Implementation Note: Because StaticString is used in the
// implementation of _precondition(), _fatalErrorMessage(), etc., we
// keep it extremely close to the bare metal. In particular, because
// we store only Builtin types, we are guaranteed that no assertions
// are involved in its construction. This feature is crucial for
// preventing infinite recursion even in non-asserting cases.
/// A string type designed to represent text that is known at compile time.
///
/// Instances of the `StaticString` type are immutable. `StaticString` provides
/// limited, pointer-based access to its contents, unlike Swift's more
/// commonly used `String` type. A static string can store its value as a
/// pointer to an ASCII code unit sequence, as a pointer to a UTF-8 code unit
/// sequence, or as a single Unicode scalar value.
@_fixed_layout
public struct StaticString
: _ExpressibleByBuiltinUnicodeScalarLiteral,
_ExpressibleByBuiltinExtendedGraphemeClusterLiteral,
_ExpressibleByBuiltinStringLiteral,
ExpressibleByUnicodeScalarLiteral,
ExpressibleByExtendedGraphemeClusterLiteral,
ExpressibleByStringLiteral,
CustomStringConvertible,
CustomDebugStringConvertible,
CustomReflectable {
/// Either a pointer to the start of UTF-8 data, represented as an integer,
/// or an integer representation of a single Unicode scalar.
@_versioned
internal var _startPtrOrData: Builtin.Word
/// If `_startPtrOrData` is a pointer, contains the length of the UTF-8 data
/// in bytes.
@_versioned
internal var _utf8CodeUnitCount: Builtin.Word
/// Extra flags:
///
/// - bit 0: set to 0 if `_startPtrOrData` is a pointer, or to 1 if it is a
/// Unicode scalar.
///
/// - bit 1: set to 1 if `_startPtrOrData` is a pointer and string data is
/// ASCII.
@_versioned
internal var _flags: Builtin.Int8
/// A pointer to the beginning of the string's UTF-8 encoded representation.
///
/// The static string must store a pointer to either ASCII or UTF-8 code
/// units. Accessing this property when `hasPointerRepresentation` is
/// `false` triggers a runtime error.
@_transparent
public var utf8Start: UnsafePointer<UInt8> {
_precondition(
hasPointerRepresentation,
"StaticString should have pointer representation")
return UnsafePointer(bitPattern: UInt(_startPtrOrData))!
}
/// The stored Unicode scalar value.
///
/// The static string must store a single Unicode scalar value. Accessing
/// this property when `hasPointerRepresentation` is `true` triggers a
/// runtime error.
@_transparent
public var unicodeScalar: UnicodeScalar {
_precondition(
!hasPointerRepresentation,
"StaticString should have Unicode scalar representation")
return UnicodeScalar(UInt32(UInt(_startPtrOrData)))!
}
/// The length in bytes of the static string's ASCII or UTF-8 representation.
///
/// - Warning: If the static string stores a single Unicode scalar value, the
/// value of `utf8CodeUnitCount` is unspecified.
@_transparent
public var utf8CodeUnitCount: Int {
_precondition(
hasPointerRepresentation,
"StaticString should have pointer representation")
return Int(_utf8CodeUnitCount)
}
/// A Boolean value indicating whether the static string stores a pointer to
/// ASCII or UTF-8 code units.
@_transparent
public var hasPointerRepresentation: Bool {
return (UInt8(_flags) & 0x1) == 0
}
/// A Boolean value that is `true` if the static string stores a pointer to
/// ASCII code units.
///
/// Use this property in conjunction with `hasPointerRepresentation` to
/// determine whether a static string with pointer representation stores an
/// ASCII or UTF-8 code unit sequence.
///
/// - Warning: If the static string stores a single Unicode scalar value, the
/// value of `isASCII` is unspecified.
@_transparent
public var isASCII: Bool {
return (UInt8(_flags) & 0x2) != 0
}
/// Invokes the given closure with a buffer containing the static string's
/// UTF-8 code unit sequence.
///
/// This method works regardless of whether the static string stores a
/// pointer or a single Unicode scalar value.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameter body: A closure that takes a buffer pointer to the static
/// string's UTF-8 code unit sequence as its sole argument. If the closure
/// has a return value, it is used as the return value of the
/// `withUTF8Buffer(invoke:)` method. The pointer argument is valid only
/// for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
public func withUTF8Buffer<R>(
_ body: (UnsafeBufferPointer<UInt8>) -> R) -> R {
if hasPointerRepresentation {
return body(UnsafeBufferPointer(
start: utf8Start, count: utf8CodeUnitCount))
} else {
var buffer: UInt64 = 0
var i = 0
let sink: (UInt8) -> Void = {
#if _endian(little)
buffer = buffer | (UInt64($0) << (UInt64(i) * 8))
#else
buffer = buffer | (UInt64($0) << (UInt64(7-i) * 8))
#endif
i += 1
}
UTF8.encode(unicodeScalar, into: sink)
return body(UnsafeBufferPointer(
start: UnsafePointer(Builtin.addressof(&buffer)),
count: i))
}
}
/// Creates an empty static string.
@_transparent
public init() {
self = ""
}
@_versioned
@_transparent
internal init(
_start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
// We don't go through UnsafePointer here to make things simpler for alias
// analysis. A higher-level algorithm may be trying to make sure an
// unrelated buffer is not accessed or freed.
self._startPtrOrData = Builtin.ptrtoint_Word(_start)
self._utf8CodeUnitCount = utf8CodeUnitCount
self._flags = Bool(isASCII)
? (0x2 as UInt8)._value
: (0x0 as UInt8)._value
}
@_versioned
@_transparent
internal init(
unicodeScalar: Builtin.Int32
) {
self._startPtrOrData = UInt(UInt32(unicodeScalar))._builtinWordValue
self._utf8CodeUnitCount = 0._builtinWordValue
self._flags = UnicodeScalar(_builtinUnicodeScalarLiteral: unicodeScalar).isASCII
? (0x3 as UInt8)._value
: (0x1 as UInt8)._value
}
@effects(readonly)
@_transparent
public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self = StaticString(unicodeScalar: value)
}
/// Creates an instance initialized to a single Unicode scalar.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you initialize a static string with a Unicode scalar.
@effects(readonly)
@_transparent
public init(unicodeScalarLiteral value: StaticString) {
self = value
}
@effects(readonly)
@_transparent
public init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
self = StaticString(
_builtinStringLiteral: start,
utf8CodeUnitCount: utf8CodeUnitCount,
isASCII: isASCII
)
}
/// Creates an instance initialized to a single character that is made up of
/// one or more Unicode code points.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you initialize a static string using an extended grapheme cluster.
@effects(readonly)
@_transparent
public init(extendedGraphemeClusterLiteral value: StaticString) {
self = value
}
@effects(readonly)
@_transparent
public init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
self = StaticString(
_start: start,
utf8CodeUnitCount: utf8CodeUnitCount,
isASCII: isASCII)
}
/// Creates an instance initialized to the value of a string literal.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you initialize a static string using a string literal.
@effects(readonly)
@_transparent
public init(stringLiteral value: StaticString) {
self = value
}
/// A string representation of the static string.
public var description: String {
return withUTF8Buffer {
(buffer) in
return String._fromWellFormedCodeUnitSequence(UTF8.self, input: buffer)
}
}
/// A textual representation of the static string, suitable for debugging.
public var debugDescription: String {
return self.description.debugDescription
}
}
extension StaticString {
public var customMirror: Mirror {
return Mirror(reflecting: description)
}
}
extension StaticString {
@available(*, unavailable, renamed: "utf8CodeUnitCount")
public var byteSize: Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "use the 'String(_:)' initializer")
public var stringValue: String {
Builtin.unreachable()
}
}
| 2b60d5cf0d03930a7eb88a63210e8b68 | 32.517483 | 84 | 0.689652 | false | false | false | false |
YoungGary/30daysSwiftDemo | refs/heads/master | day28/day28/ViewController.swift | mit | 1 | //
// ViewController.swift
// day28
//
// Created by YOUNG on 2016/10/18.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
import CoreSpotlight
import MobileCoreServices
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
@IBOutlet weak var tableView: UITableView!
var datas :NSMutableArray!
var selectedIndex : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0)
loadDatas()
setupSearchableContent()
let nib = UINib(nibName: "TableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
func loadDatas(){
let path = NSBundle.mainBundle().pathForResource("MoviesData.plist", ofType: nil)
datas = NSMutableArray(contentsOfFile: path!)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
let currentMovieInfo = datas[indexPath.row] as! [String: String]
cell.titleLabel.text = currentMovieInfo["Title"]!
cell.iconImageView.image = UIImage(named: currentMovieInfo["Image"]!)
cell.descLabel.text = currentMovieInfo["Description"]!
cell.pointLabel.text = currentMovieInfo["Rating"]!
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndex = indexPath.row
performSegueWithIdentifier("tableView2ViewController", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier else{
return
}
if identifier == "tableView2ViewController"{
let pushVC = segue.destinationViewController as! PushViewController
pushVC.movieDict = datas[selectedIndex] as! [String: String]
}
}
func setupSearchableContent() {
var searchableItems = [CSSearchableItem]()
for i in 0...(datas.count - 1) {
let movie = datas[i] as! [String: String]
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
//set the title
searchableItemAttributeSet.title = movie["Title"]!
//set the image
let imagePathParts = movie["Image"]!.componentsSeparatedByString(".")
searchableItemAttributeSet.thumbnailURL = NSBundle.mainBundle().URLForResource(imagePathParts[0], withExtension: imagePathParts[1])
// Set the description.
searchableItemAttributeSet.contentDescription = movie["Description"]!
var keywords = [String]()
let movieCategories = movie["Category"]!.componentsSeparatedByString(", ")
for movieCategory in movieCategories {
keywords.append(movieCategory)
}
let stars = movie["Stars"]!.componentsSeparatedByString(", ")
for star in stars {
keywords.append(star)
}
searchableItemAttributeSet.keywords = keywords
let searchableItem = CSSearchableItem(uniqueIdentifier: "com.appcoda.SpotIt.\(i)", domainIdentifier: "movies", attributeSet: searchableItemAttributeSet)
searchableItems.append(searchableItem)
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in
if error != nil {
print(error?.localizedDescription)
}
}
}
}
override func restoreUserActivityState(activity: NSUserActivity) {
if activity.activityType == CSSearchableItemActionType {
if let userInfo = activity.userInfo {
let selectedMovie = userInfo[CSSearchableItemActivityIdentifier] as! String
selectedIndex = Int(selectedMovie.componentsSeparatedByString(".").last!)!
performSegueWithIdentifier("tableView2ViewController", sender: self)
}
}
}
}
| 3252e09e6441ade50c3fa01842992e7c | 30.54902 | 164 | 0.624819 | false | false | false | false |
breadwallet/breadwallet-core | refs/heads/develop | Swift/BRCrypto/BRCryptoUnit.swift | mit | 1 | //
// BRCryptoUnit.swift
// BRCrypto
//
// Created by Ed Gamble on 3/27/19.
// Copyright © 2019 Breadwallet AG. 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 BRCryptoC
///
/// A unit of measure for a currency. There can be multiple units for a given currency (analogous
/// to 'System International' units of (meters, kilometers, miles, ...) for a dimension of
/// 'length'). For example, Ethereum has units of: WEI, GWEI, ETHER, METHER, ... and Bitcoin of:
/// BTC, SATOSHI, ...
///
/// Each Currency has a 'baseUnit' - which is defined as the 'integer-ish' unit - such as SATOSHI
/// ane WEI for Bitcoin and Ethereum, respectively. There can be multiple 'derivedUnits' - which
/// are derived by scaling off of a baseUnit. For example, BTC and ETHER respectively.
///
public final class Unit: Hashable {
internal let core: BRCryptoUnit
public var currency: Currency {
return Currency (core: cryptoUnitGetCurrency(core), take: false)
}
internal var uids: String {
return asUTF8String (cryptoUnitGetUids (core))
}
public var name: String {
return asUTF8String (cryptoUnitGetName (core))
}
public var symbol: String {
return asUTF8String (cryptoUnitGetSymbol (core))
}
public var base: Unit {
return Unit (core: cryptoUnitGetBaseUnit (core), take: false)
}
public var decimals: UInt8 {
return cryptoUnitGetBaseDecimalOffset (core)
}
public func isCompatible (with that: Unit) -> Bool {
return CRYPTO_TRUE == cryptoUnitIsCompatible (self.core, that.core)
}
public func hasCurrency (_ currency: Currency) -> Bool {
return CRYPTO_TRUE == cryptoUnitHasCurrency (core, currency.core);
}
internal init (core: BRCryptoUnit,
take: Bool) {
self.core = take ? cryptoUnitTake(core) : core
}
internal convenience init (core: BRCryptoUnit) {
self.init (core: core, take: true)
}
internal convenience init (currency: Currency,
code: String,
name: String,
symbol: String) {
self.init (core: cryptoUnitCreateAsBase (currency.core, code, name, symbol),
take: false)
}
internal convenience init (currency: Currency,
code: String,
name: String,
symbol: String,
base: Unit,
decimals: UInt8) {
self.init (core: cryptoUnitCreate (currency.core, code, name, symbol, base.core, decimals),
take: false)
}
deinit {
cryptoUnitGive (core)
}
public static func == (lhs: Unit, rhs: Unit) -> Bool {
return lhs === rhs || CRYPTO_TRUE == cryptoUnitIsIdentical (lhs.core, rhs.core)
}
public func hash (into hasher: inout Hasher) {
hasher.combine (uids)
}
}
| 02b64260d5a3e5bc66d7c617cdd8743c | 31.614583 | 99 | 0.600447 | false | false | false | false |
davidahouse/chute | refs/heads/master | chute/Output/DifferenceReport/DifferenceReportDetailViews.swift | mit | 1 | //
// DifferenceReportDetailViews.swift
// chute
//
// Created by David House on 11/16/17.
// Copyright © 2017 David House. All rights reserved.
//
import Foundation
struct DifferenceReportDetailViews: ChuteOutputDifferenceRenderable {
enum Constants {
static let Template = """
<style>
.gallery {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
}
.gallery img{ width: 100%; padding: 7px 0; margin-bottom: 7px; }
@media (max-width: 500px) {
.gallery {
-webkit-column-count: 1; /* Chrome, Safari, Opera */
-moz-column-count: 1; /* Firefox */
column-count: 1;
}
}
.gallery-image {
border: 1px solid lightgray;
margin-bottom: 17px;
border-radius: 5px;
width: 100%;
height: auto;
display: inline-block;
}
.gallery-image > h5 {
color: #777;
padding: 7px 5px 0px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
border-bottom: 1px solid lightgray;
}
.compare-gallery {
-webkit-column-count: 2; /* Chrome, Safari, Opera */
-moz-column-count: 2; /* Firefox */
column-count: 2;
}
.compare-gallery img{ width: 100%; padding: 7px 0; margin-bottom: 7px; }
</style>
<div class="jumbotron">
<h1>View Difference Details</h1>
<h3>New Views:</h3>
<div class="gallery">
{{new_views}}
</div>
<h3>Changed Views:</h3>
{{changed_views}}
</div>
"""
static let TestAttachmentTemplate = """
<div class="gallery-image">
<h5>{{attachment_name}}</h5>
<img src="attachments/{{attachment_file_name}}" alt="{{attachment_name}}">
</div>
"""
static let TestCompareAttachmentTemplate = """
<div class="compare-gallery">
<div class="gallery-image">
<h5>BEFORE {{attachment_name}}</h5>
<img src="attachments/{{before_attachment_file_name}}" alt="{{attachment_name}}">
</div>
<div class="gallery-image">
<h5>AFTER {{attachment_name}}</h5>
<img src="attachments/{{attachment_file_name}}" alt="{{attachment_name}}">
</div>
</div>
"""
}
func render(difference: DataCaptureDifference) -> String {
let parameters: [String: CustomStringConvertible] = [
"new_views": newViews(difference: difference),
"changed_views": changedViews(difference: difference)
]
return Constants.Template.render(parameters: parameters)
}
private func newViews(difference: DataCaptureDifference) -> String {
var views = ""
for attachment in difference.viewDifference.newViews.sortedByName() {
let attachmentParameters: [String: CustomStringConvertible] = [
"attachment_name": attachment.attachmentName,
"attachment_file_name": attachment.attachmentFileName
]
views += Constants.TestAttachmentTemplate.render(parameters: attachmentParameters)
}
return views
}
private func changedViews(difference: DataCaptureDifference) -> String {
var views = ""
for (attachment, beforeAttachment) in difference.viewDifference.changedViews {
let attachmentParameters: [String: CustomStringConvertible] = [
"attachment_name": attachment.attachmentName,
"before_attachment_file_name": "before_" + beforeAttachment.attachmentFileName,
"attachment_file_name": attachment.attachmentFileName
]
views += Constants.TestCompareAttachmentTemplate.render(parameters: attachmentParameters)
}
return views
}
}
| 1d0808d2c56ae9a80c0faedc17c0ad41 | 35.264463 | 101 | 0.518915 | false | false | false | false |
gobetti/Swift | refs/heads/master | NSBlockOperation/NSBlockOperation/ViewController.swift | mit | 1 | //
// ViewController.swift
// NSBlockOperation
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2014 Carlos Butron.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
let queue = NSOperationQueue()
let operation1 : NSBlockOperation = NSBlockOperation (
block: {
self.getWebs()
let operation2 : NSBlockOperation = NSBlockOperation(block: {
self.loadWebs()
})
queue.addOperation(operation2)
})
queue.addOperation(operation1)
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadWebs(){
let urls : NSMutableArray = NSMutableArray (objects:NSURL(string:"http://www.google.es")!, NSURL(string: "http://www.apple.com")!,NSURL(string: "http://carlosbutron.es")!, NSURL(string: "http://www.bing.com")!,NSURL(string: "http://www.yahoo.com")!)
urls.addObjectsFromArray(googlewebs as [AnyObject])
for iterator:AnyObject in urls{
/// NSData(contentsOfURL:iterator as! NSURL)
print("Downloaded \(iterator)")
}
}
var googlewebs:NSArray = []
func getWebs(){
let languages:NSArray = ["com","ad","ae","com.af","com.ag","com.ai","am","co.ao","com.ar","as","at"]
let languageWebs = NSMutableArray()
for(var i=0;i < languages.count; i++){
let webString: NSString = "http://www.google.\(languages[i])"
languageWebs.addObject(NSURL(fileURLWithPath: webString as String))
}
googlewebs = languageWebs
}
}
| e5e172c91b6cfbb42e97c299faa9d8ed | 26.470588 | 257 | 0.56424 | false | false | false | false |
AirHelp/Mimus | refs/heads/master | Sources/Mimus/Verification/VerificationHandler.swift | mit | 1 | //
// Copyright (©) 2017 AirHelp. All rights reserved.
//
import XCTest
internal class VerificationHandler {
private let mismatchMessageBuilder = MismatchMessageBuilder()
static var shared: VerificationHandler = VerificationHandler()
func verifyCall(callIdentifier: String, matchedResults: [MimusComparator.ComparisonResult], mismatchedArgumentsResults: [MimusComparator.ComparisonResult], mode: VerificationMode, testLocation: TestLocation) {
switch mode {
case .never:
assertNever(callIdentifier: callIdentifier,
matchCount: matchedResults.count,
differentArgumentsMatchCount: mismatchedArgumentsResults.count,
testLocation: testLocation)
case .atLeast(let count):
assertAtLeast(callIdentifier: callIdentifier,
times: count,
matchCount: matchedResults.count,
differentArgumentsMatch: mismatchedArgumentsResults,
testLocation: testLocation)
case .atMost(let count):
assertAtMost(callIdentifier: callIdentifier,
times: count,
matchCount: matchedResults.count,
differentArgumentsMatchCount: mismatchedArgumentsResults.count,
testLocation: testLocation)
case .times(let count):
assert(callIdentifier: callIdentifier,
times: count,
matchCount: matchedResults.count,
differentArgumentsMatch: mismatchedArgumentsResults,
testLocation: testLocation)
}
}
// MARK: Actual assertions
private func assertNever(callIdentifier: String, matchCount: Int, differentArgumentsMatchCount: Int, testLocation: TestLocation) {
guard matchCount > 0 else {
return
}
XCTFail("Expected to not receive call with identifier \(callIdentifier)",
file: testLocation.file,
line: testLocation.line)
}
private func assertAtMost(callIdentifier: String, times: Int, matchCount: Int, differentArgumentsMatchCount: Int, testLocation: TestLocation) {
guard matchCount > times else {
return
}
var message = "No call with identifier \(callIdentifier) was captured"
if matchCount > 0 {
message = "Call with identifier \(callIdentifier) was recorded \(matchCount) times, but expected at most \(times)"
}
XCTFail(message, file: testLocation.file, line: testLocation.line)
}
private func assertAtLeast(callIdentifier: String, times: Int, matchCount: Int, differentArgumentsMatch: [MimusComparator.ComparisonResult], testLocation: TestLocation) {
guard matchCount < times else {
return
}
let differentArgumentsMatchCount = differentArgumentsMatch.count
var message = "No call with identifier \(callIdentifier) was captured"
if matchCount > 0 {
let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch)
message = """
Call with identifier \(callIdentifier) was recorded \(matchCount) times, but expected at least \(times).
\(differentArgumentsMatchCount) additional call(s) matched identifier, but not arguments:\n\n\(mismatchedResultsMessage)
"""
} else if differentArgumentsMatchCount > 0 {
let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch)
message = """
Call with identifier \(callIdentifier) was recorded \(differentArgumentsMatchCount) times,
but arguments didn't match.\n\(mismatchedResultsMessage)
"""
}
XCTFail(message, file: testLocation.file, line: testLocation.line)
}
private func assert(callIdentifier: String, times: Int, matchCount: Int, differentArgumentsMatch: [MimusComparator.ComparisonResult], testLocation: TestLocation) {
guard matchCount != times else {
return
}
let differentArgumentsMatchCount = differentArgumentsMatch.count
var message = "No call with identifier \(callIdentifier) was captured"
if matchCount > 0 {
let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch)
message = """
Call with identifier was recorded \(matchCount) times, but expected \(times).
\(differentArgumentsMatchCount) additional call(s) matched identifier, but not arguments:\n\n\(mismatchedResultsMessage)
"""
} else if differentArgumentsMatchCount > 0 {
let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch)
message = """
Call with identifier \(callIdentifier) was recorded \(differentArgumentsMatchCount) times,
but arguments didn't match.\n\(mismatchedResultsMessage)
"""
}
XCTFail(message, file: testLocation.file, line: testLocation.line)
}
}
| 473026e1be49b40e2578a4d3ded380dd | 46.178571 | 213 | 0.640045 | false | true | false | false |
aolan/Cattle | refs/heads/master | CattleKit/CAProgressWidget.swift | mit | 1 | //
// CAProgressWidget.swift
// cattle
//
// Created by lawn on 15/11/5.
// Copyright © 2015年 zodiac. All rights reserved.
//
import UIKit
public class CAProgressWidget: UIView {
// MARK: - Property
/// 单例
static let sharedInstance = CAProgressWidget()
/// 黑色背景圆角
static let blackViewRadius: CGFloat = 10.0
/// 黑色背景透明度
static let blackViewAlpha: CGFloat = 0.8
/// 黑色背景边长
let blackViewWH: CGFloat = 100.0
/// 标签高度
let labelHeight: CGFloat = 15.0
/// 间距
let margin: CGFloat = 10.0
/// 控件显示的最长时间
let timeout: Double = 20.0
/// 提示信息展示时间
let shortTimeout: Double = 2.0
/// 动画时间,秒为单位
let animateTime: Double = 0.2
lazy var label: UILabel? = {
var tmpLbl = UILabel()
tmpLbl.textColor = UIColor.whiteColor()
tmpLbl.textAlignment = NSTextAlignment.Center
tmpLbl.font = UIFont.systemFontOfSize(12)
return tmpLbl
}()
lazy var detailLabel: UILabel? = {
var tmpLbl = UILabel()
tmpLbl.textColor = UIColor.whiteColor()
tmpLbl.textAlignment = NSTextAlignment.Center
tmpLbl.font = UIFont.systemFontOfSize(12)
return tmpLbl
}()
lazy var blackView: UIView? = {
var tmpView = UIView()
tmpView.backgroundColor = UIColor.blackColor()
tmpView.layer.cornerRadius = blackViewRadius
tmpView.layer.masksToBounds = true
tmpView.alpha = blackViewAlpha
return tmpView
}()
var progressView: UIActivityIndicatorView? = {
var tmpView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
return tmpView
}()
// MARK: - Private Methods
func dismissLoading(animated:NSNumber, didDissmiss: () -> Void) -> Void{
if superview == nil {
return
}
if animated.boolValue{
UIView.animateWithDuration(animateTime, animations: { () -> Void in
self.alpha = 0
}) { (isFininshed) -> Void in
self.removeAllSubViews()
self.removeFromSuperview()
didDissmiss()
}
}else{
removeAllSubViews()
removeFromSuperview()
didDissmiss()
}
}
func dismissLoading(animated: NSNumber) -> Void{
NSObject.cancelPreviousPerformRequestsWithTarget(self)
if superview == nil {
return
}
if animated.boolValue {
UIView.animateWithDuration(animateTime, animations: { () -> Void in
self.alpha = 0
}) { (isFininshed) -> Void in
self.removeAllSubViews()
self.removeFromSuperview()
}
}else{
removeAllSubViews()
removeFromSuperview()
}
}
func showLoading(inView: UIView?, text: String?, detailText: String?) {
//如果已经显示了,先隐藏
if superview != nil{
dismissLoading(NSNumber(bool: false))
}
//设置黑色背景和菊花
if inView != nil && blackView != nil && progressView != nil{
alpha = 0
frame = inView!.bounds
backgroundColor = UIColor.clearColor()
inView?.addSubview(self)
blackView?.ca_size(CGSize(width: blackViewWH, height: blackViewWH))
blackView?.ca_center(inView!.ca_center())
addSubview(blackView!)
progressView?.ca_center(inView!.ca_center())
addSubview(progressView!)
//设置标题
if text != nil && label != nil{
progressView?.ca_addY(-margin)
addSubview(label!)
label?.frame = CGRect(x: blackView!.ca_minX(), y: progressView!.ca_maxY() + margin, width: blackView!.ca_width(), height: labelHeight)
label?.text = text
//设置描述
if detailText != nil && detailLabel != nil{
progressView?.ca_addY(-margin)
label?.ca_addY(-margin)
addSubview(detailLabel!)
detailLabel?.frame = CGRect(x: blackView!.ca_minX(), y: label!.ca_maxY() + margin/2.0, width: blackView!.ca_width(), height: labelHeight)
detailLabel?.text = detailText
}
}
//显示
UIView.animateWithDuration(animateTime, animations: { () -> Void in
self.alpha = 1.0
}, completion: { (finished) -> Void in
self.progressView?.startAnimating()
self.performSelector(Selector("dismissLoading:"), withObject: NSNumber(bool: true), afterDelay: self.timeout)
})
}
}
func dismissMessage(animated: NSNumber) -> Void{
NSObject.cancelPreviousPerformRequestsWithTarget(self)
if animated.boolValue{
UIView.animateWithDuration(animateTime, animations: { () -> Void in
self.ca_addY(20.0)
self.alpha = 0
}) { (isFininshed) -> Void in
self.removeAllSubViews()
self.removeFromSuperview()
}
}else{
removeAllSubViews()
removeFromSuperview()
}
}
func showMessage(inView: UIView?, text: String?) {
//如果已经显示了,先隐藏
if superview != nil{
dismissMessage(NSNumber(bool: false))
}
if inView != nil && text != nil && blackView != nil && label != nil{
alpha = 0
frame = inView!.bounds
backgroundColor = UIColor.clearColor()
inView?.addSubview(self)
addSubview(blackView!)
addSubview(label!)
label?.text = text
label?.numberOfLines = 2
let attributes = NSDictionary(object: label!.font, forKey: NSFontAttributeName)
let size = label?.text?.boundingRectWithSize(CGSize(width: 200, height: 200), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: attributes as? [String : AnyObject], context: nil)
label?.frame = CGRect(x: 0, y: 0, width: 200, height: (size?.height)! + 30)
label?.ca_center(ca_center())
label?.ca_addY(-20.0)
blackView!.frame = label!.frame
//显示
UIView.animateWithDuration(animateTime, animations: { () -> Void in
self.alpha = 1.0
self.label?.ca_addY(20.0)
self.blackView!.frame = self.label!.frame
}, completion: { (finished) -> Void in
self.performSelector(Selector("dismissMessage:"), withObject: NSNumber(bool: true), afterDelay: self.shortTimeout)
})
}
}
// MARK: - Class Methods
/**
展示加载框
- parameter inView: 父视图
*/
class func loading(inView: UIView?) -> Void {
sharedInstance.showLoading(inView, text: nil, detailText: nil)
}
/**
展示带标题的加载框
- parameter superView: 父视图
- parameter text: 标题内容
*/
class func loading(inView: UIView?, text:String?) -> Void {
sharedInstance.showLoading(inView, text: text, detailText: nil)
}
/**
展示带标题和描述的加载框
- parameter superView: 父视图
- parameter text: 标题内容
- parameter detailText: 描述内容
*/
class func loading(inView: UIView?, text: String?, detailText: String?) -> Void{
sharedInstance.showLoading(inView, text: text, detailText: detailText)
}
/**
消息提示【几秒钟自动消失】
- parameter text: 提示信息
*/
class func message(text:String?) -> Void{
let window: UIWindow? = UIApplication.sharedApplication().keyWindow
sharedInstance.showMessage(window, text: text)
}
/**
隐藏加载框
*/
class func dismiss(didDissmiss: () -> Void) -> Void {
sharedInstance.dismissLoading(NSNumber(bool: true), didDissmiss: didDissmiss)
}
}
| 3d353cb468d0c7e1ffe538eb1e57ded9 | 29.907407 | 206 | 0.533853 | false | false | false | false |
tgu/HAP | refs/heads/master | Sources/HAP/Controllers/PairSetupController.swift | mit | 1 | import func Evergreen.getLogger
import Foundation
import HKDF
import SRP
fileprivate let logger = getLogger("hap.controllers.pair-setup")
class PairSetupController {
struct Session {
let server: SRP.Server
}
enum Error: Swift.Error {
case invalidParameters
case invalidPairingMethod
case couldNotDecryptMessage
case couldNotDecodeMessage
case couldNotSign
case couldNotEncrypt
case alreadyPaired
case alreadyPairing
case invalidSetupState
case authenticationFailed
}
let device: Device
public init(device: Device) {
self.device = device
}
func startRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8 {
guard let method = data[.pairingMethod]?.first.flatMap({ PairingMethod(rawValue: $0) }) else {
throw Error.invalidParameters
}
// TODO: according to spec, this should be `method == .pairSetup`
guard method == .default else {
throw Error.invalidPairingMethod
}
// If the accessory is already paired it must respond with
// Error_Unavailable
if device.pairingState == .paired {
throw Error.alreadyPaired
}
// If the accessory has received more than 100 unsuccessful
// authentication attempts it must respond with
// Error_MaxTries
// TODO
// If the accessory is currently performing a Pair Setup operation with
// a different controller it must respond with
// Error_Busy
if device.pairingState == .pairing {
throw Error.alreadyPairing
}
// Notify listeners of the pairing event and record the paring state
// swiftlint:disable:next force_try
try! device.changePairingState(.pairing)
let (salt, serverPublicKey) = session.server.getChallenge()
logger.info("Pair setup started")
logger.debug("<-- s \(salt.hex)")
logger.debug("<-- B \(serverPublicKey.hex)")
let result: PairTagTLV8 = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.publicKey, serverPublicKey),
(.salt, salt)
]
return result
}
func verifyRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8? {
guard let clientPublicKey = data[.publicKey], let clientKeyProof = data[.proof] else {
logger.warning("Invalid parameters")
throw Error.invalidSetupState
}
logger.debug("--> A \(clientPublicKey.hex)")
logger.debug("--> M \(clientKeyProof.hex)")
guard let serverKeyProof = try? session.server.verifySession(publicKey: clientPublicKey,
keyProof: clientKeyProof)
else {
logger.warning("Invalid PIN")
throw Error.authenticationFailed
}
logger.debug("<-- HAMK \(serverKeyProof.hex)")
let result: PairTagTLV8 = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.proof, serverKeyProof)
]
return result
}
func keyExchangeRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8 {
guard let encryptedData = data[.encryptedData] else {
throw Error.invalidParameters
}
let encryptionKey = deriveKey(algorithm: .sha512,
seed: session.server.sessionKey!,
info: "Pair-Setup-Encrypt-Info".data(using: .utf8),
salt: "Pair-Setup-Encrypt-Salt".data(using: .utf8),
count: 32)
guard let plaintext = try? ChaCha20Poly1305.decrypt(cipher: encryptedData,
nonce: "PS-Msg05".data(using: .utf8)!,
key: encryptionKey) else {
throw Error.couldNotDecryptMessage
}
guard let data: PairTagTLV8 = try? decode(plaintext) else {
throw Error.couldNotDecodeMessage
}
guard let publicKey = data[.publicKey],
let username = data[.identifier],
let signatureIn = data[.signature]
else {
throw Error.invalidParameters
}
logger.debug("--> identifier \(String(data: username, encoding: .utf8)!)")
logger.debug("--> public key \(publicKey.hex)")
logger.debug("--> signature \(signatureIn.hex)")
let hashIn = deriveKey(algorithm: .sha512,
seed: session.server.sessionKey!,
info: "Pair-Setup-Controller-Sign-Info".data(using: .utf8),
salt: "Pair-Setup-Controller-Sign-Salt".data(using: .utf8),
count: 32) +
username +
publicKey
try Ed25519.verify(publicKey: publicKey, message: hashIn, signature: signatureIn)
let hashOut = deriveKey(algorithm: .sha512,
seed: session.server.sessionKey!,
info: "Pair-Setup-Accessory-Sign-Info".data(using: .utf8),
salt: "Pair-Setup-Accessory-Sign-Salt".data(using: .utf8),
count: 32) +
device.identifier.data(using: .utf8)! +
device.publicKey
guard let signatureOut = try? Ed25519.sign(privateKey: device.privateKey, message: hashOut) else {
throw Error.couldNotSign
}
let resultInner: PairTagTLV8 = [
(.identifier, device.identifier.data(using: .utf8)!),
(.publicKey, device.publicKey),
(.signature, signatureOut)
]
logger.debug("<-- identifier \(self.device.identifier)")
logger.debug("<-- public key \(self.device.publicKey.hex)")
logger.debug("<-- signature \(signatureOut.hex)")
logger.info("Pair setup completed")
guard let encryptedResultInner = try? ChaCha20Poly1305.encrypt(message: encode(resultInner),
nonce: "PS-Msg06".data(using: .utf8)!,
key: encryptionKey)
else {
throw Error.couldNotEncrypt
}
// At this point, the pairing has completed. The first controller is granted admin role.
device.add(pairing: Pairing(identifier: username, publicKey: publicKey, role: .admin))
let resultOuter: PairTagTLV8 = [
(.state, Data(bytes: [PairSetupStep.keyExchangeResponse.rawValue])),
(.encryptedData, encryptedResultInner)
]
return resultOuter
}
}
| 578f154ccc2cf81edc754393d99c2930 | 37.530387 | 109 | 0.55879 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/06369-resolvetypedecl.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b<T where T, g = c
struct c<T where T: d = g<T where T
struct c<T where T.Element == c
var b = c<T
| ada04f8e12c4605b0832b5bc9b8e109d | 33.125 | 87 | 0.717949 | false | true | false | false |
CUITCHE/code-obfuscation | refs/heads/master | Gen/Gen/gen.swift | mit | 1 | //
// gen.swift
// Gen
//
// Created by hejunqiu on 2017/8/28.
// Copyright © 2017年 hejunqiu. All rights reserved.
//
import Foundation
struct Gen {
fileprivate var cache = EnumerateObjectiveClass()
fileprivate var fileBuffer = NSMutableString.init()
func gencode() {
guard validation() else {
print("Invalid!")
return
}
gen()
do {
try fileBuffer.write(toFile: (NSTemporaryDirectory() as NSString).appendingPathComponent("GenMetaData.cpp"), atomically: true, encoding: String.Encoding.utf8.rawValue)
print("Generate successfully! File at \(NSTemporaryDirectory())GenMetaData.cpp")
exit(0)
} catch {
print(error)
exit(-1)
}
}
}
fileprivate extension Gen {
func validation() -> Bool {
let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("output.data")
guard NSKeyedArchiver.archiveRootObject(cache, toFile: path) else {
print("Archiver Failed...")
return false
}
if let data = NSData.init(contentsOfFile: path) {
if let check = NSKeyedUnarchiver.unarchiveObject(with: data as Data) {
return NSDictionary.init(dictionary: cache).isEqual(to: check as! [AnyHashable : Any])
}
}
return false
}
func writeln(_ content: String) {
fileBuffer.append("\(content)\n")
}
func write_prepare() {
writeln("///// For iOS SDK \(ProcessInfo.processInfo.operatingSystemVersionString)\n")
writeln("#ifndef structs_h\n#define structs_h\n")
writeln("struct __method__ {\n" +
" const char *name;\n" +
"};\n")
writeln("struct __method__list {\n" +
" unsigned int reserved;\n" +
" unsigned int count;\n" +
" struct __method__ methods[0];\n" +
"};\n")
writeln("struct __class__ {\n" +
" struct __class__ *superclass;\n" +
" const char *name;\n" +
" const struct __method__list *method_list;\n" +
"};\n")
writeln("#ifndef CO_EXPORT")
writeln("#define CO_EXPORT extern \"C\"")
writeln("#endif")
}
func _write(clazzName: String, methodcount: Int, methoddesc: String) {
writeln("")
writeln("/// Meta data for \(clazzName)")
writeln("")
writeln("static struct /*__method__list_t*/ {")
writeln(" unsigned int entsize;")
writeln(" unsigned int method_count;")
writeln(" struct __method__ method_list[\(methodcount == 0 ? 1 : methodcount)];")
writeln("} _CO_METHODNAMES_\(clazzName)_$ __attribute__ ((used, section (\"__DATA,__co_const\"))) = {")
writeln(" sizeof(__method__),")
writeln(" \(methodcount),")
writeln(" {\(methoddesc)}\n};")
var super_class_t: String? = nil
if let superClass = class_getSuperclass(NSClassFromString(clazzName)) {
super_class_t = "_CO_CLASS_$_\(NSString.init(utf8String: class_getName(superClass)) ?? "")"
writeln("\nCO_EXPORT struct __class__ \(super_class_t!);")
}
writeln("CO_EXPORT struct __class__ _CO_CLASS_$_\(clazzName) __attribute__ ((used, section (\"__DATA,__co_data\"))) = {")
if super_class_t != nil {
writeln(" &\(super_class_t!),")
} else {
writeln(" 0,")
}
writeln(" \"\(clazzName)\",")
writeln(" (const struct __method__list *)&_CO_METHODNAMES_\(clazzName)_$\n};")
}
func write_tail() {
writeln("\nCO_EXPORT struct __class__ *L_CO_LABEL_CLASS_$[\(cache.count)] __attribute__((used, section (\"__DATA, __co_classlist\"))) = {")
for (key, _) in cache {
writeln(" &_CO_CLASS_$_\(key),")
}
fileBuffer.deleteCharacters(in: NSMakeRange(fileBuffer.length - 2, 1))
writeln("};")
writeln("\nCO_EXPORT struct /*__image_info*/ {\n" +
" const char *version;\n" +
" unsigned long size;\n" +
"} _CO_CLASS_IMAGE_INFO_$ __attribute__ ((used, section (\"__DATA,__co_const\"))) = {\n" +
" \"\(ProcessInfo.processInfo.operatingSystemVersionString)\",\n" +
" \(cache.count)\n" +
"};");
writeln("\n#endif");
}
func gen() {
write_prepare()
for (key, obj) in cache {
var methods = [String]()
for m in obj {
methods.append(m.method)
}
_write(clazzName: key, methodcount: obj.count, methoddesc: "{\"\(methods.joined(separator: "\"},{\""))\"}")
}
write_tail()
}
}
| 9bf795cd35dcb46b1f00834324faaa7f | 35.074074 | 179 | 0.517659 | false | false | false | false |
MxABC/LBXAlertAction | refs/heads/master | TestSwiftAlertAction/ViewController.swift | mit | 1 | //
// ViewController.swift
// TestSwiftAlertAction
//
// Created by lbxia on 16/6/17.
// Copyright © 2016年 lbx. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func testAlertView(_ sender: AnyObject)
{
// let alert = UIAlertView(title: "title", message: "message", delegate: nil, cancelButtonTitle: "cance", otherButtonTitles: "sure", "sure2")
//
// alert .show { (buttonIndex) in
//
// print(buttonIndex)
// }
let items = ["cancel","ok1","ok2"];
AlertAction.showAlert(title: "title", message: "message", btnStatements:items )
{
(buttonIndex) in
let items = ["cancel","ok1","ok2"];
print(buttonIndex)
print(items[buttonIndex])
}
}
@IBAction func testSheetView(_ sender: AnyObject)
{
let destrucitve:String? = "destructive"
// let destrucitve:String? = nil
AlertAction.showSheet(title: "title", message: "ios8之后才会显示本条信息", destructiveButtonTitle: destrucitve,cancelButtonTitle: "cancel", otherButtonTitles: ["other1","other2"]) { (buttonIdx, itemTitle) in
/*
经测试
buttonIdx: destructiveButtonTitle 为0, cancelButtonTitle 为1,otherButtonTitles按顺序增加
如果destructiveButtonTitle 传入值为nil,那么 cancelButtonTitle 为0,otherButtonTitles按顺序增加
或者按照itemTitle来判断用户点击那个按钮更稳妥
*/
print(buttonIdx)
print(itemTitle)
}
}
func alertResult(_ buttonIndex:Int) -> Void
{
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 7c1dc5328ba0c2eb933fb1c47d265b31 | 24.439024 | 206 | 0.555129 | false | false | false | false |
ben-ng/swift | refs/heads/master | stdlib/public/SDK/Foundation/NSStringEncodings.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME: one day this will be bridged from CoreFoundation and we
// should drop it here. <rdar://problem/14497260> (need support
// for CF bridging)
public var kCFStringEncodingASCII: CFStringEncoding { return 0x0600 }
extension String {
public struct Encoding : RawRepresentable {
public var rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let ascii = Encoding(rawValue: 1)
public static let nextstep = Encoding(rawValue: 2)
public static let japaneseEUC = Encoding(rawValue: 3)
public static let utf8 = Encoding(rawValue: 4)
public static let isoLatin1 = Encoding(rawValue: 5)
public static let symbol = Encoding(rawValue: 6)
public static let nonLossyASCII = Encoding(rawValue: 7)
public static let shiftJIS = Encoding(rawValue: 8)
public static let isoLatin2 = Encoding(rawValue: 9)
public static let unicode = Encoding(rawValue: 10)
public static let windowsCP1251 = Encoding(rawValue: 11)
public static let windowsCP1252 = Encoding(rawValue: 12)
public static let windowsCP1253 = Encoding(rawValue: 13)
public static let windowsCP1254 = Encoding(rawValue: 14)
public static let windowsCP1250 = Encoding(rawValue: 15)
public static let iso2022JP = Encoding(rawValue: 21)
public static let macOSRoman = Encoding(rawValue: 30)
public static let utf16 = Encoding.unicode
public static let utf16BigEndian = Encoding(rawValue: 0x90000100)
public static let utf16LittleEndian = Encoding(rawValue: 0x94000100)
public static let utf32 = Encoding(rawValue: 0x8c000100)
public static let utf32BigEndian = Encoding(rawValue: 0x98000100)
public static let utf32LittleEndian = Encoding(rawValue: 0x9c000100)
}
public typealias EncodingConversionOptions = NSString.EncodingConversionOptions
public typealias EnumerationOptions = NSString.EnumerationOptions
public typealias CompareOptions = NSString.CompareOptions
}
extension String.Encoding : Hashable {
public var hashValue : Int {
return rawValue.hashValue
}
public static func ==(lhs: String.Encoding, rhs: String.Encoding) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension String.Encoding : CustomStringConvertible {
public var description: String {
return String.localizedName(of: self)
}
}
@available(*, unavailable, renamed: "String.Encoding")
public typealias NSStringEncoding = UInt
@available(*, unavailable, renamed: "String.Encoding.ascii")
public var NSASCIIStringEncoding: String.Encoding {
return String.Encoding.ascii
}
@available(*, unavailable, renamed: "String.Encoding.nextstep")
public var NSNEXTSTEPStringEncoding: String.Encoding {
return String.Encoding.nextstep
}
@available(*, unavailable, renamed: "String.Encoding.japaneseEUC")
public var NSJapaneseEUCStringEncoding: String.Encoding {
return String.Encoding.japaneseEUC
}
@available(*, unavailable, renamed: "String.Encoding.utf8")
public var NSUTF8StringEncoding: String.Encoding {
return String.Encoding.utf8
}
@available(*, unavailable, renamed: "String.Encoding.isoLatin1")
public var NSISOLatin1StringEncoding: String.Encoding {
return String.Encoding.isoLatin1
}
@available(*, unavailable, renamed: "String.Encoding.symbol")
public var NSSymbolStringEncoding: String.Encoding {
return String.Encoding.symbol
}
@available(*, unavailable, renamed: "String.Encoding.nonLossyASCII")
public var NSNonLossyASCIIStringEncoding: String.Encoding {
return String.Encoding.nonLossyASCII
}
@available(*, unavailable, renamed: "String.Encoding.shiftJIS")
public var NSShiftJISStringEncoding: String.Encoding {
return String.Encoding.shiftJIS
}
@available(*, unavailable, renamed: "String.Encoding.isoLatin2")
public var NSISOLatin2StringEncoding: String.Encoding {
return String.Encoding.isoLatin2
}
@available(*, unavailable, renamed: "String.Encoding.unicode")
public var NSUnicodeStringEncoding: String.Encoding {
return String.Encoding.unicode
}
@available(*, unavailable, renamed: "String.Encoding.windowsCP1251")
public var NSWindowsCP1251StringEncoding: String.Encoding {
return String.Encoding.windowsCP1251
}
@available(*, unavailable, renamed: "String.Encoding.windowsCP1252")
public var NSWindowsCP1252StringEncoding: String.Encoding {
return String.Encoding.windowsCP1252
}
@available(*, unavailable, renamed: "String.Encoding.windowsCP1253")
public var NSWindowsCP1253StringEncoding: String.Encoding {
return String.Encoding.windowsCP1253
}
@available(*, unavailable, renamed: "String.Encoding.windowsCP1254")
public var NSWindowsCP1254StringEncoding: String.Encoding {
return String.Encoding.windowsCP1254
}
@available(*, unavailable, renamed: "String.Encoding.windowsCP1250")
public var NSWindowsCP1250StringEncoding: String.Encoding {
return String.Encoding.windowsCP1250
}
@available(*, unavailable, renamed: "String.Encoding.iso2022JP")
public var NSISO2022JPStringEncoding: String.Encoding {
return String.Encoding.iso2022JP
}
@available(*, unavailable, renamed: "String.Encoding.macOSRoman")
public var NSMacOSRomanStringEncoding: String.Encoding {
return String.Encoding.macOSRoman
}
@available(*, unavailable, renamed: "String.Encoding.utf16")
public var NSUTF16StringEncoding: String.Encoding {
return String.Encoding.utf16
}
@available(*, unavailable, renamed: "String.Encoding.utf16BigEndian")
public var NSUTF16BigEndianStringEncoding: String.Encoding {
return String.Encoding.utf16BigEndian
}
@available(*, unavailable, renamed: "String.Encoding.utf16LittleEndian")
public var NSUTF16LittleEndianStringEncoding: String.Encoding {
return String.Encoding.utf16LittleEndian
}
@available(*, unavailable, renamed: "String.Encoding.utf32")
public var NSUTF32StringEncoding: String.Encoding {
return String.Encoding.utf32
}
@available(*, unavailable, renamed: "String.Encoding.utf32BigEndian")
public var NSUTF32BigEndianStringEncoding: String.Encoding {
return String.Encoding.utf32BigEndian
}
@available(*, unavailable, renamed: "String.Encoding.utf32LittleEndian")
public var NSUTF32LittleEndianStringEncoding: String.Encoding {
return String.Encoding.utf32LittleEndian
}
| b4b90c55d73d093a8bb3f5dede7ec627 | 40 | 81 | 0.762981 | false | false | false | false |
tidepool-org/nutshell-ios | refs/heads/develop | Nutshell/ViewControllers/EventListViewController.swift | bsd-2-clause | 1 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import CoreData
class EventListViewController: BaseUIViewController, ENSideMenuDelegate {
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var searchTextField: NutshellUITextField!
@IBOutlet weak var searchPlaceholderLabel: NutshellUILabel!
@IBOutlet weak var tableView: NutshellUITableView!
@IBOutlet weak var coverView: UIControl!
fileprivate var sortedNutEvents = [(String, NutEvent)]()
fileprivate var filteredNutEvents = [(String, NutEvent)]()
fileprivate var filterString = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "All events"
// 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()
// Add a notification for when the database changes
let moc = NutDataController.controller().mocForNutEvents()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(EventListViewController.databaseChanged(_:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: moc)
notificationCenter.addObserver(self, selector: #selector(EventListViewController.textFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
if let sideMenu = self.sideMenuController()?.sideMenu {
sideMenu.delegate = self
menuButton.target = self
menuButton.action = #selector(EventListViewController.toggleSideMenu(_:))
let revealWidth = min(ceil((240.0/320.0) * self.view.bounds.width), 281.0)
sideMenu.menuWidth = revealWidth
sideMenu.bouncingEnabled = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate var viewIsForeground: Bool = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewIsForeground = true
configureSearchUI()
if let sideMenu = self.sideMenuController()?.sideMenu {
sideMenu.allowLeftSwipe = true
sideMenu.allowRightSwipe = true
sideMenu.allowPanGesture = true
}
if sortedNutEvents.isEmpty || eventListNeedsUpdate {
eventListNeedsUpdate = false
getNutEvents()
}
checkNotifyUserOfTestMode()
// periodically check for authentication issues in case we need to force a new login
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.checkConnection()
APIConnector.connector().trackMetric("Viewed Home Screen (Home Screen)")
}
// each first time launch of app, let user know we are still in test mode!
fileprivate func checkNotifyUserOfTestMode() {
if AppDelegate.testMode && !AppDelegate.testModeNotification {
AppDelegate.testModeNotification = true
let alert = UIAlertController(title: "Test Mode", message: "Nutshell has Test Mode enabled!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { Void in
return
}))
alert.addAction(UIAlertAction(title: "Turn Off", style: .default, handler: { Void in
AppDelegate.testMode = false
}))
self.present(alert, animated: true, completion: nil)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchTextField.resignFirstResponder()
viewIsForeground = false
if let sideMenu = self.sideMenuController()?.sideMenu {
//NSLog("swipe disabled")
sideMenu.allowLeftSwipe = false
sideMenu.allowRightSwipe = false
sideMenu.allowPanGesture = false
}
}
@IBAction func toggleSideMenu(_ sender: AnyObject) {
APIConnector.connector().trackMetric("Clicked Hamburger (Home Screen)")
toggleSideMenuView()
}
//
// MARK: - ENSideMenu Delegate
//
fileprivate func configureForMenuOpen(_ open: Bool) {
if open {
if let sideMenuController = self.sideMenuController()?.sideMenu?.menuViewController as? MenuAccountSettingsViewController {
// give sidebar a chance to update
// TODO: this should really be in ENSideMenu!
sideMenuController.menuWillOpen()
}
}
tableView.isUserInteractionEnabled = !open
self.navigationItem.rightBarButtonItem?.isEnabled = !open
coverView.isHidden = !open
}
func sideMenuWillOpen() {
//NSLog("EventList sideMenuWillOpen")
configureForMenuOpen(true)
}
func sideMenuWillClose() {
//NSLog("EventList sideMenuWillClose")
configureForMenuOpen(false)
}
func sideMenuShouldOpenSideMenu() -> Bool {
//NSLog("EventList sideMenuShouldOpenSideMenu")
return true
}
func sideMenuDidClose() {
//NSLog("EventList sideMenuDidClose")
configureForMenuOpen(false)
}
func sideMenuDidOpen() {
//NSLog("EventList sideMenuDidOpen")
configureForMenuOpen(true)
APIConnector.connector().trackMetric("Viewed Hamburger Menu (Hamburger)")
}
//
// 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.
super.prepare(for: segue, sender: sender)
if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventGroupSegue {
let cell = sender as! EventListTableViewCell
let eventGroupVC = segue.destination as! EventGroupTableViewController
eventGroupVC.eventGroup = cell.eventGroup!
APIConnector.connector().trackMetric("Clicked a Meal (Home screen)")
} else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue {
let cell = sender as! EventListTableViewCell
let eventDetailVC = segue.destination as! EventDetailViewController
let group = cell.eventGroup!
eventDetailVC.eventGroup = group
eventDetailVC.eventItem = group.itemArray[0]
APIConnector.connector().trackMetric("Clicked a Meal (Home screen)")
} else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.HomeToAddEventSegue {
APIConnector.connector().trackMetric("Click Add (Home screen)")
} else {
NSLog("Unprepped segue from eventList \(segue.identifier)")
}
}
// Back button from group or detail viewer.
@IBAction func done(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList done!")
}
// Multiple VC's on the navigation stack return all the way back to this initial VC via this segue, when nut events go away due to deletion, for test purposes, etc.
@IBAction func home(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList home!")
}
// The add/edit VC will return here when a meal event is deleted, and detail vc was transitioned to directly from this vc (i.e., the Nut event contained a single meal event which was deleted).
@IBAction func doneItemDeleted(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList doneItemDeleted")
}
@IBAction func cancel(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList cancel")
}
fileprivate var eventListNeedsUpdate: Bool = false
func databaseChanged(_ note: Notification) {
NSLog("EventList: Database Change Notification")
if viewIsForeground {
getNutEvents()
} else {
eventListNeedsUpdate = true
}
}
func getNutEvents() {
var nutEvents = [String: NutEvent]()
func addNewEvent(_ newEvent: EventItem) {
/// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING!
if newEvent.userid == nil {
newEvent.userid = NutDataController.controller().currentUserId
if let moc = newEvent.managedObjectContext {
NSLog("NOTE: Updated nil userid to \(newEvent.userid)")
moc.refresh(newEvent, mergeChanges: true)
_ = DatabaseUtils.databaseSave(moc)
}
}
/// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING!
let newEventId = newEvent.nutEventIdString()
if let existingNutEvent = nutEvents[newEventId] {
_ = existingNutEvent.addEvent(newEvent)
//NSLog("appending new event: \(newEvent.notes)")
//existingNutEvent.printNutEvent()
} else {
nutEvents[newEventId] = NutEvent(firstEvent: newEvent)
}
}
sortedNutEvents = [(String, NutEvent)]()
filteredNutEvents = [(String, NutEvent)]()
filterString = ""
// Get all Food and Activity events, chronologically; this will result in an unsorted dictionary of NutEvents.
do {
let nutEvents = try DatabaseUtils.getAllNutEvents()
for event in nutEvents {
//if let event = event as? Workout {
// NSLog("Event type: \(event.type), id: \(event.id), time: \(event.time), created time: \(event.createdTime!.timeIntervalSinceDate(event.time!)), duration: \(event.duration), title: \(event.title), notes: \(event.notes), userid: \(event.userid), timezone offset:\(event.timezoneOffset)")
//}
addNewEvent(event)
}
} catch let error as NSError {
NSLog("Error: \(error)")
}
sortedNutEvents = nutEvents.sorted() { $0.1.mostRecent.compare($1.1.mostRecent as Date) == ComparisonResult.orderedDescending }
updateFilteredAndReload()
// One time orphan check after application load
EventListViewController.checkAndDeleteOrphans(sortedNutEvents)
}
static var _checkedForOrphanPhotos = false
class func checkAndDeleteOrphans(_ allNutEvents: [(String, NutEvent)]) {
if _checkedForOrphanPhotos {
return
}
_checkedForOrphanPhotos = true
if let photoDirPath = NutUtils.photosDirectoryPath() {
var allLocalPhotos = [String: Bool]()
let fm = FileManager.default
do {
let dirContents = try fm.contentsOfDirectory(atPath: photoDirPath)
//NSLog("Photos dir: \(dirContents)")
if !dirContents.isEmpty {
for file in dirContents {
allLocalPhotos[file] = false
}
for (_, nutEvent) in allNutEvents {
for event in nutEvent.itemArray {
for url in event.photoUrlArray() {
if url.hasPrefix("file_") {
//NSLog("\(NutUtils.photoInfo(url))")
allLocalPhotos[url] = true
}
}
}
}
}
} catch let error as NSError {
NSLog("Error accessing photos at \(photoDirPath), error: \(error)")
}
let orphans = allLocalPhotos.filter() { $1 == false }
for (url, _) in orphans {
NSLog("Deleting orphaned photo: \(url)")
NutUtils.deleteLocalPhoto(url)
}
}
}
// MARK: - Search
@IBAction func dismissKeyboard(_ sender: AnyObject) {
searchTextField.resignFirstResponder()
}
func textFieldDidChange() {
updateFilteredAndReload()
}
@IBAction func searchEditingDidEnd(_ sender: AnyObject) {
configureSearchUI()
}
@IBAction func searchEditingDidBegin(_ sender: AnyObject) {
configureSearchUI()
APIConnector.connector().trackMetric("Typed into Search (Home Screen)")
}
fileprivate func searchMode() -> Bool {
var searchMode = false
if searchTextField.isFirstResponder {
searchMode = true
} else if let searchText = searchTextField.text {
if !searchText.isEmpty {
searchMode = true
}
}
return searchMode
}
fileprivate func configureSearchUI() {
let searchOn = searchMode()
searchPlaceholderLabel.isHidden = searchOn
self.title = searchOn && !filterString.isEmpty ? "Events" : "All events"
}
fileprivate func updateFilteredAndReload() {
if !searchMode() {
filteredNutEvents = sortedNutEvents
filterString = ""
} else if let searchText = searchTextField.text {
if !searchText.isEmpty {
if searchText.localizedCaseInsensitiveContains(filterString) {
// if the search is just getting longer, no need to check already filtered out items
filteredNutEvents = filteredNutEvents.filter() {
$1.containsSearchString(searchText)
}
} else {
filteredNutEvents = sortedNutEvents.filter() {
$1.containsSearchString(searchText)
}
}
filterString = searchText
} else {
filteredNutEvents = sortedNutEvents
filterString = ""
}
// Do this last, after filterString is configured
configureSearchUI()
}
tableView.reloadData()
}
}
//
// MARK: - Table view delegate
//
extension EventListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt estimatedHeightForRowAtIndexPath: IndexPath) -> CGFloat {
return 102.0;
}
func tableView(_ tableView: UITableView, heightForRowAt heightForRowAtIndexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let tuple = self.filteredNutEvents[indexPath.item]
let nutEvent = tuple.1
let cell = tableView.cellForRow(at: indexPath)
if nutEvent.itemArray.count == 1 {
self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue, sender: cell)
} else if nutEvent.itemArray.count > 1 {
self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventGroupSegue, sender: cell)
}
}
}
//
// MARK: - Table view data source
//
extension EventListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredNutEvents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Note: two different list cells are used depending upon whether a location will be shown or not.
var cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellNoLoc
var nutEvent: NutEvent?
if (indexPath.item < filteredNutEvents.count) {
let tuple = self.filteredNutEvents[indexPath.item]
nutEvent = tuple.1
if !nutEvent!.location.isEmpty {
cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellWithLoc
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! EventListTableViewCell
if let nutEvent = nutEvent {
cell.configureCell(nutEvent)
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
}
| b43a49c0ff9357cb579cce91ff1df059 | 38.587738 | 305 | 0.628785 | false | false | false | false |
JGiola/swift | refs/heads/main | validation-test/compiler_crashers_2_fixed/0207-sr7371.swift | apache-2.0 | 11 | // RUN: %target-swift-frontend -emit-ir %s
public protocol TypedParserResultTransferType {
// Remove type constraint
associatedtype Result: ParserResult
}
public struct AnyTypedParserResultTransferType<P: ParserResult>: TypedParserResultTransferType {
public typealias Result = P
// Remove property
public let result: P
}
public protocol ParserResult {}
public protocol StaticParser: ParserResult {}
// Change comformance to ParserResult
public protocol TypedStaticParser: StaticParser {
// Remove type constraint
associatedtype ResultTransferType: TypedParserResultTransferType
}
// Remove where clause
public protocol MutableSelfStaticParser: TypedStaticParser where ResultTransferType == AnyTypedParserResultTransferType<Self> {
func parseTypeVar() -> AnyTypedParserResultTransferType<Self>
}
extension MutableSelfStaticParser {
public func anyFunction() -> () {
let t = self.parseTypeVar
// Remove this and below
_ = t()
_ = self.parseTypeVar()
}
}
| 29616c54c6e7dd37c4b1f0add2ae1824 | 27.666667 | 127 | 0.747093 | false | false | false | false |
vinivendra/jokr | refs/heads/master | jokr/Translators/JKRObjcTranslator.swift | apache-2.0 | 1 | // doc
// test
class JKRObjcTranslator: JKRTranslator {
////////////////////////////////////////////////////////////////////////////
// MARK: Interface
init(writingWith writer: JKRWriter = JKRConsoleWriter()) {
self.writer = writer
}
static func create(writingWith writer: JKRWriter) -> JKRTranslator {
return JKRObjcTranslator(writingWith: writer)
}
func translate(program: JKRTreeProgram) throws {
do {
if let statements = program.statements {
changeFile("main.m")
indentation = 0
write("#import <Foundation/Foundation.h>\n\nint main(int argc, const char * argv[]) {\n")
// swiftlint:disable:previous line_length
indentation += 1
addIntentation()
write("@autoreleasepool {\n")
indentation += 1
writeWithStructure(statements)
indentation = 1
addIntentation()
write("}\n")
addIntentation()
write("return 0;\n}\n")
}
// if let declarations = program.declarations {
// }
try writer.finishWriting()
}
catch (let error) {
throw error
}
}
////////////////////////////////////////////////////////////////////////////
// MARK: Implementation
private static let valueTypes = ["int", "float", "void"]
// Transpilation (general structure)
private var indentation = 0
private func writeWithStructure(_ statements: [JKRTreeStatement]) {
for statement in statements {
writeWithStructure(statement)
}
}
private func writeWithStructure(_ statement: JKRTreeStatement) {
addIntentation()
write(translate(statement))
// if let block = statement.block {
// write(" {\n")
// indentation += 1
// writeWithStructure(block)
// indentation -= 1
// addIntentation()
// write("}\n")
// }
}
// Translation (pieces of code)
private func translate(_ statement: JKRTreeStatement) -> String {
switch statement {
case let .assignment(assignment):
return translate(assignment)
case let .functionCall(functionCall):
return translate(functionCall)
case let .returnStm(returnStm):
return translate(returnStm)
}
}
private func translate(
_ assignment: JKRTreeAssignment) -> String {
switch assignment {
case let .declaration(type, id, expression):
let typeText = string(for: type, withSpaces: true)
let idText = string(for: id)
let expressionText = translate(expression)
return "\(typeText)\(idText) = \(expressionText);\n"
case let .assignment(id, expression):
let idText = string(for: id)
let expressionText = translate(expression)
return "\(idText) = \(expressionText);\n"
}
}
private func translate(_ functionCall: JKRTreeFunctionCall) -> String {
if functionCall.id == "print" {
if functionCall.parameters.count == 0 {
return "NSLog(@\"Hello jokr!\\n\");\n"
}
else {
let format = functionCall.parameters.map {_ in "%d" }
.joined(separator: " ")
let parameters = functionCall.parameters.map(translate)
.joined(separator: ", ")
return "NSLog(@\"\(format)\\n\", \(parameters));\n"
}
}
return "\(string(for: functionCall.id))();\n"
}
private func translateHeader(
_ function: JKRTreeFunctionDeclaration) -> String {
var contents =
"- (\(string(for: function.type)))\(string(for: function.id))"
let parameters = function.parameters.map(strings(for:))
if let parameter = parameters.first {
contents += ":(\(parameter.type))\(parameter.id)"
}
for parameter in parameters.dropFirst() {
contents += " \(parameter.id):(\(parameter.type))\(parameter.id)"
}
return contents
}
private func translate(_ returnStm: JKRTreeReturn) -> String {
let expression = translate(returnStm.expression)
return "return \(expression);\n"
}
private func translate(
_ expression: JKRTreeExpression) -> String {
switch expression {
case let .int(int):
return string(for: int)
case let .parenthesized(innerExpression):
let innerExpressionText = translate(innerExpression)
return "(\(innerExpressionText))"
case let .operation(leftExpression, op, rightExpression):
let leftText = translate(leftExpression)
let rightText = translate(rightExpression)
return "\(leftText) \(op.text) \(rightText)"
case let .lvalue(id):
return string(for: id)
}
}
private func strings(
for parameter: JKRTreeParameterDeclaration)
-> (type: String, id: String)
{
return (string(for: parameter.type),
string(for: parameter.id))
}
private func string(for type: JKRTreeType,
withSpaces: Bool = false) -> String {
let lowercased = type.text.lowercased()
if JKRObjcTranslator.valueTypes.contains(lowercased) {
if withSpaces {
return lowercased + " "
}
else {
return lowercased
}
}
else {
return type.text + " *"
}
}
func string(for id: JKRTreeID) -> String {
return id.text
}
func string(for int: JKRTreeInt) -> String {
return String(int.value)
}
// Writing
private let writer: JKRWriter
private func write(_ string: String) {
writer.write(string)
}
private func changeFile(_ string: String) {
writer.changeFile(string)
}
private func addIntentation() {
for _ in 0..<indentation {
write("\t")
}
}
}
| 52439bc6ed439db574901e15c7b37f5b | 23.598086 | 93 | 0.650846 | false | false | false | false |
ben-ng/swift | refs/heads/master | test/SILGen/generic_witness.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s
protocol Runcible {
func runce<A>(_ x: A)
}
// CHECK-LABEL: sil hidden @_TF15generic_witness3foo{{.*}} : $@convention(thin) <B where B : Runcible> (@in B) -> () {
func foo<B : Runcible>(_ x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @_TF15generic_witness3bar{{.*}} : $@convention(thin) (@in Runcible) -> ()
func bar(_ x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Runcible>
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
protocol Color {}
protocol Ink {
associatedtype Paint
}
protocol Pen {}
protocol Pencil : Pen {
associatedtype Stroke : Pen
}
protocol Medium {
associatedtype Texture : Ink
func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint
}
struct Canvas<I : Ink> where I.Paint : Pen {
typealias Texture = I
func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { }
}
extension Canvas : Medium {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWuRx15generic_witness3Inkwx5PaintS_3PenrGVS_6Canvasx_S_6MediumS_FS4_4drawuRd__S_6Pencilwd__6StrokezWx7TextureS1__rfT5paintWxS7_S1__6pencilqd___T_ : $@convention(witness_method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @_TFV15generic_witness6Canvas4drawuRd__S_6Pencilwx5Paintzwd__6StrokerfT5paintwxS2_6pencilqd___T_ : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: }
| 86b3167a34de89136c42f6547dc917e4 | 41.803571 | 377 | 0.623696 | false | false | false | false |
Snail93/iOSDemos | refs/heads/dev | SnailSwiftDemos/SnailSwiftDemos/ThirdFrameworks/ViewControllers/MyImagePickerViewController.swift | apache-2.0 | 2 | //
// MyImagePickerViewController.swift
// SnailSwiftDemos
//
// Created by Jian Wu on 2017/3/23.
// Copyright © 2017年 Snail. All rights reserved.
//
import UIKit
//import ImagePicker
class MyImagePickerViewController: CustomViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navTitleLabel.text = "ImagePicker"
rightBtn.isHidden = false
}
override func rightAction() {
// Configuration.doneButtonTitle = "Finshi"
// Configuration.noImagesTitle = "Sorry! Threre"
//
// super.rightAction()
// let iPController = ImagePickerController()
// iPController.delegate = self
// self.present(iPController, animated: true, completion: nil)
}
//
// //MARK: - ImagePickerDelegate methods
// func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
// print(images.count)
// }
//
// func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
// print(images)
// }
//
// func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
// print("???")
// }
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.
}
*/
}
| 7cbc3c242cdc7f21246e5a0a27827df7 | 26.761905 | 106 | 0.64837 | false | false | false | false |
UrbanCompass/Snail | refs/heads/main | Snail/Scheduler.swift | mit | 1 | // Copyright © 2018 Compass. All rights reserved.
import Foundation
public class Scheduler {
let delay: TimeInterval
let repeats: Bool
public let observable = Observable<Void>()
private var timer: Timer?
public init(_ delay: TimeInterval, repeats: Bool = true) {
self.delay = delay
self.repeats = repeats
}
@objc public func onNext() {
observable.on(.next(()))
}
public func start() {
stop()
timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(onNext), userInfo: nil, repeats: repeats)
}
public func stop() {
timer?.invalidate()
}
}
| a437ad310ef460d6c3fa4cc54c26f3b3 | 22.068966 | 133 | 0.621824 | false | false | false | false |
NeilNie/Done- | refs/heads/master | Pods/Eureka/Source/Rows/SliderRow.swift | apache-2.0 | 1 | // SliderRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// The cell of the SliderRow
open class SliderCell: Cell<Float>, CellType {
private var awakeFromNibCalled = false
@IBOutlet open weak var titleLabel: UILabel!
@IBOutlet open weak var valueLabel: UILabel!
@IBOutlet open weak var slider: UISlider!
open var formatter: NumberFormatter?
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
if me.shouldShowTitle {
me.titleLabel = me.textLabel
me.valueLabel = me.detailTextLabel
me.setNeedsUpdateConstraints()
}
}
}
deinit {
guard !awakeFromNibCalled else { return }
NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
awakeFromNibCalled = true
}
open override func setup() {
super.setup()
if !awakeFromNibCalled {
let title = textLabel
textLabel?.translatesAutoresizingMaskIntoConstraints = false
textLabel?.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
self.titleLabel = title
let value = detailTextLabel
value?.translatesAutoresizingMaskIntoConstraints = false
value?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal)
value?.adjustsFontSizeToFitWidth = true
value?.minimumScaleFactor = 0.5
self.valueLabel = value
let slider = UISlider()
slider.translatesAutoresizingMaskIntoConstraints = false
slider.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
self.slider = slider
if shouldShowTitle {
contentView.addSubview(titleLabel)
}
if !sliderRow.shouldHideValue {
contentView.addSubview(valueLabel)
}
contentView.addSubview(slider)
setNeedsUpdateConstraints()
}
selectionStyle = .none
slider.minimumValue = 0
slider.maximumValue = 10
slider.addTarget(self, action: #selector(SliderCell.valueChanged), for: .valueChanged)
}
open override func update() {
super.update()
titleLabel.text = row.title
titleLabel.isHidden = !shouldShowTitle
valueLabel.text = row.displayValueFor?(row.value)
valueLabel.isHidden = sliderRow.shouldHideValue
slider.value = row.value ?? slider.minimumValue
slider.isEnabled = !row.isDisabled
}
@objc func valueChanged() {
let roundedValue: Float
let steps = Float(sliderRow.steps)
if steps > 0 {
let stepValue = round((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue) * steps)
let stepAmount = (slider.maximumValue - slider.minimumValue) / steps
roundedValue = stepValue * stepAmount + self.slider.minimumValue
} else {
roundedValue = slider.value
}
row.value = roundedValue
row.updateCell()
}
var shouldShowTitle: Bool {
return row?.title?.isEmpty == false
}
private var sliderRow: SliderRow {
return row as! SliderRow
}
open override func updateConstraints() {
customConstraints()
super.updateConstraints()
}
open var dynamicConstraints = [NSLayoutConstraint]()
open func customConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views: [String : Any] = ["titleLabel": titleLabel, "slider": slider, "valueLabel": valueLabel]
let metrics = ["spacing": 15.0]
valueLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
let title = shouldShowTitle ? "[titleLabel]-spacing-" : ""
let value = !sliderRow.shouldHideValue ? "-[valueLabel]" : ""
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
let hContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-\(title)[slider]\(value)-|", options: .alignAllCenterY, metrics: metrics, views: views)
dynamicConstraints.append(contentsOf: hContraints)
} else {
let hContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(title)[slider]\(value)-|", options: .alignAllCenterY, metrics: metrics, views: views)
dynamicConstraints.append(contentsOf: hContraints)
}
let vContraint = NSLayoutConstraint(item: slider, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)
dynamicConstraints.append(vContraint)
contentView.addConstraints(dynamicConstraints)
}
}
/// A row that displays a UISlider. If there is a title set then the title and value will appear above the UISlider.
public final class SliderRow: Row<SliderCell>, RowType {
public var steps: UInt = 20
public var shouldHideValue = false
required public init(tag: String?) {
super.init(tag: tag)
}
}
| 6f189abbb08d05ea61df350664b52fd3 | 38.817143 | 186 | 0.666475 | false | false | false | false |
radicalbear/radbear-ios | refs/heads/master | radbear-ios/Classes/SimpleCell.swift | mit | 1 | //
// SimpleCell.h
// radbear-ios
//
// Created by Gary Foster on 6/26/12.
// Copyright (c) 2012 Radical Bear LLC. All rights reserved.
//
public class SimpleCell: UITableViewCell {
var image_y: Int = 0
public func changeStyle(_ row: Int, cellText: String, sub1: String?, sub2: String?, sub3: String?, highlight: Bool, color: UIColor?, tableWidth: Int, imageY: Int) {
let myEnvironment = Environment.sharedInstance
image_y = imageY
if color != nil {
let bgView = UITableViewCell(frame: CGRect.zero)
bgView.backgroundColor = color
self.backgroundView = bgView
self.backgroundColor = color
}
else {
let bgView = UITableViewCell(frame: CGRect.zero)
if myEnvironment.darkTheme {
let evenColor = UIColor(patternImage: AppTools.getImage(name: "row-background-1-opaque.png")!)
let oddColor = UIColor(patternImage: AppTools.getImage(name: "row-background-2-opaque.png")!)
bgView.backgroundColor = (row % 2) == 0 ? evenColor : oddColor
} else {
let evenColor = UIColor(patternImage: AppTools.getImage(name: "row-background-1.png")!)
let oddColor = UIColor(patternImage: AppTools.getImage(name: "row-background-2.png")!)
bgView.backgroundColor = (row % 2) == 0 ? evenColor : oddColor
}
self.backgroundView = bgView
}
var lblX: Int = 17
var lblY: Int = (sub3 != nil ) ? 5 : 11
var lblW: Int = tableWidth - 70
var lblH: Int = 21
let imageW: Int = 60
var subW: Int = RBAppTools.isIpad() ? 120 : 60
var rightMargin: Int = 23
if RBAppTools.isIpad() {
rightMargin = rightMargin * 2
subW = subW * 2
}
let subX: Int = tableWidth - subW - rightMargin
let subY: Int = (sub3 != nil) ? 5 : 0
if ((self.imageView?.image) != nil) {
lblX = lblX + imageW
lblW = lblW - imageW
}
if (sub1 != nil) || (sub2 != nil) {
lblW = lblW - 40
lblY = lblY - 6
lblH = lblH + 12
}
var lbl: UILabel? = (self.viewWithTag(1) as? UILabel)
if lbl == nil {
lbl = UILabel(frame: CGRect(x: CGFloat(lblX), y: CGFloat(lblY), width: CGFloat(lblW), height: CGFloat(lblH)))
}
if highlight {
lbl?.textColor = UIColor.red
}
else {
if myEnvironment.darkTheme {
lbl?.textColor = (color == nil) ? UIColor.white : UIColor.black
} else {
lbl?.textColor = (color == nil) ? UIColor.black : UIColor.white
}
}
if (sub1 != nil) || (sub2 != nil) {
lbl?.numberOfLines = 2
lbl?.lineBreakMode = .byWordWrapping
lbl?.font = UIFont.boldSystemFont(ofSize: CGFloat(14))
lbl?.adjustsFontSizeToFitWidth = true
}
else {
lbl?.font = UIFont.boldSystemFont(ofSize: CGFloat(16))
}
lbl?.text = cellText
lbl?.backgroundColor = UIColor.clear
lbl?.tag = 1
self.contentView.addSubview(lbl!)
var lblSub1: UILabel? = (self.viewWithTag(2) as? UILabel)
if lblSub1 == nil {
lblSub1 = UILabel(frame: CGRect(x: CGFloat(subX), y: CGFloat(subY), width: CGFloat(subW), height: CGFloat(21)))
}
lblSub1?.font = UIFont.systemFont(ofSize: CGFloat(13))
lblSub1?.textColor = UIColor.darkGray
lblSub1?.adjustsFontSizeToFitWidth = false
lblSub1?.text = sub1
lblSub1?.backgroundColor = UIColor.clear
lblSub1?.tag = 2
lblSub1?.isHidden = (sub1 == nil)
self.contentView.addSubview(lblSub1!)
var lblSub2: UILabel? = (self.viewWithTag(3) as? UILabel)
if lblSub2 == nil {
lblSub2 = UILabel(frame: CGRect(x: CGFloat(subX), y: CGFloat(20), width: CGFloat(subW), height: CGFloat(21)))
}
lblSub2?.font = UIFont.systemFont(ofSize: CGFloat(13))
lblSub2?.textColor = UIColor.darkGray
lblSub2?.adjustsFontSizeToFitWidth = false
lblSub2?.text = sub2
lblSub2?.backgroundColor = UIColor.clear
lblSub2?.tag = 3
lblSub2?.isHidden = (sub2 == nil)
self.contentView.addSubview(lblSub2!)
var lblSub3: UILabel? = (self.viewWithTag(4) as? UILabel)
if lblSub3 == nil {
lblSub3 = UILabel(frame: CGRect(x: CGFloat(lblX), y: CGFloat(lblY + 22), width: CGFloat(tableWidth - lblX - 25), height: CGFloat(40)))
}
lblSub3?.font = UIFont.systemFont(ofSize: CGFloat(12))
lblSub3?.textColor = UIColor.darkGray
lblSub3?.adjustsFontSizeToFitWidth = false
lblSub3?.text = sub3
lblSub3?.backgroundColor = UIColor.clear
lblSub3?.numberOfLines = 2
lblSub3?.tag = 4
lblSub3?.isHidden = (sub3 == nil)
self.contentView.addSubview(lblSub3!)
}
public func changeStyle(_ row: Int, cellText: String, sub1: String?, sub2: String?, highlight: Bool, tableWidth: Int, imageY: Int) {
self.changeStyle(row, cellText: cellText, sub1: sub1, sub2: sub2, sub3: nil, highlight: highlight, color: nil, tableWidth: tableWidth, imageY: imageY)
}
public func changeStyle(_ cellText: String, sub1: String, sub2: String, sub3: String, highlight: Bool, color: UIColor, tableWidth: Int) {
self.changeStyle(-1, cellText: cellText, sub1: sub1, sub2: sub2, sub3: sub3, highlight: highlight, color: color, tableWidth: tableWidth, imageY: 11)
}
public override func layoutSubviews() {
super.layoutSubviews()
self.imageView?.frame = CGRect(x: CGFloat(20), y: CGFloat(image_y), width: CGFloat(48), height: CGFloat(48))
}
}
| 3443a07bb5b112483b8bbdcc1b9aabe7 | 41.3 | 168 | 0.579027 | false | false | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | refs/heads/master | Playground Collection/Part 4 - Alien Adventure 2/Advanced Operators/Advanced Operators.playground/Pages/Bitwise Operators.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
/*:
## Bitwise Operators
Bitwise NOT operator (also called INVERT)
*/
var someBits: UInt8 = 0b00001111
let invertedBits = ~someBits // equals 11110000
//: **Bitwise AND operator**
someBits = 0b01011100
var someMoreBits: UInt8 = 0b11101000
let andBits = someBits & someMoreBits // equals 0b01001000
//: **Bitwise OR operator**
someBits = 0b01101111
someMoreBits = 0b10001111
let orBits = someBits | someMoreBits // equals 0b11101111
//: **Bitwise XOR operator**
someBits = 0b11000011
someMoreBits = 0b10011001
let xorBits = someBits ^ someMoreBits // equals 0b01011010
/*:
**Bitwise Left Shift operator**
See [Apple's Docs on Advanced Operators](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html), go to the "Bitwise Left and Right Shift Operators" section)
*/
someBits = 0b00010001
var leftShiftedBits = someBits << 1 // equals 0b00100010
leftShiftedBits = leftShiftedBits << 2 // eqauls 0b10001000
/*:
**Bitwise Right Shift operator**
See [Apple's Docs on Advanced Operators](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html), go to the "Bitwise Left and Right Shift Operators" section)
*/
someBits = 0b00010001
var rightShiftedBits = someBits >> 3 // equals 0b000000010
/*:
Note: You can combine the following bitwise operators with assignment:
- <<= Left bit shift and assign
- >>= Right bit shift and assign
- &= Bitwise AND and assign
- ^= Bitwise XOR and assign
- |= Bitwise OR and assign
*/
let bottomBitMask: UInt8 = 0b00001111
someBits = 0b01011100
someMoreBits = 0b1101000
// here is an example of Bitwise AND and assignment
someBits &= bottomBitMask // equals 0b00001100
someMoreBits &= bottomBitMask // equals 0b00001000
//: Here is a more practical example with bitwise operators that seperates the RGB components of a color. Check out [this fun video](https://www.youtube.com/watch?v=5KZJbMomxa4) to see how RGB color theory works!
import UIKit
func colorFromHex(hexValue: UInt32) -> UIColor {
// 1. filters each component (rgb) with bitwise AND
// 2. shifts each component (rgb) to a 0-255 value with bitwise right shift
// 3. divides each component (rgb) by 255.0 to create a value between 0.0 - 1.0
return UIColor(
red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hexValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
let pink: UInt32 = 0xCC6699
let redComponent = (pink & 0xFF0000) // equals 0xCC0000
let greenComponent = (pink & 0x00FF00) // equals 0x006600
let blueComponent = (pink & 0x0000FF) // equals 0x000099
colorFromHex(hexValue: pink)
colorFromHex(hexValue: redComponent)
colorFromHex(hexValue: greenComponent)
colorFromHex(hexValue: blueComponent)
//: [Next](@next)
| 319f44e404ca952b83f84d5960091362 | 33.670588 | 234 | 0.734645 | false | false | false | false |
nethergrim/xpolo | refs/heads/master | XPolo/Pods/BFKit-Swift/Sources/BFKit/Linux/BFKit/BFApp.swift | gpl-3.0 | 1 | //
// BFApp.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2017 Fabrizio Brancati. 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
#if os(iOS)
import UIKit
#endif
// MARK: - Global variables
#if os(iOS)
/// Get AppDelegate. To use it, cast to AppDelegate with "as! AppDelegate".
public let appDelegate: UIApplicationDelegate? = UIApplication.shared.delegate
#endif
#if !os(Linux)
// MARK: - Global functions
/// NSLocalizedString without comment parameter.
///
/// - Parameter key: The key of the localized string.
/// - Returns: Returns a localized string.
public func NSLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
#endif
// MARK: - BFApp struct
/// This class adds some useful functions for the App.
public struct BFApp {
// MARK: - Variables
/// Used to store the BFHasBeenOpened in defaults.
private static let BFAppHasBeenOpened = "BFAppHasBeenOpened"
// MARK: - Functions
/// Executes a block only if in DEBUG mode.
///
/// More info on how to use it [here](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project/26891797#26891797).
///
/// - Parameter block: The block to be executed.
public static func debug(_ block: () -> Void) {
#if DEBUG
block()
#endif
}
/// Executes a block only if NOT in DEBUG mode.
///
/// More info on how to use it [here](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project/26891797#26891797).
///
/// - Parameter block: The block to be executed.
public static func release(_ block: () -> Void) {
#if !DEBUG
block()
#endif
}
/// If version is set returns if is first start for that version,
/// otherwise returns if is first start of the App.
///
/// - Parameter version: Version to be checked, you can use the variable BFApp.version to pass the current App version.
/// - Returns: Returns if is first start of the App or for custom version.
public static func isFirstStart(version: String = "") -> Bool {
let key: String = BFAppHasBeenOpened + "\(version)"
let defaults = UserDefaults.standard
let hasBeenOpened: Bool = defaults.bool(forKey: key)
return !hasBeenOpened
}
/// Executes a block on first start of the App, if version is set it will be for given version.
///
/// Remember to execute UI instuctions on main thread.
///
/// - Parameters:
/// - version: Version to be checked, you can use the variable BFApp.version to pass the current App version.
/// - block: The block to execute, returns isFirstStart.
public static func onFirstStart(version: String = "", block: (_ isFirstStart: Bool) -> Void) {
let key: String
if version == "" {
key = BFAppHasBeenOpened
} else {
key = BFAppHasBeenOpened + "\(version)"
}
let defaults = UserDefaults.standard
let hasBeenOpened: Bool = defaults.bool(forKey: key)
if hasBeenOpened != true {
defaults.set(true, forKey: key)
}
block(!hasBeenOpened)
}
#if !os(Linux) && !os(macOS)
/// Set the App setting for a given object and key. The file will be saved in the Library directory.
///
/// - Parameters:
/// - object: Object to set.
/// - objectKey: Key to set the object.
/// - Returns: Returns true if the operation was successful, otherwise false.
@discardableResult
public static func setAppSetting(object: Any, forKey objectKey: String) -> Bool {
return FileManager.default.setSettings(filename: BFApp.name, object: object, forKey: objectKey)
}
/// Get the App setting for a given key.
///
/// - Parameter objectKey: Key to get the object.
/// - Returns: Returns the object for the given key.
public static func getAppSetting(objectKey: String) -> Any? {
return FileManager.default.getSettings(filename: BFApp.name, forKey: objectKey)
}
#endif
}
// MARK: - BFApp extension
/// Extends BFApp with project infos.
public extension BFApp {
// MARK: - Variables
/// Return the App name.
public static var name: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleDisplayName")
}()
/// Returns the App version.
public static var version: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleShortVersionString")
}()
/// Returns the App build.
public static var build: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleVersion")
}()
/// Returns the App executable.
public static var executable: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleExecutable")
}()
/// Returns the App bundle.
public static var bundle: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleIdentifier")
}()
// MARK: - Functions
/// Returns a String from the Info dictionary of the App.
///
/// - Parameter key: Key to search.
/// - Returns: Returns a String from the Info dictionary of the App.
private static func stringFromInfoDictionary(forKey key: String) -> String {
guard let infoDictionary = Bundle.main.infoDictionary, let value = infoDictionary[key] as? String else {
return ""
}
return value
}
}
| 3e3d48c49aaf8bef6c8ec5cb7aa81e12 | 35.175532 | 153 | 0.644611 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/UIComponents/UIComponentsKit/Theme/Color+Theme.swift | lgpl-3.0 | 1 | import SwiftUI
extension Color {
// MARK: Borders
public static let borderPrimary = Color(paletteColor: .grey100)
public static let borderFocused = Color(paletteColor: .blue600)
public static let borderSuccess = Color(paletteColor: .green800)
public static let borderError = Color(paletteColor: .red600)
// MARK: Backgrounds
public static let lightContentBackground = Color(paletteColor: .grey900)
public static let viewPrimaryBackground = Color(paletteColor: .white)
public static let shimmeringLight = Color(paletteColor: .grey000)
public static let shimmeringDark = Color(paletteColor: .grey200)
// MARK: PrimaryButton
public static let buttonPrimaryBackground = Color(paletteColor: .blue600)
public static let buttonPrimaryText = Color(paletteColor: .white)
// MARK: SecondaryButton
public static let buttonSecondaryBackground = Color(paletteColor: .white)
public static let buttonSecondaryText = Color(paletteColor: .blue600)
// MARK: MinimalDoubleButton
public static let buttonMinimalDoubleBackground = Color(paletteColor: .white)
public static let buttonMinimalDoublePressedBackground = Color(paletteColor: .grey000)
public static let buttonMinimalDoubleText = Color(paletteColor: .blue600)
// MARK: Links
public static let buttonLinkText = Color(paletteColor: .blue600)
// MARK: Divider
public static let dividerLine = Color(paletteColor: .grey100)
public static let dividerLineLight = Color(paletteColor: .grey000)
// MARK: Text
public static let textTitle = Color(paletteColor: .grey900)
public static let textDetail = Color(paletteColor: .grey600)
public static let textHeading = Color(paletteColor: .grey900)
public static let textSubheading = Color(paletteColor: .grey600)
public static let textBody = Color(paletteColor: .grey800)
public static let textMuted = Color(paletteColor: .grey400)
public static let textError = Color(paletteColor: .red600)
public static let formField = Color(paletteColor: .greyFade800)
// MARK: TextField
public static let textFieldPrefilledAndDisabledBackground = Color(paletteColor: .grey100)
public static let textCallOutBackground = Color(paletteColor: .grey000)
public static let secureFieldEyeSymbol = Color(paletteColor: .grey400)
// MARK: Password Strength
public static let weakPassword = Color(paletteColor: .red600)
public static let mediumPassword = Color(paletteColor: .orange600)
public static let strongPassword = Color(paletteColor: .green600)
// MARK: Badge
public static let badgeTextInfo = Color(paletteColor: .blue400)
public static let badgeTextError = Color(paletteColor: .red400)
public static let badgeTextWarning = Color(paletteColor: .orange400)
public static let badgeTextSuccess = Color(paletteColor: .green400)
public static let badgeBackgroundInfo = Color(paletteColor: .blue000)
public static let badgeBackgroundError = Color(paletteColor: .red000)
public static let badgeBackgroundWarning = Color(paletteColor: .orange000)
public static let badgeBackgroundSuccess = Color(paletteColor: .green000)
// MARK: Other Elements
public static let backgroundFiat = Color(paletteColor: .green500)
public static let positiveTrend = Color(paletteColor: .green600)
public static let negativeTrend = Color(paletteColor: .red600)
public static let neutralTrend = Color(paletteColor: .grey600)
public static let disclosureIndicator = Color(paletteColor: .grey600)
}
| bd413a7bb21f05e963f5604c107a58ca | 40.616279 | 93 | 0.755239 | false | false | false | false |
cloudinary/cloudinary_ios | refs/heads/master | Cloudinary/Classes/Core/BaseNetwork/CLDNTaskDelegate.swift | mit | 1 | //
// CLDNTaskDelegate.swift
//
// 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
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
internal class CLDNTaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
internal let queue: OperationQueue
/// The data returned by the server.
internal var data: Data? { return nil }
/// The error generated throughout the lifecyle of the task.
internal var error: Error?
var task: URLSessionTask? {
set {
taskLock.lock(); defer { taskLock.unlock() }
_task = newValue
}
get {
taskLock.lock(); defer { taskLock.unlock() }
return _task
}
}
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
var metrics: AnyObject? // URLSessionTaskMetrics
private var _task: URLSessionTask? {
didSet { reset() }
}
private let taskLock = NSLock()
// MARK: Lifecycle
init(task: URLSessionTask?) {
_task = task
self.queue = {
let operationQueue = OperationQueue()
operationQueue.name = "com.cloudinary.CLDNTaskDelegateOperationQueue"
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
func reset() {
error = nil
initialResponseTime = nil
}
// MARK: URLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
@objc(URLSession:task:didCompleteWithError:)
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
if self.error == nil { self.error = error }
}
queue.isSuspended = false
}
}
}
// MARK: -
class CLDNDataTaskDelegate: CLDNTaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask { return task as! URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
var progress: Progress
var progressHandler: (closure: CLDNRequest.ProgressHandler, queue: DispatchQueue)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
mutableData = Data()
progress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
progress = Progress(totalUnitCount: 0)
totalBytesReceived = 0
mutableData = Data()
expectedContentLength = nil
}
// MARK: URLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
if let progressHandler = progressHandler {
progressHandler.queue.async { progressHandler.closure(self.progress) }
}
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class CLDNUploadTaskDelegate: CLDNDataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask }
var uploadProgress: Progress
var uploadProgressHandler: (closure: CLDNRequest.ProgressHandler, queue: DispatchQueue)?
// MARK: Lifecycle
override init(task: URLSessionTask?) {
uploadProgress = Progress(totalUnitCount: 0)
super.init(task: task)
}
override func reset() {
super.reset()
uploadProgress = Progress(totalUnitCount: 0)
}
// MARK: URLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
if let uploadProgressHandler = uploadProgressHandler {
uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) }
}
}
}
}
| a750775b102350bd444c832117adab9c | 32.789634 | 149 | 0.674637 | false | false | false | false |
atuooo/notGIF | refs/heads/master | notGIF/Extensions/Realm+NG.swift | mit | 1 | //
// Realm+NG.swift
// notGIF
//
// Created by Atuooo on 18/06/2017.
// Copyright © 2017 xyz. All rights reserved.
//
import Foundation
import RealmSwift
public extension List {
func add(object: Element, update: Bool) {
if update {
if !contains(object) {
append(object)
}
} else {
append(object)
}
}
func add<S: Sequence>(objectsIn objects: S, update: Bool) where S.Iterator.Element == T {
if update {
objects.forEach{ add(object: $0, update: true) }
} else {
append(objectsIn: objects)
}
}
func remove(_ object: Element) {
if let index = index(of: object) {
remove(objectAtIndex: index)
}
}
func remove<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == T {
objects.forEach {
remove($0)
}
}
}
| ba6f444fed55e34fc41555e3c5ad5173 | 21.380952 | 93 | 0.52234 | false | false | false | false |
KBvsMJ/IQKeyboardManager | refs/heads/master | IQKeyboardManagerSwift/IQToolbar/IQTitleBarButtonItem.swift | mit | 18 | //
// IQTitleBarButtonItem.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class IQTitleBarButtonItem: UIBarButtonItem {
public var font : UIFont? {
didSet {
if let unwrappedFont = font {
_titleLabel?.font = unwrappedFont
} else {
_titleLabel?.font = UIFont.boldSystemFontOfSize(12)
}
}
}
private var _titleLabel : UILabel?
private var _titleView : UIView?
override init() {
super.init()
}
init(frame : CGRect, title : String?) {
super.init(title: nil, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
_titleView = UIView(frame: frame)
_titleView?.backgroundColor = UIColor.clearColor()
_titleView?.autoresizingMask = .FlexibleWidth
_titleLabel = UILabel(frame: _titleView!.bounds)
_titleLabel?.textColor = UIColor.lightGrayColor()
_titleLabel?.backgroundColor = UIColor.clearColor()
_titleLabel?.textAlignment = .Center
_titleLabel?.text = title
_titleLabel?.autoresizingMask = .FlexibleWidth
font = UIFont.boldSystemFontOfSize(12.0)
_titleLabel?.font = self.font
customView = _titleLabel
enabled = false
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 542ed7bcdd8359ef4578e7c39c3b8c35 | 35.357143 | 91 | 0.677014 | false | false | false | false |
SomeHero/iShopAwayAPIManager | refs/heads/master | IShopAwayApiManager/Classes/models/PaymentMethod.swift | mit | 1 | //
// PaymentMethod.swift
// Pods
//
// Created by James Rhodes on 6/21/16.
//
//
import Foundation
import ObjectMapper
public class PaymentMethod: Mappable {
public var id: String!
public var type: String!
public var cardType: String!
public var cardLastFour: String!
public var expirationMonth: Int!
public var expirationYear: Int!
public var isDefault: Bool = false
public init(type: String, cardType: String, cardLastFour: String, expirationMonth: Int, expirationYear: Int, isDefault: Bool) {
self.type = type
self.cardType = cardType
self.cardLastFour = cardLastFour
self.expirationMonth = expirationMonth
self.expirationYear = expirationYear
}
public required init?(_ map: Map){
mapping(map)
}
public func mapping(map: Map) {
id <- map["_id"]
type <- map["type"]
cardType <- map["card_info.card_type"]
cardLastFour <- map["card_info.card_last_four"]
expirationMonth <- map["card_info.expiration_month"]
expirationYear <- map["card_info.expiration_year"]
isDefault <- map["is_default"]
}
}
| 3076e0705968379d9799489266be1f04 | 27.439024 | 131 | 0.638937 | false | false | false | false |
ContinuousLearning/PokemonKit | refs/heads/master | Carthage/Checkouts/PromiseKit/Sources/ErrorUnhandler.swift | mit | 1 | import Dispatch
import Foundation.NSError
/**
The unhandled error handler.
If a promise is rejected and no catch handler is called in its chain, the
provided handler is called. The default handler logs the error.
PMKUnhandledErrorHandler = { error in
println("Unhandled error: \(error)")
}
@warning *Important* The handler is executed on an undefined queue.
@warning *Important* Don’t use promises in your handler, or you risk an
infinite error loop.
@return The previous unhandled error handler.
*/
public var PMKUnhandledErrorHandler = { (error: NSError) -> Void in
dispatch_async(dispatch_get_main_queue()) {
if !error.cancelled {
NSLog("PromiseKit: Unhandled error: %@", error)
}
}
}
private class Consumable: NSObject {
let parentError: NSError
var consumed: Bool = false
deinit {
if !consumed {
PMKUnhandledErrorHandler(parentError)
}
}
init(parent: NSError) {
// we take a copy to avoid a retain cycle. A weak ref
// is no good because then the error is deallocated
// before we can call PMKUnhandledErrorHandler()
parentError = parent.copy() as! NSError
}
}
private var handle: UInt8 = 0
func consume(error: NSError) {
// The association could be nil if the objc_setAssociatedObject
// has taken a *really* long time. Or perhaps the user has
// overused `zalgo`. Thus we ignore it. This is an unlikely edge
// case and the unhandled-error feature is not mission-critical.
if let pmke = objc_getAssociatedObject(error, &handle) as? Consumable {
pmke.consumed = true
}
}
extension AnyPromise {
// objc can't see Swift top-level function :(
//TODO move this and the one in AnyPromise to a compat something
@objc class func __consume(error: NSError) {
consume(error)
}
}
func unconsume(error: NSError) {
if let pmke = objc_getAssociatedObject(error, &handle) as! Consumable? {
pmke.consumed = false
} else {
// this is how we know when the error is deallocated
// because we will be deallocated at the same time
objc_setAssociatedObject(error, &handle, Consumable(parent: error), .OBJC_ASSOCIATION_RETAIN)
}
}
private struct ErrorPair: Hashable {
let domain: String
let code: Int
init(_ d: String, _ c: Int) {
domain = d; code = c
}
var hashValue: Int {
return "\(domain):\(code)".hashValue
}
}
private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool {
return lhs.domain == rhs.domain && lhs.code == rhs.code
}
private var cancelledErrorIdentifiers = Set([
ErrorPair(PMKErrorDomain, PMKOperationCancelled),
ErrorPair(NSURLErrorDomain, NSURLErrorCancelled)
])
extension NSError {
public class func cancelledError() -> NSError {
let info: [NSObject: AnyObject] = [NSLocalizedDescriptionKey: "The operation was cancelled"]
return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info)
}
/**
You may only call this on the main thread.
*/
public class func registerCancelledErrorDomain(domain: String, code: Int) {
cancelledErrorIdentifiers.insert(ErrorPair(domain, code))
}
/**
You may only call this on the main thread.
*/
public var cancelled: Bool {
return cancelledErrorIdentifiers.contains(ErrorPair(domain, code))
}
}
| ca04fa150579a3e9e04754ed7c1a69d2 | 28 | 101 | 0.666473 | false | false | false | false |
tqtifnypmb/Framenderer | refs/heads/master | Framenderer/Sources/Filters/Blur/GaussianBlur/GaussianBlurFilter.swift | mit | 2 | //
// GaussianBlurFilter.swift
// Framenderer
//
// Created by tqtifnypmb on 12/12/2016.
// Copyright © 2016 tqitfnypmb. All rights reserved.
//
import Foundation
import OpenGLES.ES3.gl
import OpenGLES.ES3.glext
import CoreMedia
import AVFoundation
public class GaussianBlurFilter: TwoPassFilter {
private let _radius: Int
private let _sigma: Double
/// sigma value used by Gaussian algorithm
public var gaussianSigma: Double = 0
/**
init a [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) filter
- parameter radius: specifies the distance from the center of the blur effect.
- parameter implement: specifies which implement to use.
- box: mimic Gaussian blur by applying box blur mutiple times
- normal: use Gaussian algorithm
*/
public init(radius: Int = 3, sigma: Double = 0) {
if sigma == 0 {
_radius = radius
// source from OpenCV (http://docs.opencv.org/3.2.0/d4/d86/group__imgproc__filter.html)
_sigma = 0.3 * Double(_radius - 1) + 0.8
} else {
// kernel size <= 6sigma is good enough
// reference: https://en.wikipedia.org/wiki/Gaussian_blur
_radius = min(radius, Int(floor(6 * sigma)))
_sigma = sigma
}
}
override public var name: String {
return "GaussianBlurFilter"
}
override public func setUniformAttributs(context ctx: Context) {
super.setUniformAttributs(context: ctx)
let texelWidth = 1 / GLfloat(ctx.inputWidth)
_program.setUniform(name: kXOffset, value: texelWidth)
_program.setUniform(name: kYOffset, value: GLfloat(0))
_program.setUniform(name: "radius", value: _radius)
_program.setUniform(name: "sigma", value: Float(_sigma))
}
override public func setUniformAttributs2(context ctx: Context) {
super.setUniformAttributs2(context: ctx)
let texelHeight = 1 / GLfloat(ctx.inputHeight)
_program2.setUniform(name: kXOffset, value: GLfloat(0))
_program2.setUniform(name: kYOffset, value: texelHeight)
_program2.setUniform(name: "radius", value: _radius)
_program2.setUniform(name: "sigma", value: Float(_sigma))
}
override func buildProgram() throws {
_program = try Program.create(fragmentSourcePath: "GaussianBlurFragmentShader")
_program2 = try Program.create(fragmentSourcePath: "GaussianBlurFragmentShader")
}
}
| b232a1d8b28e42e4244367705856d073 | 34.583333 | 99 | 0.636222 | false | false | false | false |
nerd0geek1/TableViewManager | refs/heads/master | TableViewManager/classes/implementation/TableViewDelegate.swift | mit | 1 | //
// TableViewDelegate.swift
// TableViewManager
//
// Created by Kohei Tabata on 6/23/16.
// Copyright © 2016 Kohei Tabata. All rights reserved.
//
import Foundation
import UIKit
public class TableViewDelegate: NSObject, TableViewDelegateType {
public var didSelectRow: ((IndexPath) -> Void)?
public var didDeselectRow: ((IndexPath) -> Void)?
public weak var dataSource: TableViewDataSource?
// MARK: - UITableViewDelegate
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelectRow?(indexPath)
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
didDeselectRow?(indexPath)
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cellClass: UITableViewCell.Type? = dataSource?.cellClassResolver.cellClass(for: indexPath)
if let cellClass = cellClass, let customizedHeightCellClass = cellClass as? CustomizedCellHeightType.Type {
return customizedHeightCellClass.customizedHeight
}
return 44
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sectionData(for: section)?.headerData?.headerHeight ?? 0
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let sectionData = self.sectionData(for: section) else {
return nil
}
let sectionHeaderView = sectionData.headerView
if let sectionHeaderView = sectionHeaderView as? SectionHeaderDataAcceptableType, let sectionHeaderData = sectionData.headerData {
sectionHeaderView.update(sectionHeaderData)
}
return sectionHeaderView
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return sectionData(for: section)?.footerData?.footerHeight ?? 0
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let sectionData = self.sectionData(for: section) else {
return nil
}
let sectionFooterView = sectionData.footerView
if let sectionFooterView = sectionFooterView as? SectionFooterDataAcceptableType, let sectionFooterData = sectionData.footerData {
sectionFooterView.update(sectionFooterData)
}
return sectionFooterView
}
// MARK: - private
private func sectionData(for section: Int) -> SectionData? {
guard let dataSource = dataSource else {
return nil
}
if section > dataSource.sectionDataList.count - 1 {
return nil
}
return dataSource.sectionDataList[section]
}
}
| d5feaf65c47733e24939343498622417 | 32.423529 | 138 | 0.690602 | false | false | false | false |
jonesgithub/KeyboardMan | refs/heads/master | KeyboardMan/KeyboardMan.swift | mit | 1 | //
// KeyboardMan.swift
// Messages
//
// Created by NIX on 15/7/25.
// Copyright (c) 2015年 nixWork. All rights reserved.
//
import UIKit
public class KeyboardMan: NSObject {
var keyboardObserver: NSNotificationCenter? {
didSet {
oldValue?.removeObserver(self)
keyboardObserver?.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
keyboardObserver?.addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
keyboardObserver?.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
keyboardObserver?.addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil)
}
}
public var keyboardObserveEnabled = false {
willSet {
if newValue != keyboardObserveEnabled {
keyboardObserver = newValue ? NSNotificationCenter.defaultCenter() : nil
}
}
}
deinit {
keyboardObserveEnabled = false
}
public struct KeyboardInfo {
public let animationDuration: NSTimeInterval
public let animationCurve: UInt
public let frameBegin: CGRect
public let frameEnd: CGRect
public var height: CGFloat {
return frameEnd.height
}
public let heightIncrement: CGFloat
public enum Action {
case Show
case Hide
}
public let action: Action
let isSameAction: Bool
}
public var appearPostIndex = 0
var keyboardInfo: KeyboardInfo? {
willSet {
if let info = newValue {
if !info.isSameAction || info.heightIncrement > 0 {
// do convenient animation
let duration = info.animationDuration
let curve = info.animationCurve
let options = UIViewAnimationOptions(curve << 16 | UIViewAnimationOptions.BeginFromCurrentState.rawValue)
UIView.animateWithDuration(duration, delay: 0, options: options, animations: {
switch info.action {
case .Show:
self.animateWhenKeyboardAppear?(appearPostIndex: self.appearPostIndex, keyboardHeight: info.height, keyboardHeightIncrement: info.heightIncrement)
self.appearPostIndex++
case .Hide:
self.animateWhenKeyboardDisappear?(keyboardHeight: info.height)
self.appearPostIndex = 0
}
}, completion: nil)
// post full info
postKeyboardInfo?(keyboardMan: self, keyboardInfo: info)
}
}
}
}
public var animateWhenKeyboardAppear: ((appearPostIndex: Int, keyboardHeight: CGFloat, keyboardHeightIncrement: CGFloat) -> Void)? {
didSet {
keyboardObserveEnabled = true
}
}
public var animateWhenKeyboardDisappear: ((keyboardHeight: CGFloat) -> Void)? {
didSet {
keyboardObserveEnabled = true
}
}
public var postKeyboardInfo: ((keyboardMan: KeyboardMan, keyboardInfo: KeyboardInfo) -> Void)? {
didSet {
keyboardObserveEnabled = true
}
}
// MARK: - Actions
private func handleKeyboard(notification: NSNotification, _ action: KeyboardInfo.Action) {
if let userInfo = notification.userInfo {
let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animationCurve = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).unsignedLongValue
let frameBegin = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
let frameEnd = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let currentHeight = frameEnd.height
let previousHeight = keyboardInfo?.height ?? 0
let heightIncrement = currentHeight - previousHeight
let isSameAction: Bool
if let previousAction = keyboardInfo?.action {
isSameAction = action == previousAction
} else {
isSameAction = false
}
keyboardInfo = KeyboardInfo(
animationDuration: animationDuration,
animationCurve: animationCurve,
frameBegin: frameBegin,
frameEnd: frameEnd,
heightIncrement: heightIncrement,
action: action,
isSameAction: isSameAction
)
}
}
func keyboardWillShow(notification: NSNotification) {
handleKeyboard(notification, .Show)
}
func keyboardWillChangeFrame(notification: NSNotification) {
if let keyboardInfo = keyboardInfo {
if keyboardInfo.action == .Show {
handleKeyboard(notification, .Show)
}
} else {
handleKeyboard(notification, .Show)
}
}
func keyboardWillHide(notification: NSNotification) {
handleKeyboard(notification, .Hide)
}
func keyboardDidHide(notification: NSNotification) {
keyboardInfo = nil
}
}
| e05e1be6fa2f3bdc69b6e666513a1592 | 30.511494 | 174 | 0.602043 | false | false | false | false |
0dayZh/LTMorphingLabel | refs/heads/master | LTMorphingLabel/NSString+LTMorphingLabel.swift | apache-2.0 | 2 | //
// NSString+LTMorphingLabel.swift
// LTMorphingLabel
// https://github.com/lexrus/LTMorphingLabel
//
// Created by Lex on 6/24/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
// The MIT License (MIT)
// Copyright © 2014 Lex Tang, http://LexTang.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
enum LTCharacterDiffType: Int, DebugPrintable {
case Same = 0
case Add = 1
case Delete
case Move
case MoveAndAdd
case Replace
var debugDescription: String {
get {
switch self {
case .Same:
return "Same"
case .Add:
return "Add"
case .Delete:
return "Delete"
case .Move:
return "Move"
case .MoveAndAdd:
return "MoveAndAdd"
default:
return "Replace"
}
}
}
}
struct LTCharacterDiffResult: DebugPrintable {
var diffType: LTCharacterDiffType
var moveOffset: Int
var skip: Bool
var debugDescription: String {
get {
switch diffType {
case .Same:
return "The character is unchanged."
case .Add:
return "A new character is ADDED."
case .Delete:
return "The character is DELETED."
case .Move:
return "The character is MOVED to \(moveOffset)."
case .MoveAndAdd:
return "The character is MOVED to \(moveOffset) and a new character is ADDED."
default:
return "The character is REPLACED with a new character."
}
}
}
}
@infix func >>(lhs: String, rhs: String) -> Array<LTCharacterDiffResult> {
var diffResults = Array<LTCharacterDiffResult>()
let newChars = enumerate(rhs)
let lhsLength = countElements(lhs)
let rhsLength = countElements(rhs)
var skipIndexes = Array<Int>()
for i in 0..(max(lhsLength, rhsLength) + 1) {
var result = LTCharacterDiffResult(diffType: .Add, moveOffset: 0, skip: false)
// If new string is longer than the original one
if i > lhsLength - 1 {
result.diffType = .Add
diffResults.append(result)
continue
}
// There must be another way to get a Character in String by index
let leftChar = { (s:String) -> Character in
for (j, char) in enumerate(s) {
if i == j {
return char
}
}
return Character("")
}(lhs)
// Search left character in the new string
var foundCharacterInRhs = false
for (j, newChar) in newChars {
let currentCharWouldBeReplaced = {
(index: Int) -> Bool in
for k in skipIndexes {
if index == k {
return true
}
}
return false
}(j)
if currentCharWouldBeReplaced {
continue
}
if leftChar == newChar {
skipIndexes.append(j)
foundCharacterInRhs = true
if i == j {
// Character not changed
result.diffType = .Same
} else {
// foundCharacterInRhs and move
result.diffType = .Move
if i <= rhsLength - 1 {
// Move to a new index and add a new character to new original place
result.diffType = .MoveAndAdd
}
result.moveOffset = j - i
}
break
}
}
if !foundCharacterInRhs {
if i < countElements(rhs) - 1 {
result.diffType = .Replace
} else {
result.diffType = .Delete
}
}
if i > lhsLength - 1 {
result.diffType = .Add
}
diffResults.append(result)
}
var i = 0
for result in diffResults {
switch result.diffType {
case .Move, .MoveAndAdd:
diffResults[i + result.moveOffset].skip = true
default:
NSNotFound
}
i++
}
return diffResults
}
| fcaee16651a2f48c09ae945fbad04500 | 28.765027 | 92 | 0.544336 | false | false | false | false |
Burning-Man-Earth/iBurn-iOS | refs/heads/master | iBurn/BRCDataObject.swift | mpl-2.0 | 1 | //
// BRCDataObject.swift
// iBurn
//
// Created by Chris Ballinger on 8/7/17.
// Copyright © 2017 Burning Man Earth. All rights reserved.
//
import Foundation
extension BRCDataObjectTableViewCell {
/** Mapping between cell identifiers and cell classes */
public static let cellIdentifiers = [BRCDataObjectTableViewCell.cellIdentifier: BRCDataObjectTableViewCell.self,
BRCArtObjectTableViewCell.cellIdentifier: BRCArtObjectTableViewCell.self,
BRCEventObjectTableViewCell.cellIdentifier: BRCEventObjectTableViewCell.self,
ArtImageCell.cellIdentifier: ArtImageCell.self]
}
extension BRCDataObject {
/** Returns the cellIdentifier for table cell subclass */
@objc public var tableCellIdentifier: String {
var cellIdentifier = BRCDataObjectTableViewCell.cellIdentifier
if let art = self as? BRCArtObject {
if art.localThumbnailURL != nil {
cellIdentifier = ArtImageCell.cellIdentifier
} else {
cellIdentifier = BRCArtObjectTableViewCell.cellIdentifier
}
} else if let _ = self as? BRCEventObject {
cellIdentifier = BRCEventObjectTableViewCell.cellIdentifier
} else if let _ = self as? BRCCampObject {
cellIdentifier = BRCDataObjectTableViewCell.cellIdentifier
}
return cellIdentifier
}
/** Short address e.g. 7:45 & G */
@objc public var shortBurnerMapAddress: String? {
guard let string = self.burnerMapLocationString else { return nil }
let components = string.components(separatedBy: " & ")
guard let radial = components.first, let street = components.last, street.count > 1 else {
return self.burnerMapLocationString
}
let index = street.index(street.startIndex, offsetBy: 1)
let trimmedStreet = street[..<index]
let shortAddress = "\(radial) & \(trimmedStreet)"
return shortAddress
}
}
| 29e5193ca397c788b55668b4a4955854 | 38.711538 | 116 | 0.650847 | false | false | false | false |
richardpiazza/SOSwift | refs/heads/master | Sources/SOSwift/QuantitativeValue.swift | mit | 1 | import Foundation
/// A point value or interval for product characteristics and other purposes.
public class QuantitativeValue: StructuredValue {
/// A property-value pair representing an additional characteristics of the entity.
///
/// A product feature or another characteristic for which there is no matching property in schema.org.
///
/// - note: Publishers should be aware that applications designed to use specific schema.org properties (
/// [http://schema.org/width](http://schema.org/width),
/// [http://schema.org/color](http://schema.org/color),
/// [http://schema.org/gtin13](http://schema.org/gtin13)
/// ) will typically expect such data to be provided using those properties, rather than using the generic property/value mechanism.
public var additionalProperty: PropertyValue?
/// The upper value of some characteristic or property.
public var maxValue: Number?
/// The lower value of some characteristic or property.
public var minValue: Number?
/// The unit of measurement given using the UN/CEFACT Common Code (3 characters) or a URL.
///
/// Other codes than the UN/CEFACT Common Code may be used with a prefix followed by a colon.
public var unitCode: URLOrText?
/// A string or text indicating the unit of measurement. Useful if you cannot provide a standard unit code for unitCode.
public var unitText: String?
/// The value of the quantitative value or property value node.
///
/// - For QuantitativeValue and MonetaryAmount, the recommended type for values is 'Number'.
/// - For PropertyValue, it can be 'Text;', 'Number', 'Boolean', or 'StructuredValue'.
public var value: Value?
/// A pointer to a secondary value that provides additional information on the original value
///
/// ## For Example
/// A reference temperature.
public var valueReference: ValueReference?
internal enum QuantitativeValueCodingKeys: String, CodingKey {
case additionalProperty
case maxValue
case minValue
case unitCode
case unitText
case value
case valueReference
}
public override init() {
super.init()
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: QuantitativeValueCodingKeys.self)
additionalProperty = try container.decodeIfPresent(PropertyValue.self, forKey: .additionalProperty)
maxValue = try container.decodeIfPresent(Number.self, forKey: .maxValue)
minValue = try container.decodeIfPresent(Number.self, forKey: .minValue)
unitCode = try container.decodeIfPresent(URLOrText.self, forKey: .unitText)
unitText = try container.decodeIfPresent(String.self, forKey: .unitText)
value = try container.decodeIfPresent(Value.self, forKey: .value)
valueReference = try container.decodeIfPresent(ValueReference.self, forKey: .valueReference)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: QuantitativeValueCodingKeys.self)
try container.encodeIfPresent(additionalProperty, forKey: .additionalProperty)
try container.encodeIfPresent(maxValue, forKey: .maxValue)
try container.encodeIfPresent(minValue, forKey: .minValue)
try container.encodeIfPresent(unitCode, forKey: .unitCode)
try container.encodeIfPresent(unitText, forKey: .unitText)
try container.encodeIfPresent(value, forKey: .value)
try container.encodeIfPresent(valueReference, forKey: .valueReference)
try super.encode(to: encoder)
}
}
| 9a0db50eab83a75da6911a4aa1eb0b4e | 44.547619 | 144 | 0.689493 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/core/EmptyCollection.swift | apache-2.0 | 13 | //===--- EmptyCollection.swift - A collection with no elements ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Sometimes an operation is best expressed in terms of some other,
// larger operation where one of the parameters is an empty
// collection. For example, we can erase elements from an Array by
// replacing a subrange with the empty collection.
//
//===----------------------------------------------------------------------===//
/// A collection whose element type is `Element` but that is always empty.
@frozen // trivial-implementation
public struct EmptyCollection<Element> {
// no properties
/// Creates an instance.
@inlinable // trivial-implementation
public init() {}
}
extension EmptyCollection {
/// An iterator that never produces an element.
@frozen // trivial-implementation
public struct Iterator {
// no properties
/// Creates an instance.
@inlinable // trivial-implementation
public init() {}
}
}
extension EmptyCollection.Iterator: IteratorProtocol, Sequence {
/// Returns `nil`, indicating that there are no more elements.
@inlinable // trivial-implementation
public mutating func next() -> Element? {
return nil
}
}
extension EmptyCollection: Sequence {
/// Returns an empty iterator.
@inlinable // trivial-implementation
public func makeIterator() -> Iterator {
return Iterator()
}
}
extension EmptyCollection: RandomAccessCollection, MutableCollection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
public typealias Indices = Range<Int>
public typealias SubSequence = EmptyCollection<Element>
/// Always zero, just like `endIndex`.
@inlinable // trivial-implementation
public var startIndex: Index {
return 0
}
/// Always zero, just like `startIndex`.
@inlinable // trivial-implementation
public var endIndex: Index {
return 0
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // trivial-implementation
public func index(after i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // trivial-implementation
public func index(before i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Accesses the element at the given position.
///
/// Must never be called, since this collection is always empty.
@inlinable // trivial-implementation
public subscript(position: Index) -> Element {
get {
_preconditionFailure("Index out of range")
}
set {
_preconditionFailure("Index out of range")
}
}
@inlinable // trivial-implementation
public subscript(bounds: Range<Index>) -> SubSequence {
get {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
return self
}
set {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
}
}
/// The number of elements (always zero).
@inlinable // trivial-implementation
public var count: Int {
return 0
}
@inlinable // trivial-implementation
public func index(_ i: Index, offsetBy n: Int) -> Index {
_debugPrecondition(i == startIndex && n == 0, "Index out of range")
return i
}
@inlinable // trivial-implementation
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_debugPrecondition(i == startIndex && limit == startIndex,
"Index out of range")
return n == 0 ? i : nil
}
/// The distance between two indexes (always zero).
@inlinable // trivial-implementation
public func distance(from start: Index, to end: Index) -> Int {
_debugPrecondition(start == 0, "From must be startIndex (or endIndex)")
_debugPrecondition(end == 0, "To must be endIndex (or startIndex)")
return 0
}
@inlinable // trivial-implementation
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_debugPrecondition(index == 0, "out of bounds")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
@inlinable // trivial-implementation
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_debugPrecondition(range == indices, "invalid range for an empty collection")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
}
extension EmptyCollection: Equatable {
@inlinable // trivial-implementation
public static func == (
lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>
) -> Bool {
return true
}
}
extension EmptyCollection: Sendable { }
extension EmptyCollection.Iterator: Sendable { }
| f00dc5b1f82bdbf660ba5222e5ac9046 | 30.118644 | 83 | 0.669027 | false | false | false | false |
SlackKit/SKServer | refs/heads/main | SKServer/Sources/Middleware/MessageActionMiddleware.swift | mit | 3 | //
// MessageActionMiddleware.swift
//
// Copyright © 2017 Peter Zignego. 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.
public struct MessageActionMiddleware: Middleware {
let token: String
let routes: [MessageActionRoute]
public init(token: String, routes: [MessageActionRoute]) {
self.token = token
self.routes = routes
}
public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) {
if let form = request.0.formURLEncodedBody.first(where: {$0.name == "ssl_check"}), form.value == "1" {
return (request.0, Response(200))
}
guard
let actionRequest = MessageActionRequest(request: request.0),
let middleware = routes.first(where: {$0.action.name == actionRequest.action?.name})?.middleware,
actionRequest.token == token
else {
return (request.0, Response(400))
}
return middleware.respond(to: request)
}
}
| 924f83df516dc63de1d1914979a41688 | 43.326087 | 110 | 0.703776 | false | false | false | false |
AloneMonkey/RxSwiftStudy | refs/heads/develop | Code/RxSwiftTutorial/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift | apache-2.0 | 15 | //
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
_lock.lock()
let value = _observers.count > 0
_lock.unlock()
return value
}
fileprivate let _lock = RecursiveLock()
// state
fileprivate var _isDisposed = false
fileprivate var _isStopped = false
fileprivate var _stoppedEvent = nil as Event<Element>? {
didSet {
_isStopped = _stoppedEvent != nil
}
}
fileprivate var _observers = Bag<(Event<Element>) -> ()>()
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
func unsubscribe(_ key: DisposeKey) {
abstractMethod()
}
final var isStopped: Bool {
return _isStopped
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<E>) {
abstractMethod()
}
/// Returns observer interface for subject.
public func asObserver() -> SubjectObserverType {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
}
/// Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
///
/// - parameter bufferSize: Maximal number of elements to replay to observer after subscription.
/// - returns: New instance of replay subject.
public static func create(bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
/// Creates a new instance of `ReplaySubject` that buffers all the elements of a sequence.
/// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable'
/// number of elements.
public static func createUnbounded() -> ReplaySubject<Element> {
return ReplayAll()
}
}
fileprivate class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
func trim() {
abstractMethod()
}
func addValueToBuffer(_ value: Element) {
abstractMethod()
}
func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
abstractMethod()
}
override func on(_ event: Event<Element>) {
dispatch(_synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<E>) -> Bag<(Event<Element>) -> ()> {
_lock.lock(); defer { _lock.unlock() }
if _isDisposed {
return Bag()
}
if _isStopped {
return Bag()
}
switch event {
case .next(let value):
addValueToBuffer(value)
trim()
return _observers
case .error, .completed:
_stoppedEvent = event
trim()
let observers = _observers
_observers.removeAll()
return observers
}
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock()
let subscription = _synchronized_subscribe(observer)
_lock.unlock()
return subscription
}
func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
if _isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let anyObserver = observer.asObserver()
replayBuffer(anyObserver)
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
else {
let key = _observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock()
_synchronized_unsubscribe(disposeKey)
_lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if _isDisposed {
return
}
_ = _observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
synchronizedDispose()
}
func synchronizedDispose() {
_lock.lock()
_synchronized_dispose()
_lock.unlock()
}
func _synchronized_dispose() {
_isDisposed = true
_observers.removeAll()
}
}
final class ReplayOne<Element> : ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(_ value: Element) {
_value = value
}
override func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
if let value = _value {
observer.on(.next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_value = nil
}
}
class ReplayManyBase<Element> : ReplayBufferBase<Element> {
fileprivate var _queue: Queue<Element>
init(queueSize: Int) {
_queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(_ value: Element) {
_queue.enqueue(value)
}
override func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
for item in _queue {
observer.on(.next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_queue = Queue(capacity: 0)
}
}
final class ReplayMany<Element> : ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
_bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while _queue.count > _bufferSize {
_ = _queue.dequeue()
}
}
}
final class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
| 63bfd083d20f41e6264d0cdf30cf4446 | 25.030534 | 118 | 0.585777 | false | false | false | false |
hooman/swift | refs/heads/main | benchmark/utils/main.swift | apache-2.0 | 2 | //===--- main.swift -------------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
// This is just a driver for performance overview tests.
import TestsUtils
import DriverUtils
import Ackermann
import AngryPhonebook
import AnyHashableWithAClass
import Array2D
import ArrayAppend
import ArrayInClass
import ArrayLiteral
import ArrayOfGenericPOD
import ArrayOfGenericRef
import ArrayOfPOD
import ArrayOfRef
import ArraySetElement
import ArraySubscript
import BinaryFloatingPointConversionFromBinaryInteger
import BinaryFloatingPointProperties
import BitCount
import Breadcrumbs
import BucketSort
import BufferFill
import ByteSwap
import COWTree
import COWArrayGuaranteedParameterOverhead
import CString
import CSVParsing
import Calculator
import CaptureProp
import ChaCha
import ChainedFilterMap
import CharacterLiteralsLarge
import CharacterLiteralsSmall
import CharacterProperties
import Chars
import ClassArrayGetter
import Codable
import Combos
import CreateObjects
import DataBenchmarks
import DeadArray
import DevirtualizeProtocolComposition
import DictOfArraysToArrayOfDicts
import DictTest
import DictTest2
import DictTest3
import DictTest4
import DictTest4Legacy
import DictionaryBridge
import DictionaryBridgeToObjC
import DictionaryCompactMapValues
import DictionaryCopy
import DictionaryGroup
import DictionaryKeysContains
import DictionaryLiteral
import DictionaryOfAnyHashableStrings
import DictionaryRemove
import DictionarySubscriptDefault
import DictionarySwap
#if canImport(_Differentiation)
import Differentiation
#endif
import Diffing
import DiffingMyers
import DropFirst
import DropLast
import DropWhile
import ErrorHandling
import Exclusivity
import ExistentialPerformance
import Fibonacci
import FindStringNaive
import FlattenList
import FloatingPointConversion
import FloatingPointParsing
import FloatingPointPrinting
import Hanoi
import Hash
import Histogram
import HTTP2StateMachine
import IndexPathTest
import InsertCharacter
import IntegerParsing
import Integrate
import IterateData
import Join
import LazyFilter
import LinkedList
import LuhnAlgoEager
import LuhnAlgoLazy
import MapReduce
import Memset
import Mirror
import MonteCarloE
import MonteCarloPi
import NibbleSort
import NIOChannelPipeline
import NSDictionaryCastToSwift
import NSError
#if canImport(Darwin)
import NSStringConversion
#endif
import NopDeinit
import ObjectAllocation
#if canImport(Darwin)
import ObjectiveCBridging
import ObjectiveCBridgingStubs
#if !(SWIFT_PACKAGE || Xcode)
import ObjectiveCNoBridgingStubs
#endif
#endif
import ObserverClosure
import ObserverForwarderStruct
import ObserverPartiallyAppliedMethod
import ObserverUnappliedMethod
import OpaqueConsumingUsers
import OpenClose
import Phonebook
import PointerArithmetics
import PolymorphicCalls
import PopFront
import PopFrontGeneric
import Prefix
import PrefixWhile
import Prims
import PrimsNonStrongRef
import PrimsSplit
import ProtocolConformance
import ProtocolDispatch
import ProtocolDispatch2
import Queue
import RC4
import RGBHistogram
import Radix2CooleyTukey
import RandomShuffle
import RandomTree
import RandomValues
import RangeAssignment
import RangeIteration
import RangeOverlaps
import RangeReplaceableCollectionPlusDefault
import RecursiveOwnedParameter
import ReduceInto
import RemoveWhere
import ReversedCollections
import RomanNumbers
import SIMDRandomMask
import SIMDReduceInteger
import SequenceAlgos
import SetTests
import SevenBoom
import Sim2DArray
import SortArrayInClass
import SortIntPyramids
import SortLargeExistentials
import SortLettersInPlace
import SortStrings
import StackPromo
import StaticArray
import StrComplexWalk
import StrToInt
import StringBuilder
import StringComparison
import StringEdits
import StringEnum
import StringInterpolation
import StringMatch
import StringRemoveDupes
import StringReplaceSubrange
import StringSplitting
import StringSwitch
import StringTests
import StringWalk
import Substring
import Suffix
import SuperChars
import TwoSum
import TypeFlood
import UTF8Decode
import Walsh
import WordCount
import XorLoop
@inline(__always)
private func registerBenchmark(_ bench: BenchmarkInfo) {
registeredBenchmarks.append(bench)
}
@inline(__always)
private func registerBenchmark<
S : Sequence
>(_ infos: S) where S.Element == BenchmarkInfo {
registeredBenchmarks.append(contentsOf: infos)
}
registerBenchmark(Ackermann)
registerBenchmark(AngryPhonebook)
registerBenchmark(AnyHashableWithAClass)
registerBenchmark(Array2D)
registerBenchmark(ArrayAppend)
registerBenchmark(ArrayInClass)
registerBenchmark(ArrayLiteral)
registerBenchmark(ArrayOfGenericPOD)
registerBenchmark(ArrayOfGenericRef)
registerBenchmark(ArrayOfPOD)
registerBenchmark(ArrayOfRef)
registerBenchmark(ArraySetElement)
registerBenchmark(ArraySubscript)
registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger)
registerBenchmark(BinaryFloatingPointPropertiesBinade)
registerBenchmark(BinaryFloatingPointPropertiesNextUp)
registerBenchmark(BinaryFloatingPointPropertiesUlp)
registerBenchmark(BitCount)
registerBenchmark(Breadcrumbs)
registerBenchmark(BucketSort)
registerBenchmark(BufferFill)
registerBenchmark(ByteSwap)
registerBenchmark(COWTree)
registerBenchmark(COWArrayGuaranteedParameterOverhead)
registerBenchmark(CString)
registerBenchmark(CSVParsing)
registerBenchmark(Calculator)
registerBenchmark(CaptureProp)
registerBenchmark(ChaCha)
registerBenchmark(ChainedFilterMap)
registerBenchmark(CharacterLiteralsLarge)
registerBenchmark(CharacterLiteralsSmall)
registerBenchmark(CharacterPropertiesFetch)
registerBenchmark(CharacterPropertiesStashed)
registerBenchmark(CharacterPropertiesStashedMemo)
registerBenchmark(CharacterPropertiesPrecomputed)
registerBenchmark(Chars)
registerBenchmark(Codable)
registerBenchmark(Combos)
registerBenchmark(ClassArrayGetter)
registerBenchmark(CreateObjects)
registerBenchmark(DataBenchmarks)
registerBenchmark(DeadArray)
registerBenchmark(DevirtualizeProtocolComposition)
registerBenchmark(DictOfArraysToArrayOfDicts)
registerBenchmark(Dictionary)
registerBenchmark(Dictionary2)
registerBenchmark(Dictionary3)
registerBenchmark(Dictionary4)
registerBenchmark(Dictionary4Legacy)
registerBenchmark(DictionaryBridge)
registerBenchmark(DictionaryBridgeToObjC)
registerBenchmark(DictionaryCompactMapValues)
registerBenchmark(DictionaryCopy)
registerBenchmark(DictionaryGroup)
registerBenchmark(DictionaryKeysContains)
registerBenchmark(DictionaryLiteral)
registerBenchmark(DictionaryOfAnyHashableStrings)
registerBenchmark(DictionaryRemove)
registerBenchmark(DictionarySubscriptDefault)
registerBenchmark(DictionarySwap)
#if canImport(_Differentiation)
registerBenchmark(Differentiation)
#endif
registerBenchmark(Diffing)
registerBenchmark(DiffingMyers)
registerBenchmark(DropFirst)
registerBenchmark(DropLast)
registerBenchmark(DropWhile)
registerBenchmark(ErrorHandling)
registerBenchmark(Exclusivity)
registerBenchmark(ExistentialPerformance)
registerBenchmark(Fibonacci)
registerBenchmark(FindStringNaive)
registerBenchmark(FlattenListLoop)
registerBenchmark(FlattenListFlatMap)
registerBenchmark(FloatingPointConversion)
registerBenchmark(FloatingPointParsing)
registerBenchmark(FloatingPointPrinting)
registerBenchmark(Hanoi)
registerBenchmark(HashTest)
registerBenchmark(Histogram)
registerBenchmark(HTTP2StateMachine)
registerBenchmark(IndexPathTest)
registerBenchmark(InsertCharacter)
registerBenchmark(IntegerParsing)
registerBenchmark(IntegrateTest)
registerBenchmark(IterateData)
registerBenchmark(Join)
registerBenchmark(LazyFilter)
registerBenchmark(LinkedList)
registerBenchmark(LuhnAlgoEager)
registerBenchmark(LuhnAlgoLazy)
registerBenchmark(MapReduce)
registerBenchmark(Memset)
registerBenchmark(MirrorDefault)
registerBenchmark(MonteCarloE)
registerBenchmark(MonteCarloPi)
registerBenchmark(NSDictionaryCastToSwift)
registerBenchmark(NSErrorTest)
#if canImport(Darwin)
registerBenchmark(NSStringConversion)
#endif
registerBenchmark(NibbleSort)
registerBenchmark(NIOChannelPipeline)
registerBenchmark(NopDeinit)
registerBenchmark(ObjectAllocation)
#if canImport(Darwin)
registerBenchmark(ObjectiveCBridging)
registerBenchmark(ObjectiveCBridgingStubs)
#if !(SWIFT_PACKAGE || Xcode)
registerBenchmark(ObjectiveCNoBridgingStubs)
#endif
#endif
registerBenchmark(ObserverClosure)
registerBenchmark(ObserverForwarderStruct)
registerBenchmark(ObserverPartiallyAppliedMethod)
registerBenchmark(ObserverUnappliedMethod)
registerBenchmark(OpaqueConsumingUsers)
registerBenchmark(OpenClose)
registerBenchmark(Phonebook)
registerBenchmark(PointerArithmetics)
registerBenchmark(PolymorphicCalls)
registerBenchmark(PopFront)
registerBenchmark(PopFrontArrayGeneric)
registerBenchmark(Prefix)
registerBenchmark(PrefixWhile)
registerBenchmark(Prims)
registerBenchmark(PrimsNonStrongRef)
registerBenchmark(PrimsSplit)
registerBenchmark(ProtocolConformance)
registerBenchmark(ProtocolDispatch)
registerBenchmark(ProtocolDispatch2)
registerBenchmark(QueueGeneric)
registerBenchmark(QueueConcrete)
registerBenchmark(RC4Test)
registerBenchmark(RGBHistogram)
registerBenchmark(Radix2CooleyTukey)
registerBenchmark(RandomShuffle)
registerBenchmark(RandomTree)
registerBenchmark(RandomValues)
registerBenchmark(RangeAssignment)
registerBenchmark(RangeIteration)
registerBenchmark(RangeOverlaps)
registerBenchmark(RangeReplaceableCollectionPlusDefault)
registerBenchmark(RecursiveOwnedParameter)
registerBenchmark(ReduceInto)
registerBenchmark(RemoveWhere)
registerBenchmark(ReversedCollections)
registerBenchmark(RomanNumbers)
registerBenchmark(SIMDRandomMask)
registerBenchmark(SIMDReduceInteger)
registerBenchmark(SequenceAlgos)
registerBenchmark(SetTests)
registerBenchmark(SevenBoom)
registerBenchmark(Sim2DArray)
registerBenchmark(SortArrayInClass)
registerBenchmark(SortIntPyramids)
registerBenchmark(SortLargeExistentials)
registerBenchmark(SortLettersInPlace)
registerBenchmark(SortStrings)
registerBenchmark(StackPromo)
registerBenchmark(StaticArrayTest)
registerBenchmark(StrComplexWalk)
registerBenchmark(StrToInt)
registerBenchmark(StringBuilder)
registerBenchmark(StringComparison)
registerBenchmark(StringEdits)
registerBenchmark(StringEnum)
registerBenchmark(StringHashing)
registerBenchmark(StringInterpolation)
registerBenchmark(StringInterpolationSmall)
registerBenchmark(StringInterpolationManySmallSegments)
registerBenchmark(StringMatch)
registerBenchmark(StringNormalization)
registerBenchmark(StringRemoveDupes)
registerBenchmark(StringReplaceSubrange)
if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {
registerBenchmark(StringSplitting)
}
registerBenchmark(StringSwitch)
registerBenchmark(StringTests)
registerBenchmark(StringWalk)
registerBenchmark(SubstringTest)
registerBenchmark(Suffix)
registerBenchmark(SuperChars)
registerBenchmark(TwoSum)
registerBenchmark(TypeFlood)
registerBenchmark(TypeName)
registerBenchmark(UTF8Decode)
registerBenchmark(Walsh)
registerBenchmark(WordCount)
registerBenchmark(XorLoop)
main()
| 6043ef6e1c3a3309d8c0fbfb5271f883 | 26.987654 | 80 | 0.883458 | false | false | false | false |
kasei/kineo | refs/heads/master | Sources/Kineo/QuadStore/SPARQLClientQuadStore.swift | mit | 1 | //
// SPARQLClientQuadStore.swift
// Kineo
//
// Created by Gregory Todd Williams on 6/6/18.
//
import Foundation
import SPARQLSyntax
// swiftlint:disable:next type_body_length
open class SPARQLClientQuadStore: Sequence, QuadStoreProtocol {
var client: SPARQLClient
var defaultGraph: Term
public init(endpoint: URL, defaultGraph: Term) {
self.client = SPARQLClient(endpoint: endpoint)
self.defaultGraph = defaultGraph
}
public var count: Int {
if let r = try? client.execute("SELECT (COUNT(*) AS ?count) WHERE { { GRAPH ?g { ?s ?p ?o} } UNION { ?s ?p ?o } }") {
if case .bindings(_, let rows) = r {
return rows.count
}
}
return 0
}
public var graphsCount: Int {
return Array(graphs()).count
}
public func graphs() -> AnyIterator<Term> {
if let r = try? client.execute("SELECT ?g WHERE { GRAPH ?g {} }") {
if case .bindings(_, let rows) = r {
let graphs = rows.compactMap { $0["g"] }
return AnyIterator(graphs.makeIterator())
}
}
return AnyIterator([].makeIterator())
}
public func graphTerms(in graph: Term) -> AnyIterator<Term> {
if let r = try? client.execute("SELECT DISTINCT ?t WHERE { GRAPH \(graph) { { ?t ?p ?o } UNION { ?s ?p ?t } }") {
if case .bindings(_, let rows) = r {
let graphs = rows.compactMap { $0["t"] }
return AnyIterator(graphs.makeIterator())
}
}
return AnyIterator([].makeIterator())
}
public func makeIterator() -> AnyIterator<Quad> {
if let r = try? client.execute("SELECT * WHERE { { GRAPH ?g { ?s ?p ?o } } UNION { ?s ?p ?o } }") {
if case .bindings(_, let rows) = r {
let quads = rows.compactMap { (row) -> Quad? in
if let s = row["s"], let p = row["p"], let o = row["o"] {
if let g = row["g"] {
return Quad(subject: s, predicate: p, object: o, graph: g)
} else {
return Quad(subject: s, predicate: p, object: o, graph: defaultGraph)
}
}
return nil
}
return AnyIterator(quads.makeIterator())
}
}
return AnyIterator([].makeIterator())
}
public func results(matching pattern: QuadPattern) throws -> AnyIterator<SPARQLResultSolution<Term>> {
let query : String
if pattern.graph == .bound(defaultGraph) {
query = "SELECT * WHERE { \(pattern.subject) \(pattern.predicate) \(pattern.object) }"
} else {
query = "SELECT * WHERE { GRAPH \(pattern.graph) { \(pattern.subject) \(pattern.predicate) \(pattern.object) } }"
}
if let r = try? client.execute(query) {
if case .bindings(_, let rows) = r {
return AnyIterator(rows.makeIterator())
}
}
return AnyIterator([].makeIterator())
}
public func quads(matching pattern: QuadPattern) throws -> AnyIterator<Quad> {
var s = pattern.subject
var p = pattern.predicate
var o = pattern.object
var g = pattern.graph
if case .variable = s { s = .variable("s", binding: true) }
if case .variable = p { p = .variable("p", binding: true) }
if case .variable = o { o = .variable("o", binding: true) }
if case .variable = g { g = .variable("g", binding: true) }
let query: String
if case .bound(defaultGraph) = g {
query = "SELECT * WHERE { \(s) \(p) \(o) }"
} else if case .bound(_) = g {
query = "SELECT * WHERE { GRAPH \(g) { \(s) \(p) \(o) } }" // TODO: pull default graph also
} else {
query = """
SELECT * WHERE {
{
GRAPH \(g) { \(s) \(p) \(o) }
} UNION {
\(s) \(p) \(o)
}
}
"""
}
if let r = try? client.execute(query) {
if case .bindings(_, let rows) = r {
let quads = rows.compactMap { (row) -> Quad? in
var subj: Term
var pred: Term
var obj: Term
var graph: Term
if case .bound(let t) = s {
subj = t
} else if let s = row["s"] {
subj = s
} else {
return nil
}
if case .bound(let t) = p {
pred = t
} else if let p = row["p"] {
pred = p
} else {
return nil
}
if case .bound(let t) = o {
obj = t
} else if let o = row["o"] {
obj = o
} else {
return nil
}
if case .bound(let t) = g {
graph = t
} else {
graph = row["g"] ?? defaultGraph
}
return Quad(subject: subj, predicate: pred, object: obj, graph: graph)
}
return AnyIterator(quads.makeIterator())
}
}
return AnyIterator([].makeIterator())
}
public func countQuads(matching pattern: QuadPattern) throws -> Int {
var s = pattern.subject
var p = pattern.predicate
var o = pattern.object
var g = pattern.graph
if case .variable = s { s = .variable("s", binding: true) }
if case .variable = p { p = .variable("p", binding: true) }
if case .variable = o { o = .variable("o", binding: true) }
if case .variable = g { g = .variable("g", binding: true) }
let query: String
if case .bound(defaultGraph) = g {
query = "SELECT (COUNT(*) AS ?count) WHERE { \(s) \(p) \(o) }"
} else if case .bound(_) = g {
query = "SELECT (COUNT(*) AS ?count) WHERE { GRAPH \(g) { \(s) \(p) \(o) } }" // TODO: pull default graph also
} else {
query = """
SELECT (COUNT(*) AS ?count) WHERE {
{
GRAPH \(g) { \(s) \(p) \(o) }
} UNION {
\(s) \(p) \(o)
}
}
"""
}
if let r = try? client.execute(query) {
if case .bindings(_, let rows) = r {
guard let row = rows.first, let count = row["count"] else {
throw QueryError.evaluationError("Failed to get count of matching quads from endpoint")
}
return Int(count.numericValue)
}
}
throw QueryError.evaluationError("Failed to get count of matching quads from endpoint")
}
public func effectiveVersion(matching pattern: QuadPattern) throws -> Version? {
return nil
}
}
extension SPARQLClientQuadStore : BGPQuadStoreProtocol {
public func results(matching triples: [TriplePattern], in graph: Term) throws -> AnyIterator<SPARQLResultSolution<Term>> {
let ser = SPARQLSerializer(prettyPrint: true)
let bgp = try ser.serialize(.bgp(triples))
let query = "SELECT * WHERE { \(bgp) }"
print("Evaluating BGP against \(client):\n\(query)")
if let r = try? client.execute(query) {
if case .bindings(_, let rows) = r {
return AnyIterator(rows.makeIterator())
}
}
return AnyIterator([].makeIterator())
}
}
extension SPARQLClientQuadStore: CustomStringConvertible {
public var description: String {
return "SPARQLClientQuadStore <\(client.endpoint)>\n"
}
}
| 10c86c80d2f731d7c435c4d030879db8 | 36.814815 | 126 | 0.466577 | false | false | false | false |
ben-ng/swift | refs/heads/master | stdlib/public/core/CocoaArray.swift | apache-2.0 | 1 | //===--- CocoaArray.swift - A subset of the NSArray interface -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// To implement bridging, the core standard library needs to interact
// a little bit with Cocoa. Because we want to keep the core
// decoupled from the Foundation module, we can't use NSArray
// directly. We _can_, however, use an @objc protocol with a
// compatible API. That's _NSArrayCore.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// A wrapper around any `_NSArrayCore` that gives it
/// `Collection` conformance. Why not make
/// `_NSArrayCore` conform directly? It's a class, and I
/// don't want to pay for the dynamic dispatch overhead.
internal struct _CocoaArrayWrapper : RandomAccessCollection {
typealias Indices = CountableRange<Int>
var startIndex: Int {
return 0
}
var endIndex: Int {
return buffer.count
}
subscript(i: Int) -> AnyObject {
return buffer.objectAt(i)
}
/// Returns a pointer to the first element in the given non-empty `subRange`
/// if the subRange is stored contiguously. Otherwise, return `nil`.
///
/// The "non-empty" condition saves a branch within this method that can
/// likely be better handled in a caller.
///
/// - Note: This method should only be used as an optimization; it
/// is sometimes conservative and may return `nil` even when
/// contiguous storage exists, e.g., if array doesn't have a smart
/// implementation of countByEnumerating.
func contiguousStorage(
_ subRange: Range<Int>
) -> UnsafeMutablePointer<AnyObject>?
{
_sanityCheck(!subRange.isEmpty)
var enumerationState = _makeSwiftNSFastEnumerationState()
// This function currently returns nil unless the first
// subRange.upperBound items are stored contiguously. This is an
// acceptable conservative behavior, but could potentially be
// optimized for other cases.
let contiguousCount = withUnsafeMutablePointer(to: &enumerationState) {
self.buffer.countByEnumerating(with: $0, objects: nil, count: 0)
}
return contiguousCount >= subRange.upperBound
? UnsafeMutableRawPointer(enumerationState.itemsPtr!)
.assumingMemoryBound(to: AnyObject.self)
+ subRange.lowerBound
: nil
}
@_transparent
init(_ buffer: _NSArrayCore) {
self.buffer = buffer
}
var buffer: _NSArrayCore
}
#endif
| 361e95ec2d35079c68a992f2906881c8 | 33.97561 | 80 | 0.661437 | false | false | false | false |
mirego/PinLayout | refs/heads/master | Tests/Common/LayoutMethodSpec.swift | mit | 1 | // Copyright (c) 2017 Luc Dion
// 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 Quick
import Nimble
import PinLayout
class LayoutMethodSpec: QuickSpec {
override func spec() {
var viewController: PViewController!
var rootView: BasicView!
var aView: BasicView!
/*
root
|
- aView
*/
beforeEach {
_pinlayoutSetUnitTest(scale: 2)
Pin.lastWarningText = nil
Pin.logMissingLayoutCalls = false
viewController = PViewController()
viewController.view = BasicView()
rootView = BasicView()
rootView.frame = CGRect(x: 0, y: 0, width: 400, height: 400)
viewController.view.addSubview(rootView)
aView = BasicView()
aView.frame = CGRect(x: 40, y: 100, width: 100, height: 60)
rootView.addSubview(aView)
}
afterEach {
_pinlayoutSetUnitTest(scale: nil)
Pin.logMissingLayoutCalls = false
}
//
// layout()
//
describe("layout()") {
it("test layout() method") {
let aViewFrame = aView.frame
aView.pin.left().right()
expect(aView.frame).to(equal(CGRect(x: 0.0, y: 100.0, width: 400.0, height: 60.0)))
expect(Pin.lastWarningText).to(beNil())
aView.frame = aViewFrame
aView.pin.left().right().layout()
expect(aView.frame).to(equal(CGRect(x: 0.0, y: 100.0, width: 400.0, height: 60.0)))
}
it("should warn if layout() is not called when Pin.logMissingLayoutCalls is set to true") {
Pin.logMissingLayoutCalls = true
aView.pin.left().right()
expect(Pin.lastWarningText).to(contain(["PinLayout commands have been issued without calling the 'layout()' method"]))
}
}
}
}
| 436a387bbd8ebc67dc3174da12d92be6 | 37.518519 | 134 | 0.594872 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Pods/Down/Source/AST/Nodes/List.swift | mit | 1 | //
// List.swift
// Down
//
// Created by John Nguyen on 09.04.19.
//
import Foundation
import libcmark
public class List: BaseNode {
public enum ListType: CustomDebugStringConvertible {
case bullet
case ordered(start: Int)
public var debugDescription: String {
switch self {
case .bullet: return "Bullet"
case .ordered(let start): return "Ordered (start: \(start)"
}
}
init?(cmarkNode: CMarkNode) {
switch cmarkNode.listType {
case CMARK_BULLET_LIST: self = .bullet
case CMARK_ORDERED_LIST: self = .ordered(start: cmarkNode.listStart)
default: return nil
}
}
}
///////////////////////////////////////////////////////////////////////////
/// The type of the list, either bullet or ordered.
public lazy var listType: ListType = {
guard let type = ListType(cmarkNode: cmarkNode) else {
assertionFailure("Unsupported or missing list type. Defaulting to .bullet.")
return .bullet
}
return type
}()
/// The number of items in the list.
public lazy var numberOfItems: Int = children.count
}
// MARK: - Debug
extension List: CustomDebugStringConvertible {
public var debugDescription: String {
return "List - type: \(listType)"
}
}
| 02cf463b15977e1570a9fe746fb124fa | 24.210526 | 88 | 0.542102 | false | false | false | false |
wanglei8441226/FightingFish | refs/heads/master | FightingFish/FightingFish/Classes/Home/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// FightingFish
//
// Created by 王磊 on 2017/3/6.
// Copyright © 2017年 王磊. All rights reserved.
//
import UIKit
fileprivate var titleViewH : CGFloat = 40
class HomeViewController: UIViewController {
// MARK: - 懒加载属性
fileprivate lazy var pageTitleView: PageTitleView = {[weak self] in
let pageFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: titleViewH)
let pageTitleView = PageTitleView(frame: pageFrame, titles: ["推荐", "手游", "娱乐", "游戏","趣玩"])
pageTitleView.delegate = self
return pageTitleView
}()
fileprivate lazy var pageContentView: PageContentView = { [weak self] in
let pageY :CGFloat = kStatusBarH + kNavigationBarH + titleViewH
let pageH:CGFloat = kScreenH - pageY
let pageContentFrame = CGRect(x: 0, y: pageY, width: kScreenW, height: pageH)
var childers = [UIViewController]()
for _ in 0..<5{
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childers.append(vc)
}
let content = PageContentView(frame: pageContentFrame, childControllers: childers, parentController: self)
return content
}()
// MARK: - 父类方法
override func viewDidLoad() {
super.viewDidLoad()
// 1.初始化UI
customUI()
}
}
// MARK: - View相关
extension HomeViewController{
fileprivate func customUI(){
// 0.不需要自动偏移
automaticallyAdjustsScrollViewInsets = false
// 1.设置导航栏按钮
setUpNavigationBar()
// 2.添加pageTitleView
view.addSubview(pageTitleView)
// 3.添加pageContentView
view.addSubview(pageContentView)
}
fileprivate func setUpNavigationBar(){
// 1.设置左侧的BarButtonItem
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
// 2.设置右侧的BarButtonItem
let size = CGSize(width: 40, height: 40)
let history = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
let scan = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
let search = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
navigationItem.rightBarButtonItems = [search, scan, history ]
}
}
// MARK: - pageTitleDelegate
extension HomeViewController: PageTitleViewDelegate{
func pageTitleViewScrollLine(_ titleView: PageTitleView, seletedInde index: Int) {
print(index)
pageContentView.pageContenViewScrollIndex(index)
}
}
| 81a552ba4af29967165db976f997b514 | 36.148649 | 156 | 0.662059 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Base/Extension/String.swift | mit | 1 | //
// String.swift
// selluv-ios
//
// Created by 조백근 on 2016. 12. 29..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
extension String {
private struct AssociatedKey {
static var indexTagKey = "String.Associated.indexTagKey"
}
public var indexTag: Int {
get {
if let value = objc_getAssociatedObject(self, &AssociatedKey.indexTagKey) as? Int {
return value
}
return 0
}
set {
objc_setAssociatedObject(self, &AssociatedKey.indexTagKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
var isAlphanumeric: Bool {
return range(of: "^[a-zA-Z0-9!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?~`]+$", options: .regularExpression) != nil
}
var hangul: String {
get {
let hangle = [
["ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"],
["ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅘ","ㅙ","ㅚ","ㅛ","ㅜ","ㅝ","ㅞ","ㅟ","ㅠ","ㅡ","ㅢ","ㅣ"],
["","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ","ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"]
]
return characters.reduce("") { result, char in
if case let code = Int(String(char).unicodeScalars.reduce(0){$0.0 + $0.1.value}) - 44032, code > -1 && code < 11172 {
let cho = code / 21 / 28, jung = code % (21 * 28) / 28, jong = code % 28;
return result + hangle[0][cho] + hangle[1][jung] + hangle[2][jong]
}
return result + String(char)
}
}
}
public static func decimalAmountWithForm(value: Float, pointCount: Int) -> String {
let point = (pointCount > 0) ? Int(Array(1...pointCount).map{_ in 10}.reduce(10, *)) : 1 //pointCount 만큽 10의 제곱승을 만들어서 살려둘 자리수 만큼 곱하고 라운드 후 다시 나눈다.
let amount = round(value * Float(point)) / Float(point) //반올림
let commaValue = NumberFormatter.localizedString(from: NSNumber(value: amount), number: NumberFormatter.Style.decimal)
return commaValue
}
public static func removeFormAmount(value: String) -> String {
let formatter = NumberFormatter()
formatter.locale = NSLocale.current
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.decimalSeparator = ","
let amount = formatter.number(from: value) ?? 0
let famount = amount.floatValue
return famount.cleanValue
}
}
| 50fb4f62b7a7bfc58ac0f8b4412a44a7 | 36.970588 | 155 | 0.520139 | false | false | false | false |
Chaosspeeder/YourGoals | refs/heads/master | YourGoals/UI/Views/Progress Indicators/ProgressIndicatorView.swift | lgpl-3.0 | 1 | //
// ProgressIndicatorView.swift
// YourGoals
//
// Created by André Claaßen on 27.10.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import UIKit
import PNChart
enum ProgressIndicatorViewMode {
case normal
case mini
}
/// a circle progress indicator
class ProgressIndicatorView: UIView {
var viewMode = ProgressIndicatorViewMode.normal
var progressView:PieProgressView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
self.backgroundColor = UIColor.clear
self.progressView = PieProgressView(frame: self.bounds)
self.addSubview(progressView)
}
func setProgress(progress:Double, progressIndicator:ProgressIndicator) {
let color = calculateColor(fromIndicator: progressIndicator)
self.progressView.progressTintColor = color
self.progressView.trackTintColor = color
self.progressView.fillColor = color.withAlphaComponent(0.3)
self.progressView.progress = CGFloat(progress)
}
/// show the progress of the goal as a colored circle
/// - Parameters:
/// - goal: the goal
/// - date: calculation of progress for this date
/// - manager: a manager to retrieve actual data from the core data sotre
/// - Throws: core data exception
func setProgress(forGoal goal:Goal, forDate date: Date, withBackburned backburnedGoals:Bool, manager: GoalsStorageManager) throws {
let calculator = GoalProgressCalculator(manager: manager)
let progress = try calculator.calculateProgress(forGoal: goal, forDate: date, withBackburned: backburnedGoals)
self.setProgress(progress: progress.progress, progressIndicator: progress.indicator)
}
/// convert the progress indicator to a traffic color
///
/// - Parameter progressIndicator: the progress indicator
/// - Returns: a color represnetation the state of the progress
func calculateColor(fromIndicator progressIndicator: ProgressIndicator) -> UIColor {
switch progressIndicator {
case .met:
return UIColor.green
case .ahead:
return UIColor.blue
case .onTrack:
return UIColor.green
case .lagging:
return UIColor.orange
case .behind:
return UIColor.red
case .notStarted:
return UIColor.lightGray
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
| 31d3e7db8f98268334fcc52034c6c23c | 29.852273 | 135 | 0.648987 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/stmt/if_while_var.swift | apache-2.0 | 5 | // RUN: %target-typecheck-verify-swift
struct NonOptionalStruct {}
enum NonOptionalEnum { case foo }
func foo() -> Int? { return .none }
func nonOptionalStruct() -> NonOptionalStruct { fatalError() }
func nonOptionalEnum() -> NonOptionalEnum { fatalError() }
func use(_ x: Int) {}
func modify(_ x: inout Int) {}
if let x = foo() {
use(x)
modify(&x) // expected-error{{cannot pass immutable value as inout argument: 'x' is a 'let' constant}}
}
use(x) // expected-error{{unresolved identifier 'x'}}
if var x = foo() {
use(x)
modify(&x)
}
use(x) // expected-error{{unresolved identifier 'x'}}
if let x = nonOptionalStruct() { } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalStruct'}}
if let x = nonOptionalEnum() { } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalEnum'}}
guard let _ = nonOptionalStruct() else { fatalError() } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalStruct'}}
guard let _ = nonOptionalEnum() else { fatalError() } // expected-error{{initializer for conditional binding must have Optional type, not 'NonOptionalEnum'}}
if case let x? = nonOptionalStruct() { } // expected-error{{'?' pattern cannot match values of type 'NonOptionalStruct'}}
if case let x? = nonOptionalEnum() { } // expected-error{{'?' pattern cannot match values of type 'NonOptionalEnum'}}
class B {} // expected-note * {{did you mean 'B'?}}
class D : B {}// expected-note * {{did you mean 'D'?}}
// TODO poor recovery in these cases
if let {} // expected-error {{expected '{' after 'if' condition}} expected-error {{pattern matching in a condition requires the 'case' keyword}}
if let x = {} // expected-error{{'{' after 'if'}} expected-error {{variable binding in a condition requires an initializer}} expected-error{{initializer for conditional binding must have Optional type, not '() -> ()'}}
if let x = foo() {
} else {
// TODO: more contextual error? "x is only available on the true branch"?
use(x) // expected-error{{unresolved identifier 'x'}}
}
if let x = foo() {
use(x)
} else if let y = foo() { // expected-note {{did you mean 'y'?}}
use(x) // expected-error{{unresolved identifier 'x'}}
use(y)
} else {
use(x) // expected-error{{unresolved identifier 'x'}}
use(y) // expected-error{{unresolved identifier 'y'}}
}
var opt: Int? = .none
if let x = opt {}
if var x = opt {}
// <rdar://problem/20800015> Fix error message for invalid if-let
let someInteger = 1
if let y = someInteger {} // expected-error {{initializer for conditional binding must have Optional type, not 'Int'}}
if case let y? = someInteger {} // expected-error {{'?' pattern cannot match values of type 'Int'}}
// Test multiple clauses on "if let".
if let x = opt, let y = opt, x != y,
let a = opt, var b = opt {
}
// Leading boolean conditional.
if 1 != 2, let x = opt,
y = opt, // expected-error {{expected 'let' in conditional}} {{4-4=let }}
x != y,
let a = opt, var b = opt {
}
// <rdar://problem/20457938> typed pattern is not allowed on if/let condition
if 1 != 2, let x : Int? = opt {}
// expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{20-26=Int}}
if 1 != 2, case let x? : Int? = 42 {}
// expected-warning @-1 {{non-optional expression of type 'Int' used in a check for optionals}}
// Test error recovery.
// <rdar://problem/19939746> Improve error recovery for malformed if statements
if 1 != 2, { // expected-error {{'() -> ()' is not convertible to 'Bool'}}
} // expected-error {{expected '{' after 'if' condition}}
if 1 != 2, 4 == 57 {}
if 1 != 2, 4 == 57, let x = opt {}
// Test that these don't cause the parser to crash.
if true { if a == 0; {} } // expected-error {{expected '{' after 'if' condition}} expected-error 3{{}}
if a == 0, where b == 0 {} // expected-error 4{{}} expected-note {{}} {{25-25=_ = }}
func testIfCase(_ a : Int?) {
if case nil = a, a != nil {}
if case let (b?) = a, b != 42 {}
if let case (b?) = a, b != 42 {} // expected-error {{pattern matching binding is spelled with 'case let', not 'let case'}} {{6-10=}} {{14-14= let}}
if a != nil, let c = a, case nil = a { _ = c}
if let p? = a {_ = p} // expected-error {{pattern matching in a condition implicitly unwraps optionals}} {{11-12=}}
if let .some(x) = a {_ = x} // expected-error {{pattern matching in a condition requires the 'case' keyword}} {{6-6=case }}
if case _ = a {} // expected-warning {{'if' condition is always true}}
while case _ = a {} // expected-warning {{'while' condition is always true}}
}
// <rdar://problem/20883147> Type annotation for 'let' condition still expected to be optional
func testTypeAnnotations() {
if let x: Int = Optional(1) {_ = x}
if let x: Int = .some(1) {_ = x}
if case _ : Int8 = 19 {} // expected-warning {{'if' condition is always true}}
}
func testShadowing(_ a: Int?, b: Int?, c: Int?, d: Int?) {
guard let a = a, let b = a > 0 ? b : nil else { return }
_ = b
if let c = c, let d = c > 0 ? d : nil {
_ = d
}
}
func useInt(_ x: Int) {}
func testWhileScoping(_ a: Int?) {// expected-note {{did you mean 'a'?}}
while let x = a { }
useInt(x) // expected-error{{use of unresolved identifier 'x'}}
}
| e650e04fbb592e3a47bbc1ed9b271017 | 36.451389 | 218 | 0.640274 | false | false | false | false |
HeMet/LSSTools | refs/heads/master | Sources/ifconvert/Driver.swift | mit | 1 | //
// Driver.swift
// LSS
//
// Created by Evgeniy Gubin on 05.02.17.
//
//
import Foundation
class Driver {
let fileManager: FileManagerProtocol = FileManager.default;
let converter = ItemFilterConverter()
func run(args: [String]) throws {
guard args.count > 1 else {
print("ifconvert <input file> [output file]")
return;
}
let inputFile = args[1];
let outputFile = (args.count > 2) ? args[2] : inputFile.replacingExtension(with: "lss")
let input = try fileManager.readString(file: inputFile)
let output = try converter.convert(itemFilter: input)
try fileManager.write(string: output, to: outputFile)
}
}
| 4a481e6e1359434965aed8af2fdc0520 | 24.344828 | 95 | 0.602721 | false | false | false | false |
xmartlabs/Opera | refs/heads/master | Example/Example/Controllers/RepositoryIssuesController.swift | mit | 1 | // RepositoryIssuesController.swift
// Example-iOS ( https://github.com/xmartlabs/Example-iOS )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import OperaSwift
import RxSwift
import RxCocoa
class IssuesFilter {
enum State: Int, CustomStringConvertible {
case open
case closed
case all
var description: String {
switch self {
case .open: return "open"
case .closed: return "closed"
case .all: return "all"
}
}
}
enum Sort: Int, CustomStringConvertible {
case created
case updated
case comments
var description: String {
switch self {
case .created: return "created"
case .updated: return "updated"
case .comments: return "comments"
}
}
}
enum Direction: Int, CustomStringConvertible {
case ascendant
case descendant
var description: String {
switch self {
case .ascendant: return "asc"
case .descendant: return "desc"
}
}
}
var state = State.open
var sortBy = Sort.created
var sortDirection = Direction.descendant
var issueCreator: String?
var userMentioned: String?
}
extension IssuesFilter: FilterType {
var parameters: [String: AnyObject]? {
var baseParams = ["state": "\(state)", "sort": "\(sortBy)", "direction": "\(sortDirection)"]
if let issueCreator = issueCreator, !issueCreator.isEmpty { baseParams["creator"] = issueCreator }
if let userMentioned = userMentioned, !userMentioned.isEmpty { baseParams["mentioned"] = userMentioned }
return baseParams as [String : AnyObject]?
}
}
class RepositoryIssuesController: RepositoryBaseController {
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
let refreshControl = UIRefreshControl()
var disposeBag = DisposeBag()
fileprivate var filter = Variable<IssuesFilter>(IssuesFilter())
lazy var viewModel: PaginationViewModel<PaginationRequest<Issue>> = { [unowned self] in
return PaginationViewModel(paginationRequest: PaginationRequest(route: GithubAPI.Repository.GetIssues(owner: self.owner, repo: self.name), filter: self.filter.value))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.keyboardDismissMode = .onDrag
tableView.addSubview(self.refreshControl)
emptyStateLabel.text = "No issues found"
let refreshControl = self.refreshControl
rx.sentMessage(#selector(RepositoryForksController.viewWillAppear(_:)))
.map { _ in false }
.bind(to: viewModel.refreshTrigger)
.disposed(by: disposeBag)
tableView.rx.reachedBottom
.bind(to: viewModel.loadNextPageTrigger)
.disposed(by: disposeBag)
viewModel.loading
.drive(activityIndicatorView.rx.isAnimating)
.disposed(by: disposeBag)
Driver.combineLatest(viewModel.elements.asDriver(), viewModel.firstPageLoading) { elements, loading in return loading ? [] : elements }
.asDriver()
.drive(tableView.rx.items(cellIdentifier:"Cell")) { _, issue, cell in
cell.textLabel?.text = issue.title
cell.detailTextLabel?.text = " #\(issue.number)"
}
.disposed(by: disposeBag)
refreshControl.rx.valueChanged
.filter { refreshControl.isRefreshing }
.map { true }
.bind(to: viewModel.refreshTrigger)
.disposed(by: disposeBag)
viewModel.loading
.filter { !$0 && refreshControl.isRefreshing }
.drive(onNext: { _ in refreshControl.endRefreshing() })
.disposed(by: disposeBag)
filter
.asObservable()
.map { $0 }
.bind(to: viewModel.filterTrigger)
.disposed(by: disposeBag)
viewModel.emptyState
.drive(onNext: { [weak self] emptyState in self?.emptyStateLabel.isHidden = !emptyState })
.disposed(by: disposeBag)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let vc = (segue.destination as? UINavigationController)?.topViewController as? RepositoryIssueFilterController else { return }
vc.filter = filter
}
}
| a10167332876717e78e3cb0f4b4d703a | 32.136905 | 174 | 0.649362 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/Serialization/comments-hidden.swift | apache-2.0 | 7 | // Test the case when we compile normally
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %s
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t > %t.normal.txt
// RUN: %FileCheck %s -check-prefix=NORMAL < %t.normal.txt
// RUN: %FileCheck %s -check-prefix=NORMAL-NEGATIVE < %t.normal.txt
// Test the case when we compile with -enable-testing
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -enable-testing -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %s
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t > %t.testing.txt
// RUN: %FileCheck %s -check-prefix=TESTING < %t.testing.txt
// RUN: %FileCheck %s -check-prefix=TESTING-NEGATIVE < %t.testing.txt
// Test the case when we have .swiftsourceinfo
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -enable-testing -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t > %t.testing.txt
// RUN: %FileCheck %s -check-prefix=SOURCE-LOC < %t.testing.txt
/// PublicClass Documentation
public class PublicClass {
/// Public Function Documentation
public func f_public() { }
/// Public Init Documentation
public init(_ name: String) {}
/// Public Subscript Documentation
public subscript(_ name: String) -> Int { return 0 }
/// Internal Function Documentation NotForNormal
internal func f_internal() { }
/// Private Function Documentation NotForNormal NotForTesting
private func f_private() { }
/// Public Filter Function Documentation NotForNormal NotForTesting
public func __UnderscoredPublic() {}
/// Public Filter Init Documentation NotForNormal NotForTesting
public init(__label name: String) {}
/// Public Filter Subscript Documentation NotForNormal NotForFiltering
public subscript(__label name: String) -> Int { return 0 }
/// Public Filter Init Documentation NotForNormal NotForTesting
public init(label __name: String) {}
/// Public Filter Subscript Documentation NotForNormal NotForTesting
public subscript(label __name: String) -> Int { return 0 }
/// SPI Function Documentation NotForNormal NotForTesting
@_spi(SPI) public func f_spi() { }
}
public extension PublicClass {
/// Public Filter Operator Documentation NotForNormal NotForTesting
static func -=(__lhs: inout PublicClass, __rhs: PublicClass) {}
}
/// InternalClass Documentation NotForNormal
internal class InternalClass {
/// Internal Function Documentation NotForNormal
internal func f_internal() { }
/// Private Function Documentation NotForNormal NotForTesting
private func f_private() { }
}
/// PrivateClass Documentation NotForNormal NotForTesting
private class PrivateClass {
/// Private Function Documentation NotForNormal NotForTesting
private func f_private() { }
}
/// SPI Documentation NotForNormal NotForTesting
@_spi(SPI) public class SPIClass {
/// SPI Function Documentation NotForNormal NotForTesting
public func f_spi() { }
}
/// SPI Extension Documentation NotForNormal NotForTesting
@_spi(SPI) public extension PublicClass {
}
// NORMAL-NEGATIVE-NOT: NotForNormal
// NORMAL-NEGATIVE-NOT: NotForTesting
// NORMAL: PublicClass Documentation
// NORMAL: Public Function Documentation
// NORMAL: Public Init Documentation
// NORMAL: Public Subscript Documentation
// TESTING-NEGATIVE-NOT: NotForTesting
// TESTING: PublicClass Documentation
// TESTING: Public Function Documentation
// TESTING: Public Init Documentation
// TESTING: Public Subscript Documentation
// TESTING: Internal Function Documentation
// TESTING: InternalClass Documentation
// TESTING: Internal Function Documentation
// SOURCE-LOC: comments-hidden.swift:37:15: Func/PublicClass.__UnderscoredPublic RawComment=none BriefComment=none DocCommentAsXML=none
// SOURCE-LOC: comments-hidden.swift:39:10: Constructor/PublicClass.init RawComment=none BriefComment=none DocCommentAsXML=none
// SOURCE-LOC: comments-hidden.swift:41:10: Subscript/PublicClass.subscript RawComment=none BriefComment=none DocCommentAsXML=none
// SOURCE-LOC: comments-hidden.swift:43:10: Constructor/PublicClass.init RawComment=none BriefComment=none DocCommentAsXML=none
// SOURCE-LOC: comments-hidden.swift:45:10: Subscript/PublicClass.subscript RawComment=none BriefComment=none DocCommentAsXML=none
// SOURCE-LOC: comments-hidden.swift:52:15: Func/-= RawComment=none BriefComment=none DocCommentAsXML=none
| b1ad9b8f7a5db48f6098054490060f4d | 48.16 | 244 | 0.763019 | false | true | false | false |
googlearchive/science-journal-ios | refs/heads/master | ScienceJournal/SensorData/GetTrialSensorDumpOperation.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import third_party_sciencejournal_ios_ScienceJournalProtos
/// An operation that fetches data for a single trial sensor and converts it into a sensor data
/// dump proto.
class GetTrialSensorDumpOperation: GSJOperation {
private let sensorDataManager: SensorDataManager
private let trialID: String
private let sensorID: String
/// When the operation completes successfully this will contain the sensor data dump.
var dump: GSJScalarSensorDataDump?
/// Designated initializer.
///
/// - Parameters:
/// - sensorDataManager: A sensor data manager.
/// - trialID: A trial ID.
/// - sensorID: A sensor ID.
init(sensorDataManager: SensorDataManager, trialID: String, sensorID: String) {
self.sensorDataManager = sensorDataManager
self.trialID = trialID
self.sensorID = sensorID
}
override func execute() {
sensorDataManager.fetchSensorData(
forSensorID: sensorID,
trialID: trialID,
completion: { (dataPoints) in
guard let dataPoints = dataPoints, dataPoints.count > 0 else {
self.finish(withErrors:
[SensorDataExportError.failedToFetchDatabaseSensorData(self.trialID,
self.sensorID)])
return
}
var rows = [GSJScalarSensorDataRow]()
for dataPoint in dataPoints {
let row = GSJScalarSensorDataRow()
row.timestampMillis = dataPoint.x
row.value = dataPoint.y
rows.append(row)
}
let sensorDump = GSJScalarSensorDataDump()
sensorDump.tag = self.sensorID
sensorDump.trialId = self.trialID
sensorDump.rowsArray = NSMutableArray(array: rows)
self.dump = sensorDump
self.finish()
})
}
}
| 3585dff919b7b3a7851a53c8b964d7e3 | 32.026667 | 95 | 0.660073 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwallet/src/ViewControllers/ViewControllerTransitions/PinTransitioningDelegate.swift | mit | 1 | //
// PinTransitioningDelegate.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-05-05.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
private let duration: TimeInterval = 0.4
class PinTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
var shouldShowMaskView = true
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PresentPinAnimator(shouldShowMaskView: shouldShowMaskView)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissPinAnimator()
}
}
class PresentPinAnimator: NSObject, UIViewControllerAnimatedTransitioning {
init(shouldShowMaskView: Bool) {
self.shouldShowMaskView = shouldShowMaskView
}
private let shouldShowMaskView: Bool
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let duration = transitionDuration(using: transitionContext)
let container = transitionContext.containerView
guard let toView = transitionContext.view(forKey: .to) else { return }
guard let toVc = transitionContext.viewController(forKey: .to) as? ContentBoxPresenter else { return }
let blurView = toVc.blurView
blurView.frame = container.frame
blurView.effect = nil
container.addSubview(blurView)
let fromFrame = container.frame
let maskView = UIView(frame: CGRect(x: 0, y: fromFrame.height, width: fromFrame.width, height: 40.0))
maskView.backgroundColor = .whiteTint
if shouldShowMaskView {
container.addSubview(maskView)
}
let scaleFactor: CGFloat = 0.1
let deltaX = toVc.contentBox.frame.width * (1-scaleFactor)
let deltaY = toVc.contentBox.frame.height * (1-scaleFactor)
let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
toVc.contentBox.transform = scale.translatedBy(x: -deltaX, y: deltaY/2.0)
let finalToViewFrame = toView.frame
toView.frame = toView.frame.offsetBy(dx: 0, dy: toView.frame.height)
container.addSubview(toView)
UIView.spring(duration, animations: {
maskView.frame = CGRect(x: 0, y: fromFrame.height - 30.0, width: fromFrame.width, height: 40.0)
blurView.effect = toVc.effect
toView.frame = finalToViewFrame
toVc.contentBox.transform = .identity
}, completion: { _ in
maskView.removeFromSuperview()
transitionContext.completeTransition(true)
})
}
}
class DismissPinAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let duration = transitionDuration(using: transitionContext)
guard let fromView = transitionContext.view(forKey: .from) else { assert(false, "Missing from view"); return }
guard let fromVc = transitionContext.viewController(forKey: .from) as? ContentBoxPresenter else { return }
UIView.animate(withDuration: duration, animations: {
fromVc.blurView.effect = nil
fromView.frame = fromView.frame.offsetBy(dx: 0, dy: fromView.frame.height)
let scaleFactor: CGFloat = 0.1
let deltaX = fromVc.contentBox.frame.width * (1-scaleFactor)
let deltaY = fromVc.contentBox.frame.height * (1-scaleFactor)
let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
fromVc.contentBox.transform = scale.translatedBy(x: -deltaX, y: deltaY/2.0)
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
}
| a902fc4b0a780712ab501cbc6a312d2a | 39.637255 | 170 | 0.701809 | false | false | false | false |
omiz/CarBooking | refs/heads/master | CarBooking/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// CarBooking
//
// Created by Omar Allaham on 10/18/17.
// Copyright © 2017 Omar Allaham. All rights reserved.
//
import UIKit
import Reachability
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
let reachability = Reachability()
var internetAlert: UIAlertController?
var tabBarController: TabBarController? {
return window?.rootViewController as? TabBarController
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
ThemeManager.apply()
setupReachability()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
guard response.notification.request.content.categoryIdentifier.starts(with: Booking.notificationId) else { return completionHandler() }
UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber - 1
let userInfo = response.notification.request.content.userInfo
guard let id = userInfo["id"] as? Int else { return completionHandler() }
goToBookingDetail(with: id)
completionHandler()
}
func goToBookingDetail(with id: Int) {
let item = tabBarController?.viewControllers?.enumerated().first(where: {
guard let controller = $0.element as? UINavigationController else { return false }
return controller.viewControllers.first is BookedVehiclesViewController
})
(item?.element as? UINavigationController)?.popToRootViewController(animated: true)
let index = item?.offset ?? 0
let controller = item?.element.childViewControllers.first as? BookedVehiclesViewController
tabBarController?.selectedIndex = index
let booking = controller?.dataSource.enumerated().first(where: { $0.element.id == id })
if let booking = booking {
controller?.showDetail(for: booking.element.id)
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
let identifier = Bundle.main.bundleIdentifier ?? ""
switch shortcutItem.type {
case identifier + ".allVehicles":
tabBarController?.showAllVehiclesTab()
case identifier + ".myBooking":
tabBarController?.showMyBookingsTab()
case identifier + ".contacts":
tabBarController?.showContactsTab()
default:
break
}
completionHandler(true)
}
func setupReachability() {
guard let reachability = reachability else { return }
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(_:)), name: .reachabilityChanged, object: reachability)
try? reachability.startNotifier()
}
@objc func reachabilityChanged(_ notification: Notification) {
guard let reachability = notification.object as? Reachability else { return }
switch reachability.connection {
case .wifi:
reachableInternet()
case .cellular:
reachableInternet()
case .none:
alertNoInternet()
}
}
func alertNoInternet() {
let alert = UIAlertController.init(title: "Alert".localized,
message: "Internet is lost.\nPlease check your internet connection!".localized, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .default, handler: nil))
window?.rootViewController?.present(alert, animated: true, completion: {
self.internetAlert = alert
})
}
func reachableInternet() {
internetAlert?.dismiss(animated: true)
}
}
| 2287571bc6bfb4ca081382f15e21253e | 38.777778 | 285 | 0.66077 | false | false | false | false |
eleneakhvlediani/GalleryLS | refs/heads/master | GalleryLS/Classes/INSPhotosTransitionAnimator.swift | mit | 1 | //
// INSPhotosTransitionAnimator.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class INSPhotosTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var playVideoDelegate: PlayVideoDelegate?
var dismissing: Bool = false
var startingView: UIView?
var endingView: UIView?
var startingViewForAnimation: UIView?
var endingViewForAnimation: UIView?
var animationDurationWithZooming = 0.5
var animationDurationWithoutZooming = 0.3
var animationDurationFadeRatio = 4.0 / 9.0 {
didSet(value) {
animationDurationFadeRatio = min(value, 1.0)
}
}
var animationDurationEndingViewFadeInRatio = 0.1 {
didSet(value) {
animationDurationEndingViewFadeInRatio = min(value, 1.0)
}
}
var animationDurationStartingViewFadeOutRatio = 0.05 {
didSet(value) {
animationDurationStartingViewFadeOutRatio = min(value, 1.0)
}
}
var zoomingAnimationSpringDamping = 0.9
var shouldPerformZoomingAnimation: Bool {
get {
return self.startingView != nil && self.endingView != nil
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if shouldPerformZoomingAnimation {
return animationDurationWithZooming
}
return animationDurationWithoutZooming
}
func fadeDurationForTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) -> TimeInterval {
if shouldPerformZoomingAnimation {
return transitionDuration(using: transitionContext) * animationDurationFadeRatio
}
return transitionDuration(using: transitionContext)
}
// MARK:- UIViewControllerAnimatedTransitioning
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
//self.playVideoDelegate?.startPlaying()
setupTransitionContainerHierarchyWithTransitionContext(transitionContext)
// There is issue with startingView frame when performFadeAnimation
// is called and prefersStatusBarHidden == true originY is moved 20px up,
// so order of this two methods is important! zooming need to be first than fading
if shouldPerformZoomingAnimation {
performZoomingAnimationWithTransitionContext(transitionContext)
}
performFadeAnimationWithTransitionContext(transitionContext)
}
func setupTransitionContainerHierarchyWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
if let toView = transitionContext.view(forKey: UITransitionContextViewKey.to),
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) {
toView.frame = transitionContext.finalFrame(for: toViewController)
let containerView = transitionContext.containerView
if !toView.isDescendant(of: containerView) {
containerView.addSubview(toView)
}
}
if dismissing {
if let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) {
transitionContext.containerView.bringSubview(toFront: fromView)
}
}
}
func performFadeAnimationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
let fadeView = dismissing ? transitionContext.view(forKey: UITransitionContextViewKey.from) : transitionContext.view(forKey: UITransitionContextViewKey.to)
let beginningAlpha: CGFloat = dismissing ? 1.0 : 1.0
let endingAlpha: CGFloat = dismissing ? 0.0 : 1.0
fadeView?.alpha = beginningAlpha
UIView.animate(withDuration: fadeDurationForTransitionContext(transitionContext), animations: { () -> Void in
fadeView?.alpha = endingAlpha
}) { finished in
if !self.shouldPerformZoomingAnimation {
self.completeTransitionWithTransitionContext(transitionContext)
}
}
}
func performZoomingAnimationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
// self.playVideoDelegate.initVideo(player: dataSource.photoAtIndex(0)?.video)
// self.playVideoDelegate?.startPlaying()
let containerView = transitionContext.containerView
guard let startingView = startingView, let endingView = endingView else {
return
}
guard let startingViewForAnimation = self.startingViewForAnimation ?? self.startingView?.ins_snapshotView(),
let endingViewForAnimation = self.endingViewForAnimation ?? self.endingView?.ins_snapshotView() else {
return
}
let finalEndingViewTransform = endingView.transform
let endingViewInitialTransform = startingViewForAnimation.frame.height / endingViewForAnimation.frame.height
let translatedStartingViewCenter = startingView.ins_translatedCenterPointToContainerView(containerView)
startingViewForAnimation.center = translatedStartingViewCenter
endingViewForAnimation.transform = endingViewForAnimation.transform.scaledBy(x: endingViewInitialTransform, y: endingViewInitialTransform)
endingViewForAnimation.center = translatedStartingViewCenter
endingViewForAnimation.alpha = 0.0
containerView.addSubview(startingViewForAnimation)
containerView.addSubview(endingViewForAnimation)
// Hide the original ending view and starting view until the completion of the animation.
endingView.alpha = 0.0
startingView.alpha = 0.0
let fadeInDuration = transitionDuration(using: transitionContext) * animationDurationEndingViewFadeInRatio
let fadeOutDuration = transitionDuration(using: transitionContext) * animationDurationStartingViewFadeOutRatio
// Ending view / starting view replacement animation
UIView.animate(withDuration: fadeInDuration, delay: 0.0, options: [.allowAnimatedContent,.beginFromCurrentState], animations: { () -> Void in
endingViewForAnimation.alpha = 1.0
}) { result in
UIView.animate(withDuration: fadeOutDuration, delay: 0.0, options: [.allowAnimatedContent,.beginFromCurrentState], animations: { () -> Void in
startingViewForAnimation.alpha = 0.0
}, completion: { result in
startingViewForAnimation.removeFromSuperview()
})
}
let startingViewFinalTransform = 1.0 / endingViewInitialTransform
let translatedEndingViewFinalCenter = endingView.ins_translatedCenterPointToContainerView(containerView)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping:CGFloat(zoomingAnimationSpringDamping), initialSpringVelocity:0, options: [.allowAnimatedContent,.beginFromCurrentState], animations: { () -> Void in
endingViewForAnimation.transform = finalEndingViewTransform
endingViewForAnimation.center = translatedEndingViewFinalCenter
startingViewForAnimation.transform = startingViewForAnimation.transform.scaledBy(x: startingViewFinalTransform, y: startingViewFinalTransform)
startingViewForAnimation.center = translatedEndingViewFinalCenter
}) { result in
endingViewForAnimation.removeFromSuperview()
endingView.alpha = 1.0
startingView.alpha = 1.0
self.completeTransitionWithTransitionContext(transitionContext)
}
}
func completeTransitionWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
if transitionContext.isInteractive {
if transitionContext.transitionWasCancelled {
transitionContext.cancelInteractiveTransition()
} else {
transitionContext.finishInteractiveTransition()
}
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
| 41a2596ae32ede8a0df1c10f131edeb2 | 45.28866 | 267 | 0.70657 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.