repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gumbright/UIXRangeSlider
|
UIXRangeSlider/UIXRangeSlider.swift
|
1
|
23822
|
//
// UIXRangeSlider.swift
// UIXRangeSlider
//
// Created by Guy Umbright on 8/18/16.
// Copyright © 2016 Umbright Consulting, Inc. All rights reserved.
//
import UIKit
@IBDesignable class UIXRangeSlider: UIControl
{
override var enabled : Bool
{
didSet {
updateAllElements()
}
}
var barHeight : CGFloat = 2.0
{
didSet {
self.updateImageForElement(.InactiveBar)
self.updateImageForElement(.ActiveBar)
}
}
/////////////////////////////////////////////////////
// Component views
/////////////////////////////////////////////////////
var inactiveBarView:UIImageView = UIImageView()
var activeBarView:UIImageView = UIImageView()
var leftThumbView:UIImageView = UIImageView()
var rightThumbView:UIImageView = UIImageView()
var middleThumbView:UIImageView = UIImageView()
/////////////////////////////////////////////////////
// Values
/////////////////////////////////////////////////////
@IBInspectable var minimumValue:Float = 0.0
{
didSet {
if (minimumValue > maximumValue)
{
minimumValue = maximumValue
}
self.setNeedsLayout()
}
}
@IBInspectable var maximumValue:Float = 1.0
{
didSet {
if (maximumValue < minimumValue)
{
maximumValue = minimumValue
}
self.setNeedsLayout()
}
}
@IBInspectable var leftValue:Float = 0.3
{
didSet {
if (leftValue <= self.minimumValue)
{
leftValue = self.minimumValue
}
self.setNeedsLayout()
}
}
@IBInspectable var rightValue:Float = 0.7
{
didSet {
if (rightValue >= self.maximumValue)
{
rightValue = self.maximumValue
}
self.setNeedsLayout()
}
}
/////////////////////////////////////////////////////
// Tracking
/////////////////////////////////////////////////////
enum ElementTracked
{
case None
case LeftThumb
case MiddleThumb
case RightThumb
}
var trackedElement = ElementTracked.None
var movingLeftThumb : Bool = false
var movingMiddleThumb : Bool = false
var movingRightThumb : Bool = false
var previousLocation : CGPoint!
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
override init(frame: CGRect)
{
super.init(frame: frame)
self.commonInit()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
required init?(coder: NSCoder)
{
super.init(coder: coder)
self.commonInit()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
override func awakeFromNib()
{
self.commonInit()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func commonInit()
{
setTint(UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0), forElement: .ActiveBar, forControlState: .Normal)
self.configureDefaultLeftThumbView(self.leftThumbView)
self.configureDefaultRightThumbView(self.rightThumbView)
self.configureDefaultActiveBarView(self.activeBarView)
self.configureDefaultInactiveBarView(self.inactiveBarView)
self.configureDefaultMiddleThumbView(self.middleThumbView)
self.allocateDefaultViews()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func allocateDefaultViews()
{
self.orderSubviews()
self.setNeedsLayout()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func orderSubviews()
{
for view in self.subviews as [UIView]
{
view.removeFromSuperview()
}
self.addSubview(self.inactiveBarView)
self.addSubview(self.leftThumbView)
self.addSubview(self.middleThumbView)
self.addSubview(self.rightThumbView)
self.addSubview(self.activeBarView)
}
enum UIXRangeSliderElement : UInt {
case LeftThumb = 0
case RightThumb
case MiddleThumb
case ActiveBar
case InactiveBar
}
typealias stateImageDictionary = [UInt : UIImage]
var elementImages : [UInt : stateImageDictionary] = [:]
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func stateImageDictionaryForElement(element : UIXRangeSliderElement) -> stateImageDictionary?
{
return elementImages[element.rawValue]
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func setImage(image : UIImage?, forElement element : UIXRangeSliderElement, forControlState state :UIControlState)
{
var dict = self.stateImageDictionaryForElement(element)
if (dict == nil)
{
dict = stateImageDictionary()
elementImages[element.rawValue] = dict
}
elementImages[element.rawValue]![state.rawValue] = image
//dict![state.rawValue] = image
self.updateImageForElement(element)
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func image(forElement element: UIXRangeSliderElement, forState state :UIControlState) -> UIImage?
{
var result : UIImage? = nil
if let imageDict = self.stateImageDictionaryForElement(element)
{
result = imageDict[state.rawValue]
}
return result
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func imageForCurrentState(element : UIXRangeSliderElement) -> UIImage?
{
let image : UIImage? = self.image(forElement: element, forState: self.state) ?? self.image(forElement: element, forState: .Normal)
return image
}
typealias stateTintDictionary = [UInt : UIColor]
var elementTints : [UInt : stateTintDictionary] = [:]
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func stateTintDictionaryForElement(element : UIXRangeSliderElement) -> stateTintDictionary?
{
return elementTints[element.rawValue]
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func setTint(tint : UIColor, forElement element : UIXRangeSliderElement, forControlState state :UIControlState)
{
var dict = self.stateTintDictionaryForElement(element)
if (dict == nil)
{
dict = stateTintDictionary()
elementTints[element.rawValue] = dict
}
elementTints[element.rawValue]![state.rawValue] = tint
self.updateImageForElement(element)
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func tint(forElement element: UIXRangeSliderElement, forState state :UIControlState) -> UIColor?
{
var result : UIColor? = nil
if let tintDict = self.stateTintDictionaryForElement(element)
{
result = tintDict[state.rawValue]
}
return result
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func tintForCurrentState(element : UIXRangeSliderElement) -> UIColor
{
let color = self.tint(forElement: element, forState: self.state) ?? self.tint(forElement: element, forState: .Normal)
return color ?? UIColor.grayColor()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func updateAllElements()
{
updateImageForElement(.LeftThumb)
updateImageForElement(.RightThumb)
updateImageForElement(.MiddleThumb)
updateImageForElement(.ActiveBar)
updateImageForElement(.InactiveBar)
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func updateImageForElement(element : UIXRangeSliderElement)
{
let state = self.enabled ? UIControlState.Normal : UIControlState.Disabled
switch element
{
case .LeftThumb:
self.leftThumbView.image = imageForCurrentState(element)
if self.leftThumbView.image == nil
{
self.configureDefaultLeftThumbView(self.leftThumbView)
}
else
{
if let sublayers = self.leftThumbView.layer.sublayers
{
for layer in sublayers
{
layer.removeFromSuperlayer()
}
}
}
self.leftThumbView.tintColor = tint(forElement: element, forState: state)
self.setNeedsLayout()
case .RightThumb:
self.rightThumbView.image = imageForCurrentState(element)
if self.rightThumbView.image == nil
{
self.configureDefaultRightThumbView(self.rightThumbView)
}
else
{
if let sublayers = self.rightThumbView.layer.sublayers
{
for layer in sublayers
{
layer.removeFromSuperlayer()
}
}
}
self.rightThumbView.tintColor = tint(forElement: element, forState: state)
self.setNeedsLayout()
case .MiddleThumb:
self.middleThumbView.image = imageForCurrentState(element)
if self.middleThumbView.image == nil
{
self.configureDefaultMiddleThumbView(self.middleThumbView)
}
else
{
self.middleThumbView.backgroundColor = UIColor.clearColor()
self.middleThumbView.frame = CGRectMake(0,0, self.middleThumbView.image!.size.width, self.middleThumbView.image!.size.height)
}
self.middleThumbView.tintColor = tint(forElement: element, forState: state)
self.setNeedsLayout()
case .ActiveBar:
self.activeBarView.image = imageForCurrentState(element)
if self.activeBarView.image == nil
{
self.configureDefaultActiveBarView(self.activeBarView)
}
else
{
self.activeBarView.backgroundColor = UIColor.clearColor()
self.activeBarView.frame = CGRectMake(0,0, self.activeBarView.image!.size.width, self.activeBarView.image!.size.height)
}
self.activeBarView.tintColor = tint(forElement: element, forState: state)
self.setNeedsLayout()
case .InactiveBar:
self.inactiveBarView.image = imageForCurrentState(element)
if self.inactiveBarView.image == nil
{
self.configureDefaultInactiveBarView(self.inactiveBarView)
}
else
{
self.inactiveBarView.backgroundColor = UIColor.clearColor()
self.inactiveBarView.frame = CGRectMake(0,0, self.inactiveBarView.image!.size.width, self.inactiveBarView.image!.size.height)
}
self.inactiveBarView.tintColor = tint(forElement: element, forState: state)
self.setNeedsLayout()
}
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func currentLeftThumbImage() -> UIImage?
{
return leftThumbView.image!;
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func currentRightThumbImage() -> UIImage?
{
return rightThumbView.image!;
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func currentMiddleThumbImage() -> UIImage?
{
return middleThumbView.image!;
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func currentActiveBarImage() -> UIImage?
{
return activeBarView.image!;
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func currentInactiveBarImage() -> UIImage?
{
return inactiveBarView.image!;
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
override func layoutSubviews()
{
let viewCenter = self.convertPoint(self.center, fromView: self.superview)
self.inactiveBarView.center.y = viewCenter.y
var frame = self.inactiveBarView.frame
frame.origin.x = self.leftThumbView.frame.width
frame.size.width = self.bounds.width - (self.leftThumbView.bounds.width + self.rightThumbView.bounds.width)
self.inactiveBarView.frame = frame
self.leftThumbView.center.y = viewCenter.y
self.positionLeftThumb()
self.rightThumbView.center.y = viewCenter.y
self.positionRightThumb()
self.middleThumbView.center.y = viewCenter.y
frame = self.middleThumbView.frame
frame.origin.x = CGRectGetMaxX(self.leftThumbView.frame)
frame.size.width = CGRectGetMinX(self.rightThumbView.frame) - frame.origin.x
self.middleThumbView.frame = frame
self.activeBarView.center.y = viewCenter.y
frame = self.activeBarView.frame
frame.origin.x = CGRectGetMaxX(self.leftThumbView.frame)
frame.size.width = CGRectGetMinX(self.rightThumbView.frame) - frame.origin.x
self.activeBarView.frame = frame
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func positionLeftThumb()
{
let pos = positionForValue(self.leftValue)
var frame = self.leftThumbView.frame
frame.origin.x = CGFloat(pos - self.leftThumbView.bounds.width)
self.leftThumbView.frame = frame;
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func positionRightThumb()
{
let pos = CGFloat(positionForValue(self.rightValue))
var frame = self.rightThumbView.frame
frame.origin.x = CGFloat(pos)
self.rightThumbView.frame = frame;
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func positionForValue(value:Float) -> CGFloat
{
let pos = Float(self.inactiveBarView.frame.width) * (value - self.minimumValue) / (self.maximumValue - self.minimumValue) + Float(self.inactiveBarView.frame.origin.x)
return CGFloat(pos)
}
}
// MARK: -- Tracking --
extension UIXRangeSlider
{
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool
{
previousLocation = touch.locationInView(self)
// Hit test the thumb layers
if leftThumbView.frame.contains(previousLocation)
{
trackedElement = .LeftThumb
}
else if rightThumbView.frame.contains(previousLocation)
{
trackedElement = .RightThumb
}
else if middleThumbView.frame.contains(previousLocation)
{
trackedElement = .MiddleThumb
}
return trackedElement != .None
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool
{
let location = touch.locationInView(self)
// 1. Determine by how much the user has dragged
let deltaLocation = Double(location.x - previousLocation.x)
let deltaValue = (Double(maximumValue) - Double(minimumValue)) * deltaLocation / Double(bounds.width /*- thumbWidth*/)
switch trackedElement
{
case .LeftThumb:
handleLeftThumbMove(location, delta: deltaValue)
case .MiddleThumb:
handleMiddleThumbMove(location, delta: deltaValue)
case .RightThumb:
handleRightThumbMove(location, delta: deltaValue)
default:
break
}
previousLocation = location
return true
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func handleLeftThumbMove(location:CGPoint, delta:Double)
{
let translation = CGPointMake(location.x - previousLocation.x,location.y - previousLocation.y)
let range = self.maximumValue - self.minimumValue
let availableWidth = self.inactiveBarView.frame.width
let newValue = self.leftValue + Float(translation.x) / Float(availableWidth) * range
self.leftValue = newValue
if (self.leftValue < minimumValue)
{
self.leftValue = minimumValue
}
if (self.leftValue > self.rightValue)
{
self.leftValue = self.rightValue
}
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
self.setNeedsLayout()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func handleMiddleThumbMove(location:CGPoint, delta:Double)
{
let translation = CGPointMake(location.x - previousLocation.x,location.y - previousLocation.y)
let range = self.maximumValue - self.minimumValue
let availableWidth = self.inactiveBarView.frame.width
let diff = self.rightValue - self.leftValue
let newLeftValue = self.leftValue + Float(translation.x) / Float(availableWidth) * range
if (newLeftValue < minimumValue)
{
self.leftValue = self.minimumValue
self.rightValue = self.leftValue + diff
}
else
{
let newRightValue = self.rightValue + Float(translation.x) / Float(availableWidth) * range
if (newRightValue > self.maximumValue)
{
self.rightValue = self.maximumValue
self.leftValue = self.rightValue - diff
}
else
{
self.leftValue = newLeftValue
self.rightValue = self.leftValue + diff
}
}
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
self.setNeedsLayout()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
func handleRightThumbMove(location:CGPoint, delta:Double)
{
let translation = CGPointMake(location.x - previousLocation.x,location.y - previousLocation.y)
let range = self.maximumValue - self.minimumValue
let availableWidth = self.inactiveBarView.frame.width
let newValue = self.rightValue + Float(translation.x) / Float(availableWidth) * range
self.rightValue = newValue
if (self.rightValue > self.maximumValue)
{
self.rightValue = self.maximumValue
}
if (self.rightValue < self.leftValue)
{
self.rightValue = self.leftValue
}
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
self.setNeedsLayout()
}
/////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////
override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?)
{
trackedElement = .None
}
}
// MARK: -- DefaultViews --
extension UIXRangeSlider
{
func configureDefaultLeftThumbView(view : UIImageView)
{
view.image = nil
view.frame = CGRectMake(0, 0, 27, 27)
let path = UIBezierPath(arcCenter: CGPointMake(27.0, 13.5), radius: CGFloat(13.5), startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(M_PI*1.5), clockwise: true)
path.closePath()
let layer = CAShapeLayer()
layer.path = path.CGPath
layer.fillColor = UIColor.whiteColor().CGColor
layer.strokeColor = UIColor.lightGrayColor().CGColor
layer.lineWidth = 0.25
layer.shadowOpacity = 0.25
layer.shadowOffset = CGSizeMake(-3.0, 4.0)
layer.shadowColor = UIColor.grayColor().CGColor
layer.shadowRadius = 2.0
view.layer.addSublayer(layer)
view.userInteractionEnabled = false
view.tintColor = UIColor.grayColor()
}
func configureDefaultRightThumbView(view : UIImageView)
{
view.image = nil
view.frame = CGRectMake(0, 0, 27, 27)
let path = UIBezierPath(arcCenter: CGPointMake(0.0, 13.5), radius: CGFloat(13.5), startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(M_PI*1.5), clockwise: false)
path.closePath()
let layer = CAShapeLayer()
layer.path = path.CGPath
layer.fillColor = UIColor.whiteColor().CGColor
layer.strokeColor = UIColor.lightGrayColor().CGColor
layer.lineWidth = 0.25
layer.shadowOpacity = 0.25
layer.shadowOffset = CGSizeMake(3.0, 4.0)
layer.shadowColor = UIColor.grayColor().CGColor
view.layer.addSublayer(layer)
view.userInteractionEnabled = false
}
func configureDefaultMiddleThumbView(view : UIImageView)
{
view.image = nil
view.frame = CGRectMake(0, 0, 1, 27)
view.backgroundColor = self.tintForCurrentState(.MiddleThumb)
view.layer.opacity = 0.5
view.layer.shadowOpacity = 0.25
view.layer.shadowOffset = CGSizeMake(0.0, 4.0)
view.layer.shadowColor = UIColor.grayColor().CGColor
view.layer.shadowRadius = 2.0
view.userInteractionEnabled = false
}
func configureDefaultActiveBarView(view : UIImageView)
{
view.image = nil
view.frame = CGRectMake(0, 0, 2, self.barHeight)
view.backgroundColor = self.tintForCurrentState(.ActiveBar)
view.userInteractionEnabled = false
}
func configureDefaultInactiveBarView(view : UIImageView)
{
view.image = nil
view.frame = CGRectMake(0, 0, 2, self.barHeight)
view.backgroundColor = self.tintForCurrentState(.InactiveBar)
view.userInteractionEnabled = false
}
}
|
mit
|
f328e2e8afef08f823b19f4c1beed8da
| 32.788652 | 175 | 0.500651 | 5.498846 | false | false | false | false |
Stitch7/mclient
|
mclient/PrivateMessages/_MessageKit/Models/LocationMessageSnapshotOptions.swift
|
1
|
2789
|
/*
MIT License
Copyright (c) 2017-2018 MessageKit
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 MapKit
/// An object grouping the settings used by the `MKMapSnapshotter` through the `LocationMessageDisplayDelegate`.
public struct LocationMessageSnapshotOptions {
/// Initialize LocationMessageSnapshotOptions with given parameters
///
/// - Parameters:
/// - showsBuildings: A Boolean value indicating whether the snapshot image should display buildings.
/// - showsPointsOfInterest: A Boolean value indicating whether the snapshot image should display points of interest.
/// - span: The span of the snapshot.
/// - scale: The scale of the snapshot.
public init(showsBuildings: Bool = false, showsPointsOfInterest: Bool = false, span: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0, longitudeDelta: 0), scale: CGFloat = UIScreen.main.scale) {
self.showsBuildings = showsBuildings
self.showsPointsOfInterest = showsPointsOfInterest
self.span = span
self.scale = scale
}
/// A Boolean value indicating whether the snapshot image should display buildings.
///
/// The default value of this property is `false`.
public var showsBuildings: Bool
/// A Boolean value indicating whether the snapshot image should display points of interest.
///
/// The default value of this property is `false`.
public var showsPointsOfInterest: Bool
/// The span of the snapshot.
///
/// The default value of this property uses a width of `0` and height of `0`.
public var span: MKCoordinateSpan
/// The scale of the snapshot.
///
/// The default value of this property uses the `UIScreen.main.scale`.
public var scale: CGFloat
}
|
mit
|
fb5ca333c197dbde829deb42b08c7048
| 42.578125 | 202 | 0.732162 | 4.945035 | false | false | false | false |
Kushki/kushki-ios
|
Kushki/Classes/Struct/MerchantSettings.swift
|
2
|
1379
|
import Foundation
struct MerchantSettings: Decodable {
var processors: ProcessorSettings?
var processorName: String?
var country: String?
var sandboxBaconKey: String?
var prodBaconKey: String?
var merchantName: String?
var sandboxAccountId: String?
var prodAccountId: String?
var code: String?
var message: String?
enum CodingKeys: String, CodingKey {
case processors
case processorName = "processor_name"
case country
case sandboxBaconKey
case prodBaconKey
case merchantName = "merchant_name"
case sandboxAccountId
case prodAccountId
case code
case message
}
}
struct ProcessorSettings: Decodable {
var card: [ProcessorName]?
var cash: [ProcessorName]?
var transfer: [ProcessorName]?
var payoutsCash: [ProcessorName]?
var payoutsTransfer: [ProcessorName]?
var achTransfer: [[String: String]]?
var transferSubscriptions: [[String: String]]?
enum CodingKeys: String, CodingKey {
case card
case cash
case transfer
case payoutsCash = "payouts-cash"
case payoutsTransfer = "payouts-transfer"
case achTransfer = "ach transfer"
case transferSubscriptions = "transfer-subscriptions"
}
}
struct ProcessorName: Decodable {
let processorName: String
}
|
mit
|
f2823a22fe0b9d1d2c15deb25c000847
| 26.039216 | 61 | 0.663524 | 4.658784 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
swift/example_code/iam/CreateServiceLinkedRole/Sources/ServiceHandler/ServiceHandler.swift
|
1
|
3172
|
/*
A class containing functions that interact with AWS services.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// snippet-start:[iam.swift.createservicelinkedrole.handler]
// snippet-start:[iam.swift.createservicelinkedrole.handler.imports]
import Foundation
import AWSIAM
import ClientRuntime
import AWSClientRuntime
// snippet-end:[iam.swift.createservicelinkedrole.handler.imports]
// snippet-start:[iam.swift.createservicelinkedrole.enum.service-error]
/// Errors returned by `ServiceHandler` functions.
enum ServiceHandlerError: Error {
case noSuchUser /// No matching user found.
case noSuchRole /// No matching role found, or unable to create the role.
}
// snippet-end:[iam.swift.createservicelinkedrole.enum.service-error]
/// A class containing all the code that interacts with the AWS SDK for Swift.
public class ServiceHandler {
public let client: IamClient
/// Initialize and return a new ``ServiceHandler`` object, which is used
/// to drive the AWS calls used for the example. The Region string
/// `AWS_GLOBAL` is used because users are shared across all Regions.
///
/// - Returns: A new ``ServiceHandler`` object, ready to be called to
/// execute AWS operations.
// snippet-start:[iam.swift.createservicelinkedrole.handler.init]
public init() async {
do {
client = try IamClient(region: "AWS_GLOBAL")
} catch {
print("ERROR: ", dump(error, name: "Initializing Amazon IAM client"))
exit(1)
}
}
// snippet-end:[iam.swift.createservicelinkedrole.handler.init]
/// Create a new AWS Identity and Access Management (IAM) role.
///
/// - Parameters:
/// - service: The name of the service to link the new role to.
/// - suffix: A suffix string to append to the service name to use as
/// the new role's name.
/// - description: An optional `String` describing the new role.
///
/// - Returns: A `IamClientTypes.Role` object describing the new role.
///
/// The `service` parameter should be a string derived that looks like a
/// URL but has no `http://` at the beginning, such as
/// `elasticbeanstalk.amazonaws.com`.
// snippet-start:[iam.swift.createservicelinkedrole.handler.createservicelinkedrole]
public func createServiceLinkedRole(service: String, suffix: String? = nil, description: String?)
async throws -> IamClientTypes.Role {
let input = CreateServiceLinkedRoleInput(
aWSServiceName: service,
customSuffix: suffix,
description: description
)
do {
let output = try await client.createServiceLinkedRole(input: input)
guard let role = output.role else {
throw ServiceHandlerError.noSuchRole
}
return role
} catch {
throw error
}
}
// snippet-end:[iam.swift.createservicelinkedrole.handler.createservicelinkedrole]
}
// snippet-end:[iam.swift.createservicelinkedrole.handler]
|
apache-2.0
|
5f5321afa20862f7e8ac319617d86a38
| 39.151899 | 101 | 0.664565 | 4.119481 | false | false | false | false |
JoMo1970/cordova-plugin-qrcode-reader
|
src/ios/SwitchCameraButton.swift
|
6
|
7293
|
/*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.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 camera switch button.
@IBDesignable
public final class SwitchCameraButton: UIButton {
@IBInspectable var edgeColor: UIColor = UIColor.white {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var fillColor: UIColor = UIColor.darkGray {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var edgeHighlightedColor: UIColor = UIColor.white
@IBInspectable var fillHighlightedColor: UIColor = UIColor.black
public override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
let center = width / 2
let middle = height / 2
let strokeLineWidth = CGFloat(2)
// Colors
let paintColor = (self.state != .highlighted) ? fillColor : fillHighlightedColor
let strokeColor = (self.state != .highlighted) ? edgeColor : edgeHighlightedColor
// Camera box
let cameraWidth = width * 0.4
let cameraHeight = cameraWidth * 0.6
let cameraX = center - cameraWidth / 2
let cameraY = middle - cameraHeight / 2
let cameraRadius = cameraWidth / 80
let boxPath = UIBezierPath(roundedRect: CGRect(x: cameraX, y: cameraY, width: cameraWidth, height: cameraHeight), cornerRadius: cameraRadius)
// Camera lens
let outerLensSize = cameraHeight * 0.8
let outerLensX = center - outerLensSize / 2
let outerLensY = middle - outerLensSize / 2
let innerLensSize = outerLensSize * 0.7
let innerLensX = center - innerLensSize / 2
let innerLensY = middle - innerLensSize / 2
let outerLensPath = UIBezierPath(ovalIn: CGRect(x: outerLensX, y: outerLensY, width: outerLensSize, height: outerLensSize))
let innerLensPath = UIBezierPath(ovalIn: CGRect(x: innerLensX, y: innerLensY, width: innerLensSize, height: innerLensSize))
// Draw flash box
let flashBoxWidth = cameraWidth * 0.8
let flashBoxHeight = cameraHeight * 0.17
let flashBoxDeltaWidth = flashBoxWidth * 0.14
let flashLeftMostX = cameraX + (cameraWidth - flashBoxWidth) * 0.5
let flashBottomMostY = cameraY
let flashPath = UIBezierPath()
flashPath.move(to: CGPoint(x: flashLeftMostX, y: flashBottomMostY))
flashPath.addLine(to: CGPoint(x: flashLeftMostX + flashBoxWidth, y: flashBottomMostY))
flashPath.addLine(to: CGPoint(x: flashLeftMostX + flashBoxWidth - flashBoxDeltaWidth, y: flashBottomMostY - flashBoxHeight))
flashPath.addLine(to: CGPoint(x: flashLeftMostX + flashBoxDeltaWidth, y: flashBottomMostY - flashBoxHeight))
flashPath.close()
flashPath.lineCapStyle = .round
flashPath.lineJoinStyle = .round
// Arrows
let arrowHeadHeigth = cameraHeight * 0.5
let arrowHeadWidth = ((width - cameraWidth) / 2) * 0.3
let arrowTailHeigth = arrowHeadHeigth * 0.6
let arrowTailWidth = ((width - cameraWidth) / 2) * 0.7
// Draw left arrow
let arrowLeftX = center - cameraWidth * 0.2
let arrowLeftY = middle + cameraHeight * 0.45
let leftArrowPath = UIBezierPath()
leftArrowPath.move(to: CGPoint(x: arrowLeftX, y: arrowLeftY))
leftArrowPath.addLine(to: CGPoint(x: arrowLeftX - arrowHeadWidth, y: arrowLeftY - arrowHeadHeigth / 2))
leftArrowPath.addLine(to: CGPoint(x: arrowLeftX - arrowHeadWidth, y: arrowLeftY - arrowTailHeigth / 2))
leftArrowPath.addLine(to: CGPoint(x: arrowLeftX - arrowHeadWidth - arrowTailWidth, y: arrowLeftY - arrowTailHeigth / 2))
leftArrowPath.addLine(to: CGPoint(x: arrowLeftX - arrowHeadWidth - arrowTailWidth, y: arrowLeftY + arrowTailHeigth / 2))
leftArrowPath.addLine(to: CGPoint(x: arrowLeftX - arrowHeadWidth, y: arrowLeftY + arrowTailHeigth / 2))
leftArrowPath.addLine(to: CGPoint(x: arrowLeftX - arrowHeadWidth, y: arrowLeftY + arrowHeadHeigth / 2))
// Right arrow
let arrowRightX = center + cameraWidth * 0.2
let arrowRightY = middle + cameraHeight * 0.60
let rigthArrowPath = UIBezierPath()
rigthArrowPath.move(to: CGPoint(x: arrowRightX, y: arrowRightY))
rigthArrowPath.addLine(to: CGPoint(x: arrowRightX + arrowHeadWidth, y: arrowRightY - arrowHeadHeigth / 2))
rigthArrowPath.addLine(to: CGPoint(x: arrowRightX + arrowHeadWidth, y: arrowRightY - arrowTailHeigth / 2))
rigthArrowPath.addLine(to: CGPoint(x: arrowRightX + arrowHeadWidth + arrowTailWidth, y: arrowRightY - arrowTailHeigth / 2))
rigthArrowPath.addLine(to: CGPoint(x: arrowRightX + arrowHeadWidth + arrowTailWidth, y: arrowRightY + arrowTailHeigth / 2))
rigthArrowPath.addLine(to: CGPoint(x: arrowRightX + arrowHeadWidth, y: arrowRightY + arrowTailHeigth / 2))
rigthArrowPath.addLine(to: CGPoint(x: arrowRightX + arrowHeadWidth, y: arrowRightY + arrowHeadHeigth / 2))
rigthArrowPath.close()
// Drawing
paintColor.setFill()
rigthArrowPath.fill()
strokeColor.setStroke()
rigthArrowPath.lineWidth = strokeLineWidth
rigthArrowPath.stroke()
paintColor.setFill()
boxPath.fill()
strokeColor.setStroke()
boxPath.lineWidth = strokeLineWidth
boxPath.stroke()
strokeColor.setFill()
outerLensPath.fill()
paintColor.setFill()
innerLensPath.fill()
paintColor.setFill()
flashPath.fill()
strokeColor.setStroke()
flashPath.lineWidth = strokeLineWidth
flashPath.stroke()
leftArrowPath.close()
paintColor.setFill()
leftArrowPath.fill()
strokeColor.setStroke()
leftArrowPath.lineWidth = strokeLineWidth
leftArrowPath.stroke()
}
// MARK: - UIResponder Methods
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
setNeedsDisplay()
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
setNeedsDisplay()
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
setNeedsDisplay()
}
public override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
super.touchesCancelled(touches!, with: event)
setNeedsDisplay()
}
}
|
mit
|
be5db82462e6df1682c7824b8cc25cde
| 38.209677 | 145 | 0.717674 | 4.029282 | false | false | false | false |
TheInfiniteKind/duckduckgo-iOS
|
Core/URLExtension.swift
|
1
|
2805
|
//
// URLExtension.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 25/01/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import Foundation
extension URL {
private static let webUrlRegex = "^(https?:\\/\\/)?([\\da-z\\.-]+\\.[a-z\\.]{2,6}|[\\d\\.]+)([\\/:?=&#]{1}[\\da-z\\.-]+)*[\\/\\?]?$"
public func getParam(name: String) -> String? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return nil }
guard let query = components.queryItems else { return nil }
return query.filter({ (item) in item.name == name }).first?.value
}
public func addParam(name: String, value: String?) -> URL {
let clearedUrl = removeParam(name: name)
guard var components = URLComponents(url: clearedUrl, resolvingAgainstBaseURL: false) else { return self }
var query = components.queryItems ?? [URLQueryItem]()
query.append(URLQueryItem(name: name, value: value))
components.queryItems = query
return components.url ?? self
}
public func addParams(_ params: [URLQueryItem]) -> URL {
var url = self
for param in params {
url = url.addParam(name: param.name, value: param.value)
}
return url
}
public func removeParam(name: String) -> URL {
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return self }
guard var query = components.queryItems else { return self }
for (index, param) in query.enumerated() {
if param.name == name {
query.remove(at: index)
}
}
components.queryItems = query
return components.url ?? self
}
public static func webUrl(fromText text: String) -> URL? {
guard isWebUrl(text: text) else {
return nil
}
let urlText = text.hasPrefix("http") ? text : appendScheme(path: text)
return URL(string: urlText)
}
public static func isWebUrl(text: String) -> Bool {
let pattern = webUrlRegex
let webRegex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = webRegex.matches(in: text, options: .anchored, range:NSMakeRange(0, text.characters.count))
return matches.count == 1
}
private static func appendScheme(path: String) -> String {
return "http://\(path)"
}
public static func encode(queryText: String) -> String? {
return queryText.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
}
public static func decode(query: String) -> String? {
return query.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
}
}
|
apache-2.0
|
b2eea2a02611bd894cac5124d394e00f
| 35.894737 | 136 | 0.61127 | 4.436709 | false | false | false | false |
rharri/swift-ios
|
CityDetail/CityDetail/MasterViewController.swift
|
1
|
2400
|
//
// MasterViewController.swift
// CityDetail
//
// Created by Ryan Harri on 2016-05-03.
// Copyright © 2016 Ryan Harri. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var cities = [City]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Cities"
let toronto = City(name: "Toronto", country: "Canada", population: 2615060, grossDomesticProduct: 276.3, url: "http://www.toronto.com", image: UIImage(named: "City Blue"))
let montreal = City(name: "Montreal", country: "Canada", population: 1649519, grossDomesticProduct: 155.9, url: "http://www.ville.montreal.qc.ca/", image: UIImage(named: "City Red"))
let vancouver = City(name: "Vancouver", country: "Canada", population: 603502, grossDomesticProduct: 109.8, url: "http://vancouver.ca/", image: UIImage(named: "City Green"))
cities.append(toronto)
cities.append(montreal)
cities.append(vancouver)
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let detailNavigationViewController = segue.destinationViewController as! UINavigationController
let controller = detailNavigationViewController.topViewController as! DetailViewController
let city = cities[indexPath.row]
controller.city = city
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let city = cities[indexPath.row]
cell.textLabel?.text = city.name
return cell
}
}
|
mit
|
51fb0a2081b7180ad37ac3c6f7af8718
| 37.079365 | 190 | 0.657774 | 4.750495 | false | false | false | false |
jhihguan/JSON2Realm
|
Pods/Argo/Argo/Types/JSON.swift
|
6
|
2372
|
import Foundation
/// A type safe representation of JSON.
public enum JSON {
case Object([Swift.String: JSON])
case Array([JSON])
case String(Swift.String)
case Number(NSNumber)
case Bool(Swift.Bool)
case Null
}
public extension JSON {
/**
Transform an `AnyObject` instance into `JSON`.
This is used to move from a loosely typed object (like those returned from
`NSJSONSerialization`) to the strongly typed `JSON` tree structure.
- parameter json: A loosely typed object
*/
init(_ json: AnyObject) {
switch json {
case let v as [AnyObject]:
self = .Array(v.map(JSON.init))
case let v as [Swift.String: AnyObject]:
self = .Object(v.map(JSON.init))
case let v as Swift.String:
self = .String(v)
case let v as NSNumber:
if v.isBool {
self = .Bool(v as Swift.Bool)
} else {
self = .Number(v)
}
default:
self = .Null
}
}
}
extension JSON: Decodable {
/**
Decode `JSON` into `Decoded<JSON>`.
This simply wraps the provided `JSON` in `.Success`. This is useful because
it means we can use `JSON` values with the `<|` family of operators to pull
out sub-keys.
- parameter j: The `JSON` value to decode
- returns: The provided `JSON` wrapped in `.Success`
*/
public static func decode(j: JSON) -> Decoded<JSON> {
return pure(j)
}
}
extension JSON: CustomStringConvertible {
public var description: Swift.String {
switch self {
case let .String(v): return "String(\(v))"
case let .Number(v): return "Number(\(v))"
case let .Bool(v): return "Bool(\(v))"
case let .Array(a): return "Array(\(a.description))"
case let .Object(o): return "Object(\(o.description))"
case .Null: return "Null"
}
}
}
extension JSON: Equatable { }
public func == (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case let (.String(l), .String(r)): return l == r
case let (.Number(l), .Number(r)): return l == r
case let (.Bool(l), .Bool(r)): return l == r
case let (.Array(l), .Array(r)): return l == r
case let (.Object(l), .Object(r)): return l == r
case (.Null, .Null): return true
default: return false
}
}
/// MARK: Deprecations
extension JSON {
@available(*, deprecated=3.0, renamed="init")
static func parse(json: AnyObject) -> JSON {
return JSON(json)
}
}
|
mit
|
1a97101d27ba8d4f9139fd96b3fd8871
| 23.204082 | 79 | 0.620152 | 3.583082 | false | false | false | false |
tidepool-org/nutshell-ios
|
Nutshell/ViewControllers/MenuAccountSettingsViewController.swift
|
1
|
10841
|
//
// MenuAccountSettingsViewController.swift
// Nutshell
//
// Created by Larry Kenyon on 9/14/15.
// Copyright © 2015 Tidepool. All rights reserved.
//
import UIKit
import CocoaLumberjack
class MenuAccountSettingsViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var loginAccount: UILabel!
@IBOutlet weak var versionString: NutshellUILabel!
@IBOutlet weak var usernameLabel: NutshellUILabel!
@IBOutlet weak var sidebarView: UIView!
@IBOutlet weak var healthKitSwitch: UISwitch!
@IBOutlet weak var healthKitLabel: NutshellUILabel!
@IBOutlet weak var healthStatusContainerView: UIStackView!
@IBOutlet weak var healthStatusLine1: UILabel!
@IBOutlet weak var healthStatusLine2: UILabel!
@IBOutlet weak var healthStatusLine3: UILabel!
@IBOutlet weak var privacyTextField: UITextView!
var hkTimeRefreshTimer: Timer?
fileprivate let kHKTimeRefreshInterval: TimeInterval = 30.0
//
// MARK: - Base Methods
//
override func viewDidLoad() {
super.viewDidLoad()
let curService = APIConnector.connector().currentService!
if curService == "Production" {
versionString.text = "V" + UIApplication.appVersion()
} else{
versionString.text = "V" + UIApplication.appVersion() + " on " + curService
}
loginAccount.text = NutDataController.controller().currentUserName
//let attributes = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let str = "Privacy and Terms of Use"
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = .center
let attributedString = NSMutableAttributedString(string:str, attributes:[NSFontAttributeName: Styles.mediumVerySmallSemiboldFont, NSForegroundColorAttributeName: Styles.blackColor, NSParagraphStyleAttributeName: paragraphStyle])
attributedString.addAttribute(NSLinkAttributeName, value: URL(string: "http://developer.tidepool.io/privacy-policy/")!, range: NSRange(location: 0, length: 7))
attributedString.addAttribute(NSLinkAttributeName, value: URL(string: "http://developer.tidepool.io/terms-of-use/")!, range: NSRange(location: attributedString.length - 12, length: 12))
privacyTextField.attributedText = attributedString
privacyTextField.delegate = self
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(MenuAccountSettingsViewController.handleUploaderNotification(_:)), name: NSNotification.Name(rawValue: HealthKitDataUploader.Notifications.Updated), object: nil)
}
deinit {
let nc = NotificationCenter.default
nc.removeObserver(self, name: nil, object: nil)
hkTimeRefreshTimer?.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func menuWillOpen() {
// Late binding here because profile fetch occurs after login complete!
// Treat this like viewWillAppear...
usernameLabel.text = NutDataController.controller().userFullName
configureHKInterface()
}
//
// MARK: - Navigation
//
@IBAction func done(_ segue: UIStoryboardSegue) {
print("unwind segue to menuaccount done!")
}
//
// MARK: - Button/switch handling
//
@IBAction func supportButtonHandler(_ sender: AnyObject) {
APIConnector.connector().trackMetric("Clicked Tidepool Support (Hamburger)")
let email = "[email protected]"
let url = URL(string: "mailto:\(email)")
UIApplication.shared.openURL(url!)
}
@IBAction func logOutTapped(_ sender: AnyObject) {
APIConnector.connector().trackMetric("Clicked Log Out (Hamburger)")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.logout()
}
//
// MARK: - Healthkit Methods
//
@IBAction func enableHealthData(_ sender: AnyObject) {
if let enableSwitch = sender as? UISwitch {
if enableSwitch.isOn {
enableHealthKitInterfaceForCurrentUser()
} else {
NutDataController.controller().disableHealthKitInterface()
}
configureHKInterface()
}
}
fileprivate func startHKTimeRefreshTimer() {
if hkTimeRefreshTimer == nil {
hkTimeRefreshTimer = Timer.scheduledTimer(timeInterval: kHKTimeRefreshInterval, target: self, selector: #selector(MenuAccountSettingsViewController.nextHKTimeRefresh), userInfo: nil, repeats: true)
}
}
func stopHKTimeRefreshTimer() {
hkTimeRefreshTimer?.invalidate()
hkTimeRefreshTimer = nil
}
func nextHKTimeRefresh() {
DDLogInfo("nextHKTimeRefresh")
configureHKInterface()
}
internal func handleUploaderNotification(_ notification: Notification) {
DDLogInfo("handleUploaderNotification: \(notification.name)")
configureHKInterface()
}
fileprivate func configureHKInterface() {
// Late binding here because profile fetch occurs after login complete!
usernameLabel.text = NutDataController.controller().userFullName
let hkCurrentEnable = appHealthKitConfiguration.healthKitInterfaceEnabledForCurrentUser()
healthKitSwitch.isOn = hkCurrentEnable
if hkCurrentEnable {
self.configureHealthStatusLines()
// make sure timer is turned on to prevent a stale interface...
startHKTimeRefreshTimer()
} else {
stopHKTimeRefreshTimer()
}
var hideHealthKitUI = false
// Note: Right now this is hard-wired true
if !AppDelegate.healthKitUIEnabled {
hideHealthKitUI = true
}
// The isDSAUser variable only becomes valid after user profile fetch, so if it is not set, assume true. Otherwise use it as main control of whether we show the HealthKit UI.
if let isDSAUser = NutDataController.controller().isDSAUser {
if !isDSAUser {
hideHealthKitUI = true
}
}
healthKitSwitch.isHidden = hideHealthKitUI
healthKitLabel.isHidden = hideHealthKitUI
healthStatusContainerView.isHidden = hideHealthKitUI || !hkCurrentEnable
}
fileprivate func enableHealthKitInterfaceForCurrentUser() {
if appHealthKitConfiguration.healthKitInterfaceConfiguredForOtherUser() {
// use dialog to confirm delete with user!
let curHKUserName = appHealthKitConfiguration.healthKitUserTidepoolUsername() ?? "Unknown"
//let curUserName = usernameLabel.text!
let titleString = "Are you sure?"
let messageString = "A different account (" + curHKUserName + ") is currently associated with Health Data on this device"
let alert = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { Void in
self.healthKitSwitch.isOn = false
return
}))
alert.addAction(UIAlertAction(title: "Change Account", style: .default, handler: { Void in
NutDataController.controller().enableHealthKitInterface()
}))
self.present(alert, animated: true, completion: nil)
} else {
NutDataController.controller().enableHealthKitInterface()
}
}
let healthKitUploadStatusMostRecentSamples: String = "Uploading last 14 days of Dexcom data\u{2026}"
let healthKitUploadStatusUploadPausesWhenPhoneIsLocked: String = "FYI upload pauses when phone is locked"
let healthKitUploadStatusDaysUploaded: String = "%d of %d days"
let healthKitUploadStatusUploadingCompleteHistory: String = "Uploading complete history of Dexcom data"
let healthKitUploadStatusLastUploadTime: String = "Last reading %@"
let healthKitUploadStatusNoDataAvailableToUpload: String = "No data available to upload"
let healthKitUploadStatusDexcomDataDelayed3Hours: String = "Dexcom data from Health is delayed 3 hours"
fileprivate func configureHealthStatusLines() {
let hkDataUploader = HealthKitDataUploader.sharedInstance
var phase = hkDataUploader.uploadPhaseBloodGlucoseSamples
// if we haven't actually uploaded a first historical sample, act like we're still doing most recent samples...
if phase == .historicalSamples && hkDataUploader.totalDaysHistoricalBloodGlucoseSamples == 0 {
phase = .mostRecentSamples
}
switch phase {
case .mostRecentSamples:
healthStatusLine1.text = healthKitUploadStatusMostRecentSamples
healthStatusLine2.text = healthKitUploadStatusUploadPausesWhenPhoneIsLocked
healthStatusLine3.text = ""
case .historicalSamples:
healthStatusLine1.text = healthKitUploadStatusUploadingCompleteHistory
var healthKitUploadStatusDaysUploadedText = ""
if hkDataUploader.totalDaysHistoricalBloodGlucoseSamples > 0 {
healthKitUploadStatusDaysUploadedText = String(format: healthKitUploadStatusDaysUploaded, hkDataUploader.currentDayHistoricalBloodGlucoseSamples, hkDataUploader.totalDaysHistoricalBloodGlucoseSamples)
}
healthStatusLine2.text = healthKitUploadStatusDaysUploadedText
healthStatusLine3.text = healthKitUploadStatusUploadPausesWhenPhoneIsLocked
case .currentSamples:
if hkDataUploader.totalUploadCountBloodGlucoseSamples > 0 {
let lastUploadTimeAgoInWords = hkDataUploader.lastUploadTimeBloodGlucoseSamples.timeAgoInWords(Date())
healthStatusLine1.text = String(format: healthKitUploadStatusLastUploadTime, lastUploadTimeAgoInWords)
} else {
healthStatusLine1.text = healthKitUploadStatusNoDataAvailableToUpload
}
healthStatusLine2.text = healthKitUploadStatusDexcomDataDelayed3Hours
healthStatusLine3.text = ""
}
}
//
// MARK: - UITextView delegate
//
// Intercept links in order to track metrics...
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if URL.absoluteString.contains("privacy-policy") {
APIConnector.connector().trackMetric("Clicked privacy (Hamburger)")
} else {
APIConnector.connector().trackMetric("Clicked Terms of Use (Hamburger)")
}
return true
}
}
|
bsd-2-clause
|
24593018e8bd9709a3d40109472c335c
| 43.42623 | 236 | 0.68976 | 5.246854 | false | false | false | false |
groue/GRDB.swift
|
Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift
|
1
|
11035
|
import XCTest
@testable import GRDB
class DatabaseQueueSchemaCacheTests : GRDBTestCase {
func testCache() throws {
try makeDatabaseQueue().inDatabase { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
// Warm cache
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
// Assert that cache is warmed
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
// Empty cache after schema change
try db.execute(sql: "DROP TABLE items")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
do {
// Assert that cache is used: we expect an error now that
// the cache is empty.
_ = try db.primaryKey("items")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!, "no such table: items")
XCTAssertEqual(error.description, "SQLite error 1: no such table: items")
}
}
}
func testCacheInvalidationWithCursor() throws {
try makeDatabaseQueue().inDatabase { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
// Warm cache
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
// Assert that cache is warmed
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
// Assert that cache is still warm until the DROP TABLE statement has been executed
let statement = try db.makeStatement(sql: "DROP TABLE items")
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
let cursor = try Row.fetchCursor(statement)
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") != nil)
_ = try cursor.next()
// Assert that cache is empty after cursor has run sqlite3_step
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
}
}
func testTempCache() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TEMPORARY TABLE items (id INTEGER PRIMARY KEY)")
}
dbQueue.inDatabase { db in
// Assert that cache is empty
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
// Warm cache
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
// Assert that cache is warmed
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") != nil)
}
try dbQueue.inDatabase { db in
// Empty cache after schema change
try db.execute(sql: "DROP TABLE items")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") == nil)
}
try dbQueue.inDatabase { db in
do {
// Assert that cache is used: we expect an error now that
// the cache is empty.
_ = try db.primaryKey("items")
XCTFail()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message!, "no such table: items")
XCTAssertEqual(error.description, "SQLite error 1: no such table: items")
}
}
}
func testMainShadowedByTemp() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") == nil)
}
do {
try db.execute(sql: """
CREATE TABLE items (id INTEGER PRIMARY KEY);
INSERT INTO items (id) VALUES (1);
""")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
XCTAssertTrue(db.schemaCache[.main].primaryKey("items")!.value != nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items") == nil)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT id FROM items"), 1)
}
do {
try db.execute(sql: """
CREATE TEMPORARY TABLE items (otherID INTEGER PRIMARY KEY);
INSERT INTO items (otherID) VALUES (2);
""")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "otherID")
XCTAssertTrue(db.schemaCache[.main].primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items")!.value != nil)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT otherID FROM items"), 2)
}
do {
try db.execute(sql: "DROP TABLE items")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.rowIDColumn, "id")
XCTAssertTrue(db.schemaCache[.main].primaryKey("items")!.value != nil)
XCTAssertTrue(db.schemaCache[.temp].primaryKey("items")!.value == nil)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT id FROM items"), 1)
}
}
}
func testMainShadowedByAttachedDatabase() throws {
#if SQLITE_HAS_CODEC
// Avoid error due to key not being provided:
// file is not a database - while executing `ATTACH DATABASE...`
throw XCTSkip("This test does not support encrypted databases")
#endif
let attached1 = try makeDatabaseQueue(filename: "attached1")
try attached1.write { db in
try db.execute(sql: """
CREATE TABLE item (attached1Column TEXT);
INSERT INTO item VALUES('attached1');
""")
try XCTAssertEqual(String.fetchOne(db, sql: "SELECT * FROM item"), "attached1")
try XCTAssertEqual(db.columns(in: "item").first?.name, "attached1Column")
}
let attached2 = try makeDatabaseQueue(filename: "attached2")
try attached2.write { db in
try db.execute(sql: """
CREATE TABLE item (attached2Column TEXT);
INSERT INTO item VALUES('attached2');
""")
try XCTAssertEqual(String.fetchOne(db, sql: "SELECT * FROM item"), "attached2")
try XCTAssertEqual(db.columns(in: "item").first?.name, "attached2Column")
}
let main = try makeDatabaseQueue(filename: "main")
try main.writeWithoutTransaction { db in
try XCTAssertFalse(db.tableExists("item"))
try db.execute(literal: "ATTACH DATABASE \(attached1.path) AS attached1")
try XCTAssertEqual(String.fetchOne(db, sql: "SELECT * FROM item"), "attached1")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA table_info(item)")?["name"], "attached1Column")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA attached1.table_info(item)")?["name"], "attached1Column")
try XCTAssertTrue(db.tableExists("item"))
try XCTAssertEqual(db.columns(in: "item").first?.name, "attached1Column")
// Main shadows attached1
try db.execute(sql: """
CREATE TABLE item (mainColumn TEXT);
INSERT INTO item VALUES('main');
""")
try XCTAssertEqual(String.fetchOne(db, sql: "SELECT * FROM item"), "main")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA main.table_info(item)")?["name"], "mainColumn")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA attached1.table_info(item)")?["name"], "attached1Column")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA table_info(item)")?["name"], "mainColumn")
try XCTAssertTrue(db.tableExists("item"))
try XCTAssertEqual(db.columns(in: "item").first?.name, "mainColumn")
// Main no longer shadows attached1
try db.execute(sql: "DROP TABLE item")
try XCTAssertEqual(String.fetchOne(db, sql: "SELECT * FROM item"), "attached1")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA attached1.table_info(item)")?["name"], "attached1Column")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA table_info(item)")?["name"], "attached1Column")
try XCTAssertTrue(db.tableExists("item"))
try XCTAssertEqual(db.columns(in: "item").first?.name, "attached1Column")
// Attached1 shadows attached2
try db.execute(literal: "ATTACH DATABASE \(attached2.path) AS attached2")
try XCTAssertEqual(String.fetchOne(db, sql: "SELECT * FROM item"), "attached1")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA attached1.table_info(item)")?["name"], "attached1Column")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA attached2.table_info(item)")?["name"], "attached2Column")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA table_info(item)")?["name"], "attached1Column")
try XCTAssertTrue(db.tableExists("item"))
try XCTAssertEqual(db.columns(in: "item").first?.name, "attached1Column")
// Attached1 no longer shadows attached2
try db.execute(sql: "DETACH DATABASE attached1")
try XCTAssertEqual(String.fetchOne(db, sql: "SELECT * FROM item"), "attached2")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA attached2.table_info(item)")?["name"], "attached2Column")
try XCTAssertEqual(Row.fetchOne(db, sql: "PRAGMA table_info(item)")?["name"], "attached2Column")
try XCTAssertTrue(db.tableExists("item"))
try XCTAssertEqual(db.columns(in: "item").first?.name, "attached2Column")
// Attached2 no longer shadows main
try db.execute(sql: "DETACH DATABASE attached2")
try XCTAssertFalse(db.tableExists("item"))
}
}
}
|
mit
|
fd7e24ec5661c89f1436fe39cc407e41
| 46.564655 | 118 | 0.570186 | 4.859093 | false | false | false | false |
xipengyang/SwiftApp1
|
we sale assistant/we sale assistant/CoreDataHelper.swift
|
1
|
6837
|
//
// CoreDataHelper.swift
// we sale assistant
//
// Created by xipeng yang on 15/02/15.
// Copyright (c) 2015 xipeng yang. All rights reserved.
//
import CoreData
import UIKit
class CoreDataHelper: NSObject {
// 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 "com.xipengyang.TODO_App" 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("we_sale_assistant", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("we_sale_assistant.sqlite")
var error: NSError? = nil
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 var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [NSObject: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// 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 \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func getContext() -> NSManagedObjectContext! {
return managedObjectContext
}
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
func rollbackContext () {
if let moc = self.managedObjectContext {
if moc.hasChanges {
moc.rollback()
}
}
}
func getEntities(name : String ) -> [AnyObject] {
let request = NSFetchRequest(entityName: name)
request.returnsObjectsAsFaults = false
request.predicate = nil
var e: NSError?
var result: [AnyObject]?
do {
result = try managedObjectContext!.executeFetchRequest(request)
} catch let error as NSError {
e = error
result = nil
}
if(result == nil) {
if let error = e {
print("fetch error \(error.localizedDescription)")
}
return [AnyObject]()
}else {
return result!
}
}
func getEntityByPredicate(name: String, predicate: NSPredicate?) -> [AnyObject] {
let request = NSFetchRequest(entityName: name)
request.predicate = predicate
var e: NSError?
var result: [AnyObject]?
do {
result = try managedObjectContext!.executeFetchRequest(request)
} catch let error as NSError {
e = error
result = nil
}
if(result == nil) {
if let error = e {
print("fetch error \(error.localizedDescription)")
}
return [AnyObject]()
}else {
return result!
}
}
func getOrNewEntityByPredicate(name: String, predicate: NSPredicate?) -> AnyObject {
let entities = self.getEntityByPredicate(name, predicate: predicate)
if entities.count > 0 {
return entities.last!
}
return NSEntityDescription.insertNewObjectForEntityForName(name, inManagedObjectContext: self.managedObjectContext!)
}
func newEntity(name: String) -> AnyObject {
return NSEntityDescription.insertNewObjectForEntityForName(name, inManagedObjectContext: self.managedObjectContext!)
}
func deleteObject( obj : NSManagedObject) {
managedObjectContext?.deleteObject(obj)
}
}
|
mit
|
176c790b63eed5e38faebce970803d22
| 37.195531 | 290 | 0.615328 | 5.858612 | false | false | false | false |
onekiloparsec/SwiftAA
|
Tests/SwiftAATests/PlanetaryPhenomenaTests.swift
|
2
|
1462
|
//
// PlanetaryPhenomenaTests.swift
// SwiftAA
//
// Created by Cédric Foellmi on 16/02/2017.
// Copyright © 2017 onekiloparsec. All rights reserved.
//
import XCTest
@testable import SwiftAA
class PlanetaryPhenomenaTests: XCTestCase {
// See AA. p.252
func testMercuryInferiorConjunction() {
let jd = JulianDay(year: 1993, month: 10, day: 1)
let mercury = Mercury(julianDay: jd)
XCTAssertEqual(mercury.inferiorConjunction(mean: false).value, 2449297.644, accuracy: 0.001)
}
// See AA. p.252
func testSaturnConjunction() {
// We take month = 6, to force looking for first conjunction after beginning of 2015, as in AA book.
let jd = JulianDay(year: 2125, month: 6, day: 1)
let saturn = Saturn(julianDay: jd)
XCTAssertEqual(saturn.conjunction(mean: false).value, 2497437.903, accuracy: 0.001)
}
// See AA. p.253 & 254.
func testMercuryWesternElongation() {
let jd = JulianDay(year: 1993, month: 11, day: 1)
let mercury = Mercury(julianDay: jd)
XCTAssertEqual(mercury.westernElongation(mean: false).value, 2449314.14, accuracy: 0.002)
XCTAssertEqual(mercury.elongationValue(eastern: false).value, 19.7506, accuracy: 0.0001)
}
// // See AA. p.254.
// func testMarsStation() {
// let mars = Mars(julianDay: JulianDay(2450537.510))
// AssertEqual(mars.station1(), JulianDay(2450566.255))
// }
}
|
mit
|
0ab9dd37440c58330e7e02036c5149d4
| 32.953488 | 108 | 0.653425 | 3.578431 | false | true | false | false |
PFei-He/Project-Swift
|
Project/BaseFramework/ViewModel/BaseTableViewController.swift
|
1
|
7728
|
//
// BaseTableViewController.swift
// Project
//
// Created by PFei_He on 16/5/10.
// Copyright © 2016年 PFei_He. All rights reserved.
//
// __________ __________ _________ ___________ ___________ __________ ___________
// | _______ \ | _______ \ / _______ \ |______ __|| _________| / _________||____ ____|
// | | \ || | \ || / \ | | | | | | / | |
// | |_______/ || |_______/ || | | | | | | |_________ | | | |
// | ________/ | _____ _/ | | | | _ | | | _________|| | | |
// | | | | \ \ | | | || | | | | | | | | |
// | | | | \ \ | \_______/ || \____/ | | |_________ | \_________ | |
// |_| |_| \_\ \_________/ \______/ |___________| \__________| |_|
//
//
// The framework design by https://github.com/PFei-He/Project-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 UIKit
import PFKitSwift
import SVProgressHUD
///调试模式
private var DEBUG_MODE = false
public class BaseTableViewController: UITableViewController {
///请求成功返回的结果
public var successResult: AnyObject? {
return _successResult
}
private var _successResult: AnyObject?
///请求失败返回的结果
public var failureResult: AnyObject? {
return _failureResult
}
private var _failureResult: AnyObject?
///请求返回的附加结果
public var additionalResults: AnyObject? {
return _additionalResults
}
private var _additionalResults: AnyObject?
///请求的发送者
public var sender: AnyObject? {
return _sender
}
private var _sender: AnyObject?
///请求是否成功
public var requestIsSuccess: Bool {
return _requestIsSuccess
}
private var _requestIsSuccess = Bool()
///所有的请求
private var requests = Array<BaseRequest>()
//MARK: - Life Cycle
deinit {
removeAllRequests()
}
// MARK: - Request Management
/**
初始化请求
- Note: 无
- Parameter requests: 所有的请求
- Returns: 无
*/
public func addRequests(requests: Array<BaseRequest>) {
self.requests = requests
for request in requests {
request.add(self)
}
}
/**
移除请求
- Note: 无
- Parameter requests: 所有的请求
- Returns: 无
*/
// public func remove(requests requests: Array<BaseRequest>) {
// for request in requests {
// request.removeRequester(self)
// }
// }
///移除请求
private func removeAllRequests() {
for request in self.requests {
request.remove(self)
}
}
// MARK: - Notification Management
//请求开始通知
final func requestStartedNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request started with sender: \(notification.object!).")
print("[ PROJECT ][ DEBUG ] Requester: \(String(classForCoder)).")
}
//请求开始
requestStarted()
}
//请求结束通知
final func requestEndedNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request ended with sender: \(notification.object!).")
}
//请求结束
requestEnded()
}
//请求成功通知
final func requestSuccessNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request success with result: \(notification.object!).")
}
//处理请求结果
_successResult = notification.object
if notification.userInfo is Dictionary<String, AnyObject> {
var dictionary: Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
_additionalResults = dictionary.removeValueForKey("sender")
}
_sender = notification.userInfo?["sender"]
_requestIsSuccess = true
//请求成功
requestSuccess()
}
//请求失败通知
final func requestFailureNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request failure with result: \(notification.object!).")
}
//处理请求结果
_failureResult = notification.object
if notification.userInfo is Dictionary<String, AnyObject> {
var dictionary: Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
_additionalResults = dictionary.removeValueForKey("sender")
}
_sender = notification.userInfo?["sender"]
_requestIsSuccess = false
//请求失败
requestFailure()
}
// MARK: - Public Methods
/**
请求开始
- Note: 此方法已实现提示框的处理,如需自定义,请自行重写此方法
- Parameter 无
- Returns: 无
*/
public func requestStarted() {
//显示提示框
SVProgressHUD.showWithStatus("加载中")
}
/**
请求结束
- Note: 此方法已实现提示框的处理,如需自定义,请自行重写此方法
- Parameter 无
- Returns: 无
*/
public func requestEnded() {
if _requestIsSuccess {//请求成功
//移除提示框
SVProgressHUD.dismiss()
} else {//请求失败
//显示请求失败的提示框
SVProgressHUD.showErrorWithStatus("请求失败")
}
}
/**
请求成功
- Note: 无
- Parameter 无
- Returns: 无
*/
public func requestSuccess() {
// Override this method to process the request when request success.
}
/**
请求失败
- Note: 无
- Parameter 无
- Returns: 无
*/
public func requestFailure() {
// Override this method to process the request when request failure.
}
/**
调试模式
- Note: 无
- Parameter openOrNot: 是否打开调试模式
- Returns: 无
*/
public class func debugMode(openOrNot: Bool) {
DEBUG_MODE = openOrNot
}
}
|
mit
|
5c2f051621c6ffadebb49e379ca83b32
| 28.599174 | 115 | 0.537345 | 4.378362 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard
|
GrandCentralBoard/Widgets/Harvest/View/HarvestWidgetView.swift
|
2
|
3045
|
//
// HarvestWidgetView.swift
// GrandCentralBoard
//
// Created by Michał Laskowski on 18.05.2016.
// Copyright © 2016 Macoscope. All rights reserved.
//
import UIKit
import GCBUtilities
import GCBCore
struct HarvestWidgetViewModel {
let lastDayChartModel: CircleChartViewModel
let lastNDaysChartModel: CircleChartViewModel
let lastDaysLabelText: String
init(lastDayChartModel: CircleChartViewModel, lastNDaysChartModel: CircleChartViewModel, numberOfLastDays: Int) {
self.lastDayChartModel = lastDayChartModel
self.lastNDaysChartModel = lastNDaysChartModel
if numberOfLastDays == 1 {
lastDaysLabelText = "Last\nDay".localized.uppercaseString
} else {
lastDaysLabelText = String(format: "Last\n%d Days".localized, numberOfLastDays).uppercaseString
}
}
}
extension HarvestWidgetViewModel {
static func viewModelFromBillingStats(stats: [DailyBillingStats]) -> HarvestWidgetViewModel {
//sort with timestamp descending
let stats = stats.sort { (left, right) -> Bool in
left.day > right.day
}
guard let lastDayStats = stats.first else {
let emptyCircleChartViewModel = CircleChartViewModel.emptyViewModel()
return HarvestWidgetViewModel(lastDayChartModel: emptyCircleChartViewModel,
lastNDaysChartModel: emptyCircleChartViewModel,
numberOfLastDays: stats.count)
}
let lastDayChartViewModel = CircleChartViewModel.chartViewModelFromBillingStats([lastDayStats])
let lastNDaysChartViewModel = CircleChartViewModel.chartViewModelFromBillingStats(stats)
return HarvestWidgetViewModel(lastDayChartModel: lastDayChartViewModel,
lastNDaysChartModel: lastNDaysChartViewModel,
numberOfLastDays: stats.count)
}
}
final class HarvestWidgetView: UIView {
@IBOutlet private weak var lastDayCircleChart: CircleChart!
@IBOutlet private weak var lastNDaysCircleChart: CircleChart!
@IBOutlet private weak var lastNDaysLabel: LabelWithSpacing!
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
func startAnimatingActivityIndicator() {
activityIndicator.hidden = false
activityIndicator.startAnimating()
}
func stopAnimatingActivityIndicator() {
activityIndicator.hidden = true
activityIndicator.stopAnimating()
}
func configureWithViewModel(viewModel: HarvestWidgetViewModel) {
lastDayCircleChart.configureWithViewModel(viewModel.lastDayChartModel)
lastNDaysCircleChart.configureWithViewModel(viewModel.lastNDaysChartModel)
lastNDaysLabel.text = viewModel.lastDaysLabelText
}
// MARK - fromNib
class func fromNib() -> HarvestWidgetView {
return NSBundle.mainBundle().loadNibNamed("HarvestWidgetView", owner: nil, options: nil)[0] as! HarvestWidgetView
}
}
|
gpl-3.0
|
51f0f9308df85de92a13476a79e49cf1
| 36.109756 | 121 | 0.706211 | 5.157627 | false | false | false | false |
seem-sky/ios-charts
|
Charts/Classes/Renderers/ChartRendererBase.swift
|
1
|
1793
|
//
// ChartRendererBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartRendererBase: NSObject
{
/// the component that handles the drawing area of the chart and it's offsets
public var viewPortHandler: ChartViewPortHandler!;
internal var _minX: Int = 0;
internal var _maxX: Int = 0;
public override init()
{
super.init();
}
public init(viewPortHandler: ChartViewPortHandler)
{
super.init();
self.viewPortHandler = viewPortHandler;
}
/// Returns true if the specified value fits in between the provided min and max bounds, false if not.
internal func fitsBounds(val: Float, min: Float, max: Float) -> Bool
{
if (val < min || val > max)
{
return false;
}
else
{
return true;
}
}
/// Calculates the minimum and maximum x-value the chart can currently display (with the given zoom level).
internal func calcXBounds(trans: ChartTransformer!)
{
var minx = trans.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: 0.0)).x;
var maxx = trans.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: 0.0)).x;
if (isnan(minx))
{
minx = 0;
}
if (isnan(maxx))
{
maxx = 0;
}
if (!isinf(minx))
{
_minX = max(0, Int(minx));
}
if (!isinf(maxx))
{
_maxX = max(0, Int(ceil(maxx)));
}
}
}
|
apache-2.0
|
1f4592b101e64dbe4c4e4fa6786fa1d5
| 24.267606 | 111 | 0.57111 | 4.341404 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
ClientTests/NavigationRouterTests.swift
|
1
|
3882
|
/* 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
@testable import Client
import WebKit
import XCTest
class NavigationRouterTests: XCTestCase {
var appScheme: String {
let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as! [AnyObject]
let urlType = urlTypes.first as! [String : AnyObject]
let urlSchemes = urlType["CFBundleURLSchemes"] as! [String]
return urlSchemes.first!
}
func testOpenURLScheme() {
let url = "http://google.com?a=1&b=2&c=foo%20bar".escape()!
let appURL = "\(appScheme)://open-url?url=\(url)"
let navItem = NavigationPath(url: URL(string: appURL)!)!
XCTAssertEqual(navItem, NavigationPath.url(webURL: URL(string: url.unescape()!)!, isPrivate: false))
let emptyNav = NavigationPath(url: URL(string: "\(appScheme)://open-url?private=true")!)
XCTAssertEqual(emptyNav, NavigationPath.url(webURL: nil, isPrivate: true))
let badNav = NavigationPath(url: URL(string: "\(appScheme)://open-url?url=blah")!)
XCTAssertEqual(badNav, NavigationPath.url(webURL: URL(string: "blah"), isPrivate: false))
}
// Test EVERY deep link
func testDeepLinks() {
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/clear-private-data")!), NavigationPath.deepLink(DeepLink.settings(.clearPrivateData)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/newTab")!), NavigationPath.deepLink(DeepLink.settings(.newtab)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/newTab/")!), NavigationPath.deepLink(DeepLink.settings(.newtab)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/homePage")!), NavigationPath.deepLink(DeepLink.settings(.homepage)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/mailto")!), NavigationPath.deepLink(DeepLink.settings(.mailto)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/search")!), NavigationPath.deepLink(DeepLink.settings(.search)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/fxa")!), NavigationPath.deepLink(DeepLink.settings(.fxa)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/bookmarks")!), NavigationPath.deepLink(DeepLink.homePanel(.bookmarks)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/top-sites")!), NavigationPath.deepLink(DeepLink.homePanel(.topSites)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/history")!), NavigationPath.deepLink(DeepLink.homePanel(.history)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/reading-list")!), NavigationPath.deepLink(DeepLink.homePanel(.readingList)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/default-browser/system-settings")!), NavigationPath.deepLink(DeepLink.defaultBrowser(.systemSettings)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/badbad")!), nil)
}
func testFxALinks() {
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://fxa-signin?signin=coolcodes&user=foo&email=bar")!), NavigationPath.fxa(params: FxALaunchParams(query: ["user": "foo","email": "bar", "signin": "coolcodes"])))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://fxa-signin?user=foo&email=bar")!), nil)
}
}
|
mpl-2.0
|
35b69fbd93c6de807797e2264fcdc6db
| 69.581818 | 229 | 0.710974 | 4.347144 | false | true | false | false |
xqz001/WeatherMap
|
WeatherAroundUs/Temperature.swift
|
8
|
932
|
//
// Temperature.swift
// WeatherMap
//
// Created by Yifei Teng on 6/27/15.
// Copyright (c) 2015 Takefive Interactive. All rights reserved.
//
import Foundation
enum TUnit {
case Celcius
case Fahrenheit
}
extension TUnit {
var stringValue: String {
switch self {
case .Celcius:
return "C"
case .Fahrenheit:
return "F"
}
}
// True if and only if Fahrenheit
var boolValue: Bool {
return self == .Fahrenheit
}
func format(var temperature: Int) -> String {
if self == .Fahrenheit {
temperature = WeatherMapCalculations.degreeToF(temperature)
}
return "\(temperature)°\(self.stringValue)"
}
var inverse: TUnit {
switch self {
case .Celcius:
return .Fahrenheit
case .Fahrenheit:
return .Celcius
}
}
}
|
apache-2.0
|
2546e47cf7397354217241f33b2a0b5d
| 18 | 71 | 0.54565 | 4.350467 | false | false | false | false |
xqz001/WeatherMap
|
WeatherAroundUs/Pods/Spring/Spring/SpringLabel.swift
|
30
|
2701
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SpringLabel: UILabel, Springable {
@IBInspectable public var autostart: Bool = false
@IBInspectable public var autohide: Bool = false
@IBInspectable public var animation: String = ""
@IBInspectable public var force: CGFloat = 1
@IBInspectable public var delay: CGFloat = 0
@IBInspectable public var duration: CGFloat = 0.7
@IBInspectable public var damping: CGFloat = 0.7
@IBInspectable public var velocity: CGFloat = 0.7
@IBInspectable public var repeatCount: Float = 1
@IBInspectable public var x: CGFloat = 0
@IBInspectable public var y: CGFloat = 0
@IBInspectable public var scaleX: CGFloat = 1
@IBInspectable public var scaleY: CGFloat = 1
@IBInspectable public var rotate: CGFloat = 0
@IBInspectable public var curve: String = ""
public var opacity: CGFloat = 1
public var animateFrom: Bool = false
lazy private var spring : Spring = Spring(self)
override public func awakeFromNib() {
super.awakeFromNib()
self.spring.customAwakeFromNib()
}
override public func didMoveToWindow() {
super.didMoveToWindow()
self.spring.customDidMoveToWindow()
}
public func animate() {
self.spring.animate()
}
public func animateNext(completion: () -> ()) {
self.spring.animateNext(completion)
}
public func animateTo() {
self.spring.animateTo()
}
public func animateToNext(completion: () -> ()) {
self.spring.animateToNext(completion)
}
}
|
apache-2.0
|
6222a250db0fc5109ee70dd14d02406c
| 36.527778 | 81 | 0.710848 | 4.67301 | false | false | false | false |
460467069/smzdm
|
什么值得买7.1.1版本/什么值得买(5月12日)/Classes/HaoJia(好价)/View/ZZHaoJiaHeaderView.swift
|
1
|
1876
|
//
// ZZHaoJiaHeaderView.swift
// 什么值得买
//
// Created by Wang_ruzhou on 2016/11/3.
// Copyright © 2016年 Wang_ruzhou. All rights reserved.
//
import UIKit
@objcMembers class ZZHaoJiaHeaderView: UIView {
@IBOutlet var imageViews: [UIImageView]!
@IBOutlet weak var cycleScrollView: ZZCycleScrollView!
weak var delegate: ZZActionDelegate?
@objc var contentHeader: ZZContentHeader? {
didSet {
var picArray = [Any]()
guard let contentHeader = contentHeader else { return }
for headLine in contentHeader.rows {
picArray.append(headLine.img)
}
cycleScrollView.imageURLStringsGroup = picArray
for (key1, littleBanner) in contentHeader.little_banner.enumerated() {
for (key2, imageView) in imageViews.enumerated() {
if key1 == key2 {
imageView.yy_setImage(with: URL.init(string: littleBanner.img), options: .showNetworkActivity)
}
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
for (index, imageView) in imageViews.enumerated(){
imageView.isUserInteractionEnabled = true
imageView.tag = index
let tapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(imageViewDidTap(tap:)))
imageView.addGestureRecognizer(tapGestureRecognizer)
}
}
@objc fileprivate func imageViewDidTap(tap: UITapGestureRecognizer){
let tag = tap.view?.tag
let littleBanner = contentHeader?.little_banner[tag!]
if let redirectData = littleBanner?.redirectData {
delegate?.itemDidClick(redirectData: redirectData)
}
}
}
|
mit
|
b1171b270b2174d5c7abc388fe1ee541
| 29.048387 | 122 | 0.597424 | 4.954787 | false | false | false | false |
EricHein/Swift3.0Practice2016
|
00.ScratchWork/ParseServerStarterProject/ParseStarterProject/FeedTableViewController.swift
|
1
|
5336
|
//
// FeedTableViewController.swift
// ParseStarterProject-Swift
//
// Created by Eric H on 26/12/2016.
// Copyright © 2016 Parse. All rights reserved.
//
import UIKit
import Parse
class FeedTableViewController: UITableViewController {
var users = [String: String]()
var messages = [String]()
var username = [String]()
var imageFiles = [PFFile]()
override func viewDidLoad() {
super.viewDidLoad()
let query = PFUser.query()
query?.findObjectsInBackground(block: {(objects, error) in
if let users = objects {
self.users.removeAll()
for object in users{
if let user = object as? PFUser{
self.users[user.objectId!] = user.username!
}
}
}
let getFollowedUsersQuery = PFQuery(className: "Followers")
getFollowedUsersQuery.whereKey("follower", equalTo: (PFUser.current()?.objectId!)!)
getFollowedUsersQuery.findObjectsInBackground(block: {(objects, error) in
if let followers = objects {
for object in followers{
if let follower = object as? PFObject{
let followedUser = follower["following"] as! String
let query = PFQuery(className: "Posts")
query.whereKey("userid", equalTo: followedUser)
query.findObjectsInBackground(block: {(objects, error) in
if let posts = objects{
for object in posts {
if let post = object as? PFObject{
self.messages.append(post["message"] as! String)
self.username.append(self.users[post["userid"] as! String]!)
self.imageFiles.append(post["imageFile"] as! PFFile)
self.tableView.reloadData()
}
}
}
})
}
}
}
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FeedTableViewCell
cell.postedImage.image = UIImage(named: "")
imageFiles[indexPath.row].getDataInBackground(block: {(data,error) in
if let imageData = data {
if let downloadedImage = UIImage(data: imageData){
cell.postedImage.image = downloadedImage
}
}
})
cell.usernameLabel.text = username[indexPath.row]
cell.messageLabel.text = messages[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-3.0
|
a854657b6f2d84d7fc123aecfa62defe
| 34.098684 | 136 | 0.529147 | 5.888521 | false | false | false | false |
PaulTaykalo/thing-speak-macosx
|
ThingSpeak/ThingSpeak/TSMenulet.swift
|
1
|
3485
|
//
// TSMenulet.swift
// ThingSpeak
//
// Created by Paul Taykalo on 12/23/14.
// Copyright (c) 2014 Stanfy LLC. All rights reserved.
//
import Cocoa
import AppKit
class TSMenulet: NSObject {
var item : NSStatusItem?
var shouldTrackWhenOpened = false
@IBOutlet weak var shouldTrackWhenOpenedItem: NSMenuItem!
@IBAction func trackWhenOpenedChanged(sender: NSMenuItem) {
if (sender.state == 0) {
sender.state = 1
shouldTrackWhenOpened = true
} else {
sender.state = 0;
shouldTrackWhenOpened = false
}
}
override func awakeFromNib() {
item = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
let itm = item!
itm.enabled = true
itm.highlightMode = true
itm.toolTip = "There's nothing to see here"
itm.menu = (NSApplication.sharedApplication().delegate as AppDelegate).mainMenu
itm.image = NSBundle.mainBundle().imageForResource("yellow-on-16")
tryToLoadDataOnce()
}
func tryToLoadDataOnce() {
let url = NSURL(string:"https://api.thingspeak.com/channels/20910/feeds/last.json?api_key=4KBZITI1B7KSTT8R")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url)
{(data, response, error) in
// We don't care
if ((error) != nil) {
self.retryDownload(timeout: 60)
return
}
var jsonError: NSError?
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil)
let jsonDict = jsonObject as NSDictionary
let fieldValue = jsonDict["field1"]! as NSString
let createdAt = jsonDict["created_at"]! as NSString
NSLog("\(jsonObject)")
dispatch_async(dispatch_get_main_queue()) {
// update the tool tim
self.updateItemWithValue(fieldValue, time: createdAt)
self.retryDownload(timeout: 30)
}
}
task.resume()
}
func updateItemWithValue(value:NSString, time:NSString) {
let itm = self.item!
var openState = "CLOSED"
if (value.floatValue > 500) {
itm.image = NSBundle.mainBundle().imageForResource("red-on-16")
} else {
itm.image = NSBundle.mainBundle().imageForResource("green-on-16")
openState = "OPENED"
if (self.shouldTrackWhenOpened) {
self.sendOpenedNotification()
self.shouldTrackWhenOpened = false;
self.shouldTrackWhenOpenedItem!.state = 0;
}
}
itm.toolTip = "\(openState) at \(time)"
}
func retryDownload(timeout:Double = 30) {
delay(timeout, {
self.tryToLoadDataOnce()
})
}
func sendOpenedNotification() {
let notification:NSUserNotification = NSUserNotification()
notification.title = "Hurry! Be the first!"
notification.informativeText = "Should I show you how to go there on maps?"
notification.deliveryDate = NSDate().dateByAddingTimeInterval(1)
notification.soundName = "Submarine"
notification.setValue(NSBundle.mainBundle().imageForResource("green-on-16"), forKey: "_identityImage")
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(notification);
}
}
|
mit
|
5033877102c7c6542434d5bb8b0fcb1a
| 31.570093 | 138 | 0.608608 | 4.703104 | false | false | false | false |
huonw/swift
|
benchmark/single-source/Calculator.swift
|
3
|
1169
|
//===--- Calculator.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
public let Calculator = BenchmarkInfo(
name: "Calculator",
runFunction: run_Calculator,
tags: [.validation])
@inline(never)
func my_atoi_impl(_ input : String) -> Int {
switch input {
case "0": return 0
case "1": return 1
case "2": return 2
case "3": return 3
case "4": return 4
case "5": return 5
case "6": return 6
case "7": return 7
case "8": return 8
case "9": return 9
default: return 0
}
}
@inline(never)
public func run_Calculator(_ N: Int) {
var c = 0
for _ in 1...N*5000 {
c += my_atoi_impl(identity("10"))
}
CheckResults(c == 0)
}
|
apache-2.0
|
c6f8a8654ced5774fa3b2d784bdf1815
| 24.413043 | 80 | 0.573139 | 3.962712 | false | false | false | false |
healerkx/swallow
|
swallow/tests/semantics/TestOptional_OptionalChaining_Property.swift
|
2
|
940
|
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if buildingName != nil {
return buildingName
} else if buildingNumber != nil {
return buildingNumber
} else {
return nil
}
}
}
class Room
{
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
println("The number of rooms is \(numberOfRooms)")
}
var address: Address?
}
class Person {
var residence: Residence?
}
let john = Person()
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
john.residence?.address = someAddress
|
bsd-3-clause
|
10fd9d2301af53f332617d1d8c614495
| 19.434783 | 58 | 0.571277 | 4.497608 | false | false | false | false |
Nexmind/Swiftizy
|
Swiftizy/Classes/Extension/DateExtension.swift
|
1
|
1302
|
//
// DateExtension.swift
// Crunchizy
//
// Created by Julien Henrard on 14/12/15.
// Copyright © 2015 NexMind. All rights reserved.
//
import Foundation
public extension NSDate {
// -> Date System Formatted Medium
func ToDateMediumString() -> NSString? {
let formatter = DateFormatter()
formatter.dateStyle = .medium;
formatter.timeStyle = .none;
return formatter.string(from: self as Date) as NSString?
}
func dateTimeToString() -> NSString? {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
return formatter.string(from: self as Date) as NSString?
}
func dateToStringHyphen() -> NSString? {
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
return formatter.string(from: self as Date) as NSString?
}
func dateTimeFrString() -> NSString? {
let formatter = DateFormatter()
formatter.dateFormat = "Le dd du MM yyyy à HH:mm"
return formatter.string(from: self as Date) as NSString?
}
func toString() -> NSString? {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
return formatter.string(from: self as Date) as NSString?
}
}
|
mit
|
9a00e2317f0a705cfd691d49cce29b7d
| 27.888889 | 64 | 0.622308 | 4.276316 | false | false | false | false |
walokra/Haikara
|
Haikara/Helpers/OpenInChromeController.swift
|
1
|
4650
|
// Copyright (c) 2015 Ce Zheng
//
// Copyright 2012, Google 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import UIKit
private let googleChromeHTTPScheme: String = "googlechrome:"
private let googleChromeHTTPSScheme: String = "googlechromes:"
private let googleChromeCallbackScheme: String = "googlechrome-x-callback:"
private func encodeByAddingPercentEscapes(_ input: String?) -> String {
let allowedCharacterSet = NSCharacterSet.urlQueryAllowed as! NSMutableCharacterSet
allowedCharacterSet.removeCharacters(in: "\n:#[]/?@!$&'()*+,;=") // these characters need to be left alone
return input!.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet as CharacterSet)!
}
open class OpenInChromeController {
public static let sharedInstance = OpenInChromeController()
open func isChromeInstalled() -> Bool {
let simpleURL = URL(string: googleChromeHTTPScheme)!
let callbackURL = URL(string: googleChromeCallbackScheme)!
return UIApplication.shared.canOpenURL(simpleURL) || UIApplication.shared.canOpenURL(callbackURL);
}
open func openInChrome(_ url: URL, callbackURL: URL? = nil, createNewTab: Bool = false) -> Bool {
let chromeSimpleURL = URL(string: googleChromeHTTPScheme)!
let chromeCallbackURL = URL(string: googleChromeCallbackScheme)!
if UIApplication.shared.canOpenURL(chromeCallbackURL) {
var appName = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String
// CFBundleDisplayName is an optional key, so we will use CFBundleName if it does not exist
if appName == nil {
appName = Bundle.main.infoDictionary?["CFBundleName"] as? String
}
let scheme = url.scheme!.lowercased()
if scheme == "http" || scheme == "https" {
var chromeURLString = String(format: "%@//x-callback-url/open/?x-source=%@&url=%@", googleChromeCallbackScheme, encodeByAddingPercentEscapes(appName), encodeByAddingPercentEscapes(url.absoluteString))
if callbackURL != nil {
chromeURLString += String(format: "&x-success=%@", encodeByAddingPercentEscapes(callbackURL!.absoluteString))
}
if createNewTab {
chromeURLString += "&create-new-tab"
}
return UIApplication.shared.openURL(URL(string: chromeURLString)!)
}
} else if UIApplication.shared.canOpenURL(chromeSimpleURL) {
let scheme = url.scheme!.lowercased()
var chromeScheme: String? = nil
if scheme == "http" {
chromeScheme = googleChromeHTTPScheme
} else if scheme == "https" {
chromeScheme = googleChromeHTTPSScheme
}
if let chromeScheme = chromeScheme {
let absoluteURLString = url.absoluteString
let chromeURLString = chromeScheme + String(absoluteURLString[absoluteURLString.range(of: ":")!.lowerBound...])
return UIApplication.shared.openURL(URL(string: chromeURLString)!)
}
}
return false;
}
}
|
mit
|
4dfe6dd77efd6c5ddd614ec49c008a12
| 51.840909 | 216 | 0.691828 | 5.065359 | false | false | false | false |
yonadev/yona-app-ios
|
Yona/Yona/AdminRequestManager.swift
|
1
|
2095
|
//
// AdminRequestManager.swift
// Yona
//
// Created by Ben Smith on 03/05/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
class AdminRequestManager {
/**
Holds a reference to our shared instance of APIServiceManager
*/
let APIService = APIServiceManager.sharedInstance
static let sharedInstance = AdminRequestManager()
fileprivate init() {}
/**
Creates an admin request, if the user tries to create an account with same mobile number because they have lost their phone but what to retrieve the account
- parameter userBody: BodyDataDictionary Dictionary of user details for the admin request, we need the mobile from here
- parameter onCompletion: APIResponse, returns success or fail of the method and server messages
*/
func adminRequestOverride(_ mobileNumber: String?, onCompletion: @escaping APIResponse) {
UserRequestManager.sharedInstance.getUser(GetUserRequest.allowed) { (success, message, code, user) in
if let mobileNumber = user?.mobileNumber {
let path = YonaConstants.commands.adminRequestOverride + mobileNumber.replacePlusSign()
//not in user body need to hardcode
self.APIService.callRequestWithAPIServiceResponse(nil, path: path, httpMethod: httpMethods.post) { (success, json, error) in
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error))
}
} else if let mobileNumber = mobileNumber {
let path = YonaConstants.commands.adminRequestOverride + mobileNumber.replacePlusSign()
//not in user body need to hardcode
self.APIService.callRequestWithAPIServiceResponse(nil, path: path, httpMethod: httpMethods.post) { (success, json, error) in
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error))
}
}
}
}
}
|
mpl-2.0
|
c6d7b7278a9a31e49536dd5db1cc9ef2
| 42.625 | 161 | 0.678606 | 5.328244 | false | false | false | false |
MartinOSix/DemoKit
|
dSwift/SwiftDemoKit/SwiftDemoKit/CoreAnimationViewController.swift
|
1
|
2476
|
//
// CoreAnimationViewController.swift
// SwiftDemoKit
//
// Created by runo on 17/5/26.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
class CoreAnimationViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
let tableView = UITableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
let dataSource = [("基本动画","BaseAnimationViewController"),
("转场动画","TransactionAnimationViewController"),
("关键帧动画","KeyFrameAnimationViewController"),
("折叠图片动画","OverturnViewController"),
("文字渐变效果","ColorfulTextViewController")
] as [(String,String)]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.frame = kScreenBounds
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = dataSource[indexPath.row].0
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 1.获取命名空间
guard let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] else {
print("命名空间不存在")
return
}
let classString = dataSource[indexPath.row].1
// 2.通过命名空间和类名转换成类
let cls : AnyClass? = NSClassFromString((clsName as! String) + "." + classString)
// swift 中通过Class创建一个对象,必须告诉系统Class的类型
guard let clsType = cls as? UIViewController.Type else {
print("无法转换成UITableViewController")
return
}
let vc = clsType.init()
vc.title = dataSource[indexPath.row].0
vc.view.backgroundColor = UIColor.white
self.navigationController?.pushViewController(vc, animated: true)
}
}
|
apache-2.0
|
7d14fac867089e26a6f9dbff3a15689d
| 33.701493 | 158 | 0.628387 | 5.189732 | false | false | false | false |
jilouc/kuromoji-swift
|
kuromoji-swift/dict/GenericDictionaryEntry.swift
|
1
|
1568
|
//
// GenericDictionaryEntry.swift
// kuromoji-swift
//
// Created by Jean-Luc Dagon on 20/11/2016.
// Copyright © 2016 Cocoapps. All rights reserved.
//
import Foundation
class GenericDictionaryEntry: DictionaryEntryBase {
internal let partOfSpeechFeatures: [String]
internal let otherFeatures: [String]
init(_ builder: Builder) {
partOfSpeechFeatures = builder.partOfSpeechFeatures
otherFeatures = builder.otherFeatures
super.init(surface: builder.surface, leftId: builder.leftId, rightId: builder.rightId, wordCost: builder.wordCost)
}
public struct Builder {
internal var surface: String = ""
internal var leftId: Int16 = 0
internal var rightId: Int16 = 0
internal var wordCost: Int16 = 0
internal var partOfSpeechFeatures: [String] = []
internal var otherFeatures: [String] = []
public func build() -> GenericDictionaryEntry {
return GenericDictionaryEntry(self);
}
}
public static func fromCSV(_ record: [String]) -> GenericDictionaryEntry {
let surface = record[0]
let leftId = Int16(record[1])!
let rightId = Int16(record[2])!
let wordCost = Int16(record[3])!
let pos = [String](record[4..<10])
let features = [String](record[10..<record.count])
let builder = Builder(surface: surface, leftId: leftId, rightId: rightId, wordCost: wordCost, partOfSpeechFeatures: pos, otherFeatures: features)
return builder.build()
}
}
|
apache-2.0
|
5205c02d07496c59927f28846418dba8
| 33.065217 | 153 | 0.64582 | 4.235135 | false | false | false | false |
fxm90/GradientProgressBar
|
GradientProgressBar/Sources/GradientProgressBar.swift
|
1
|
5486
|
//
// GradientProgressBar.swift
// GradientProgressBar
//
// Created by Felix Mau on 01.03.17.
// Copyright © 2017 Felix Mau. All rights reserved.
//
import Combine
import UIKit
/// Protocol for managing a progress bar, as defined by `UIProgressView` from Apple.
/// To provide the same interface with `GradientProgressBar`, we're gonna make both classes conform to this protocol.
///
/// - SeeAlso: [Apple documentation for `UIProgressView`](https://apple.co/2HjwstS)
protocol UIProgressHandling {
/// The current progress shown by the receiver (between 0.0 and 1.0, inclusive).
var progress: Float { get set }
/// Adjusts the current progress shown by the receiver, optionally animating the change.
///
/// - Parameters:
/// - progress: The new progress value (between 0.0 and 1.0, inclusive).
/// - animated: `true` if the change should be animated, `false` if the change should happen immediately.
func setProgress(_ progress: Float, animated: Bool)
}
extension UIProgressView: UIProgressHandling {}
/// A customizable gradient progress view.
@IBDesignable
open class GradientProgressBar: UIView {
// MARK: - Public properties
/// Gradient colors for the progress view.
public var gradientColors: [UIColor] {
get { gradientLayerViewModel.gradientColors }
set { gradientLayerViewModel.gradientColors = newValue }
}
/// Animation duration for calls to `setProgress(x, animated: true)`.
public var animationDuration: TimeInterval {
get { maskLayerViewModel.animationDuration }
set { maskLayerViewModel.animationDuration = newValue }
}
/// Animation timing function for calls to `setProgress(x, animated: true)`.
public var timingFunction: CAMediaTimingFunction {
get { maskLayerViewModel.timingFunction }
set { maskLayerViewModel.timingFunction = newValue }
}
/// Layer containing the gradient.
private let gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.anchorPoint = .zero
layer.startPoint = .zero
layer.endPoint = CGPoint(x: 1, y: 0)
return layer
}()
/// Alpha mask for showing only the visible "progress"-part of the gradient layer.
public let maskLayer: CALayer = {
let maskLayer = CALayer()
maskLayer.backgroundColor = UIColor.white.cgColor
return maskLayer
}()
// MARK: - Private properties
/// View-model containing all logic related to the gradient-layer.
private let gradientLayerViewModel = GradientLayerViewModel()
/// View-model containing all logic related to the mask-layer.
private let maskLayerViewModel = MaskLayerViewModel()
/// The dispose bag for the observables.
private var subscriptions = Set<AnyCancellable>()
// MARK: - Instance Lifecycle
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - Public methods
override open func layoutSubviews() {
super.layoutSubviews()
// Unfortunately `CALayer` is not affected by autolayout, so any change in the size of the view will not change the gradient layer.
// That's why we'll have to update the frame here manually.
gradientLayer.frame = bounds
// Inform the view-model about the changed bounds, so it can calculate a new frame for the mask-layer, based on the current progress value.
maskLayerViewModel.bounds = bounds
}
// MARK: - Private methods
private func commonInit() {
setupProgressView()
bindViewModelsToView()
}
private func setupProgressView() {
backgroundColor = UIColor.GradientProgressBar.backgroundColor
// Apply the mask to the gradient layer, in order to show only the current progress of the gradient.
gradientLayer.mask = maskLayer
layer.insertSublayer(gradientLayer, at: 0)
}
private func bindViewModelsToView() {
gradientLayerViewModel.gradientLayerColors.sink { [weak self] gradientLayerColors in
self?.gradientLayer.colors = gradientLayerColors
}.store(in: &subscriptions)
maskLayerViewModel.maskLayerFrameAnimation.sink { [weak self] maskLayerFrameAnimation in
self?.animateMaskLayer(frame: maskLayerFrameAnimation.frame,
duration: maskLayerFrameAnimation.duration,
timingFunction: maskLayerFrameAnimation.timingFunction)
}.store(in: &subscriptions)
}
private func animateMaskLayer(frame: CGRect, duration: TimeInterval, timingFunction: CAMediaTimingFunction) {
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(timingFunction)
maskLayer.frame = frame
CATransaction.commit()
}
}
// MARK: - `UIProgressHandling` conformance
extension GradientProgressBar: UIProgressHandling {
// MARK: - Public properties
@IBInspectable
open var progress: Float {
get { maskLayerViewModel.progress }
set { maskLayerViewModel.progress = newValue }
}
// MARK: - Public methods
public func setProgress(_ progress: Float, animated: Bool) {
maskLayerViewModel.setProgress(progress, animated: animated)
}
}
|
mit
|
7a4ea0b312e0618019fed1191a8d60ba
| 32.445122 | 147 | 0.683865 | 5.116604 | false | false | false | false |
parrotbait/CorkWeather
|
Pods/SWLogger/SWLogger/LogLevel.swift
|
1
|
323
|
//
// Log.swift
// Cork Weather
//
// Created by Eddie Long on 07/09/2017.
// Copyright © 2017 eddielong. All rights reserved.
//
import Foundation
public enum LogLevel: Int {
case silent = 0
case verbose = 1
case debug = 2
case info = 3
case warning = 4
case error = 5
case severe = 6
}
|
mit
|
3cc774fd05c5dd829b137b4fee235c68
| 15.947368 | 52 | 0.614907 | 3.389474 | false | false | false | false |
ming1016/smck
|
smck/Parser/JSSb.swift
|
1
|
1125
|
//
// JSSb.swift
// smck
//
// Created by DaiMing on 2017/5/2.
// Copyright © 2017年 Starming. All rights reserved.
//
import Foundation
class JSSb {
public static let rBktL = "("
public static let rBktR = ")"
public static let bktL = "["
public static let bktR = "]"
public static let braceL = "{"
public static let braceR = "}"
public static let comma = ","
public static let colon = ":"
public static let dot = "."
public static let add = "+"
public static let minus = "-"
public static let tilde = "~"
public static let excMk = "!"
public static let asterisk = "*"
public static let percent = "%"
public static let agBktL = "<"
public static let agBktR = ">"
public static let equal = "="
public static let and = "&"
public static let upArrow = "^"
public static let pipe = "|"
public static let qM = "?"
public static let semicolon = ";"
//keywords
//this new delete void typeof instanceof var if else do while for in continue break return with switch case default throw try catch finally function import
}
|
apache-2.0
|
bb596eba994833a225f0cdad4567f15c
| 28.526316 | 159 | 0.623886 | 4.094891 | false | false | false | false |
Awalz/ark-ios-monitor
|
ArkMonitor/Explorer/ExplorerViewController.swift
|
1
|
9752
|
// Copyright (c) 2016 Ark
//
// 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
import SwiftyArk
class ExplorerViewController: ArkViewController {
fileprivate var tableView : ArkTableView!
fileprivate var searchView : UISearchBar!
fileprivate var account : Account?
fileprivate var delegate : Delegate?
fileprivate var transaction : Transaction?
fileprivate var block : Block?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Explorer"
tableView = ArkTableView(CGRect.zero)
tableView.delegate = self
tableView.dataSource = self
searchView = UISearchBar(frame: CGRect(x: 0.0, y: 0.0, width: _screenWidth, height: 50.0))
searchView.autocorrectionType = .no
searchView.autocapitalizationType = .none
searchView.updateColors()
searchView.delegate = self
tableView.tableHeaderView = searchView
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setTableData()
}
fileprivate func setTableData() {
tableView.reloadData()
if account != nil || delegate != nil || block != nil || transaction != nil {
let backgroundView = UIView()
tableView.backgroundView = backgroundView
return
}
let emptyBackgroundView = UIView(frame: tableView.frame)
let emptyLabel = UILabel()
emptyLabel.textColor = ArkPalette.highlightedTextColor
emptyLabel.font = UIFont.systemFont(ofSize: 18.0, weight: .semibold)
emptyLabel.textAlignment = .center
if searchView.text == "" {
emptyLabel.numberOfLines = 2
emptyLabel.text = "Search for a block,transaction,\naddress, or delegate"
} else {
emptyLabel.numberOfLines = 1
emptyLabel.text = "No matching records found!"
}
emptyBackgroundView.addSubview(emptyLabel)
emptyLabel.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
tableView.backgroundView = emptyBackgroundView
}
private func parseSearchString(_ searchText: String) {
account = nil
transaction = nil
block = nil
delegate = nil
setTableData()
if searchText.count == 34 && (searchText.first == "A" || searchText.first == "D") {
fetchAddress(searchText)
} else if searchText.count == 64 {
fetchTransaction(searchText)
} else if searchText.count >= 19 && searchText.isNumeric() {
fetchBlock(searchText)
} else {
fetchDelegate(searchText)
}
}
private func fetchAddress(_ address: String) {
ArkDataManager.manager.account(address: address) { (error, account) in
if let searchedAccount = account {
self.account = searchedAccount
self.setTableData()
}
}
}
private func fetchTransaction(_ transactionID: String) {
ArkDataManager.manager.transaction(id: transactionID) { (error, transaction) in
if let searchedTransaction = transaction {
self.transaction = searchedTransaction
self.setTableData()
}
}
}
private func fetchBlock(_ blockID: String) {
ArkDataManager.manager.block(blockID) { (error, block) in
if let searchedBlock = block {
self.block = searchedBlock
self.setTableData()
}
}
}
private func fetchDelegate(_ delegateName: String) {
ArkDataManager.manager.delegate(delegateName.lowercased()) { (error, delegate) in
if let searchedDelegate = delegate {
self.delegate = searchedDelegate
self.setTableData()
}
}
}
}
extension ExplorerViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: _screenWidth, height: 35.0))
headerView.backgroundColor = ArkPalette.backgroundColor
let headerLabel = UILabel(frame: CGRect(x: 12.5, y: 0.0, width: _screenWidth - 12.5, height: 35.0))
headerLabel.textColor = ArkPalette.highlightedTextColor
headerLabel.textAlignment = .center
headerLabel.font = UIFont.systemFont(ofSize: 18.0, weight: .semibold)
if account != nil {
headerLabel.text = "Account"
}
if delegate != nil {
headerLabel.text = "Delegate"
}
if transaction != nil {
headerLabel.text = "Transaction"
}
if block != nil {
headerLabel.text = "Block"
}
headerView.addSubview(headerLabel)
return headerView
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
searchView.endEditing(true)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? ExplorerDelegateTableViewCell {
let vc = DelegateDetailViewController(cell.delegate)
navigationController?.pushViewController(vc, animated: true)
}
if let cell = tableView.cellForRow(at: indexPath) as? ExplorerTransactionTableViewCell {
let vc = TransactionDetailViewController(cell.transaction)
navigationController?.pushViewController(vc, animated: true)
}
if let cell = tableView.cellForRow(at: indexPath) as? ExplorerAccountTableViewCell {
let vc = AccountDetailViewController(cell.account)
navigationController?.pushViewController(vc, animated: true)
}
if let cell = tableView.cellForRow(at: indexPath) as? ExplorerBlockTableViewCell {
let vc = BlockDetailViewController(cell.block)
navigationController?.pushViewController(vc, animated: true)
}
}
}
extension ExplorerViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
var count = 0
if account != nil {
count += 1
}
if delegate != nil {
count += 1
}
if transaction != nil {
count += 1
}
if block != nil {
count += 1
}
return count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35.0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if transaction != nil {
return 65.0
} else {
return 45.0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let searchedAccount = account {
let cell = ExplorerAccountTableViewCell(searchedAccount)
return cell
} else if let searchedDelegate = delegate {
let cell = ExplorerDelegateTableViewCell(searchedDelegate)
return cell
} else if let searchedTransaction = transaction {
let cell = ExplorerTransactionTableViewCell(searchedTransaction)
return cell
} else if let searchedBlock = block {
let cell = ExplorerBlockTableViewCell(searchedBlock)
return cell
}
else {
let cell = UITableViewCell()
return cell
}
}
}
extension ExplorerViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
guard let searchText = searchBar.text else {
return
}
parseSearchString(searchText)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "" {
account = nil
transaction = nil
block = nil
delegate = nil
setTableData()
}
}
}
|
mit
|
9d033a3b70e402ba3929794844322d4a
| 34.333333 | 137 | 0.611567 | 5.346491 | false | false | false | false |
maximedegreve/Walllpaper
|
Sources/App/Controllers/Admin/AdminControllerCreators.swift
|
1
|
2226
|
//
// AdminControllerCreators.swift
// Walllpaper
//
// Created by Maxime De Greve on 25/02/2017.
//
//
import Vapor
import HTTP
final class AdminCreatorsController {
func addRoutes(to drop: Droplet) {
drop.group(AdminProtectMiddleware()) { secure in
secure.get("admin","creators", handler: creators)
secure.post("admin","contacted", handler: contactedPost)
secure.delete("admin","contacted", handler: contactedDelete)
secure.post("admin","status", handler: statusPost)
}
}
func creators(_ request: Request) throws -> ResponseRepresentable {
let users = try User.withShots().sorted(by: { (user, otherUser) -> Bool in
return user.followersCount > otherUser.followersCount
}) .makeNode()
return try drop.view.make("admin-creator", [
"users": users,
])
}
func contactedPost(_ request: Request) throws -> ResponseRepresentable {
guard let userID = request.data["id"]?.int else {
throw Abort.badRequest
}
var user = try User.find(userID)
user?.contacted = true
try user?.save()
return Response(status: .created, body: "Set to contacted...")
}
func contactedDelete(_ request: Request) throws -> ResponseRepresentable {
guard let userID = request.data["id"]?.int else {
throw Abort.badRequest
}
var user = try User.find(userID)
user?.contacted = false
try user?.save()
return Response(status: .created, body: "Set to not contacted...")
}
func statusPost(_ request: Request) throws -> ResponseRepresentable {
guard let userID = request.data["user_id"]?.int else {
throw Abort.badRequest
}
guard let status = request.data["status"]?.int else {
throw Abort.badRequest
}
var user = try User.find(userID)
user?.consented = status
try user?.save()
return Response(status: .created, body: "Status set...")
}
}
|
mit
|
5f99a71b1b0db3dc25263fd1481ef362
| 26.825 | 82 | 0.560198 | 4.716102 | false | false | false | false |
iAugux/GuillotineMenu
|
GuillotineMenuExample/GuillotineMenuExample/ViewController.swift
|
1
|
2211
|
//
// ViewController.swift
// GuillotineMenu
//
// Created by Maksym Lazebnyi on 3/24/15.
// Copyright (c) 2015 Yalantis. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let reuseIdentifier = "ContentCell"
private let cellHeight: CGFloat = 210
private let cellSpacing: CGFloat = 20
@IBOutlet var barButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let navBar = self.navigationController!.navigationBar
navBar.barTintColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1)
navBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Your Menu View Controller vew must know the following data for the proper animatio
let destinationVC = segue.destinationViewController as! GuillotineMenuViewController
destinationVC.hostNavigationBarHeight = self.navigationController!.navigationBar.frame.size.height
destinationVC.hostTitleText = self.navigationItem.title
destinationVC.view.backgroundColor = self.navigationController!.navigationBar.barTintColor
destinationVC.setMenuButtonWithImage(barButton.imageView!.image!)
}
}
// The follwing is just for the presentation. You can ignore it
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: AnyObject? = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
return cell as! UICollectionViewCell!
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(collectionView.bounds.width - cellSpacing, cellHeight)
}
}
|
mit
|
d9762676b67cb903e6385e6d887084d9
| 39.2 | 130 | 0.739484 | 5.486352 | false | false | false | false |
buscarini/vitemo
|
vitemo/Carthage/Checkouts/GRMustache.swift/Mustache/Goodies/ZipFilter.swift
|
4
|
3460
|
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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
let ZipFilter = VariadicFilter { (boxes, error) -> MustacheBox? in
// Turn collection arguments into generators. Generators can be iterated
// all together, and this is what we need.
//
// Other kinds of arguments generate an error.
var zippedGenerators: [GeneratorOf<MustacheBox>] = []
for box in boxes {
if box.isEmpty {
// Missing collection does not provide anything
} else if let array = box.arrayValue {
// Array
zippedGenerators.append(GeneratorOf(array.generate()))
} else {
// Error
if error != nil {
error.memory = NSError(domain: GRMustacheErrorDomain, code: GRMustacheErrorCodeRenderingError, userInfo: [NSLocalizedDescriptionKey: "Non-enumerable argument in zip filter: `\(box.value)`"])
}
return nil
}
}
// Build an array of custom render functions
var renderFunctions: [RenderFunction] = []
while true {
// Extract from all generators the boxes that should enter the rendering
// context at each iteration.
//
// Given the [1,2,3], [a,b,c] input collections, those boxes would be
// [1,a] then [2,b] and finally [3,c].
var zippedBoxes: [MustacheBox] = []
for generator in zippedGenerators {
var generator = generator
if let box = generator.next() {
zippedBoxes.append(box)
}
}
// All generators have been enumerated: stop
if zippedBoxes.isEmpty {
break;
}
// Build a render function which extends the rendering context with
// zipped boxes before rendering the tag.
let renderFunction = { (info: RenderingInfo, error: NSErrorPointer) -> Rendering? in
var context = info.context
for box in zippedBoxes {
context = context.extendedContext(box)
}
return info.tag.render(context, error: error)
}
renderFunctions.append(renderFunction)
}
// Return a box of those boxed render functions
return Box(map(renderFunctions, Box))
}
|
mit
|
9abf8dc0fc991d1ab238866907e3a3ee
| 34.670103 | 206 | 0.631107 | 5.005789 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new
|
Source/DownloadsAccessoryView.swift
|
2
|
4937
|
//
// DownloadsAccessoryView.swift
// edX
//
// Created by Akiva Leffert on 9/24/15.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
class DownloadsAccessoryView : UIView {
enum State {
case Available
case Downloading
case Done
}
private let downloadButton = UIButton(type: .System)
private let downloadSpinner = SpinnerView(size: .Medium, color: .Primary)
private let iconFontSize : CGFloat = 15
private let countLabel : UILabel = UILabel()
override init(frame : CGRect) {
state = .Available
itemCount = nil
super.init(frame: frame)
downloadButton.tintColor = OEXStyles.sharedStyles().neutralBase()
downloadButton.contentEdgeInsets = UIEdgeInsetsMake(15, 10, 15, 10)
downloadButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
countLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
downloadSpinner.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
self.addSubview(downloadButton)
self.addSubview(downloadSpinner)
self.addSubview(countLabel)
// This view is atomic from an accessibility point of view
self.isAccessibilityElement = true
downloadSpinner.accessibilityTraits = UIAccessibilityTraitNotEnabled;
countLabel.accessibilityTraits = UIAccessibilityTraitNotEnabled;
downloadButton.accessibilityTraits = UIAccessibilityTraitNotEnabled;
downloadSpinner.stopAnimating()
downloadSpinner.snp_makeConstraints {make in
make.center.equalTo(self)
}
downloadButton.snp_makeConstraints {make in
make.trailing.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self)
}
countLabel.snp_makeConstraints {make in
make.leading.equalTo(self)
make.centerY.equalTo(self)
make.trailing.equalTo(downloadButton.imageView!.snp_leading).offset(-6)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func useIcon(icon : Icon?) {
downloadButton.setImage(icon?.imageWithFontSize(iconFontSize), forState:.Normal)
}
var downloadAction : (() -> Void)? = nil {
didSet {
downloadButton.oex_removeAllActions()
downloadButton.oex_addAction({ _ in self.downloadAction?() }, forEvents: .TouchUpInside)
}
}
var itemCount : Int? {
didSet {
let count = itemCount ?? 0
let text = (count > 0 ? "\(count)" : "")
let styledText = CourseOutlineItemView.detailFontStyle.attributedStringWithText(text)
countLabel.attributedText = styledText
}
}
var state : State {
didSet {
switch state {
case .Available:
useIcon(.ContentCanDownload)
downloadSpinner.hidden = true
downloadButton.userInteractionEnabled = true
downloadButton.hidden = false
self.userInteractionEnabled = true
countLabel.hidden = false
if let count = itemCount {
let message = Strings.downloadManyVideos(videoCount: count)
self.accessibilityLabel = message
}
else {
self.accessibilityLabel = Strings.download
}
self.accessibilityTraits = UIAccessibilityTraitButton
case .Downloading:
downloadSpinner.startAnimating()
downloadSpinner.hidden = false
downloadButton.userInteractionEnabled = true
self.userInteractionEnabled = true
downloadButton.hidden = true
countLabel.hidden = true
self.accessibilityLabel = Strings.downloading
self.accessibilityTraits = UIAccessibilityTraitButton
case .Done:
useIcon(.ContentDidDownload)
downloadSpinner.hidden = true
self.userInteractionEnabled = false
downloadButton.hidden = false
countLabel.hidden = false
if let count = itemCount {
let message = Strings.downloadManyVideos(videoCount: count)
self.accessibilityLabel = message
}
else {
self.accessibilityLabel = Strings.downloaded
}
self.accessibilityTraits = UIAccessibilityTraitStaticText
}
}
}
}
|
apache-2.0
|
161ad3aec9c6fa738715733ee258e714
| 34.768116 | 111 | 0.594611 | 6.162297 | false | false | false | false |
iCrany/iOSExample
|
iOSExample/Module/UIBenchMarkExample/View/UICornerRadiusOptTestCell.swift
|
1
|
2437
|
//
// UICornerRadiusOptTestCell.swift
// iOSExample
//
// Created by iCrany on 2018/5/23.
// Copyright © 2018年 iCrany. All rights reserved.
//
import Foundation
class UICornerRadiusOptTestCell: UITableViewCell, CornerRadiusCellProtocol {
struct Constant {
static let kImgInsets: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 0)
static let kImgSize: CGSize = CGSize(width: 40, height: 40)
}
private lazy var customImgView: UIImageView = {
let v = UIImageView()
v.isOpaque = true
return v
}()
private var customLabel: UILabel = {
let v = UILabel()
v.backgroundColor = UIColor.white
return v
}()
private lazy var shapeLayer: CAShapeLayer = {
let v = CAShapeLayer()
return v
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
self.contentView.addSubview(customImgView)
customImgView.snp.makeConstraints { (maker) in
maker.left.equalToSuperview().offset(Constant.kImgInsets.left)
maker.top.equalToSuperview().offset(Constant.kImgInsets.top)
maker.size.equalTo(Constant.kImgSize)
}
self.contentView.addSubview(self.customLabel)
self.customLabel.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(10)
maker.right.equalToSuperview().offset(-10)
maker.bottom.equalToSuperview().offset(-10)
}
//自己画圆
let path = UIBezierPath(roundedRect: CGRect(origin: .zero, size: Constant.kImgSize),
cornerRadius: Constant.kImgSize.width / 2)
let shapeLayer = CAShapeLayer()
shapeLayer.frame = customImgView.bounds
shapeLayer.path = path.cgPath
self.shapeLayer = shapeLayer
customImgView.layer.mask = shapeLayer
}
func updateUI(text: String) {
self.customLabel.text = text
let imgPath = Bundle.main.path(forResource: "jucat", ofType: "jpeg")
if let path = imgPath {
let img = UIImage(contentsOfFile: path)
self.customImgView.image = img
}
}
}
|
mit
|
5e0545982893ec84072381c81c8391df
| 30.102564 | 99 | 0.630256 | 4.56015 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/remove-k-digits.swift
|
2
|
789
|
/**
* https://leetcode.com/problems/remove-k-digits/
*
*
*/
// Date: Wed May 13 09:29:38 PDT 2020
class Solution {
func removeKdigits(_ num: String, _ k: Int) -> String {
if k == num.count { return "0" }
var stack = [Character]()
var k = k
for c in num {
while k > 0, let last = stack.last, last > c {
stack.removeLast()
k -= 1
}
stack.append(c)
}
// Case: 1122, k = 2
while k > 0 {
stack.removeLast()
k -= 1
}
// Case: 10000, k = 1
while let first = stack.first, "0" == String(first) {
stack.removeFirst()
}
return stack.isEmpty ? "0" : String(stack)
}
}
|
mit
|
d38569c8cc57e419dbb3bb2fea9927d8
| 23.65625 | 61 | 0.434728 | 3.793269 | false | false | false | false |
AdilVirani/IntroiOS
|
DNApp/StoriesTableViewController.swift
|
1
|
6055
|
//
// StoriesTableViewController.swift
// DNApp
//
// Created by Meng To on 2015-03-07.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
class StoriesTableViewController: UITableViewController, StoryTableViewCellDelegate, MenuViewControllerDelegate, LoginViewControllerDelegate {
let transitionManager = TransitionManager()
var stories: JSON! = []
var isFirstTime = true
var section = ""
@IBOutlet weak var loginButton: UIBarButtonItem!
func refreshStories() {
loadStories(section, page: 1)
SoundPlayer.play("refresh.wav")
}
func loadStories(section: String, page: Int) {
DNService.storiesForSection(section, page: page) { (JSON) -> () in
self.stories = JSON["stories"]
self.tableView.reloadData()
self.view.hideLoading()
self.refreshControl?.endRefreshing()
}
if LocalStore.getToken() == nil {
loginButton.title = "Login"
loginButton.enabled = true
} else {
loginButton.title = ""
loginButton.enabled = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
loadStories("", page: 1)
refreshControl?.addTarget(self, action: "refreshStories", forControlEvents: UIControlEvents.ValueChanged)
navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Avenir Next", size: 18)!], forState: UIControlState.Normal)
loginButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Avenir Next", size: 18)!], forState: UIControlState.Normal)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
if isFirstTime {
view.showLoading()
isFirstTime = false
}
}
@IBAction func menuButtonDidTouch(sender: AnyObject) {
performSegueWithIdentifier("MenuSegue", sender: self)
}
@IBAction func loginButtonDidTouch(sender: AnyObject) {
performSegueWithIdentifier("LoginSegue", sender: self)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("StoryCell") as! StoryTableViewCell
let story = stories[indexPath.row]
cell.configureWithStory(story)
cell.delegate = self
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("WebSegue", sender: indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: StoryTableViewCellDelegate
func storyTableViewCellDidTouchUpvote(cell: StoryTableViewCell, sender: AnyObject) {
if let token = LocalStore.getToken() {
let indexPath = tableView.indexPathForCell(cell)!
let story = stories[indexPath.row]
let storyId = story["id"].int!
DNService.upvoteStoryWithId(storyId, token: token, response: { (successful) -> () in
print(successful)
})
LocalStore.saveUpvotedStory(storyId)
cell.configureWithStory(story)
} else {
performSegueWithIdentifier("LoginSegue", sender: self)
}
}
func storyTableViewCellDidTouchComment(cell: StoryTableViewCell, sender: AnyObject) {
performSegueWithIdentifier("CommentsSegue", sender: cell)
}
// MARK: MenuViewControllerDelegate
func menuViewControllerDidTouchTop(controller: MenuViewController) {
view.showLoading()
loadStories("", page: 1)
navigationItem.title = "Top Stories"
section = ""
}
func menuViewControllerDidTouchRecent(controller: MenuViewController) {
view.showLoading()
loadStories("recent", page: 1)
navigationItem.title = "Recent Stories"
section = "recent"
}
func menuViewControllerDidTouchLogout(controller: MenuViewController) {
loadStories(section, page: 1)
view.showLoading()
}
// MARK: Misc
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "CommentsSegue" {
let toView = segue.destinationViewController as! CommentsTableViewController
let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)!
toView.story = stories[indexPath.row]
}
if segue.identifier == "WebSegue" {
let toView = segue.destinationViewController as! WebViewController
let indexPath = sender as! NSIndexPath
let url = stories[indexPath.row]["url"].string!
toView.url = url
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade)
toView.transitioningDelegate = transitionManager
}
if segue.identifier == "MenuSegue" {
let toView = segue.destinationViewController as! MenuViewController
toView.delegate = self
}
if segue.identifier == "LoginSegue" {
let toView = segue.destinationViewController as! LoginViewController
toView.delegate = self
}
}
// MARK: LoginViewControllerDelegate
func loginViewControllerDidLogin(controller: LoginViewController) {
loadStories(section, page: 1)
view.showLoading()
}
}
|
apache-2.0
|
6728f86ac11088eb46ba32db3d51d242
| 34 | 160 | 0.6436 | 5.637803 | false | false | false | false |
weichsel/ZIPFoundation
|
Sources/ZIPFoundation/Archive.swift
|
1
|
18698
|
//
// Archive.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
/// The default chunk size when reading entry data from an archive.
public let defaultReadChunkSize = Int(16*1024)
/// The default chunk size when writing entry data to an archive.
public let defaultWriteChunkSize = defaultReadChunkSize
/// The default permissions for newly added entries.
public let defaultFilePermissions = UInt16(0o644)
/// The default permissions for newly added directories.
public let defaultDirectoryPermissions = UInt16(0o755)
let defaultPOSIXBufferSize = defaultReadChunkSize
let defaultDirectoryUnitCount = Int64(1)
let minEndOfCentralDirectoryOffset = Int64(22)
let endOfCentralDirectoryStructSignature = 0x06054b50
let localFileHeaderStructSignature = 0x04034b50
let dataDescriptorStructSignature = 0x08074b50
let centralDirectoryStructSignature = 0x02014b50
let memoryURLScheme = "memory"
/// A sequence of uncompressed or compressed ZIP entries.
///
/// You use an `Archive` to create, read or update ZIP files.
/// To read an existing ZIP file, you have to pass in an existing file `URL` and `AccessMode.read`:
///
/// var archiveURL = URL(fileURLWithPath: "/path/file.zip")
/// var archive = Archive(url: archiveURL, accessMode: .read)
///
/// An `Archive` is a sequence of entries. You can
/// iterate over an archive using a `for`-`in` loop to get access to individual `Entry` objects:
///
/// for entry in archive {
/// print(entry.path)
/// }
///
/// Each `Entry` in an `Archive` is represented by its `path`. You can
/// use `path` to retrieve the corresponding `Entry` from an `Archive` via subscripting:
///
/// let entry = archive['/path/file.txt']
///
/// To create a new `Archive`, pass in a non-existing file URL and `AccessMode.create`. To modify an
/// existing `Archive` use `AccessMode.update`:
///
/// var archiveURL = URL(fileURLWithPath: "/path/file.zip")
/// var archive = Archive(url: archiveURL, accessMode: .update)
/// try archive?.addEntry("test.txt", relativeTo: baseURL, compressionMethod: .deflate)
public final class Archive: Sequence {
typealias LocalFileHeader = Entry.LocalFileHeader
typealias DataDescriptor = Entry.DefaultDataDescriptor
typealias ZIP64DataDescriptor = Entry.ZIP64DataDescriptor
typealias CentralDirectoryStructure = Entry.CentralDirectoryStructure
/// An error that occurs during reading, creating or updating a ZIP file.
public enum ArchiveError: Error {
/// Thrown when an archive file is either damaged or inaccessible.
case unreadableArchive
/// Thrown when an archive is either opened with AccessMode.read or the destination file is unwritable.
case unwritableArchive
/// Thrown when the path of an `Entry` cannot be stored in an archive.
case invalidEntryPath
/// Thrown when an `Entry` can't be stored in the archive with the proposed compression method.
case invalidCompressionMethod
/// Thrown when the stored checksum of an `Entry` doesn't match the checksum during reading.
case invalidCRC32
/// Thrown when an extract, add or remove operation was canceled.
case cancelledOperation
/// Thrown when an extract operation was called with zero or negative `bufferSize` parameter.
case invalidBufferSize
/// Thrown when uncompressedSize/compressedSize exceeds `Int64.max` (Imposed by file API).
case invalidEntrySize
/// Thrown when the offset of local header data exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderDataOffset
/// Thrown when the size of local header exceeds `Int64.max` (Imposed by file API).
case invalidLocalHeaderSize
/// Thrown when the offset of central directory exceeds `Int64.max` (Imposed by file API).
case invalidCentralDirectoryOffset
/// Thrown when the size of central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectorySize
/// Thrown when number of entries in central directory exceeds `UInt64.max` (Imposed by ZIP specification).
case invalidCentralDirectoryEntryCount
/// Thrown when an archive does not contain the required End of Central Directory Record.
case missingEndOfCentralDirectoryRecord
}
/// The access mode for an `Archive`.
public enum AccessMode: UInt {
/// Indicates that a newly instantiated `Archive` should create its backing file.
case create
/// Indicates that a newly instantiated `Archive` should read from an existing backing file.
case read
/// Indicates that a newly instantiated `Archive` should update an existing backing file.
case update
}
/// The version of an `Archive`
enum Version: UInt16 {
/// The minimum version for deflate compressed archives
case v20 = 20
/// The minimum version for archives making use of ZIP64 extensions
case v45 = 45
}
struct EndOfCentralDirectoryRecord: DataSerializable {
let endOfCentralDirectorySignature = UInt32(endOfCentralDirectoryStructSignature)
let numberOfDisk: UInt16
let numberOfDiskStart: UInt16
let totalNumberOfEntriesOnDisk: UInt16
let totalNumberOfEntriesInCentralDirectory: UInt16
let sizeOfCentralDirectory: UInt32
let offsetToStartOfCentralDirectory: UInt32
let zipFileCommentLength: UInt16
let zipFileCommentData: Data
static let size = 22
}
/// URL of an Archive's backing file.
public let url: URL
/// Access mode for an archive file.
public let accessMode: AccessMode
var archiveFile: FILEPointer
var endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
var zip64EndOfCentralDirectory: ZIP64EndOfCentralDirectory?
var preferredEncoding: String.Encoding?
var totalNumberOfEntriesInCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.totalNumberOfEntriesInCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.totalNumberOfEntriesInCentralDirectory)
}
var sizeOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.sizeOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.sizeOfCentralDirectory)
}
var offsetToStartOfCentralDirectory: UInt64 {
zip64EndOfCentralDirectory?.record.offsetToStartOfCentralDirectory
?? UInt64(endOfCentralDirectoryRecord.offsetToStartOfCentralDirectory)
}
/// Initializes a new ZIP `Archive`.
///
/// You can use this initalizer to create new archive files or to read and update existing ones.
/// The `mode` parameter indicates the intended usage of the archive: `.read`, `.create` or `.update`.
/// - Parameters:
/// - url: File URL to the receivers backing file.
/// - mode: Access mode of the receiver.
/// - preferredEncoding: Encoding for entry paths. Overrides the encoding specified in the archive.
/// This encoding is only used when _decoding_ paths from the receiver.
/// Paths of entries added with `addEntry` are always UTF-8 encoded.
/// - Returns: An archive initialized with a backing file at the passed in file URL and the given access mode
/// or `nil` if the following criteria are not met:
/// - Note:
/// - The file URL _must_ point to an existing file for `AccessMode.read`.
/// - The file URL _must_ point to a non-existing file for `AccessMode.create`.
/// - The file URL _must_ point to an existing file for `AccessMode.update`.
public init?(url: URL, accessMode mode: AccessMode, preferredEncoding: String.Encoding? = nil) {
self.url = url
self.accessMode = mode
self.preferredEncoding = preferredEncoding
guard let config = Archive.makeBackingConfiguration(for: url, mode: mode) else {
return nil
}
self.archiveFile = config.file
self.endOfCentralDirectoryRecord = config.endOfCentralDirectoryRecord
self.zip64EndOfCentralDirectory = config.zip64EndOfCentralDirectory
setvbuf(self.archiveFile, nil, _IOFBF, Int(defaultPOSIXBufferSize))
}
#if swift(>=5.0)
var memoryFile: MemoryFile?
/// Initializes a new in-memory ZIP `Archive`.
///
/// You can use this initalizer to create new in-memory archive files or to read and update existing ones.
///
/// - Parameters:
/// - data: `Data` object used as backing for in-memory archives.
/// - mode: Access mode of the receiver.
/// - preferredEncoding: Encoding for entry paths. Overrides the encoding specified in the archive.
/// This encoding is only used when _decoding_ paths from the receiver.
/// Paths of entries added with `addEntry` are always UTF-8 encoded.
/// - Returns: An in-memory archive initialized with passed in backing data.
/// - Note:
/// - The backing `data` _must_ contain a valid ZIP archive for `AccessMode.read` and `AccessMode.update`.
/// - The backing `data` _must_ be empty (or omitted) for `AccessMode.create`.
public init?(data: Data = Data(), accessMode mode: AccessMode, preferredEncoding: String.Encoding? = nil) {
guard let url = URL(string: "\(memoryURLScheme)://"),
let config = Archive.makeBackingConfiguration(for: data, mode: mode) else {
return nil
}
self.url = url
self.accessMode = mode
self.preferredEncoding = preferredEncoding
self.archiveFile = config.file
self.memoryFile = config.memoryFile
self.endOfCentralDirectoryRecord = config.endOfCentralDirectoryRecord
self.zip64EndOfCentralDirectory = config.zip64EndOfCentralDirectory
}
#endif
deinit {
fclose(self.archiveFile)
}
public func makeIterator() -> AnyIterator<Entry> {
let totalNumberOfEntriesInCD = self.totalNumberOfEntriesInCentralDirectory
var directoryIndex = self.offsetToStartOfCentralDirectory
var index = 0
return AnyIterator {
guard index < totalNumberOfEntriesInCD else { return nil }
guard let centralDirStruct: CentralDirectoryStructure = Data.readStruct(from: self.archiveFile,
at: directoryIndex) else {
return nil
}
let offset = UInt64(centralDirStruct.effectiveRelativeOffsetOfLocalHeader)
guard let localFileHeader: LocalFileHeader = Data.readStruct(from: self.archiveFile,
at: offset) else { return nil }
var dataDescriptor: DataDescriptor?
var zip64DataDescriptor: ZIP64DataDescriptor?
if centralDirStruct.usesDataDescriptor {
let additionalSize = UInt64(localFileHeader.fileNameLength) + UInt64(localFileHeader.extraFieldLength)
let isCompressed = centralDirStruct.compressionMethod != CompressionMethod.none.rawValue
let dataSize = isCompressed
? centralDirStruct.effectiveCompressedSize
: centralDirStruct.effectiveUncompressedSize
let descriptorPosition = offset + UInt64(LocalFileHeader.size) + additionalSize + dataSize
if centralDirStruct.isZIP64 {
zip64DataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
} else {
dataDescriptor = Data.readStruct(from: self.archiveFile, at: descriptorPosition)
}
}
defer {
directoryIndex += UInt64(CentralDirectoryStructure.size)
directoryIndex += UInt64(centralDirStruct.fileNameLength)
directoryIndex += UInt64(centralDirStruct.extraFieldLength)
directoryIndex += UInt64(centralDirStruct.fileCommentLength)
index += 1
}
return Entry(centralDirectoryStructure: centralDirStruct, localFileHeader: localFileHeader,
dataDescriptor: dataDescriptor, zip64DataDescriptor: zip64DataDescriptor)
}
}
/// Retrieve the ZIP `Entry` with the given `path` from the receiver.
///
/// - Note: The ZIP file format specification does not enforce unique paths for entries.
/// Therefore an archive can contain multiple entries with the same path. This method
/// always returns the first `Entry` with the given `path`.
///
/// - Parameter path: A relative file path identifying the corresponding `Entry`.
/// - Returns: An `Entry` with the given `path`. Otherwise, `nil`.
public subscript(path: String) -> Entry? {
if let encoding = preferredEncoding {
return self.first { $0.path(using: encoding) == path }
}
return self.first { $0.path == path }
}
// MARK: - Helpers
static func scanForEndOfCentralDirectoryRecord(in file: FILEPointer)
-> EndOfCentralDirectoryStructure? {
var eocdOffset: UInt64 = 0
var index = minEndOfCentralDirectoryOffset
fseeko(file, 0, SEEK_END)
let archiveLength = Int64(ftello(file))
while eocdOffset == 0 && index <= archiveLength {
fseeko(file, off_t(archiveLength - index), SEEK_SET)
var potentialDirectoryEndTag: UInt32 = UInt32()
fread(&potentialDirectoryEndTag, 1, MemoryLayout<UInt32>.size, file)
if potentialDirectoryEndTag == UInt32(endOfCentralDirectoryStructSignature) {
eocdOffset = UInt64(archiveLength - index)
guard let eocd: EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: eocdOffset) else {
return nil
}
let zip64EOCD = scanForZIP64EndOfCentralDirectory(in: file, eocdOffset: eocdOffset)
return (eocd, zip64EOCD)
}
index += 1
}
return nil
}
private static func scanForZIP64EndOfCentralDirectory(in file: FILEPointer, eocdOffset: UInt64)
-> ZIP64EndOfCentralDirectory? {
guard UInt64(ZIP64EndOfCentralDirectoryLocator.size) < eocdOffset else {
return nil
}
let locatorOffset = eocdOffset - UInt64(ZIP64EndOfCentralDirectoryLocator.size)
guard UInt64(ZIP64EndOfCentralDirectoryRecord.size) < locatorOffset else {
return nil
}
let recordOffset = locatorOffset - UInt64(ZIP64EndOfCentralDirectoryRecord.size)
guard let locator: ZIP64EndOfCentralDirectoryLocator = Data.readStruct(from: file, at: locatorOffset),
let record: ZIP64EndOfCentralDirectoryRecord = Data.readStruct(from: file, at: recordOffset) else {
return nil
}
return ZIP64EndOfCentralDirectory(record: record, locator: locator)
}
}
extension Archive.EndOfCentralDirectoryRecord {
var data: Data {
var endOfCDSignature = self.endOfCentralDirectorySignature
var numberOfDisk = self.numberOfDisk
var numberOfDiskStart = self.numberOfDiskStart
var totalNumberOfEntriesOnDisk = self.totalNumberOfEntriesOnDisk
var totalNumberOfEntriesInCD = self.totalNumberOfEntriesInCentralDirectory
var sizeOfCentralDirectory = self.sizeOfCentralDirectory
var offsetToStartOfCD = self.offsetToStartOfCentralDirectory
var zipFileCommentLength = self.zipFileCommentLength
var data = Data()
withUnsafePointer(to: &endOfCDSignature, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
withUnsafePointer(to: &numberOfDisk, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
withUnsafePointer(to: &numberOfDiskStart, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
withUnsafePointer(to: &totalNumberOfEntriesOnDisk, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
withUnsafePointer(to: &totalNumberOfEntriesInCD, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
withUnsafePointer(to: &sizeOfCentralDirectory, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
withUnsafePointer(to: &offsetToStartOfCD, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
withUnsafePointer(to: &zipFileCommentLength, { data.append(UnsafeBufferPointer(start: $0, count: 1))})
data.append(self.zipFileCommentData)
return data
}
init?(data: Data, additionalDataProvider provider: (Int) throws -> Data) {
guard data.count == Archive.EndOfCentralDirectoryRecord.size else { return nil }
guard data.scanValue(start: 0) == endOfCentralDirectorySignature else { return nil }
self.numberOfDisk = data.scanValue(start: 4)
self.numberOfDiskStart = data.scanValue(start: 6)
self.totalNumberOfEntriesOnDisk = data.scanValue(start: 8)
self.totalNumberOfEntriesInCentralDirectory = data.scanValue(start: 10)
self.sizeOfCentralDirectory = data.scanValue(start: 12)
self.offsetToStartOfCentralDirectory = data.scanValue(start: 16)
self.zipFileCommentLength = data.scanValue(start: 20)
guard let commentData = try? provider(Int(self.zipFileCommentLength)) else { return nil }
guard commentData.count == Int(self.zipFileCommentLength) else { return nil }
self.zipFileCommentData = commentData
}
init(record: Archive.EndOfCentralDirectoryRecord,
numberOfEntriesOnDisk: UInt16,
numberOfEntriesInCentralDirectory: UInt16,
updatedSizeOfCentralDirectory: UInt32,
startOfCentralDirectory: UInt32) {
self.numberOfDisk = record.numberOfDisk
self.numberOfDiskStart = record.numberOfDiskStart
self.totalNumberOfEntriesOnDisk = numberOfEntriesOnDisk
self.totalNumberOfEntriesInCentralDirectory = numberOfEntriesInCentralDirectory
self.sizeOfCentralDirectory = updatedSizeOfCentralDirectory
self.offsetToStartOfCentralDirectory = startOfCentralDirectory
self.zipFileCommentLength = record.zipFileCommentLength
self.zipFileCommentData = record.zipFileCommentData
}
}
|
mit
|
ac45f43f52b8752ead03ebb3d40e0bc4
| 50.365385 | 118 | 0.683532 | 4.8213 | false | false | false | false |
mrdepth/EVEUniverse
|
Legacy/Neocom/Neocom/ContractInfoPresenter.swift
|
2
|
9284
|
//
// ContractInfoPresenter.swift
// Neocom
//
// Created by Artem Shimanski on 11/12/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import TreeController
import EVEAPI
class ContractInfoPresenter: TreePresenter {
typealias View = ContractInfoViewController
typealias Interactor = ContractInfoInteractor
typealias Presentation = [AnyTreeItem]
weak var view: View?
lazy var interactor: Interactor! = Interactor(presenter: self)
var content: Interactor.Content?
var presentation: Presentation?
var loading: Future<Presentation>?
required init(view: View) {
self.view = view
}
func configure() {
view?.tableView.register([Prototype.TreeSectionCell.default,
Prototype.TreeDefaultCell.default,
Prototype.TreeDefaultCell.attribute,
Prototype.TreeDefaultCell.contact])
interactor.configure()
applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in
self?.applicationWillEnterForeground()
}
}
private var applicationWillEnterForegroundObserver: NotificationObserver?
func presentation(for content: Interactor.Content) -> Future<Presentation> {
var rows = [Tree.Item.Row<Tree.Content.Default>]()
let contract = content.value.contract
let contacts = content.value.contacts
let locations = content.value.locations
let api = interactor.api
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Type", comment: "").uppercased(),
subtitle: contract.type.title),
diffIdentifier: "Type"))
if let description = contract.title, !description.isEmpty {
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Description", comment: "").uppercased(),
subtitle: description),
diffIdentifier: "Description"))
}
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Availability", comment: "").uppercased(),
subtitle: contract.availability.title),
diffIdentifier: "Availability"))
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Status", comment: "").uppercased(),
subtitle: contract.currentStatus.title),
diffIdentifier: "Status"))
if let fromID = contract.startLocationID, let toID = contract.endLocationID, fromID != toID, let from = locations?[fromID], let to = locations?[toID] {
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Start Location", comment: "").uppercased(),
attributedSubtitle: from.displayName),
diffIdentifier: "StartLocation"))
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("End Location", comment: "").uppercased(),
attributedSubtitle: to.displayName),
diffIdentifier: "EndLocation"))
}
else if let locationID = contract.startLocationID, let location = locations?[locationID] {
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Location", comment: "").uppercased(),
attributedSubtitle: location.displayName),
diffIdentifier: "Location"))
}
if let price = contract.price, price > 0 {
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Buyer Will Pay", comment: "").uppercased(),
subtitle: UnitFormatter.localizedString(from: price, unit: .isk, style: .long)),
diffIdentifier: "Price"))
}
if let reward = contract.reward, reward > 0 {
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Buyer Will Get", comment: "").uppercased(),
subtitle: UnitFormatter.localizedString(from: reward, unit: .isk, style: .long)),
diffIdentifier: "Reward"))
}
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Date Issued", comment: "").uppercased(),
subtitle: DateFormatter.localizedString(from: contract.dateIssued, dateStyle: .medium, timeStyle: .medium)),
diffIdentifier: "Issued"))
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Date Expired", comment: "").uppercased(),
subtitle: DateFormatter.localizedString(from: contract.dateExpired, dateStyle: .medium, timeStyle: .medium)),
diffIdentifier: "Expired"))
if let date = contract.dateAccepted {
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Date Accepted", comment: "").uppercased(),
subtitle: DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium)),
diffIdentifier: "Accepted"))
}
if let date = contract.dateCompleted {
rows.append(Tree.Item.Row(Tree.Content.Default(prototype: Prototype.TreeDefaultCell.attribute,
title: NSLocalizedString("Date Completed", comment: "").uppercased(),
subtitle: DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium)),
diffIdentifier: "Completed"))
}
var sections = [Tree.Item.SimpleSection(title: NSLocalizedString("Details", comment: "").uppercased(), treeController: view?.treeController, children: rows).asAnyItem]
if let items = content.value.items, !items.isEmpty {
let context = Services.sde.viewContext
func makeRow(_ item: ESI.Contracts.Item) -> Tree.Item.Row<Tree.Content.Default> {
let type = context.invType(item.typeID)
return Tree.Item.RoutableRow(Tree.Content.Default(title: type?.typeName ?? NSLocalizedString("Unknown", comment: ""),
subtitle: String.localizedStringWithFormat(NSLocalizedString("Quantity: %@", comment: ""), UnitFormatter.localizedString(from: item.quantity, unit: .none, style: .long)),
image: Image(type?.icon ?? context.eveIcon(.defaultType)),
accessoryType: .disclosureIndicator),
diffIdentifier: item,
route: type.map{Router.SDE.invTypeInfo(.type($0))})
}
let get = items.filter{$0.isIncluded}.map{makeRow($0)}
let pay = items.filter{!$0.isIncluded}.map{makeRow($0)}
if !get.isEmpty {
sections.append(Tree.Item.SimpleSection(title: NSLocalizedString("Buyer Will Get", comment: "").uppercased(), treeController: view?.treeController, children: get).asAnyItem)
}
if !pay.isEmpty {
sections.append(Tree.Item.SimpleSection(title: NSLocalizedString("Buyer Will Pay", comment: "").uppercased(), treeController: view?.treeController, children: pay).asAnyItem)
}
}
if let bids = content.value.bids, !bids.isEmpty {
let rows = bids.sorted {$0.amount > $1.amount}.map {
Tree.Item.BidRow($0, contact: contacts?[Int64($0.bidderID)], api: api)
}
if !rows.isEmpty {
sections.append(Tree.Item.SimpleSection(title: NSLocalizedString("Bids", comment: "").uppercased(), treeController: view?.treeController, children: rows).asAnyItem)
}
}
return .init(sections)
}
}
extension Tree.Item {
class BidRow: Row<ESI.Contracts.Bid> {
var api: API
var contact: Contact?
init(_ content: ESI.Contracts.Bid, contact: Contact?, api: API) {
self.api = api
super.init(content)
}
override var prototype: Prototype? {
return contact?.recipientType == .character ? Prototype.TreeDefaultCell.contact : Prototype.TreeDefaultCell.default
}
var image: UIImage?
override func configure(cell: UITableViewCell, treeController: TreeController?) {
super.configure(cell: cell, treeController: treeController)
guard let cell = cell as? TreeDefaultCell else {return}
cell.titleLabel?.text = UnitFormatter.localizedString(from: content.amount, unit: .isk, style: .long)
cell.subtitleLabel?.text = contact?.name
cell.subtitleLabel?.isHidden = false
cell.iconView?.isHidden = false
cell.iconView?.image = image ?? UIImage()
if let contact = contact, image == nil {
let dimension = Int(cell.iconView!.bounds.width)
api.image(contact: contact, dimension: dimension, cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak self, weak treeController] result in
guard let strongSelf = self else {return}
strongSelf.image = result.value
treeController?.reloadRow(for: strongSelf, with: .none)
}.catch(on: .main) { [weak self] _ in
self?.image = UIImage()
}
}
}
}
}
|
lgpl-2.1
|
bbe5120d1ae56b3cbbb3b90730ccb84f
| 43.204762 | 200 | 0.69331 | 4.246569 | false | false | false | false |
rosslebeau/bytefish
|
App/Models/Link.swift
|
1
|
1044
|
import Vapor
import Foundation
enum LinkError: ErrorProtocol {
case InvalidURL
}
final class Link {
var id: String
var seq: Int64
var slug: String
var originalUrl: NSURL
var shortUrl: NSURL
init(id: String, seq: Int64, slug: String, originalUrl: NSURL, shortUrl: NSURL) {
self.id = id
self.seq = seq
self.slug = slug
self.originalUrl = originalUrl
self.shortUrl = shortUrl
}
}
extension Link: JsonRepresentable {
func makeJson() -> Json {
return Json([
"id": "\(id)",
"slug": "\(slug)",
"originalUrl": "\(originalUrl)",
"shortUrl:": "\(shortUrl)"
])
}
}
extension Link: StringInitializable {
convenience init?(from slug: String) throws {
self.init(fromSlug: slug)
}
}
extension String {
func hasHttpPrefix() -> Bool {
return self.hasPrefix("http://") || self.hasPrefix("https://")
}
func hasScheme() -> Bool {
return range(of: "://") != nil
}
}
|
mit
|
2c07e49c0f9f818cb55a01e615d7cb74
| 20.306122 | 85 | 0.564176 | 4.062257 | false | false | false | false |
jimmatthews/poll2016
|
Poll 2016/PollsterModel.swift
|
1
|
8519
|
//
// PollsterModel.swift
// Poll 2016
//
// Created by James Matthews on 8/25/2016.
// Copyright © 2016 Fetch Softworks. All rights reserved.
//
import Foundation
class PollsterModelManager {
static let shared = PollsterModelManager()
var model: PollsterModel?
func isNewer(model newModel: PollsterModel) -> Bool {
return self.model == nil || newModel.timestamp > self.model!.timestamp
}
}
public enum MarginTrend: Int {
case Up = 1
case Down = -1
case Unchanged = 0
}
public struct Results2016 {
let date: Date
let clintonVote: Float
let trumpVote: Float
}
public struct PollsterModel {
let results: [Results2016]
}
extension Results2016 {
static let kDateKey = "DATE"
static let kClintonKey = "CLINTON"
static let kTrumpKey = "TRUMP"
public init?(dict: [String:AnyObject]) {
guard let date = dict[Results2016.kDateKey] as? Date,
let clinton = dict[Results2016.kClintonKey] as? Float,
let trump = dict[Results2016.kTrumpKey] as? Float else {
return nil
}
self.date = date
self.clintonVote = clinton
self.trumpVote = trump
}
public func convertToDictionary() -> [String: AnyObject]? {
return [Results2016.kDateKey : self.date as NSDate,
Results2016.kClintonKey : NSNumber(floatLiteral: Double(self.clintonVote)),
Results2016.kTrumpKey : NSNumber(floatLiteral: Double(self.trumpVote))]
}
func computeLeaderAndMargin() -> (String, Float) {
let leaderName = clintonVote > trumpVote ? "Clinton" : "Trump"
let margin = abs(clintonVote - trumpVote)
return (leaderName, margin)
}
}
extension PollsterModel {
var leader: String { return results.isEmpty ? "" : (results[0].clintonVote > results[0].trumpVote ? "Clinton" : "Trump") }
var margin: Float { return results.isEmpty ? 0.0 : abs(results[0].clintonVote - results[0].trumpVote) }
var trend: MarginTrend { return calculateMarginTrend() }
var timestamp: Date { return results.isEmpty ? Date() : results[0].date }
typealias JSONPayload = [String:Any]
struct Candidate {
let lastname: String
let vote: Float
}
init?(json: JSONPayload) {
guard let lastUpdate = json["last_updated"] as? String,
let estimates = json["estimates"] as? [JSONPayload],
let estimatesByDate = json["estimates_by_date"] as? [JSONPayload] else {
return nil
}
let timestamp = dateFromLastUpdateDateString(string: lastUpdate)
var candidates = estimates.map { (payload: JSONPayload) -> PollsterModel.Candidate in
let lastname = payload["last_name"] as! String
if let stringValue = payload["value"] as? String, let value = Float(stringValue) {
return Candidate(lastname: lastname, vote: value)
} else {
return Candidate(lastname: lastname, vote: payload["value"] as! Float)
}
}
candidates.sort { $0.vote > $1.vote }
var currentResults: [String:Float] = [:]
for candidate in candidates {
currentResults[candidate.lastname] = candidate.vote
}
let currentPollResults = Results2016(date: timestamp, clintonVote: currentResults["Clinton"]!, trumpVote: currentResults["Trump"]!)
let previousResults = estimatesByDate.map { (payload: JSONPayload) -> Results2016 in
let pollDate = dateFromPollDateString(string: payload["date"] as! String)
let pollEstimates = payload["estimates"] as! [JSONPayload]
var results: [String:Float] = [:]
for candidate in pollEstimates {
let candidateName = candidate["choice"] as! String
let candidateResult = candidate["value"] as! Float
results[candidateName] = candidateResult
}
return Results2016(date: pollDate, clintonVote: results["Clinton"]!, trumpVote: results["Trump"]!)
}
self.results = [currentPollResults] + previousResults
}
public init?(jsonData: Data) {
guard let jsonTemp = try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions()),
let json = jsonTemp as? JSONPayload else {
print("serialization error")
return nil
}
self.init(json: json)
}
public init?(fileURL: URL) {
guard let data = try? Data(contentsOf: fileURL) else {
return nil
}
self.init(jsonData: data)
}
static func update(completionHandler: @escaping (PollsterModel?) -> Void) {
let urlString = "http://elections.huffingtonpost.com/pollster/api/charts/2016-general-election-trump-vs-clinton.json"
let request = URLRequest(url: URL(string: urlString)!)
httpGet(request: request) {
(data, response, error) -> Void in
var newModel: PollsterModel? = nil
defer {
completionHandler(newModel)
}
guard error == nil else {
print("httpGet error: \(error!)")
return
}
guard let data = data else {
print("no data")
return
}
guard let model = PollsterModel(jsonData: data) else {
print("json parse error")
return
}
newModel = model
}
}
public var marginString: String {
let trendText: String
switch self.trend {
case .Up: trendText = "⬆︎"
case .Down: trendText = "⬇︎"
case .Unchanged: trendText = ""
}
return String(format: "+%.1f%@", self.margin, trendText)
}
public var horseraceString: String {
guard let clintonVote = results.first?.clintonVote,
let trumpVote = results.first?.trumpVote else { return "" }
if clintonVote > trumpVote {
return String(format: "Clinton: %.1f Trump: %.1f", clintonVote, trumpVote)
} else {
return String(format: "Trump: %.1f Clinton: %.1f", trumpVote, clintonVote)
}
}
public var timestampString: String {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter.string(from: timestamp)
}
private static let kResultsKey = "RESULTS"
public init?(dict: [String: AnyObject]) {
guard let resultDictionaries = dict[PollsterModel.kResultsKey] as? [[String:AnyObject]] else {
return nil
}
self.results = resultDictionaries.flatMap() { Results2016(dict: $0) }
}
public func convertToDictionary() -> [String: AnyObject]? {
let convertedResults = self.results.map { return $0.convertToDictionary()! }
return [PollsterModel.kResultsKey : convertedResults as NSArray]
}
func calculateMarginTrend() -> MarginTrend {
guard results.count > 1 else { return .Unchanged }
let (leader, margin) = results[0].computeLeaderAndMargin()
let (previousLeader, previousMargin) = results[1].computeLeaderAndMargin()
if leader != previousLeader || (margin - previousMargin >= 0.05) {
return .Up
} else if previousMargin - margin >= 0.05 {
return .Down
} else {
return .Unchanged
}
}
}
// MARK: - Utilities
private func httpGet(request: URLRequest!, callback: @escaping (Data?, URLResponse?, Error?) -> Void) {
URLSession.shared.dataTask(with: request, completionHandler: callback).resume()
}
private func dateFromPollDateString(string dateString: String) -> Date {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy'-'MM'-'dd"
return formatter.date(from: dateString)!
}
private func dateFromLastUpdateDateString(string dateString: String) -> Date {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"
return formatter.date(from: dateString)!
}
|
mit
|
9f56be43c0da01f27ebc633dd27eff41
| 33.734694 | 139 | 0.605288 | 4.321991 | false | false | false | false |
szk-atmosphere/URLEmbeddedView
|
URLEmbeddedView/Core/Downloader/OpenGraphDataDownloader.swift
|
1
|
3868
|
//
// OpenGraphDataDownloader.swift
// URLEmbeddedView
//
// Created by marty-suzuki on 2018/07/14.
// Copyright © 2018年 marty-suzuki. All rights reserved.
//
import Foundation
/// Use for Test
protocol OpenGraphDataDownloaderProtocol: class {
func fetchOGData(urlString: String, completion: ((OpenGraphDataDownloader.Result) -> Void)?) -> Task
func fetchOGData(urlString: String, task: Task, completion: ((OpenGraphDataDownloader.Result) -> Void)?) -> Task
func cancelLoading(_ task: Task, shouldContinueDownloading: Bool)
}
/// OGP object downloader
@objc public final class OpenGraphDataDownloader: NSObject, OpenGraphDataDownloaderProtocol {
@objc(sharedInstance)
public static let shared = OpenGraphDataDownloader()
private let session: OGSessionProtocol
init(session: OGSessionProtocol = OGSession(configuration: .default)) {
self.session = session
super.init()
}
@discardableResult
@objc public func fetchOGData(withURLString urlString: String, completion: ((OpenGraphData?, Swift.Error?) -> Void)? = nil) -> Task {
return fetchOGData(urlString: urlString) { completion?($0.data as OpenGraphData?, $0.error) }
}
@discardableResult
@nonobjc public func fetchOGData(urlString: String, completion: ((Result) -> Void)? = nil) -> Task {
return fetchOGData(urlString: urlString, task: .init(), completion: completion)
}
@discardableResult
func fetchOGData(urlString: String, task: Task, completion: ((Result) -> Void)? = nil) -> Task {
guard let url = URL(string: urlString) else {
completion?(.failure(error: Error.createURLFailed(urlString), isExpired: false))
return task
}
let failure: (OGSession.Error, Bool) -> Void = { error, isExpired in
completion?(.failure(error: error, isExpired: isExpired))
}
if url.host?.contains("youtube.com") == true {
guard let request = YoutubeEmbedRequest(url: url) else {
completion?(.failure(error: Error.createYoutubeRequestFailed(urlString), isExpired: false))
return task
}
return session.send(request, task: task, success: { youtube, isExpired in
let data = OpenGraph.Data(youtube: youtube, sourceUrl: url.absoluteString)
completion?(.success(data: data, isExpired: isExpired))
}, failure: failure)
} else {
let request = HtmlRequest(url: url)
return session.send(request, task: task, success: { html, isExpired in
let data = OpenGraph.Data(html: html, sourceUrl: url.absoluteString)
completion?(.success(data: data, isExpired: isExpired))
}, failure: failure)
}
}
@objc public func cancelLoading(_ task: Task, shouldContinueDownloading: Bool) {
task.expire(shouldContinueDownloading: shouldContinueDownloading)
}
}
extension OpenGraphDataDownloader {
/// Represents error
public enum Error: Swift.Error {
case createURLFailed(String)
case createYoutubeRequestFailed(String)
}
/// Represents download result
public enum Result {
case success(data: OpenGraph.Data, isExpired: Bool)
case failure(error: Swift.Error, isExpired: Bool)
}
}
extension OpenGraphDataDownloader.Result {
public var isExpired: Bool {
switch self {
case .failure(_, let isExpired): return isExpired
case .success(_, let isExpired): return isExpired
}
}
public var data: OpenGraph.Data? {
if case .success(let data, _) = self {
return data
}
return nil
}
public var error: Swift.Error? {
if case .failure(let error, _) = self {
return error
}
return nil
}
}
|
mit
|
1a0b994d52d14b512d430d076f136163
| 34.458716 | 137 | 0.644761 | 4.573964 | false | false | false | false |
semiroot/SwiftyConstraints
|
Examples/macOS/macOS/ViewController.swift
|
1
|
1007
|
//
// ViewController.swift
// Example-Mac-Swift2.3
//
// Created by Hansmartin Geiser on 25/03/17.
// Copyright © 2017 Hansmartin Geiser. All rights reserved.
//
import Foundation
import SwiftyConstraints
class ViewController: NSViewController {
override func loadView() {
view = NSView()
}
override func viewDidLoad() {
super.viewDidLoad()
let sc = view.swiftyConstraints()
for i in 1...100 {
let view = SCView() // SCView is an alias fro UIView or NSView
let floatedIndex = CGFloat(Float(100-i) / 100)
view.wantsLayer = true
view.layer?.backgroundColor = NSColor(
red: floatedIndex,
green: floatedIndex,
blue: floatedIndex,
alpha: 1
).cgColor
sc.attach(view)
.top()
.left()
.widthOfSuperview(0.1)
.heightFromWidth()
.stackLeft()
if i % 10 == 0 {
sc.resetStackLeft()
.stackTop()
}
}
}
}
|
mit
|
f7e60fcff794acd6cd8f938924aa83c5
| 19.530612 | 68 | 0.570577 | 4.209205 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/Plans/PlanDetailViewModel.swift
|
2
|
3229
|
import Foundation
import WordPressShared
struct PlanDetailViewModel {
let plan: Plan
let features: FeaturesViewModel
enum FeaturesViewModel {
case loading
case error(String)
case ready([PlanFeature])
}
func withFeatures(_ features: FeaturesViewModel) -> PlanDetailViewModel {
return PlanDetailViewModel(
plan: plan,
features: features
)
}
var tableViewModel: ImmuTable {
switch features {
case .loading, .error:
return ImmuTable.Empty
case .ready(let features):
let featureSlugs = plan.features.split(separator: ",")
// Assume the order of the slugs is the order we want to display features.
let planFeatures = featureSlugs.compactMap { slug -> PlanFeature? in
return features.filter { feature -> Bool in
return feature.slug == slug
}.first
}
let rows: [ImmuTableRow] = planFeatures.map({ feature in
let row = FeatureItemRow(title: feature.title, description: feature.summary, iconURL: nil)
return row
})
return ImmuTable(sections: [ImmuTableSection(headerText: "", rows: rows, footerText: nil)])
}
}
var noResultsViewModel: NoResultsViewController.Model? {
switch features {
case .loading:
return NoResultsViewController.Model(title: LocalizedText.loadingTitle)
case .ready:
return nil
case .error:
if let appDelegate = WordPressAppDelegate.shared,
appDelegate.connectionAvailable {
return NoResultsViewController.Model(title: LocalizedText.errorTitle,
subtitle: LocalizedText.errorSubtitle,
buttonText: LocalizedText.errorButtonText)
} else {
return NoResultsViewController.Model(title: LocalizedText.noConnectionTitle,
subtitle: LocalizedText.noConnectionSubtitle)
}
}
}
private struct LocalizedText {
static let loadingTitle = NSLocalizedString("Loading Plan...", comment: "Text displayed while loading plans details")
static let errorTitle = NSLocalizedString("Oops", comment: "An informal exclaimation that means `something went wrong`.")
static let errorSubtitle = NSLocalizedString("There was an error loading the plan", comment: "Text displayed when there is a failure loading the plan details")
static let errorButtonText = NSLocalizedString("Contact support", comment: "Button label for contacting support")
static let noConnectionTitle = NSLocalizedString("No connection", comment: "An error message title shown when there is no internet connection.")
static let noConnectionSubtitle = NSLocalizedString("An active internet connection is required to view plans", comment: "An error message shown when there is no internet connection.")
static let price = NSLocalizedString("%@ per year", comment: "Plan yearly price")
}
}
|
gpl-2.0
|
f8b8a9259bfd9432e5b4d2a94c24d17b
| 44.478873 | 191 | 0.627439 | 5.715044 | false | false | false | false |
imxieyi/iosu
|
iosu/Beatmap/Renderer/ActionSet.swift
|
1
|
2908
|
//
// ActionSet.swift
// iosu
//
// Created by xieyi on 2017/5/16.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import SpriteKit
class ActionSet {
fileprivate var actions:[HitObjectAction]=[]
fileprivate var actnums:[Int] = []
fileprivate var actcols:[UIColor] = []
fileprivate weak var scene:SKScene!
fileprivate var nextindex:Int=0
open static weak var difficulty:BMDifficulty?
open static weak var current:ActionSet?
func destroy() {
for act in actions {
act.destroy()
}
actions.removeAll()
}
init(beatmap:Beatmap,scene:SKScene) {
ActionSet.difficulty = beatmap.difficulty
self.scene=scene
let colors=beatmap.colors
var colorindex=0
var number=0
for obj in beatmap.hitobjects {
switch obj.type {
case .circle:
if obj.newCombo {
number=1
colorindex+=1
if colorindex == colors.count {
colorindex = 0
}
} else {
number+=1
}
actnums.append(number)
actions.append(CircleAction(obj: obj as! HitCircle))
actcols.append(colors[colorindex])
break
case .slider:
if obj.newCombo {
number=1
colorindex+=1
if colorindex == colors.count {
colorindex = 0
}
} else {
number+=1
}
actnums.append(number)
actions.append(SliderAction(obj: obj as! Slider, timing: beatmap.getTimingPoint(obj.time)))
actcols.append(colors[colorindex])
break
case .spinner:
break
case .none:
break
}
}
ActionSet.current=self
}
open func prepare() {
var layer:CGFloat = 100000
for i in 0...actions.count-1 {
actions[i].prepare(actcols[i], number: actnums[i], layer: layer)
layer-=1
}
}
open func hasnext() -> Bool {
return nextindex<actions.count
}
//In ms
open func shownext(_ offset:Double) {
if offset >= 0 {
actions[nextindex].show(scene, offset: offset)
}
nextindex+=1
}
open func nexttime() -> Double {
if nextindex < actions.count {
return actions[nextindex].gettime()
}
return Double(Int.max)
}
open var pointer=0
open func currentact() -> HitObjectAction? {
if pointer<actions.count {
return actions[pointer]
}
return nil
}
}
|
mit
|
7c390dd924a5f3fe745c729a03fe9e54
| 25.651376 | 107 | 0.492255 | 4.685484 | false | false | false | false |
NougatFramework/Switchboard
|
Sources/Route.swift
|
1
|
1684
|
protocol RouteHandlingType {
func perform(_ request: MatchedRequest) -> Response?
}
public struct Route {
public typealias Middleware = (_ request: Request, _ next: (Request) throws -> Response) throws -> Response
public let method: Method
public let wildcardPath: WildcardPath
public let middleware: [Middleware]
let handler: RouteHandlingType
init(method: Method, wildcardPath: WildcardPath, middleware: [Middleware] = [], handler: RouteHandlingType) {
self.method = method
self.wildcardPath = wildcardPath
self.middleware = middleware
self.handler = handler
}
public func matches(_ request: Request) -> Bool {
return matches(request.method, path: request.path)
}
public func matches(_ method: Method, path: Path) -> Bool {
guard self.method == method else { return false }
guard wildcardPath.matches(path: path) else { return false }
return true
}
public func handle(_ request: Request) throws -> Response {
return try handle(request, middlewareGenerator: middleware.makeIterator())
}
fileprivate func handle(_ request: Request, middlewareGenerator: IndexingIterator<[Middleware]>) throws -> Response {
var mutableMiddlewareGenerator = middlewareGenerator
if let middleware = mutableMiddlewareGenerator.next() {
return try middleware(request, { (aRequest) -> Response in
return try self.handle(aRequest, middlewareGenerator: mutableMiddlewareGenerator)
})
}
let matchedRequest = MatchedRequest(request: request, route: self)
guard let response = handler.perform(matchedRequest) else {
throw RoutingError.notFound(request.method, request.path)
}
return response
}
}
|
mit
|
4a35cfed5540352a8b870e86526a5591
| 29.071429 | 118 | 0.727435 | 4.189055 | false | false | false | false |
sessionm/ios-smp-example
|
Campaigns/CampaignsTableViewController.swift
|
1
|
3825
|
//
// CampaignTableViewController.swift
// SMPExample
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMCampaignsKit
import UIKit
class CampaignCell: UITableViewCell {
@IBOutlet var header: UILabel!
@IBOutlet var subheader: UILabel!
@IBOutlet var details: UILabel!
@IBOutlet var icon: UIImageView!
@IBOutlet var imge: UIImageView!
@IBOutlet var imageWidth: NSLayoutConstraint!
}
class CampaignTableViewController: UITableViewController {
private let campaignsManager = SMCampaignsManager.instance()
private var feedMessages: [SMFeedMessage] = []
@IBAction private func onRefresh(_ sender: UIRefreshControl) {
fetchMessages()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fetchMessages()
}
private func fetchMessages() {
self.refreshControl?.beginRefreshing()
campaignsManager.fetchFeedMessages(completionHandler: { (messages: [SMFeedMessage]?, error: SMError?) in
if let err = error {
Util.failed(self, message: err.message)
} else if let feed = messages {
self.feedMessages = feed
self.tableView.reloadData()
}
self.refreshControl?.endRefreshing()
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedMessages.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let message = feedMessages[indexPath.row]
if message.imageURL != nil {
return 240.0
} else {
return 96.0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = feedMessages[indexPath.row]
var cell: CampaignCell? = nil
if message.imageURL != nil {
cell = tableView.dequeueReusableCell(withIdentifier: "CampaignCellImage", for: indexPath) as? CampaignCell
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "CampaignCellNoImage", for: indexPath) as? CampaignCell
}
if let c = cell, let header = c.header, let subheader = c.subheader, let details = c.details, let icon = c.icon {
header.text = message.header
subheader.text = message.subheader
details.text = message.details
if let img = message.imageURL {
Util.loadFrom(img, callback: { (image) in
if let i = c.imge {
i.image = nil
c.imageWidth.constant = c.frame.size.height
Util.imageToView(image, view: i, contain: c)
}
})
}
if let icn = message.iconURL {
if (icn.count > 0) {
Util.loadFrom(icn, callback: { (image) in
icon.image = image
})
}
}
}
message.notifySeen()
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = feedMessages[indexPath.row]
message.notifyTapped()
campaignsManager.executeAction(for: message)
}
@IBAction private func logout(_ sender: AnyObject) {
if let provider = SessionM.authenticationProvider() as? SessionMOAuthProvider {
provider.logOutUser { (authState, error) in
LoginViewController.loginIfNeeded(self)
}
}
}
}
|
mit
|
148d8fc04e9687bd61dac8d6af02ab3f
| 31.965517 | 121 | 0.601726 | 5.024967 | false | false | false | false |
ethan-fang/Alamofire
|
Source/Alamofire.swift
|
2
|
10679
|
// Alamofire.swift
//
// Copyright (c) 2014–2015 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
/// Alamofire errors
public let AlamofireErrorDomain = "com.alamofire.error"
public let AlamofireInputStreamReadFailed = -6000
public let AlamofireOutputStreamWriteFailed = -6001
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
*/
public protocol URLStringConvertible {
/**
A URL that conforms to RFC 2396.
Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
See http://tools.ietf.org/html/rfc2396
See http://tools.ietf.org/html/rfc1738
See http://tools.ietf.org/html/rfc1808
*/
var URLString: String { get }
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString!
}
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
// MARK: - URLRequestConvertible
/**
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
*/
public protocol URLRequestConvertible {
/// The URL request.
var URLRequest: NSURLRequest { get }
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSURLRequest {
return self
}
}
// MARK: - Convenience
func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
return mutableURLRequest
}
// MARK: - Request Methods
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return Manager.sharedInstance.request(method, URLString, parameters: parameters, encoding: encoding)
}
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
return Manager.sharedInstance.request(URLRequest.URLRequest)
}
// MARK: - Upload Methods
// MARK: File
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
:param: method The HTTP method.
:param: URLString The URL string.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(method, URLString, file: file)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and file.
:param: URLRequest The URL request.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest, file: file)
}
// MARK: Data
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
:param: method The HTTP method.
:param: URLString The URL string.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(method, URLString, data: data)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and data.
:param: URLRequest The URL request.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest, data: data)
}
// MARK: Stream
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
:param: method The HTTP method.
:param: URLString The URL string.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(method, URLString, stream: stream)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and stream.
:param: URLRequest The URL request.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest, stream: stream)
}
// MARK: MultipartFormData
/**
Creates an upload request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: multipartFormData The closure used to append body parts to the `MultipartFormData`.
:param: encodingMemoryThreshold The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold`
by default.
:param: encodingCompletion The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
method: Method,
#URLString: URLStringConvertible,
#multipartFormData: MultipartFormData -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
#encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
{
return Manager.sharedInstance.upload(
method,
URLString,
multipartFormData: multipartFormData,
encodingMemoryThreshold: encodingMemoryThreshold,
encodingCompletion: encodingCompletion
)
}
/**
Creates an upload request using the shared manager instance for the specified method and URL string.
:param: URLRequest The URL request.
:param: multipartFormData The closure used to append body parts to the `MultipartFormData`.
:param: encodingMemoryThreshold The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold`
by default.
:param: encodingCompletion The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
URLRequest: URLRequestConvertible,
#multipartFormData: MultipartFormData -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
#encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)
{
return Manager.sharedInstance.upload(
URLRequest,
multipartFormData: multipartFormData,
encodingMemoryThreshold: encodingMemoryThreshold,
encodingCompletion: encodingCompletion
)
}
// MARK: - Download Methods
// MARK: URL Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(method, URLString, destination: destination)
}
/**
Creates a download request using the shared manager instance for the specified URL request.
:param: URLRequest The URL request.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest, destination: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(data, destination: destination)
}
|
mit
|
1be9345c878b3ff60c2f844acca3a900
| 34.471761 | 208 | 0.737286 | 5.017387 | false | false | false | false |
oskarpearson/rileylink_ios
|
MinimedKit/PumpEvents/BolusReminderPumpEvent.swift
|
1
|
981
|
//
// Mystery69PumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 9/23/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct BolusReminderPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public init?(availableData: Data, pumpModel: PumpModel) {
if pumpModel.larger {
length = 9
} else {
length = 7 // This may not actually occur, as I don't think x22 and earlier pumps have missed bolus reminders.
}
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "BolusReminder",
]
}
}
|
mit
|
9a39c21f4248db99a5c69d89d9acf1e5
| 25.486486 | 122 | 0.608163 | 4.780488 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie
|
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Other-其他/View/XMGPushGuideView.swift
|
1
|
1939
|
//
// XMGPushGuideView.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/2/19.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
class XMGPushGuideView: UIView {
class func show(){
if isNewupdate() == true{
let window:UIWindow = UIApplication.sharedApplication().keyWindow!
let guideview = XMGPushGuideView.viewFromXIB()
guideview.frame = window.bounds
window.addSubview(guideview)
}
}
class func isNewupdate() -> Bool{
// 1.获取当前软件的版本号 --> info.plist
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
// 2.获取以前的软件版本号 --> 从本地文件中读取(以前自己存储的)
let sandboxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
print("current = \(currentVersion) sandbox = \(sandboxVersion)")
// 3.比较当前版本号和以前版本号
// 2.0 1.0
if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending{
// 3.1如果当前>以前 --> 有新版本
// 3.1.1存储当前最新的版本号
// iOS7以后就不用调用同步方法了
NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString")
return true
}
// 3.2如果当前< | == --> 没有新版本
return false
}
/*
class func guideView()->XMGPushGuideView{
return NSBundle.mainBundle().loadNibNamed("XMGPushGuideView", owner: nil, options: nil).last as! XMGPushGuideView
}
*/
@IBAction func close(sender: UIButton) {
self.removeFromSuperview()
}
}
|
apache-2.0
|
a5ee6108518ffe5ac8bc4dc35e9cd2f1
| 27.225806 | 127 | 0.589714 | 4.521964 | false | false | false | false |
chayelheinsen/GamingStreams-tvOS-App
|
StreamCenter/TwitchChannel.swift
|
3
|
3278
|
//
// TwitchChannel.swift
// TestTVApp
//
// Created by Olivier Boucher on 2015-09-13.
import Foundation
struct TwitchChannel {
let id : Int!
let name : String!
let displayName : String!
let links : [String : String]!
let broadcasterLanguage : String?
let language : String!
let gameName : String!
let logo : String?
let status : String!
let videoBanner : String?
let lastUpdate : NSDate!
let followers : Int!
let views : Int!
init(id : Int, name : String, displayName : String, links : [String : String], broadcasterLanguage : String?,
language : String, gameName : String, logo : String?, status : String, videoBanner : String?,
lastUpdate : NSDate, followers : Int, views : Int) {
self.id = id
self.name = name
self.displayName = displayName
self.links = links
self.broadcasterLanguage = broadcasterLanguage
self.language = language
self.gameName = gameName
self.logo = logo
self.status = status
self.videoBanner = videoBanner
self.lastUpdate = lastUpdate
self.followers = followers
self.views = views
}
init?(dict: [String : AnyObject]) {
guard let id = dict["_id"] as? Int else {
return nil
}
guard let name = dict["name"] as? String else {
return nil
}
guard let displayName = dict["display_name"] as? String else {
return nil
}
guard let links = dict["_links"] as? [String : String] else {
return nil
}
guard let language = dict["language"] as? String else {
return nil
}
guard let gameName = dict["game"] as? String else {
return nil
}
guard let status = dict["status"] as? String else {
return nil
}
self.id = id
self.name = name
self.displayName = displayName
self.links = links
self.language = language
self.gameName = gameName
self.status = status
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssXXX"
if let updateDateString = dict["updated_at"] as? String, updateDate = dateFormatter.dateFromString(updateDateString) {
self.lastUpdate = updateDate
}
else {
self.lastUpdate = NSDate()
}
if let followers = dict["followers"] as? Int {
self.followers = followers
}
else {
self.followers = 0
}
if let views = dict["views"] as? Int {
self.views = views
}
else {
self.views = 0
}
self.broadcasterLanguage = dict["broadcaster_language"] as? String
self.videoBanner = dict["video_banner"] as? String
self.logo = dict["logo"] as? String
}
var displayLanguage: String? {
get {
if let display = NSLocale(localeIdentifier: language).displayNameForKey(NSLocaleLanguageCode, value: language) {
return display.lowercaseString
}
return nil
}
}
}
|
mit
|
3535faed47d35b22b543d7bd6b2da1e9
| 29.082569 | 126 | 0.554606 | 4.703013 | false | false | false | false |
edx/edx-app-ios
|
Source/JSONFormBuilder.swift
|
1
|
18193
|
//
// JSONFormBuilder.swift
// edX
//
// Created by Michael Katz on 9/29/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
import edXCore
private func equalsCaseInsensitive(lhs: String, _ rhs: String) -> Bool {
return lhs.caseInsensitiveCompare(rhs) == .orderedSame
}
/** Model for the built form must allow for reads and updates */
protocol FormData {
func valueForField(key: String) -> String?
func displayValueForKey(key: String) -> String?
func setValue(value: String?, key: String)
}
/** Decorate the cell with the model object */
protocol FormCell {
func applyData(field: JSONFormBuilder.Field, data: FormData)
}
private func loadJSON(jsonFile: String) throws -> JSON {
var js: JSON
if let filePath = Bundle.main.path(forResource: jsonFile, ofType: "json") {
if let data = NSData(contentsOfFile: filePath) {
var error: NSError?
js = JSON(data: data as Data, error: &error)
if error != nil { throw error! }
} else {
js = JSON(NSNull())
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
} else {
js = JSON(NSNull())
throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil)
}
return js
}
/** Function to turn a specialized JSON file (https://openedx.atlassian.net/wiki/display/MA/Profile+Forms) into table rows, with various editor views and view controllers */
class JSONFormBuilder {
/** Show a segmented control from a limited set of options */
class SegmentCell: UITableViewCell, FormCell {
static let Identifier = "JSONForm.SwitchCell"
let titleLabel = UILabel()
let descriptionLabel = UILabel()
let typeControl = UISegmentedControl()
var values = [String]()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(titleLabel)
contentView.addSubview(typeControl)
contentView.addSubview(descriptionLabel)
titleLabel.textAlignment = .natural
descriptionLabel.textAlignment = .natural
descriptionLabel.numberOfLines = 0
descriptionLabel.preferredMaxLayoutWidth = 200 //value doesn't seem to matter as long as it's small enough
typeControl.tintColor = OEXStyles.shared().primaryBaseColor()
typeControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: UIControl.State.selected)
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(contentView.snp.leadingMargin)
make.top.equalTo(contentView.snp.topMargin)
make.trailing.equalTo(contentView.snp.trailingMargin)
}
typeControl.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.equalTo(contentView.snp.leadingMargin)
make.trailing.equalTo(contentView.snp.trailingMargin)
}
descriptionLabel.snp.makeConstraints { make in
make.top.equalTo(typeControl.snp.bottom).offset(6)
make.leading.equalTo(contentView.snp.leadingMargin)
make.trailing.equalTo(contentView.snp.trailingMargin)
make.bottom.equalTo(contentView.snp.bottomMargin)
}
setAccessibilityIdentifiers()
}
private func setAccessibilityIdentifiers() {
contentView.accessibilityIdentifier = "SegmentCell:content-view"
titleLabel.accessibilityIdentifier = "SegmentCell:title-label"
descriptionLabel.accessibilityIdentifier = "SegmentCell:description-label"
typeControl.accessibilityIdentifier = "SegmentCell:type-control"
}
func applyData(field: JSONFormBuilder.Field, data: FormData) {
let titleStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralBlack())
let descriptionStyle = OEXMutableTextStyle(weight: .light, size: .xSmall, color: OEXStyles.shared().neutralXDark())
descriptionStyle.lineBreakMode = .byTruncatingTail
titleLabel.attributedText = titleStyle.attributedString(withText: field.title)
descriptionLabel.attributedText = descriptionStyle.attributedString(withText: field.instructions)
if let hint = field.accessibilityHint {
typeControl.accessibilityHint = hint
}
values.removeAll(keepingCapacity: true)
typeControl.removeAllSegments()
if let optionsValues = field.options?["values"]?.arrayObject {
for valueDict in optionsValues {
let dict = valueDict as? NSDictionary
let title = dict?["name"] as! String
let value = dict?["value"] as! String
typeControl.insertSegment(withTitle: title, at: values.count, animated: false)
values.append(value)
}
}
if let val = data.valueForField(key: field.name), let selectedIndex = values.firstIndex(of: val) {
typeControl.selectedSegmentIndex = selectedIndex
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/** Show a cell that provides a long list of options in a new viewcontroller */
class OptionsCell: UITableViewCell, FormCell {
static let Identifier = "JSONForm.OptionsCell"
private let choiceView = ChoiceLabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
func setup() {
accessoryType = .disclosureIndicator
contentView.addSubview(choiceView)
choiceView.snp.makeConstraints { make in
make.edges.equalTo(contentView).inset(UIEdgeInsets(top: 0, left: StandardHorizontalMargin, bottom: 0, right: StandardHorizontalMargin))
}
contentView.accessibilityIdentifier = "OptionsCell:content-view"
choiceView.accessibilityIdentifier = "OptionsCell:choice-view"
}
func applyData(field: Field, data: FormData) {
choiceView.titleText = Strings.formLabel(label: field.title!)
choiceView.valueText = data.displayValueForKey(key: field.name) ?? field.placeholder ?? ""
}
}
/** Show an editable text area in a new view */
class TextAreaCell: UITableViewCell, FormCell {
static let Identifier = "JSONForm.TextAreaCell"
private let choiceView = ChoiceLabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
func setup() {
accessoryType = .disclosureIndicator
contentView.addSubview(choiceView)
choiceView.snp.makeConstraints { make in
make.edges.equalTo(contentView).inset(UIEdgeInsets(top: 0, left: StandardHorizontalMargin, bottom: 0, right: StandardHorizontalMargin))
}
contentView.accessibilityIdentifier = "TextAreaCell:content-view"
choiceView.accessibilityIdentifier = "TextAreaCell:choice-view"
}
func applyData(field: Field, data: FormData) {
choiceView.titleText = Strings.formLabel(label: field.title ?? "")
let placeholderText = field.placeholder
choiceView.valueText = data.valueForField(key: field.name) ?? placeholderText ?? ""
}
}
/** Add the cell types to the tableview */
static func registerCells(tableView: UITableView) {
tableView.register(OptionsCell.self, forCellReuseIdentifier: OptionsCell.Identifier)
tableView.register(TextAreaCell.self, forCellReuseIdentifier: TextAreaCell.Identifier)
tableView.register(SegmentCell.self, forCellReuseIdentifier: SegmentCell.Identifier)
}
/** Fields parsed out of the json. Each field corresponds to it's own row with specialized editor */
struct Field {
enum FieldType: String {
case Select = "select"
case TextArea = "textarea"
case Switch = "switch"
init?(jsonVal: String?) {
if let str = jsonVal {
if let type = FieldType(rawValue: str) {
self = type
} else {
return nil
}
} else {
return nil
}
}
var cellIdentifier: String {
switch self {
case .Select:
return OptionsCell.Identifier
case .TextArea:
return TextAreaCell.Identifier
case .Switch:
return SegmentCell.Identifier
}
}
}
//Field Data types Supported by the form builder
enum DataType : String {
case StringType = "string"
case CountryType = "country"
case LanguageType = "language"
init(_ rawValue: String?) {
guard let val = rawValue else { self = .StringType; return }
switch val {
case "country":
self = .CountryType
case "language":
self = .LanguageType
default:
self = .StringType
}
}
}
let type: FieldType
let name: String
var cellIdentifier: String { return type.cellIdentifier }
var title: String?
let instructions: String?
let subInstructions: String?
let accessibilityHint: String?
let options: [String: JSON]?
let dataType: DataType
let defaultValue: String?
let placeholder: String?
init (json: JSON) {
type = FieldType(jsonVal: json["type"].string)!
title = json["label"].string
name = json["name"].string!
instructions = json["instructions"].string
subInstructions = json["sub_instructions"].string
options = json["options"].dictionary
dataType = DataType(json["data_type"].string)
defaultValue = json["default"].string
accessibilityHint = json["accessibility_hint"].string
placeholder = json["placeholder"].string
}
private func attributedChooserRow(icon: Icon, title: String, value: String?) -> NSAttributedString {
let iconStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralBase())
let icon = icon.attributedTextWithStyle(style: iconStyle)
let titleStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralBlackT())
let titleAttrStr = titleStyle.attributedString(withText: " " + title)
let valueStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().primaryXLightColor())
let valAttrString = valueStyle.attributedString(withText: value)
return NSAttributedString.joinInNaturalLayout(attributedStrings: [icon, titleAttrStr, valAttrString])
}
private func selectAction(data: FormData, controller: UIViewController) {
let selectionController = JSONFormViewController<String>()
var tableData = [ChooserDatum<String>]()
if let rangeMin:Int = options?["range_min"]?.int, let rangeMax:Int = options?["range_max"]?.int {
let range = rangeMin...rangeMax
let titles = range.map { String($0)} .reversed()
tableData = titles.map { ChooserDatum(value: $0, title: $0, attributedTitle: nil) }
} else if let file = options?["reference"]?.string {
if file == "countries" {
let locale = Locale.current
let codes = Locale.isoRegionCodes
for code in codes {
let name = locale.localizedString(forRegionCode: code) ?? ""
tableData.append(ChooserDatum(value: code, title: name, attributedTitle: nil))
}
tableData = tableData.sorted(by: { $0.title ?? "" < $1.title ?? "" })
}
else {
do {
let json = try loadJSON(jsonFile: file)
if let values = json.array {
for value in values {
for (code, name) in value {
tableData.append(ChooserDatum(value: code, title: name.rawString(), attributedTitle: nil))
}
}
}
} catch {
Logger.logError("JSON", "Error parsing JSON: \(error)")
}
}
}
var defaultRow = -1
let allowsNone = options?["allows_none"]?.bool ?? false
if allowsNone {
let noneTitle = options?["none_label"]?.string ?? ""
tableData.insert(ChooserDatum(value: "--", title: noneTitle, attributedTitle: nil), at: 0)
defaultRow = 0
}
if let alreadySetValue = data.valueForField(key: name) {
defaultRow = tableData.firstIndex { equalsCaseInsensitive(lhs: $0.value, alreadySetValue) } ?? defaultRow
}
if dataType == .CountryType {
if let id = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
let countryName = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: id)
let title = attributedChooserRow(icon: Icon.Country, title: Strings.Profile.currentLocationLabel, value: countryName)
tableData.insert(ChooserDatum(value: id, title: nil, attributedTitle: title), at: 0)
if defaultRow >= 0 { defaultRow += 1 }
}
} else if dataType == .LanguageType {
if let id = (Locale.current as NSLocale).object(forKey: .languageCode) as? String {
let languageName = (Locale.current as NSLocale).displayName(forKey: .languageCode, value: id)
let title = attributedChooserRow(icon: Icon.Comment, title: Strings.Profile.currentLanguageLabel, value: languageName)
tableData.insert(ChooserDatum(value: id, title: nil, attributedTitle: title), at: 0)
if defaultRow >= 0 { defaultRow += 1 }
}
}
let dataSource = ChooserDataSource(data: tableData)
dataSource.selectedIndex = defaultRow
selectionController.dataSource = dataSource
selectionController.title = title
selectionController.instructions = instructions
selectionController.subInstructions = subInstructions
selectionController.doneChoosing = { value in
if allowsNone && value != nil && value! == "--" {
data.setValue(value: nil, key: self.name)
} else {
data.setValue(value: value, key: self.name)
}
}
controller.navigationController?.pushViewController(selectionController, animated: true)
}
/** What happens when the user selects the row */
func takeAction(data: FormData, controller: UIViewController) {
switch type {
case .Select:
selectAction(data: data, controller: controller)
case .TextArea:
let text = data.valueForField(key: name)
let textController = JSONFormBuilderTextEditorViewController(text: text, placeholder: placeholder)
textController.title = title
textController.doneEditing = { value in
if value == "" {
data.setValue(value: nil, key: self.name)
} else {
data.setValue(value: value, key: self.name)
}
}
controller.navigationController?.pushViewController(textController, animated: true)
case .Switch:
//no action on cell selection - let control in cell handle action
break;
}
}
}
let json: JSON
lazy var fields: [Field]? = {
return self.json["fields"].array?.map { return Field(json: $0) }
}()
init?(jsonFile: String) {
do {
json = try loadJSON(jsonFile: jsonFile)
} catch {
json = JSON(NSNull())
return nil
}
}
init(json: JSON) {
self.json = json
}
}
|
apache-2.0
|
f15f499bcf99e9f0e443deec7da88e73
| 41.306977 | 173 | 0.566238 | 5.472924 | false | false | false | false |
PureSwift/BluetoothLinux
|
Sources/BluetoothLinux/RFCOMM/IOCTL/RFCOMMCreateDevice.swift
|
1
|
2614
|
//
// RFCOMMCreateDevice.swift
//
//
// Created by Alsey Coleman Miller on 26/10/21.
//
import Bluetooth
import SystemPackage
import Socket
public extension RFCOMMIO {
/// RFCOMM Create Device
struct CreateDevice: Equatable, Hashable, IOControlValue {
@_alwaysEmitIntoClient
public static var id: RFCOMMIO { .createDevice }
@usableFromInline
internal private(set) var bytes: CInterop.RFCOMMDeviceRequest
@usableFromInline
internal init(_ bytes: CInterop.RFCOMMDeviceRequest) {
self.bytes = bytes
}
@_alwaysEmitIntoClient
public init(
id: HostController.ID,
flags: BitMaskOptionSet<RFCOMMFlag>,
source: BluetoothAddress,
destination: BluetoothAddress,
channel: UInt8 = 1
) {
self.init(CInterop.RFCOMMDeviceRequest(
device: id.rawValue,
flags: flags.rawValue,
source: source,
destination: destination,
channel: channel)
)
}
@_alwaysEmitIntoClient
public mutating func withUnsafeMutablePointer<Result>(_ body: (UnsafeMutableRawPointer) throws -> (Result)) rethrows -> Result {
try Swift.withUnsafeMutableBytes(of: &bytes) { buffer in
try body(buffer.baseAddress!)
}
}
}
}
public extension RFCOMMIO.CreateDevice {
@_alwaysEmitIntoClient
var id: HostController.ID {
return .init(rawValue: bytes.device)
}
@_alwaysEmitIntoClient
var flags: BitMaskOptionSet<RFCOMMFlag> {
return .init(rawValue: bytes.flags)
}
@_alwaysEmitIntoClient
var source: BluetoothAddress {
return bytes.source
}
@_alwaysEmitIntoClient
var destination: BluetoothAddress {
return bytes.destination
}
@_alwaysEmitIntoClient
var channel: UInt8 {
return bytes.channel
}
}
// MARK: - File Descriptor
internal extension SocketDescriptor {
@usableFromInline
func rfcommCreateDevice(
id: HostController.ID,
flags: BitMaskOptionSet<RFCOMMFlag> = [],
source: BluetoothAddress,
destination: BluetoothAddress,
channel: UInt8 = 1
) throws {
var request = RFCOMMIO.CreateDevice(
id: id,
flags: flags,
source: source,
destination: destination,
channel: channel
)
try inputOutput(&request)
}
}
|
mit
|
d03ff79722ef79a79d117be7edeb99b5
| 24.134615 | 136 | 0.587223 | 5.217565 | false | false | false | false |
sinorychan/iOS-11-by-Examples
|
iOS-11-by-Examples/CoreML/UIImage+Processing.swift
|
1
|
3608
|
//
// UIImage+Processing.swift
// iOS-11-by-Examples
//
// Created by Artem Novichkov on 18/06/2017.
// Copyright © 2017 Artem Novichkov. All rights reserved.
//
import UIKit
extension UIImage {
func resize(newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
defer {
UIGraphicsEndImageContext()
}
draw(in: CGRect(origin: .zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
return newImage
}
var pixelBuffer: CVPixelBuffer? {
guard let newImage = resize(newSize: CGSize(width: 149.5, height: 149.5)) else {
print("Can't get image from current context")
return nil
}
guard let ciimage = CIImage(image: newImage) else {
print("Can't get CI image")
return nil
}
let tempContext = CIContext(options: nil)
guard let cgImage = tempContext.createCGImage(ciimage, from: ciimage.extent) else {
print("Can't get CI image from context")
return nil
}
let cfnumPointer = UnsafeMutablePointer<UnsafeRawPointer>.allocate(capacity: 1)
let cfnum = CFNumberCreate(kCFAllocatorDefault, .intType, cfnumPointer)
let keys: [CFString] = [kCVPixelBufferCGImageCompatibilityKey,
kCVPixelBufferCGBitmapContextCompatibilityKey,
kCVPixelBufferBytesPerRowAlignmentKey]
let values: [CFTypeRef] = [kCFBooleanTrue, kCFBooleanTrue, cfnum!]
let keysPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
let valuesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 1)
keysPointer.initialize(to: keys)
valuesPointer.initialize(to: values)
let options = CFDictionaryCreate(kCFAllocatorDefault, keysPointer, valuesPointer, keys.count, nil, nil)
let width = cgImage.width
let height = cgImage.height
var pxbuffer: CVPixelBuffer?
var status = CVPixelBufferCreate(kCFAllocatorDefault,
width,
height,
kCVPixelFormatType_32BGRA,
options,
&pxbuffer)
status = CVPixelBufferLockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0))
let bufferAddress = CVPixelBufferGetBaseAddress(pxbuffer!)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bytesperrow = CVPixelBufferGetBytesPerRow(pxbuffer!)
let context = CGContext(data: bufferAddress,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesperrow,
space: rgbColorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
context?.concatenate(CGAffineTransform(rotationAngle: 0))
context?.concatenate(__CGAffineTransformMake( 1, 0, 0, -1, 0, CGFloat(height) )) //Flip Vertical
context?.draw(cgImage, in: CGRect(origin: .zero, size: CGSize(width: width, height: width)))
status = CVPixelBufferUnlockBaseAddress(pxbuffer!, CVPixelBufferLockFlags(rawValue: 0))
return pxbuffer
}
}
|
mit
|
9dc46277be80194f3d81dd434f2cb21f
| 42.457831 | 131 | 0.592182 | 5.680315 | false | false | false | false |
DarielChen/DemoCode
|
iOS动画指南/iOS动画指南 - 2.Layer Animations的基本使用/layer/ViewController.swift
|
1
|
10739
|
//
// ViewController.swift
// layer
//
// Created by Dariel on 16/6/15.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
// 延迟执行
func delay(seconds seconds: Double, completion:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
class ViewController: UIViewController {
let dogImageView = UIImageView(image: UIImage(named: "Snip20160615_3"))
let info = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
dogImageView.sizeToFit()
dogImageView.center.y = view.center.y
dogImageView.layer.cornerRadius = 4
dogImageView.layer.position.x = view.center.x
view.addSubview(dogImageView)
dogImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: Selector("dogImageViewTap"))
dogImageView.addGestureRecognizer(tap)
info.frame = CGRect(x: 0, y: dogImageView.frame.origin.y + 200, width: view.frame.size.width, height: 30)
info.backgroundColor = UIColor.lightGrayColor()
info.textAlignment = .Center
info.textColor = UIColor.orangeColor()
info.text = "This is Label Text"
view.addSubview(info)
delay(seconds: 3) { () -> () in
// self.debuging()
// self.delegate()
// self.kvc()
// self.animationKey()
// self.animationGroup()
// self.fillMode()
}
}
func dogImageViewTap() {
print("dogImageViewTap")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// move()
// debuging()
// 停止动画
// dogImageView.layer.removeAnimationForKey("p")
// info.layer.removeAllAnimations()
// info.layer.removeAnimationForKey("infoappear")
// dogImageView.layer.removeAllAnimations()
// self.animationGroup()
self.layerSprings()
}
// 右移动
func move() {
let flyRight = CABasicAnimation(keyPath: "position.x")
flyRight.fromValue = 80
flyRight.toValue = 230
flyRight.duration = 0.5
// flyRight.removedOnCompletion = false
// flyRight.fillMode = kCAFillModeForwards
// 延迟执行
flyRight.beginTime = CACurrentMediaTime() + 0.2
dogImageView.layer.addAnimation(flyRight, forKey: nil)
// dogImageView.layer.position.x = 230
}
// fillMode
// kCAFillModeRemoved 默认样式 动画结束后会回到layer的开始的状态
// kCAFillModeForwards 动画结束后,layer会保持结束状态
// kCAFillModeBackwards layer跳到fromValue的值处,然后从fromValue到toValue播放动画,最后回到layer的开始的状态
// kCAFillModeBoth kCAFillModeForwards和kCAFillModeBackwards的结合,即动画结束后layer保持在结束状态
func fillMode() {
let flyRight = CABasicAnimation(keyPath: "position.x")
// 保证fillMode起作用
flyRight.removedOnCompletion = false
flyRight.fillMode = kCAFillModeBoth
flyRight.fromValue = 100
flyRight.toValue = 230
flyRight.duration = 0.5
// 延迟执行
flyRight.beginTime = CACurrentMediaTime() + 1
dogImageView.layer.addAnimation(flyRight, forKey: nil)
}
// layer动画并不是真实的,如果要变成真实的需要改变其position
// 图片可以有监听事件
// 一般动画设计的时候,我们可以把默认值就设置为动画结束的位置
// 使用场景:视图不需要交互,且动画的开始和结束需要设置特殊的值
func debuging() {
let flyRight = CABasicAnimation(keyPath: "position.x")
// 保证动画不被移除掉
// flyRight.removedOnCompletion = false
flyRight.fillMode = kCAFillModeBoth
flyRight.fromValue = 60
flyRight.toValue = 230
flyRight.duration = 0.5
// 延迟执行
flyRight.beginTime = CACurrentMediaTime() + 1
dogImageView.layer.addAnimation(flyRight, forKey: nil)
dogImageView.layer.position.x = 230
}
// 代理
func delegate() {
let flyRight = CABasicAnimation(keyPath: "position.x")
flyRight.delegate = self
// 保证动画不被移除掉
// flyRight.removedOnCompletion = false
flyRight.fillMode = kCAFillModeBoth
flyRight.fromValue = 60
flyRight.toValue = 230
flyRight.duration = 0.5
// 延迟执行
flyRight.beginTime = CACurrentMediaTime() + 1
dogImageView.layer.addAnimation(flyRight, forKey: nil)
dogImageView.layer.position.x = 230
}
// KVC设置layer的名称
// 当我们把flyRight添加到多个控件的时候,怎么设置代理区分,用kvc
func kvc() {
let flyRight = CABasicAnimation(keyPath: "position.x")
// 保证动画不被移除掉
// flyRight.removedOnCompletion = false
flyRight.fillMode = kCAFillModeBoth
flyRight.fromValue = 80
flyRight.toValue = 230
flyRight.duration = 0.5
flyRight.delegate = self
// 设置名称
flyRight.setValue("form", forKey: "name")
flyRight.setValue(dogImageView.layer, forKey: "layer")
// 延迟执行
flyRight.beginTime = CACurrentMediaTime() + 1
dogImageView.layer.addAnimation(flyRight, forKey: "p")
dogImageView.layer.position.x = 230
}
// 怎样在动画运行的时候做一些设置
// 一次运行多个动画,怎样利用key控制运行动画
func animationKey() {
let flyLeft = CABasicAnimation(keyPath: "position.x")
flyLeft.fromValue = info.layer.position.x + view.frame.size.width
flyLeft.toValue = info.layer.position.x
flyLeft.duration = 5.0
// key的作用是当动画开始的时候进行控制的
info.layer.addAnimation(flyLeft, forKey: "infoappear")
// 通过利用removeAnimationForKey停止动画
let fadeLabelIn = CABasicAnimation(keyPath: "opacity")
fadeLabelIn.fromValue = 0.2
fadeLabelIn.toValue = 1.0
fadeLabelIn.duration = 4.5
info.layer.addAnimation(fadeLabelIn, forKey: "fadein")
// 所以这可以在一个layer上执行多个独立的动画
print(info.layer.animationKeys()!)
}
// 组
func animationGroup() {
let groupAnimation = CAAnimationGroup()
// 延迟1秒
groupAnimation.beginTime = CACurrentMediaTime() + 1
// 整个动画持续3秒
groupAnimation.duration = 3
groupAnimation.removedOnCompletion = false
groupAnimation.fillMode = kCAFillModeBoth
// 缓慢加速缓慢减速
groupAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// 重复次数
groupAnimation.repeatCount = 4.5
// 来回往返执行
groupAnimation.autoreverses = true
// 速度
groupAnimation.speed = 2.0
let scaleDown = CABasicAnimation(keyPath: "transform.scale")
scaleDown.fromValue = 1.5
scaleDown.toValue = 1.0
let roate = CABasicAnimation(keyPath: "transform.rotation")
roate.fromValue = CGFloat(M_PI_4)
roate.toValue = 0.0
let fade = CABasicAnimation(keyPath: "opacity")
fade.fromValue = 0.5
fade.toValue = 1.0
groupAnimation.animations = [scaleDown, roate, fade]
dogImageView.layer.addAnimation(groupAnimation, forKey: nil)
}
// 弹簧效果
func layerSprings() {
let scaleDown = CASpringAnimation(keyPath: "transform.scale")
scaleDown.fromValue = 1.5
scaleDown.toValue = 1.0
// settlingDuration:结算时间(根据动画参数估算弹簧开始运动到停止的时间,动画设置的时间最好根据此时间来设置)
scaleDown.duration = scaleDown.settlingDuration
// mass:质量(影响弹簧的惯性,质量越大,弹簧惯性越大,运动的幅度越大) 默认值为1
scaleDown.mass = 10.0
// stiffness:弹性系数(弹性系数越大,弹簧的运动越快)默认值为100
scaleDown.stiffness = 1500.0
// damping:阻尼系数(阻尼系数越大,弹簧的停止越快)默认值为10
scaleDown.damping = 50
// initialVelocity:初始速率(弹簧动画的初始速度大小,弹簧运动的初始方向与初始速率的正负一致,若初始速率为0,表示忽略该属性)默认值为0
scaleDown.initialVelocity = 100
dogImageView.layer.addAnimation(scaleDown, forKey: nil)
// dogImageView.layer.borderWidth = 3.0
// dogImageView.layer.borderColor = UIColor.clearColor().CGColor
//
// let flash = CASpringAnimation(keyPath: "borderColor")
// flash.damping = 7.0
// flash.stiffness = 200.0
// flash.fromValue = UIColor(red: 0.96, green: 0.27, blue: 0.0, alpha: 1).CGColor
// flash.toValue = UIColor.clearColor().CGColor
// flash.duration = flash.settlingDuration
// dogImageView.layer.addAnimation(flash, forKey: nil)
}
}
// MARK: - animationDelegate
extension ViewController {
override func animationDidStart(anim: CAAnimation) {
print("动画开始调用")
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
print("动画结束调用")
if let name = anim.valueForKey("name") as? String {
if name == "form" {
print("name is form")
// 动画结束后设置一个先放大然后缩小的效果
let layer = anim.valueForKey("layer") as? CALayer
anim.setValue(nil, forKey: "layer")
let pulse = CABasicAnimation(keyPath: "transform.scale")
pulse.fromValue = 1.25
pulse.toValue = 1.0
pulse.duration = 3.25
layer?.addAnimation(pulse, forKey: nil)
}
}
}
}
|
mit
|
c9df4ea7d77f8f1da467ecda9abc4758
| 28.9125 | 113 | 0.596114 | 4.229783 | false | false | false | false |
abelsanchezali/ViewBuilder
|
Source/Document/Model/Resources/Resources.swift
|
1
|
2636
|
//
// Resources.swift
// ViewBuilder
//
// Created by Abel Sanchez on 6/23/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import Foundation
open class Resources: NSObject, Sequence {
public required override init() {
}
public required init?(path: String, builder: DocumentBuilder? = nil) {
let builder = builder ?? DocumentBuilder.shared
let options = BuildOptions()
super.init()
options.instantiation = InstantiationOptions(instance: self)
guard let _ = builder.loadResources(path, options: options) else {
Log.shared.write("Could not load resources from path = \(path)")
return nil
}
}
internal var itemsByName = [String: Item]()
open func addItem(_ item: Item) {
itemsByName[item.name] = item
}
open func addItems<T: Sequence>(_ items: T) where T.Iterator.Element == Item {
for item in items {
addItem(item)
}
}
open func mergeWithResource(_ resource: Resources) {
addItems(resource)
}
open subscript(name: String) -> Any? {
return itemsByName[name]?.value
}
open var count: Int {
return itemsByName.count
}
// MARK: - SequenceType
open func makeIterator() -> Dictionary<String, Item>.Values.Iterator {
return itemsByName.values.makeIterator()
}
}
extension Resources: KeyValueResolverProtocol {
public func resolveValue(for key: String) -> Any? {
return self[key]
}
}
// MARK: - CustomStringConvertible
extension Resources {
open override var description: String {
get {
let total = itemsByName.count
guard total > 0 else {
return "{Empty}"
}
var summary = "{items = \(total)"
if total > 0 {
summary += ", names = ("
var count = 0
for (name, _) in itemsByName {
summary += "\"\(name)\""
count += 1
if count < total {
summary += ", "
}
if count == 10 {
break
}
}
if count < total {
summary += "... and \(total - count) more)"
} else {
summary += ")"
}
}
summary += "}"
return summary
}
}
}
|
mit
|
74638333619dea9d6f7c871271395092
| 24.095238 | 82 | 0.481214 | 5.106589 | false | false | false | false |
stratistore/waterLogic
|
FloTest/Bucket.swift
|
1
|
924
|
//
// Bucket.swift
// WaterLogic
//
// Created by dev on 24/02/2016.
// Copyright © 2016 dev. All rights reserved.
//
import UIKit
class Bucket: NSObject {
// A text description of this item.
var text: String
// A text description of this last action taken eith this bucket.
var lastAction: String
// An Int value that determines the capacity of this bucket.
var capacity: Int
// An Int value that determines the current amount of water in this bucket.
var currentAmount: Int
// An Int value that determines the available capacity of this bucket.
var availableCapacity: Int
//
var filledFirstFlag:Bool
// Returns a Bucket initialized with the given text.
init(text: String, capacity: Int) {
self.text = text
self.lastAction = "INIT "
self.capacity = capacity
self.currentAmount = 0
self.availableCapacity = self.capacity - self.currentAmount
self.filledFirstFlag = false
}
}
|
gpl-3.0
|
1a1192a94c0d3d4da922f1e589f85b17
| 22.075 | 76 | 0.71831 | 3.577519 | false | false | false | false |
ZeeQL/ZeeQL3
|
Sources/ZeeQL/Access/DatabaseOperation.swift
|
1
|
2004
|
//
// DatabaseOperation.swift
// ZeeQL3
//
// Created by Helge Hess on 15.05.17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
/**
* This is like an AdaptorOperation at a higher level. It represents an UPDATE,
* DELETE, INSERT on a DatabaseObject. Technically this could result in multiple
* adaptor operations.
*/
open class DatabaseOperation : SmartDescription {
open var log : ZeeQLLogger = globalZeeQLLogger
public typealias Operator = AdaptorOperation.Operator
public var entity : Entity
public var object : DatabaseObject // TBD
public var databaseOperator : Operator = .none
var dbSnapshot : Snapshot?
var newRow : Snapshot?
/// Adaptor operations associated with this database operation. Usually there
/// is just one, but there can be more.
/// E.g. an insert may require a sequence fetch.
var adaptorOperations = [ AdaptorOperation ]()
/// Run when the operation did complete
open var completionBlock : (() -> ())?
public init(_ object: DatabaseObject, _ entity: Entity) {
self.object = object
self.entity = entity
}
public init(_ object: ActiveRecordType, _ entity: Entity? = nil) {
self.object = object
if let entity = entity {
self.entity = entity
}
else {
self.entity = object.entity
}
}
// MARK: - mapped operations
func addAdaptorOperation(_ op: AdaptorOperation) {
// used by adaptorOperationsForDatabaseOperations
adaptorOperations.append(op)
}
func didPerformAdaptorOperations() {
// Note: doesn't say anything about success!
if let cb = completionBlock {
completionBlock = nil
cb()
}
}
// MARK: - Description
public func appendToDescription(_ ms: inout String) {
ms += " \(object)"
ms += " \(entity.name)"
ms += " \(databaseOperator)"
if let snap = dbSnapshot { ms += " snap=\(snap)" }
if let snap = newRow { ms += " new=\(snap)" }
}
}
|
apache-2.0
|
454e419f55d8afe1fe5cbb579d79ebb2
| 25.012987 | 80 | 0.642037 | 4.363834 | false | false | false | false |
Cleverlance/Alamofire
|
Source/Request.swift
|
1
|
18998
|
// Alamofire.swift
//
// Copyright (c) 2014–2015 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
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
*/
public class Request {
// MARK: - Properties
let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest { return task.originalRequest }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress { return delegate.progress }
// MARK: - Lifecycle
init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: - Authentication
/**
Associates an HTTP Basic credential with the request.
:param: user The user.
:param: password The password.
:returns: The request.
*/
public func authenticate(#user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
:param: credential The credential.
:returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: - Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes expected to read.
:param: closure The code to be executed periodically during the lifecycle of the request.
:returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
/**
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
This closure returns the bytes most recently received from the server, not including data from previous calls. If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is also important to note that the `response` closure will be called with nil `responseData`.
:param: closure The code to be executed periodically during the lifecycle of the request.
:returns: The request.
*/
public func stream(closure: (NSData -> Void)? = nil) -> Self {
if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataStream = closure
}
return self
}
// MARK: - Response
/**
A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
*/
public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public class func responseDataSerializer() -> Serializer {
return { request, response, data in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.responseDataSerializer(), completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: serializer The closure responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
delegate.queue.addOperationWithBlock {
let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
}
}
return self
}
// MARK: - State
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let downloadDelegate = delegate as? DownloadTaskDelegate,
downloadTask = downloadDelegate.downloadTask
{
downloadTask.cancelByProducingResumeData { data in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
// MARK: - TaskDelegate
class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: NSOperationQueue
let progress: NSProgress
var data: NSData? { return nil }
var error: NSError?
var credential: NSURLCredential?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.suspended = true
if operationQueue.respondsToSelector("qualityOfService") {
operationQueue.qualityOfService = NSQualityOfService.Utility
}
return operationQueue
}()
}
deinit {
queue.cancelAllOperations()
queue.suspended = true
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
var redirectRequest: NSURLRequest? = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if taskDidReceiveChallenge != nil {
(disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
var bodyStream: NSInputStream?
if taskNeedNewBodyStream != nil {
bodyStream = taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if taskDidCompleteWithError != nil {
taskDidCompleteWithError!(session, task, error)
} else {
if error != nil {
self.error = error
}
queue.suspended = false
}
}
}
// MARK: - DataTaskDelegate
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
private var totalBytesReceived: Int64 = 0
private var mutableData: NSMutableData
override var data: NSData? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
private var expectedContentLength: Int64?
private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
private var dataStream: ((data: NSData) -> Void)?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if dataTaskDidReceiveData != nil {
dataTaskDidReceiveData!(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data: data)
} else {
mutableData.appendData(data)
}
totalBytesReceived += data.length
let totalBytesExpectedToReceive = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpectedToReceive
progress.completedUnitCount = totalBytesReceived
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpectedToReceive)
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
var cachedResponse: NSCachedURLResponse? = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - Printable
extension Request: Printable {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received.
public var description: String {
var components: [String] = []
if request.HTTPMethod != nil {
components.append(request.HTTPMethod!)
}
components.append(request.URL!.absoluteString!)
if response != nil {
components.append("(\(response!.statusCode))")
}
return join(" ", components)
}
}
// MARK: - DebugPrintable
extension Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = request.URL
if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
components.append("-X \(request.HTTPMethod!)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL!.host!, port: URL!.port?.integerValue ?? 0, `protocol`: URL!.scheme!, realm: URL!.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
// Temporarily disabled on OS X due to build failure for CocoaPods
// See https://github.com/CocoaPods/swift/issues/24
#if !os(OSX)
if session.configuration.HTTPShouldSetCookies {
if let cookieStorage = session.configuration.HTTPCookieStorage,
cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie]
where !cookies.isEmpty
{
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
#endif
if request.allHTTPHeaderFields != nil {
for (field, value) in request.allHTTPHeaderFields! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if session.configuration.HTTPAdditionalHeaders != nil {
for (field, value) in session.configuration.HTTPAdditionalHeaders! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let HTTPBody = request.HTTPBody,
escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
{
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(URL!.absoluteString!)\"")
return join(" \\\n\t", components)
}
/// The textual representation used when written to an output stream, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
|
mit
|
110128e1b8284240562bdeb9e0b26cf1
| 37.453441 | 321 | 0.640082 | 5.958595 | false | false | false | false |
february29/Learning
|
swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/First.swift
|
38
|
1210
|
//
// First.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/31/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
fileprivate final class FirstSink<Element, O: ObserverType> : Sink<O>, ObserverType where O.E == Element? {
typealias E = Element
typealias Parent = First<E>
func on(_ event: Event<E>) {
switch event {
case .next(let value):
forwardOn(.next(value))
forwardOn(.completed)
dispose()
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
forwardOn(.next(nil))
forwardOn(.completed)
dispose()
}
}
}
final class First<Element>: Producer<Element?> {
fileprivate let _source: Observable<Element>
init(source: Observable<Element>) {
_source = source
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element? {
let sink = FirstSink(observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
|
mit
|
edd61e8f9003a4c3981b680523381cbd
| 27.785714 | 146 | 0.600496 | 4.287234 | false | false | false | false |
FrancisBaileyH/Swift-Sociables
|
Sociables/RuleEditorViewController.swift
|
1
|
3473
|
//
// RuleEditorViewController.swift
// Socialables
//
// Created by Francis Bailey on 2015-05-03.
//
import UIKit
class RuleEditorViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet weak var ruleTextField: UITextView!
@IBOutlet weak var ruleTitleField: UITextField!
@IBOutlet weak var cardTypeLabel: UILabel!
var ruleText: String? = nil
var ruleTitle: String? = nil
var cardRank: String? = nil
let rm = RuleManager.sharedInstance
override func viewDidLoad() {
ruleTextField.text = ruleText
ruleTitleField.text = ruleTitle
cardTypeLabel.text = cardRank
ruleTextField.delegate = self
ruleTitleField.delegate = self
ruleTextField.layer.borderWidth = 0
ruleTextField.layer.borderColor = UIColor.lightGrayColor().CGColor
ruleTextField.layer.cornerRadius = 5
let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
tapRecognizer.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tapRecognizer)
}
@IBAction func saveButtonPressed() {
let card = rm.getRule(cardRank!)
if card.rule.explanation == ruleTextField.text && card.rule.title == ruleTitleField.text {
let message = UIAlertController(title: "Rule Unchanged", message: "Please change the values of the rule title or rule text in order to save.", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
message.addAction(OKAction)
self.presentViewController(message, animated: true, completion: nil)
}
else {
let order = RuleManager.defaultRules[cardTypeLabel.text!]?.order
let rule = CardAndRuleType(rule: RuleType(title: ruleTitleField.text, explanation: ruleTextField.text, order: order!), rank: cardTypeLabel.text!, isDefault: false)
if let err = rm.saveRule(rule) {
let warning = UIAlertController(title: "Error", message: "An error occurred and the rule was not successfully saved. Please try again.", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
warning.addAction(OKAction)
self.presentViewController(warning, animated: true, completion: nil)
} else {
self.navigationController?.popViewControllerAnimated(true)
}
}
}
@IBAction func resetButtonPressed() {
rm.removePersistentRule(cardTypeLabel.text!)
let card = rm.getRule(cardRank!)
ruleTitleField.text = card.rule.title
ruleTextField.text = card.rule.explanation
let message = UIAlertController(title: "Rule Reset", message: "Rule reset to default value.", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
message.addAction(OKAction)
self.presentViewController(message, animated: true, completion: nil)
}
func handleSingleTap(recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
|
gpl-3.0
|
b2fa798919bf2458d521dd634140ddb2
| 33.73 | 178 | 0.642384 | 5.092375 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Localization/Sources/Localization/LocalizationConstants+SecureChannel.swift
|
1
|
7135
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
// swiftlint:disable all
import Foundation
extension LocalizationConstants {
public enum SecureChannel {}
}
extension LocalizationConstants.SecureChannel {
public enum ConfirmationSheet {
public enum Authorized {
public static let title = NSLocalizedString(
"Authorized Device Detected",
comment: "Secure Channel - Confirmation Sheet - Authorized - title"
)
public static let subtitle = NSLocalizedString(
"We noticed a login attempt from an authorized device.",
comment: "Secure Channel - Confirmation Sheet - Authorized - subtitle"
)
}
public enum New {
public static let title = NSLocalizedString(
"Log In Request From Web",
comment: "Secure Channel - Confirmation Sheet - New Device - title"
)
public static let subtitle = NSLocalizedString(
"We noticed a log in attempt from a device you don't usually use.",
comment: "Secure Channel - Confirmation Sheet - New Device - subtitle"
)
}
public enum Fields {
public static let location = NSLocalizedString(
"Location",
comment: "Secure Channel - Confirmation Sheet - Field - Location"
)
public static let ipAddress = NSLocalizedString(
"IP Address",
comment: "Secure Channel - Confirmation Sheet - Field - IP Address"
)
public static let browser = NSLocalizedString(
"Browser",
comment: "Secure Channel - Confirmation Sheet - Field - Browser User Agent"
)
public static let date = NSLocalizedString(
"Date",
comment: "Secure Channel - Confirmation Sheet - Field - Date"
)
public static let lastSeen = NSLocalizedString(
"Last seen",
comment: "Secure Channel - Confirmation Sheet - Field - Last seen"
)
public static let never = NSLocalizedString(
"Never",
comment: "Secure Channel - Confirmation Sheet - Field - Last seen - Never"
)
}
public enum CTA {
public static let deny = NSLocalizedString(
"Deny",
comment: "Secure Channel - Confirmation Sheet - CTA"
)
public static let approve = NSLocalizedString(
"Approve",
comment: "Secure Channel - Confirmation Sheet - CTA"
)
}
public enum Text {
public static let warning = NSLocalizedString(
"If this was you, approve the device below. If you do not recognize this device, deny & block the device now.",
comment: "Secure Channel - Confirmation Sheet - Warning"
)
}
}
public enum Notification {
public enum Authorized {
public static let title = NSLocalizedString(
"QR Code Log In",
comment: "Secure Channel - Notification - Authorized - title"
)
public static let subtitle = NSLocalizedString(
"Open your mobile Blockchain.com Wallet now to securely login your desktop Wallet.",
comment: "Secure Channel - Notification - Authorized - subtitle"
)
}
public enum New {
public static let title = NSLocalizedString(
"New Login Attempt",
comment: "Secure Channel - Notification - New Device - title"
)
public static let subtitle = NSLocalizedString(
"A new device is attempting to access your Blockchain.com Wallet. Approve or Deny now.",
comment: "Secure Channel - Notification - New Device - subtitle"
)
}
}
public enum ResultSheet {
public enum Approved {
public static let title = NSLocalizedString(
"Device Approved",
comment: "Secure Channel - Result Sheet - Approved - title"
)
public static let subtitle = NSLocalizedString(
"Logging you in on the web now.",
comment: "Secure Channel - Result Sheet - Approved - subtitle"
)
}
public enum Denied {
public static let title = NSLocalizedString(
"Device Denied",
comment: "Secure Channel - Result Sheet - Denied - title"
)
public static let subtitle = NSLocalizedString(
"Your wallet is safe. We have blocked this device from logging into your wallet.",
comment: "Secure Channel - Result Sheet - Denied - subtitle"
)
}
public enum Error {
public static let title = NSLocalizedString(
"Error",
comment: "Secure Channel - Result Sheet - Error - title"
)
public static let subtitle = NSLocalizedString(
"An error occurred, try again later.",
comment: "Secure Channel - Result Sheet - Error - subtitle"
)
}
public enum CTA {
public static let ok = NSLocalizedString(
"OK",
comment: "Secure Channel - Result Sheet - CTA - OK"
)
}
}
public enum Alert {
public static let title = NSLocalizedString(
"QR Code Login",
comment: "Secure Channel - Alert title"
)
public static let network = NSLocalizedString(
"There was a network error logging in. Please try again.",
comment: "Secure Channel - Network error in requests"
)
public static let ipMismatch = NSLocalizedString(
"For security reasons, you must be on the same WiFi as the device you are authorizing the log in for.",
comment: "Secure Channel - IP mismatch error"
)
public static let originIP = NSLocalizedString(
"Origin IP",
comment: "Secure Channel - Origin IP"
)
public static let deviceIP = NSLocalizedString(
"Device IP",
comment: "Secure Channel - Device IP"
)
public static let connectionExpired = NSLocalizedString(
"Your login request has expired. Please regenerate the QR code and try again.",
comment: "Secure Channel - Connection expired error"
)
public static let generic = NSLocalizedString(
"There was an error logging in. Please try again.",
comment: "Secure Channel - Generic login error"
)
public static let loginRequired = NSLocalizedString(
"You need to authenticate to be able to respond to the login request.",
comment: "Secure Channel - Login Required"
)
}
}
|
lgpl-3.0
|
d441cfc00ad18cadfc964be330a85c72
| 38.414365 | 127 | 0.558733 | 5.842752 | false | false | false | false |
abertelrud/swift-package-manager
|
Sources/PackageModel/Target.swift
|
2
|
29422
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
import protocol TSCUtility.PolymorphicCodableProtocol
import Basics
public class Target: PolymorphicCodableProtocol {
public static var implementations: [PolymorphicCodableProtocol.Type] = [
SwiftTarget.self,
ClangTarget.self,
SystemLibraryTarget.self,
BinaryTarget.self,
PluginTarget.self,
]
/// The target kind.
public enum Kind: String, Codable {
case executable
case library
case systemModule = "system-target"
case test
case binary
case plugin
case snippet
}
/// A reference to a product from a target dependency.
public struct ProductReference: Codable {
/// The name of the product dependency.
public let name: String
/// The name of the package containing the product.
public let package: String?
/// Module aliases for targets of this product dependency. The key is an
/// original target name and the value is a new unique name that also
/// becomes the name of its .swiftmodule binary.
public let moduleAliases: [String: String]?
/// Fully qualified name for this product dependency: package ID + name of the product
public var identity: String {
if let pkg = package {
return pkg.lowercased() + "_" + name
}
// package ID won't be included for products referenced only by name
return name
}
/// Creates a product reference instance.
public init(name: String, package: String?, moduleAliases: [String: String]? = nil) {
self.name = name
self.package = package
self.moduleAliases = moduleAliases
}
}
/// A target dependency to a target or product.
public enum Dependency {
/// A dependency referencing another target, with conditions.
case target(_ target: Target, conditions: [PackageConditionProtocol])
/// A dependency referencing a product, with conditions.
case product(_ product: ProductReference, conditions: [PackageConditionProtocol])
/// The target if the dependency is a target dependency.
public var target: Target? {
if case .target(let target, _) = self {
return target
} else {
return nil
}
}
/// The product reference if the dependency is a product dependency.
public var product: ProductReference? {
if case .product(let product, _) = self {
return product
} else {
return nil
}
}
/// The dependency conditions.
public var conditions: [PackageConditionProtocol] {
switch self {
case .target(_, let conditions):
return conditions
case .product(_, let conditions):
return conditions
}
}
/// The name of the target or product of the dependency.
public var name: String {
switch self {
case .target(let target, _):
return target.name
case .product(let product, _):
return product.name
}
}
}
/// A usage of a plugin target or product. Implemented as a dependency
/// for now and added to the `dependencies` array, since they currently
/// have exactly the same characteristics and to avoid duplicating the
/// implementation for now.
public typealias PluginUsage = Dependency
/// The name of the target.
///
/// NOTE: This name is not the language-level target (i.e., the importable
/// name) name in many cases, instead use c99name if you need uniqueness.
public private(set) var name: String
/// Module aliases needed to build this target. The key is an original name of a
/// dependent target and the value is a new unique name mapped to the name
/// of its .swiftmodule binary.
public private(set) var moduleAliases: [String: String]?
/// Used to store pre-chained / pre-overriden module aliases
public private(set) var prechainModuleAliases: [String: String]?
/// Used to store aliases that should be referenced directly in source code
public private(set) var directRefAliases: [String: [String]]?
/// Add module aliases (if applicable) for dependencies of this target.
///
/// For example, adding an alias `Bar` for a target name `Foo` will result in
/// compiling references to `Foo` in source code of this target as `Bar.swiftmodule`.
/// If the name argument `Foo` is the same as this target's name, this target will be
/// renamed as `Bar` and the resulting binary will be `Bar.swiftmodule`.
///
/// - Parameters:
/// - name: The original name of a dependent target or this target
/// - alias: A new unique name mapped to the resulting binary name
public func addModuleAlias(for name: String, as alias: String) {
if moduleAliases == nil {
moduleAliases = [name: alias]
} else {
moduleAliases?[name] = alias
}
}
public func removeModuleAlias(for name: String) {
moduleAliases?.removeValue(forKey: name)
if moduleAliases?.isEmpty ?? false {
moduleAliases = nil
}
}
public func addPrechainModuleAlias(for name: String, as alias: String) {
if prechainModuleAliases == nil {
prechainModuleAliases = [name: alias]
} else {
prechainModuleAliases?[name] = alias
}
}
public func addDirectRefAliases(for name: String, as aliases: [String]) {
if directRefAliases == nil {
directRefAliases = [name: aliases]
} else {
directRefAliases?[name] = aliases
}
}
@discardableResult
public func applyAlias() -> Bool {
// If there's an alias for this target, rename
if let alias = moduleAliases?[name] {
self.name = alias
self.c99name = alias.spm_mangledToC99ExtendedIdentifier()
return true
}
return false
}
/// The dependencies of this target.
public let dependencies: [Dependency]
/// The language-level target name.
public private(set) var c99name: String
/// The bundle name, if one is being generated.
public var bundleName: String? {
return resources.isEmpty ? nil : potentialBundleName
}
public let potentialBundleName: String?
/// Suffix that's expected for test targets.
public static let testModuleNameSuffix = "Tests"
/// The kind of target.
public let type: Kind
/// The path of the target.
public let path: AbsolutePath
/// The sources for the target.
public let sources: Sources
/// The resource files in the target.
public let resources: [Resource]
/// Files in the target that were marked as ignored.
public let ignored: [AbsolutePath]
/// Other kinds of files in the target.
public let others: [AbsolutePath]
/// The build settings assignments of this target.
public let buildSettings: BuildSettings.AssignmentTable
/// The usages of package plugins by this target.
public let pluginUsages: [PluginUsage]
fileprivate init(
name: String,
potentialBundleName: String? = nil,
type: Kind,
path: AbsolutePath,
sources: Sources,
resources: [Resource] = [],
ignored: [AbsolutePath] = [],
others: [AbsolutePath] = [],
dependencies: [Target.Dependency],
buildSettings: BuildSettings.AssignmentTable,
pluginUsages: [PluginUsage]
) {
self.name = name
self.potentialBundleName = potentialBundleName
self.type = type
self.path = path
self.sources = sources
self.resources = resources
self.ignored = ignored
self.others = others
self.dependencies = dependencies
self.c99name = self.name.spm_mangledToC99ExtendedIdentifier()
self.buildSettings = buildSettings
self.pluginUsages = pluginUsages
}
private enum CodingKeys: String, CodingKey {
case name, potentialBundleName, defaultLocalization, platforms, type, path, sources, resources, ignored, others, buildSettings, pluginUsages
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
// FIXME: dependencies property is skipped on purpose as it points to
// the actual target dependency object.
try container.encode(name, forKey: .name)
try container.encode(potentialBundleName, forKey: .potentialBundleName)
try container.encode(type, forKey: .type)
try container.encode(path, forKey: .path)
try container.encode(sources, forKey: .sources)
try container.encode(resources, forKey: .resources)
try container.encode(ignored, forKey: .ignored)
try container.encode(others, forKey: .others)
try container.encode(buildSettings, forKey: .buildSettings)
// FIXME: pluginUsages property is skipped on purpose as it points to
// the actual target dependency object.
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.potentialBundleName = try container.decodeIfPresent(String.self, forKey: .potentialBundleName)
self.type = try container.decode(Kind.self, forKey: .type)
self.path = try container.decode(AbsolutePath.self, forKey: .path)
self.sources = try container.decode(Sources.self, forKey: .sources)
self.resources = try container.decode([Resource].self, forKey: .resources)
self.ignored = try container.decode([AbsolutePath].self, forKey: .ignored)
self.others = try container.decode([AbsolutePath].self, forKey: .others)
// FIXME: dependencies property is skipped on purpose as it points to
// the actual target dependency object.
self.dependencies = []
self.c99name = self.name.spm_mangledToC99ExtendedIdentifier()
self.buildSettings = try container.decode(BuildSettings.AssignmentTable.self, forKey: .buildSettings)
// FIXME: pluginUsages property is skipped on purpose as it points to
// the actual target dependency object.
self.pluginUsages = []
}
}
extension Target: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
public static func == (lhs: Target, rhs: Target) -> Bool {
ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
extension Target: CustomStringConvertible {
public var description: String {
return "<\(Swift.type(of: self)): \(name)>"
}
}
public final class SwiftTarget: Target {
/// The default name for the test entry point file located in a package.
public static let defaultTestEntryPointName = "XCTMain.swift"
/// The list of all supported names for the test entry point file located in a package.
public static var testEntryPointNames: [String] {
[defaultTestEntryPointName, "LinuxMain.swift"]
}
public init(name: String, dependencies: [Target.Dependency], testDiscoverySrc: Sources) {
self.swiftVersion = .v5
super.init(
name: name,
type: .library,
path: .root,
sources: testDiscoverySrc,
dependencies: dependencies,
buildSettings: .init(),
pluginUsages: []
)
}
/// The swift version of this target.
public let swiftVersion: SwiftLanguageVersion
public init(
name: String,
potentialBundleName: String? = nil,
type: Kind,
path: AbsolutePath,
sources: Sources,
resources: [Resource] = [],
ignored: [AbsolutePath] = [],
others: [AbsolutePath] = [],
dependencies: [Target.Dependency] = [],
swiftVersion: SwiftLanguageVersion,
buildSettings: BuildSettings.AssignmentTable = .init(),
pluginUsages: [PluginUsage] = []
) {
self.swiftVersion = swiftVersion
super.init(
name: name,
potentialBundleName: potentialBundleName,
type: type,
path: path,
sources: sources,
resources: resources,
ignored: ignored,
others: others,
dependencies: dependencies,
buildSettings: buildSettings,
pluginUsages: pluginUsages
)
}
/// Create an executable Swift target from test entry point file.
public init(name: String, dependencies: [Target.Dependency], testEntryPointPath: AbsolutePath) {
// Look for the first swift test target and use the same swift version
// for linux main target. This will need to change if we move to a model
// where we allow per target swift language version build settings.
let swiftTestTarget = dependencies.first {
guard case .target(let target as SwiftTarget, _) = $0 else { return false }
return target.type == .test
}.flatMap { $0.target as? SwiftTarget }
// FIXME: This is not very correct but doesn't matter much in practice.
// We need to select the latest Swift language version that can
// satisfy the current tools version but there is not a good way to
// do that currently.
self.swiftVersion = swiftTestTarget?.swiftVersion ?? SwiftLanguageVersion(string: String(SwiftVersion.current.major)) ?? .v4
let sources = Sources(paths: [testEntryPointPath], root: testEntryPointPath.parentDirectory)
super.init(
name: name,
type: .executable,
path: .root,
sources: sources,
dependencies: dependencies,
buildSettings: .init(),
pluginUsages: []
)
}
private enum CodingKeys: String, CodingKey {
case swiftVersion
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(swiftVersion, forKey: .swiftVersion)
try super.encode(to: encoder)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.swiftVersion = try container.decode(SwiftLanguageVersion.self, forKey: .swiftVersion)
try super.init(from: decoder)
}
}
public final class SystemLibraryTarget: Target {
/// The name of pkgConfig file, if any.
public let pkgConfig: String?
/// List of system package providers, if any.
public let providers: [SystemPackageProviderDescription]?
/// True if this system library should become implicit target
/// dependency of its dependent packages.
public let isImplicit: Bool
public init(
name: String,
path: AbsolutePath,
isImplicit: Bool = true,
pkgConfig: String? = nil,
providers: [SystemPackageProviderDescription]? = nil
) {
let sources = Sources(paths: [], root: path)
self.pkgConfig = pkgConfig
self.providers = providers
self.isImplicit = isImplicit
super.init(
name: name,
type: .systemModule,
path: sources.root,
sources: sources,
dependencies: [],
buildSettings: .init(),
pluginUsages: []
)
}
private enum CodingKeys: String, CodingKey {
case pkgConfig, providers, isImplicit
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(pkgConfig, forKey: .pkgConfig)
try container.encode(providers, forKey: .providers)
try container.encode(isImplicit, forKey: .isImplicit)
try super.encode(to: encoder)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.pkgConfig = try container.decodeIfPresent(String.self, forKey: .pkgConfig)
self.providers = try container.decodeIfPresent([SystemPackageProviderDescription].self, forKey: .providers)
self.isImplicit = try container.decode(Bool.self, forKey: .isImplicit)
try super.init(from: decoder)
}
}
public final class ClangTarget: Target {
/// The default public include directory component.
public static let defaultPublicHeadersComponent = "include"
/// The path to include directory.
public let includeDir: AbsolutePath
/// The target's module map type, which determines whether this target vends a custom module map, a generated module map, or no module map at all.
public let moduleMapType: ModuleMapType
/// The headers present in the target.
///
/// Note that this contains both public and non-public headers.
public let headers: [AbsolutePath]
/// True if this is a C++ target.
public let isCXX: Bool
/// The C language standard flag.
public let cLanguageStandard: String?
/// The C++ language standard flag.
public let cxxLanguageStandard: String?
public init(
name: String,
potentialBundleName: String? = nil,
cLanguageStandard: String?,
cxxLanguageStandard: String?,
includeDir: AbsolutePath,
moduleMapType: ModuleMapType,
headers: [AbsolutePath] = [],
type: Kind,
path: AbsolutePath,
sources: Sources,
resources: [Resource] = [],
ignored: [AbsolutePath] = [],
others: [AbsolutePath] = [],
dependencies: [Target.Dependency] = [],
buildSettings: BuildSettings.AssignmentTable = .init()
) throws {
guard includeDir.isDescendantOfOrEqual(to: sources.root) else {
throw StringError("\(includeDir) should be contained in the source root \(sources.root)")
}
self.isCXX = sources.containsCXXFiles
self.cLanguageStandard = cLanguageStandard
self.cxxLanguageStandard = cxxLanguageStandard
self.includeDir = includeDir
self.moduleMapType = moduleMapType
self.headers = headers
super.init(
name: name,
potentialBundleName: potentialBundleName,
type: type,
path: path,
sources: sources,
resources: resources,
ignored: ignored,
others: others,
dependencies: dependencies,
buildSettings: buildSettings,
pluginUsages: []
)
}
private enum CodingKeys: String, CodingKey {
case includeDir, moduleMapType, headers, isCXX, cLanguageStandard, cxxLanguageStandard
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(includeDir, forKey: .includeDir)
try container.encode(moduleMapType, forKey: .moduleMapType)
try container.encode(headers, forKey: .headers)
try container.encode(isCXX, forKey: .isCXX)
try container.encode(cLanguageStandard, forKey: .cLanguageStandard)
try container.encode(cxxLanguageStandard, forKey: .cxxLanguageStandard)
try super.encode(to: encoder)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.includeDir = try container.decode(AbsolutePath.self, forKey: .includeDir)
self.moduleMapType = try container.decode(ModuleMapType.self, forKey: .moduleMapType)
self.headers = try container.decode([AbsolutePath].self, forKey: .headers)
self.isCXX = try container.decode(Bool.self, forKey: .isCXX)
self.cLanguageStandard = try container.decodeIfPresent(String.self, forKey: .cLanguageStandard)
self.cxxLanguageStandard = try container.decodeIfPresent(String.self, forKey: .cxxLanguageStandard)
try super.init(from: decoder)
}
}
public final class BinaryTarget: Target {
/// The kind of binary artifact.
public let kind: Kind
/// The original source of the binary artifact.
public let origin: Origin
/// The binary artifact path.
public var artifactPath: AbsolutePath {
return self.sources.root
}
public init(
name: String,
kind: Kind,
path: AbsolutePath,
origin: Origin
) {
self.origin = origin
self.kind = kind
let sources = Sources(paths: [], root: path)
super.init(
name: name,
type: .binary,
path: .root,
sources: sources,
dependencies: [],
buildSettings: .init(),
pluginUsages: []
)
}
private enum CodingKeys: String, CodingKey {
case kind
case origin
case artifactSource // backwards compatibility 2/2021
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.origin, forKey: .origin)
try container.encode(self.kind, forKey: .kind)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// backwards compatibility 2/2021
if !container.contains(.kind) {
self.kind = .xcframework
} else {
self.kind = try container.decode(Kind.self, forKey: .kind)
}
// backwards compatibility 2/2021
if container.contains(.artifactSource) {
self.origin = try container.decode(Origin.self, forKey: .artifactSource)
} else {
self.origin = try container.decode(Origin.self, forKey: .origin)
}
try super.init(from: decoder)
}
public enum Kind: String, RawRepresentable, Codable, CaseIterable {
case xcframework
case artifactsArchive
case unknown // for non-downloaded artifacts
public var fileExtension: String {
switch self {
case .xcframework:
return "xcframework"
case .artifactsArchive:
return "artifactbundle"
case .unknown:
return "unknown"
}
}
}
public var containsExecutable: Bool {
// FIXME: needs to be revisited once libraries are supported in artifact bundles
return self.kind == .artifactsArchive
}
public enum Origin: Equatable, Codable {
/// Represents an artifact that was downloaded from a remote URL.
case remote(url: String)
/// Represents an artifact that was available locally.
case local
private enum CodingKeys: String, CodingKey {
case remote, local
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .remote(let a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .remote)
try unkeyedContainer.encode(a1)
case .local:
try container.encodeNil(forKey: .local)
}
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let key = values.allKeys.first(where: values.contains) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key"))
}
switch key {
case .remote:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode(String.self)
self = .remote(url: a1)
case .local:
self = .local
}
}
}
}
public final class PluginTarget: Target {
/// Declared capability of the plugin.
public let capability: PluginCapability
/// API version to use for PackagePlugin API availability.
public let apiVersion: ToolsVersion
public init(
name: String,
sources: Sources,
apiVersion: ToolsVersion,
pluginCapability: PluginCapability,
dependencies: [Target.Dependency] = []
) {
self.capability = pluginCapability
self.apiVersion = apiVersion
super.init(
name: name,
type: .plugin,
path: .root,
sources: sources,
dependencies: dependencies,
buildSettings: .init(),
pluginUsages: []
)
}
private enum CodingKeys: String, CodingKey {
case capability
case apiVersion
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.capability, forKey: .capability)
try container.encode(self.apiVersion, forKey: .apiVersion)
try super.encode(to: encoder)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.capability = try container.decode(PluginCapability.self, forKey: .capability)
self.apiVersion = try container.decode(ToolsVersion.self, forKey: .apiVersion)
try super.init(from: decoder)
}
}
public enum PluginCapability: Hashable, Codable {
case buildTool
case command(intent: PluginCommandIntent, permissions: [PluginPermission])
private enum CodingKeys: String, CodingKey {
case buildTool, command
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .buildTool:
try container.encodeNil(forKey: .buildTool)
case .command(let a1, let a2):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .command)
try unkeyedContainer.encode(a1)
try unkeyedContainer.encode(a2)
}
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let key = values.allKeys.first(where: values.contains) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key"))
}
switch key {
case .buildTool:
self = .buildTool
case .command:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode(PluginCommandIntent.self)
let a2 = try unkeyedValues.decode([PluginPermission].self)
self = .command(intent: a1, permissions: a2)
}
}
public init(from desc: TargetDescription.PluginCapability) {
switch desc {
case .buildTool:
self = .buildTool
case .command(let intent, let permissions):
self = .command(intent: .init(from: intent), permissions: permissions.map{ .init(from: $0) })
}
}
}
public enum PluginCommandIntent: Hashable, Codable {
case documentationGeneration
case sourceCodeFormatting
case custom(verb: String, description: String)
public init(from desc: TargetDescription.PluginCommandIntent) {
switch desc {
case .documentationGeneration:
self = .documentationGeneration
case .sourceCodeFormatting:
self = .sourceCodeFormatting
case .custom(let verb, let description):
self = .custom(verb: verb, description: description)
}
}
}
public enum PluginPermission: Hashable, Codable {
case writeToPackageDirectory(reason: String)
public init(from desc: TargetDescription.PluginPermission) {
switch desc {
case .writeToPackageDirectory(let reason):
self = .writeToPackageDirectory(reason: reason)
}
}
}
public extension Sequence where Iterator.Element == Target {
var executables: [Target] {
return filter {
switch $0.type {
case .binary:
return ($0 as? BinaryTarget)?.containsExecutable == true
case .executable:
return true
default:
return false
}
}
}
}
|
apache-2.0
|
bd05b1fac60eb0950b089c4987ba6eb0
| 34.836784 | 150 | 0.627864 | 4.899584 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock
|
Pods/Charts/Charts/Classes/Data/Implementations/ChartBaseDataSet.swift
|
6
|
9185
|
//
// BaseDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 16/1/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class ChartBaseDataSet: NSObject, IChartDataSet
{
public required override init()
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
valueColors.append(NSUIColor.black)
}
public init(label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
valueColors.append(NSUIColor.black)
self.label = label
}
// MARK: - Data functions and accessors
/// Use this method to tell the data set that the underlying data has changed
open func notifyDataSetChanged()
{
calcMinMax(start: 0, end: entryCount - 1)
}
open func calcMinMax(start: Int, end: Int)
{
fatalError("calcMinMax is not implemented in ChartBaseDataSet")
}
open var yMin: Double
{
fatalError("yMin is not implemented in ChartBaseDataSet")
}
open var yMax: Double
{
fatalError("yMax is not implemented in ChartBaseDataSet")
}
open var entryCount: Int
{
fatalError("entryCount is not implemented in ChartBaseDataSet")
}
open func yValForXIndex(_ x: Int) -> Double
{
fatalError("yValForXIndex is not implemented in ChartBaseDataSet")
}
open func yValsForXIndex(_ x: Int) -> [Double]
{
fatalError("yValsForXIndex is not implemented in ChartBaseDataSet")
}
open func entryForIndex(_ i: Int) -> ChartDataEntry?
{
fatalError("entryForIndex is not implemented in ChartBaseDataSet")
}
open func entryForXIndex(_ x: Int, rounding: ChartDataSetRounding) -> ChartDataEntry?
{
fatalError("entryForXIndex is not implemented in ChartBaseDataSet")
}
open func entryForXIndex(_ x: Int) -> ChartDataEntry?
{
fatalError("entryForXIndex is not implemented in ChartBaseDataSet")
}
open func entriesForXIndex(_ x: Int) -> [ChartDataEntry]
{
fatalError("entriesForXIndex is not implemented in ChartBaseDataSet")
}
open func entryIndex(xIndex x: Int, rounding: ChartDataSetRounding) -> Int
{
fatalError("entryIndex is not implemented in ChartBaseDataSet")
}
open func entryIndex(entry e: ChartDataEntry) -> Int
{
fatalError("entryIndex is not implemented in ChartBaseDataSet")
}
open func addEntry(_ e: ChartDataEntry) -> Bool
{
fatalError("addEntry is not implemented in ChartBaseDataSet")
}
open func addEntryOrdered(_ e: ChartDataEntry) -> Bool
{
fatalError("addEntryOrdered is not implemented in ChartBaseDataSet")
}
open func removeEntry(_ entry: ChartDataEntry) -> Bool
{
fatalError("removeEntry is not implemented in ChartBaseDataSet")
}
open func removeEntry(xIndex: Int) -> Bool
{
if let entry = entryForXIndex(xIndex)
{
return removeEntry(entry)
}
return false
}
open func removeFirst() -> Bool
{
if let entry = entryForIndex(0)
{
return removeEntry(entry)
}
return false
}
open func removeLast() -> Bool
{
if let entry = entryForIndex(entryCount - 1)
{
return removeEntry(entry)
}
return false
}
open func contains(_ e: ChartDataEntry) -> Bool
{
fatalError("removeEntry is not implemented in ChartBaseDataSet")
}
open func clear()
{
fatalError("clear is not implemented in ChartBaseDataSet")
}
// MARK: - Styling functions and accessors
/// All the colors that are used for this DataSet.
/// Colors are reused as soon as the number of Entries the DataSet represents is higher than the size of the colors array.
open var colors = [NSUIColor]()
/// List representing all colors that are used for drawing the actual values for this DataSet
open var valueColors = [NSUIColor]()
/// The label string that describes the DataSet.
open var label: String? = "DataSet"
/// The axis this DataSet should be plotted against.
open var axisDependency = ChartYAxis.AxisDependency.left
/// - returns: the color at the given index of the DataSet's color array.
/// This prevents out-of-bounds by performing a modulus on the color index, so colours will repeat themselves.
open func colorAt(_ index: Int) -> NSUIColor
{
var index = index
if (index < 0)
{
index = 0
}
return colors[index % colors.count]
}
/// Resets all colors of this DataSet and recreates the colors array.
open func resetColors()
{
colors.removeAll(keepingCapacity: false)
}
/// Adds a new color to the colors array of the DataSet.
/// - parameter color: the color to add
open func addColor(_ color: NSUIColor)
{
colors.append(color)
}
/// Sets the one and **only** color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
/// - parameter color: the color to set
open func setColor(_ color: NSUIColor)
{
colors.removeAll(keepingCapacity: false)
colors.append(color)
}
/// Sets colors to a single color a specific alpha value.
/// - parameter color: the color to set
/// - parameter alpha: alpha to apply to the set `color`
open func setColor(_ color: NSUIColor, alpha: CGFloat)
{
setColor(color.withAlphaComponent(alpha))
}
/// Sets colors with a specific alpha value.
/// - parameter colors: the colors to set
/// - parameter alpha: alpha to apply to the set `colors`
open func setColors(_ colors: [NSUIColor], alpha: CGFloat)
{
var colorsWithAlpha = colors
for i in 0 ..< colorsWithAlpha.count
{
colorsWithAlpha[i] = colorsWithAlpha[i] .withAlphaComponent(alpha)
}
self.colors = colorsWithAlpha
}
/// if true, value highlighting is enabled
open var highlightEnabled = true
/// the formatter used to customly format the values
internal var _valueFormatter: NumberFormatter? = ChartUtils.defaultValueFormatter()
/// The formatter used to customly format the values
open var valueFormatter: NumberFormatter?
{
get
{
return _valueFormatter
}
set
{
if newValue == nil
{
_valueFormatter = ChartUtils.defaultValueFormatter()
}
else
{
_valueFormatter = newValue
}
}
}
/// Sets/get a single color for value text.
/// Setting the color clears the colors array and adds a single color.
/// Getting will return the first color in the array.
open var valueTextColor: NSUIColor
{
get
{
return valueColors[0]
}
set
{
valueColors.removeAll(keepingCapacity: false)
valueColors.append(newValue)
}
}
/// - returns: the color at the specified index that is used for drawing the values inside the chart. Uses modulus internally.
open func valueTextColorAt(_ index: Int) -> NSUIColor
{
var index = index
if (index < 0)
{
index = 0
}
return valueColors[index % valueColors.count]
}
/// the font for the value-text labels
open var valueFont: NSUIFont = NSUIFont.systemFont(ofSize: 7.0)
/// Set this to true to draw y-values on the chart
open var drawValuesEnabled = true
/// Set the visibility of this DataSet. If not visible, the DataSet will not be drawn to the chart upon refreshing it.
open var visible = true
// MARK: - NSObject
open override var description: String
{
return String(format: "%@, label: %@, %i entries", arguments: [NSStringFromClass(type(of: self)), self.label ?? "", self.entryCount])
}
open override var debugDescription: String
{
var desc = description + ":"
for i in 0 ..< self.entryCount
{
desc += "\n" + (self.entryForIndex(i)?.description ?? "")
}
return desc
}
// MARK: - NSCopying
open func copyWithZone(_ zone: NSZone?) -> Any
{
let copy = type(of: self).init()
copy.colors = colors
copy.valueColors = valueColors
copy.label = label
return copy
}
}
|
mit
|
5acfc9969651db8a23ea0069b7fd3614
| 26.917933 | 141 | 0.601089 | 4.81142 | false | false | false | false |
Alamofire/Alamofire
|
Source/MultipartUpload.swift
|
8
|
3424
|
//
// MultipartUpload.swift
//
// Copyright (c) 2014-2018 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
/// Internal type which encapsulates a `MultipartFormData` upload.
final class MultipartUpload {
lazy var result = Result { try build() }
@Protected
private(set) var multipartFormData: MultipartFormData
let encodingMemoryThreshold: UInt64
let request: URLRequestConvertible
let fileManager: FileManager
init(encodingMemoryThreshold: UInt64,
request: URLRequestConvertible,
multipartFormData: MultipartFormData) {
self.encodingMemoryThreshold = encodingMemoryThreshold
self.request = request
fileManager = multipartFormData.fileManager
self.multipartFormData = multipartFormData
}
func build() throws -> UploadRequest.Uploadable {
let uploadable: UploadRequest.Uploadable
if $multipartFormData.contentLength < encodingMemoryThreshold {
let data = try $multipartFormData.read { try $0.encode() }
uploadable = .data(data)
} else {
let tempDirectoryURL = fileManager.temporaryDirectory
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
do {
try $multipartFormData.read { try $0.writeEncodedData(to: fileURL) }
} catch {
// Cleanup after attempted write if it fails.
try? fileManager.removeItem(at: fileURL)
throw error
}
uploadable = .file(fileURL, shouldRemove: true)
}
return uploadable
}
}
extension MultipartUpload: UploadConvertible {
func asURLRequest() throws -> URLRequest {
var urlRequest = try request.asURLRequest()
$multipartFormData.read { multipartFormData in
urlRequest.headers.add(.contentType(multipartFormData.contentType))
}
return urlRequest
}
func createUploadable() throws -> UploadRequest.Uploadable {
try result.get()
}
}
|
mit
|
dbf7767d6719988c8a17cda5e4ed0c62
| 37.47191 | 115 | 0.695093 | 5.275809 | false | false | false | false |
cdtschange/SwiftMKit
|
SwiftMKitDemo/SwiftMKitDemo/UI/Data/NetworkRequest/MKCoreDataNetworkRequestViewModel.swift
|
1
|
1425
|
//
// MKDataStoreViewModel.swift
// SwiftMKitDemo
//
// Created by Mao on 4/21/16.
// Copyright © 2016 cdts. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import CoreData
public class MKCoreDataNetworkRequestViewModel: BaseListFetchViewModel {
// fileprivate var signalPX500PhotosCoreData: SignalProducer<PX500PopularPhotosCoreDataApiData, NetError> {
// get {
// return PX500PopularPhotosCoreDataApiData(page:self.dataIndex+1, number:self.listLoadNumber).signal().on(
// failed: { [weak self] error in
// self?.showTip(error.message)
// }, value: { [weak self] data in
// self?.fetchCachedData()
// })
// }
// }
// fileprivate var _fetchRequest: NSFetchRequest<NSFetchRequestResult>?
// override var fetchRequest: NSFetchRequest<NSFetchRequestResult>? {
// if _fetchRequest == nil {
// _fetchRequest = NSFetchRequest(entityName: NSStringFromClass(PX500PhotoEntity.self))
// _fetchRequest?.sortDescriptors = BaseEntityProperty.defaultSort
// _fetchRequest?.fetchBatchSize = Int(listLoadNumber)
// _fetchRequest?.fetchLimit = Int(listLoadNumber * (dataIndex + 1))
// }
// return _fetchRequest
// }
//
// override func fetchData() {
// signalPX500PhotosCoreData.start()
// }
}
|
mit
|
b5e476e6c725a33b34378fb028ecdc70
| 34.6 | 118 | 0.640449 | 4.328267 | false | false | false | false |
manfengjun/KYMart
|
Section/Home/View/Product/KYProductCVCell.swift
|
1
|
914
|
//
// KYProductCVCell.swift
// KYMart
//
// Created by Jun on 2017/6/5.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYProductCVCell: UICollectionViewCell {
@IBOutlet weak var productIV: UIImageView!
@IBOutlet weak var productInfoL: UILabel!
@IBOutlet weak var countL: UILabel!
@IBOutlet weak var buyBtn: UIButton!
@IBOutlet weak var productTypeIV: UIImageView!
var good:Good?{
didSet {
if let id = good?.goods_id {
productIV.sd_setImage(with: imageUrl(goods_id: id), placeholderImage: nil)
}
if let text = good?.goods_name {
productInfoL.text = text
}
if let text = good?.shop_price {
countL.text = text
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
|
mit
|
1212c55f772db5cb2cab9a9ea61577a0
| 23.621622 | 90 | 0.578485 | 4.276995 | false | false | false | false |
ztolley/VideoStationViewer
|
VideoStationViewerTests/SessionAPITests.swift
|
1
|
1796
|
import XCTest
import OHHTTPStubs
class SessionTests: XCTestCase {
var session = SessionAPI()
override func setUp() {
super.setUp()
let preferences: NSUserDefaults = NSUserDefaults.standardUserDefaults()
preferences.setObject("test.com", forKey: "HOSTNAME")
preferences.setObject("user", forKey: "USERID")
preferences.setObject("password", forKey: "PASSWORD")
preferences.synchronize()
}
override func tearDown() {
OHHTTPStubs.removeAllStubs()
super.tearDown()
}
func testLoginReturnsSession() {
let expectation = expectationWithDescription("GET login")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest) -> Bool in
let url = request.URL!
if let pathComponents = url.pathComponents {
if pathComponents.contains("auth.cgi") {
return true
}
}
return false
}, withStubResponse: { (request: NSURLRequest) -> OHHTTPStubsResponse in
let obj = [
"data": [
"sid": "1234"
]
]
return OHHTTPStubsResponse(JSONObject: obj, statusCode:200, headers:nil)
})
session.login { (session, error) -> Void in
if let sessionValue = session {
XCTAssert(sessionValue == "1234")
} else {
XCTFail()
}
expectation.fulfill()
}
waitForExpectationsWithTimeout(500, handler: {
error in XCTAssertNil(error, "Oh, we got timeout")
})
}
// test bad login
}
|
gpl-3.0
|
469fcf7dc324835a56a7889b012d4400
| 24.671429 | 84 | 0.520045 | 5.907895 | false | true | false | false |
chinlam91/edx-app-ios
|
Test/SnapshotTestCase.swift
|
2
|
5221
|
//
// SnapshotTestCase
// edX
//
// Created by Akiva Leffert on 5/14/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
private let StandardTolerance : CGFloat = 1.0
protocol SnapshotTestable {
func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws
var snapshotSize : CGSize { get }
}
extension UIView : SnapshotTestable {
func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws {
try testCase.compareSnapshotOfView(self, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance)
}
var snapshotSize : CGSize {
return bounds.size
}
}
extension CALayer : SnapshotTestable {
func snapshotTestWithCase(testCase : FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws {
try testCase.compareSnapshotOfLayer(self, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance)
}
var snapshotSize : CGSize {
return bounds.size
}
}
extension UIViewController : SnapshotTestable {
func prepareForSnapshot() {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = self
window.makeKeyAndVisible()
}
func snapshotTestWithCase(testCase: FBSnapshotTestCase, referenceImagesDirectory: String, identifier: String) throws {
try testCase.compareSnapshotOfView(self.view, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance : StandardTolerance)
}
func finishSnapshot() {
view.window?.removeFromSuperview()
}
var snapshotSize : CGSize {
return view.bounds.size
}
}
class SnapshotTestCase : FBSnapshotTestCase {
override func setUp() {
super.setUp()
// Run "./gradlew recordSnapshots --continue" to regenerate all snapshots
#if RECORD_SNAPSHOTS
recordMode = true
#endif
}
var screenSize : CGSize {
// Standardize on a size so we don't have to worry about different simulators
// etc.
// Pick a non standard width so we can catch width assumptions.
return CGSizeMake(380, 568)
}
private var majorVersion : Int {
return NSProcessInfo.processInfo().operatingSystemVersion.majorVersion
}
private final func qualifyIdentifier(identifier : String?, content : SnapshotTestable) -> String {
let rtl = UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft ? "_rtl" : ""
let suffix = "ios\(majorVersion)\(rtl)_\(Int(content.snapshotSize.width))x\(Int(content.snapshotSize.height))"
if let identifier = identifier {
return identifier + suffix
}
else {
return suffix
}
}
// Asserts that a snapshot matches expectations
// This is similar to the objc only FBSnapshotTest macros
// But works in swift
func assertSnapshotValidWithContent(content : SnapshotTestable, identifier : String? = nil, message : String? = nil, file : String = __FILE__, line : UInt = __LINE__) {
let qualifiedIdentifier = qualifyIdentifier(identifier, content : content)
do {
try content.snapshotTestWithCase(self, referenceImagesDirectory: FB_REFERENCE_IMAGE_DIR, identifier: qualifiedIdentifier)
}
catch let error as NSError {
let unknownError = "Unknown Error"
XCTFail("Snapshot comparison failed: \(error.localizedDescription ?? unknownError)", file : file, line : line)
if let message = message {
XCTFail(message, file : file, line : line)
}
else {
XCTFail(file : file, line : line)
}
}
XCTAssertFalse(recordMode, "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file : file, line : line)
}
func inScreenNavigationContext(controller : UIViewController, @noescape action : () -> ()) {
let container = UINavigationController(rootViewController: controller)
inScreenDisplayContext(container, action: action)
}
/// Makes a window and adds the controller to it
/// to ensure that our controller actually loads properly
/// Otherwise, sometimes viewWillAppear: type methods don't get called
func inScreenDisplayContext(controller : UIViewController, @noescape action : () -> ()) {
let window = UIWindow(frame: CGRectZero)
window.rootViewController = controller
window.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
window.makeKeyAndVisible()
controller.view.frame = window.bounds
controller.view.updateConstraintsIfNeeded()
controller.view.setNeedsLayout()
controller.view.layoutIfNeeded()
action()
window.removeFromSuperview()
}
}
|
apache-2.0
|
345797137822bb9ea9c4afb3f065c48e
| 35.774648 | 180 | 0.669029 | 5.427235 | false | true | false | false |
barbosa/clappr-ios
|
Example/Tests/UIPluginTests.swift
|
1
|
1427
|
import Quick
import Nimble
import Clappr
class UIPluginTests: QuickSpec {
override func spec() {
describe("Instantiation") {
it("Should enable plugin by default") {
let plugin = UIPlugin()
expect(plugin.enabled).to(beTrue())
}
}
describe("Behavior") {
var plugin: UIPlugin!
beforeEach() {
plugin = UIPlugin()
}
context("Enabling") {
it("Should not be hidden") {
plugin.enabled = false
plugin.enabled = true
expect(plugin.hidden).to(beFalse())
}
}
context("Disabling") {
it("Should be hidden") {
plugin.enabled = false
expect(plugin.hidden).to(beTrue())
}
it("Should stop listening to events") {
var eventWasCalled = false
plugin.on("event") { _ in
eventWasCalled = true
}
plugin.enabled = false
plugin.trigger("event")
expect(eventWasCalled).to(beFalse())
}
}
}
}
}
|
bsd-3-clause
|
e517e23696c619b07522da577cb045c0
| 27 | 56 | 0.385424 | 6.231441 | false | false | false | false |
feiin/GesturePassword4Swift
|
GesturePassword4Swift/GesturePasswordControllerViewController.swift
|
1
|
4453
|
//
// GesturePasswordControllerViewController.swift
// GesturePassword4Swift
//
// Created by feiin on 14/11/22.
// Copyright (c) 2014年 swiftmi. All rights reserved.
//
// Edited by Glitter on 16/01/12.
import UIKit
class GesturePasswordControllerViewController: UIViewController,VerificationDelegate,ResetDelegate,GesturePasswordDelegate {
var gesturePasswordView:GesturePasswordView!
var previousString:String? = ""
var password:String? = ""
var secKey:String = "GesturePassword4Swift"
override func viewDidLoad() {
super.viewDidLoad()
previousString = ""
password = KeychainWrapper.stringForKey(secKey)
if( password == "" || password == nil){
self.reset()
}
else{
self.verify()
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - 验证手势密码
func verify(){
gesturePasswordView = GesturePasswordView(frame: UIScreen.main.bounds)
gesturePasswordView.tentacleView!.rerificationDelegate = self
gesturePasswordView.tentacleView!.style = 1
gesturePasswordView.gesturePasswordDelegate = self
self.view.addSubview(gesturePasswordView)
}
//MARK: - 重置手势密码
func reset(){
gesturePasswordView = GesturePasswordView(frame: UIScreen.main.bounds)
gesturePasswordView.tentacleView!.resetDelegate = self
gesturePasswordView.tentacleView!.style = 2
gesturePasswordView.forgetButton!.isHidden = true
gesturePasswordView.changeButton!.isHidden = true
self.view.addSubview(gesturePasswordView)
}
func exist()->Bool{
password = KeychainWrapper.stringForKey(secKey)
if password == "" {
return false
}
return true
}
//MARK: - 清空记录
func clear(){
KeychainWrapper.removeObjectForKey(secKey)
}
//MARK: - 改变手势密码
func change(){
print("改变手势密码")
}
//MARK: - 忘记密码
func forget(){
print("忘记密码")
}
func verification(_ result:String)->Bool{
// println("password:\(result)====\(password)")
if(result == password){
gesturePasswordView.state!.textColor = UIColor.white
gesturePasswordView.state!.text = "输入正确"
return true
}
gesturePasswordView.state!.textColor = UIColor.red
gesturePasswordView.state!.text = "手势密码错误"
return false
}
func resetPassword(_ result: String) -> Bool {
if(previousString == ""){
previousString = result
gesturePasswordView.tentacleView!.enterArgin()
gesturePasswordView.state!.textColor = UIColor(red: 2/255, green: 174/255, blue: 240/255, alpha: 1)
gesturePasswordView.state!.text = "请验证输入密码"
return true
}else{
if(result == previousString){
KeychainWrapper.setString(result, forKey: secKey)
gesturePasswordView.state!.textColor = UIColor(red: 2/255, green: 174/255, blue: 240/255, alpha: 1)
gesturePasswordView.state!.text = "已保存手势密码"
return true;
}else{
previousString = "";
gesturePasswordView.state!.textColor = UIColor.red
gesturePasswordView.state!.text = "两次密码不一致,请重新输入"
return false
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
e51b5578405afc97ea1a31c4786b4b51
| 26.420382 | 124 | 0.570732 | 5.161871 | false | false | false | false |
caiomello/utilities
|
Sources/Utilities/Protocols & Classes/Formatters.swift
|
1
|
960
|
//
// Formatters.swift
//
//
// Created by Caio Mello on 14.03.22.
//
import Foundation
enum Formatters {
static let shortDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM d, yyyy"
return formatter
}()
static let fullDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d, yyyy"
return formatter
}()
static let nearFutureDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d"
return formatter
}()
static let weekdayDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE"
return formatter
}()
static let yearDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
return formatter
}()
}
|
mit
|
3159512403de4fc1b6916f153a3b747e
| 23 | 57 | 0.626042 | 5.052632 | false | false | false | false |
edragoev1/pdfjet
|
Sources/Example_10/main.swift
|
1
|
5967
|
import Foundation
import PDFjet
///
/// Example_10.swift
///
public class Example_10 {
public init() throws {
let rotate = ClockWise._0_degrees
if let stream = OutputStream(toFileAtPath: "Example_10.pdf", append: false) {
let pdf = PDF(stream)
pdf.setTitle("Using TextColumn and Paragraph classes")
pdf.setSubject("Examples")
pdf.setAuthor("Innovatics Inc.")
let image1 = try Image(
pdf,
InputStream(fileAtPath: "images/sz-map.png")!,
ImageType.PNG)
let f1 = Font(pdf, CoreFont.HELVETICA)
f1.setSize(10.0)
let f2 = Font(pdf, CoreFont.HELVETICA_BOLD)
f2.setSize(14.0)
let f3 = Font(pdf, CoreFont.HELVETICA_BOLD)
f3.setSize(12.0)
let f4 = Font(pdf, CoreFont.HELVETICA_OBLIQUE)
f4.setSize(10.0)
let page = Page(pdf, Letter.PORTRAIT)
image1.setLocation(90.0, 35.0)
image1.scaleBy(0.75)
image1.drawOn(page)
let column = TextColumn(rotate)
column.setSpaceBetweenLines(5.0)
column.setSpaceBetweenParagraphs(10.0)
let p1 = Paragraph()
p1.setAlignment(Align.CENTER)
p1.add(TextLine(f2, "Switzerland"))
let p2 = Paragraph()
p2.add(TextLine(f2, "Introduction"))
var buf = String()
buf.append("The Swiss Confederation was founded in 1291 as a defensive ")
buf.append("alliance among three cantons. In succeeding years, other ")
buf.append("localities joined the original three. ")
buf.append("The Swiss Confederation secured its independence from the ")
buf.append("Holy Roman Empire in 1499. Switzerland's sovereignty and ")
buf.append("neutrality have long been honored by the major European ")
buf.append("powers, and the country was not involved in either of the ")
buf.append("two World Wars. The political and economic integration of ")
buf.append("Europe over the past half century, as well as Switzerland's ")
buf.append("role in many UN and international organizations, has ")
buf.append("strengthened Switzerland's ties with its neighbors. ")
buf.append("However, the country did not officially become a UN member ")
buf.append("until 2002.")
let p3 = Paragraph()
// p3.setAlignment(Align.LEFT)
// p3.setAlignment(Align.RIGHT)
p3.setAlignment(Align.JUSTIFY)
var text = TextLine(f1, buf)
p3.add(text)
buf = String()
buf.append("Switzerland remains active in many UN and international ")
buf.append("organizations but retains a strong commitment to neutrality.")
text = TextLine(f1, buf)
text.setColor(Color.red)
p3.add(text)
let p4 = Paragraph()
p4.add(TextLine(f3, "Economy"))
buf = String()
buf.append("Switzerland is a peaceful, prosperous, and stable modern ")
buf.append("market economy with low unemployment, a highly skilled ")
buf.append("labor force, and a per capita GDP larger than that of the ")
buf.append("big Western European economies. The Swiss in recent years ")
buf.append("have brought their economic practices largely into ")
buf.append("conformity with the EU's to enhance their international ")
buf.append("competitiveness. Switzerland remains a safehaven for ")
buf.append("investors, because it has maintained a degree of bank secrecy ")
buf.append("and has kept up the franc's long-term external value. ")
buf.append("Reflecting the anemic economic conditions of Europe, GDP ")
buf.append("growth stagnated during the 2001-03 period, improved during ")
buf.append("2004-05 to 1.8% annually and to 2.9% in 2006.")
let p5 = Paragraph()
p5.setAlignment(Align.JUSTIFY)
text = TextLine(f1, buf)
p5.add(text)
text = TextLine(f4,
"Even so, unemployment has remained at less than half the EU average.")
text.setColor(Color.blue)
p5.add(text)
let p6 = Paragraph()
p6.setAlignment(Align.RIGHT)
text = TextLine(f1, "Source: The world fact book.")
text.setColor(Color.blue)
text.setURIAction(
"https://www.cia.gov/library/publications/the-world-factbook/geos/sz.html")
p6.add(text)
column.addParagraph(p1)
column.addParagraph(p2)
column.addParagraph(p3)
column.addParagraph(p4)
column.addParagraph(p5)
column.addParagraph(p6)
if rotate == ClockWise._0_degrees {
column.setLocation(90.0, 300.0)
}
else if rotate == ClockWise._90_degrees {
column.setLocation(90.0, 780.0)
}
else if rotate == ClockWise._270_degrees {
column.setLocation(550.0, 310.0)
}
let columnWidth: Float = 470.0
column.setSize(columnWidth, 100.0)
let xy = column.drawOn(page)
if rotate == ClockWise._0_degrees {
Line(
xy[0],
xy[1],
xy[0] + columnWidth,
xy[1]).drawOn(page)
}
pdf.complete()
}
}
} // End of Example_10.swift
let time0 = Int64(Date().timeIntervalSince1970 * 1000)
_ = try Example_10()
let time1 = Int64(Date().timeIntervalSince1970 * 1000)
print("Example_10 => \(time1 - time0)")
|
mit
|
c713b5611b14bd72070a34629f7aba8f
| 36.062112 | 95 | 0.565108 | 4.123704 | false | false | false | false |
crazypoo/PTools
|
PooToolsSource/DarkMode/PTDrakModeOption.swift
|
1
|
10667
|
//
// PTDrakModeOption.swift
// PooTools_Example
//
// Created by Macmini on 2022/6/15.
// Copyright © 2022 crazypoo. All rights reserved.
//
import UIKit
// MARK: - 方法的调用
extension PTDrakModeOption: PTThemeable {
public func apply() {}
}
public class PTDrakModeOption {
/// 智能换肤的时间区间的key
private static let PTSmartPeelingTimeIntervalKey = "PTSmartPeelingTimeIntervalKey"
/// 跟随系统的key
private static let PTDarkToSystemKey = "PTDarkToSystemKey"
/// 是否浅色模式的key
private static let PTLightDarkKey = "PTLightDarkKey"
/// 智能换肤的key
private static let PTSmartPeelingKey = "PTSmartPeelingKey"
/// 是否浅色
public static var isLight: Bool {
if isSmartPeeling {
return isSmartPeelingTime() ? false : true
}
if let value = UserDefaults.pt.userDefaultsGetValue(key: PTLightDarkKey) as? Bool {
return value
}
return true
}
///默认不是智能
public static var isSmartPeeling: Bool {
if let value = UserDefaults.pt.userDefaultsGetValue(key: PTSmartPeelingKey) as? Bool {
return value
}
return false
}
/// 智能模式的时间段:默认是:21:00~8:00
public static var smartPeelingTimeIntervalValue: String {
get {
if let value = UserDefaults.pt.userDefaultsGetValue(key: PTSmartPeelingTimeIntervalKey) as? String {
return value
}
return "22:00~9:00"
}
set {
UserDefaults.pt.userDefaultsSetValue(value: newValue, key: PTSmartPeelingTimeIntervalKey)
}
}
/// 是否跟随系统
public static var isFollowSystem: Bool {
if #available(iOS 13, *) {
if let value = UserDefaults.pt.userDefaultsGetValue(key: PTDarkToSystemKey) as? Bool {
return value
}
return true
}
return false
}
}
public extension PTDrakModeOption {
// MARK: 初始化的调用
/// 默认设置
static func defaultDark() {
if #available(iOS 13.0, *) {
// 默认跟随系统暗黑模式开启监听
if (PTDrakModeOption.isFollowSystem) {
PTDrakModeOption.setDarkModeFollowSystem(isFollowSystem: true)
} else {
UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.overrideUserInterfaceStyle = PTDrakModeOption.isLight ? .light : .dark
}
}
}
// MARK: 设置系统是否跟随
static func setDarkModeFollowSystem(isFollowSystem: Bool) {
if #available(iOS 13.0, *) {
// 1.1、设置是否跟随系统
UserDefaults.pt.userDefaultsSetValue(value: isFollowSystem, key: PTDarkToSystemKey)
let result = UITraitCollection.current.userInterfaceStyle == .light ? true : false
UserDefaults.pt.userDefaultsSetValue(value: result, key: PTLightDarkKey)
UserDefaults.pt.userDefaultsSetValue(value: false, key: PTSmartPeelingKey)
// 1.2、设置模式的保存
if isFollowSystem {
UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.overrideUserInterfaceStyle = .unspecified
} else {
UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.overrideUserInterfaceStyle = UITraitCollection.current.userInterfaceStyle
}
}
}
// MARK: 设置:浅色 / 深色
static func setDarkModeCustom(isLight: Bool) {
if #available(iOS 13.0, *) {
// 1.1、只要设置了模式:就是黑或者白
UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.overrideUserInterfaceStyle = isLight ? .light : .dark
// 1.2、设置跟随系统和智能换肤:否
UserDefaults.pt.userDefaultsSetValue(value: false, key: PTDarkToSystemKey)
UserDefaults.pt.userDefaultsSetValue(value: false, key: PTSmartPeelingKey)
// 1.3、黑白模式的设置
UserDefaults.pt.userDefaultsSetValue(value: isLight, key: PTLightDarkKey)
} else {
UserDefaults.pt.userDefaultsSetValue(value: false, key: PTSmartPeelingKey)
// 模式存储
UserDefaults.pt.userDefaultsSetValue(value: isLight, key: PTLightDarkKey)
// 通知模式更新
LegacyThemeProvider.shared.updateTheme()
}
}
// MARK: 设置:智能换肤
/// 智能换肤
/// - Parameter isSmartPeeling: 是否智能换肤
static func setSmartPeelingDarkMode(isSmartPeeling: Bool) {
if #available(iOS 13.0, *) {
// 1.1、设置智能换肤
UserDefaults.pt.userDefaultsSetValue(value: isSmartPeeling, key: PTSmartPeelingKey)
// 1.2、智能换肤根据时间段来设置:黑或者白
UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.overrideUserInterfaceStyle = isLight ? .light : .dark
// 1.3、设置跟随系统:否
UserDefaults.pt.userDefaultsSetValue(value: false, key: PTDarkToSystemKey)
UserDefaults.pt.userDefaultsSetValue(value: isLight, key: PTLightDarkKey)
} else {
// 模式存储
// 1.1、设置智能换肤
UserDefaults.pt.userDefaultsSetValue(value: isSmartPeeling, key: PTSmartPeelingKey)
// 1.2、设置跟随系统:否
UserDefaults.pt.userDefaultsSetValue(value: isLight, key: PTLightDarkKey)
// 1.3、通知模式更新
LegacyThemeProvider.shared.updateTheme()
}
}
// MARK: 智能换肤时间选择后
/// 智能换肤时间选择后
static func setSmartPeelingTimeChange(startTime: String, endTime: String) {
/// 是否是浅色
var light: Bool = false
if PTDrakModeOption.isSmartPeelingTime(startTime: startTime, endTime: endTime), PTDrakModeOption.isLight {
light = false
} else {
if !PTDrakModeOption.isLight {
light = true
} else {
PTDrakModeOption.smartPeelingTimeIntervalValue = startTime + "~" + endTime
return
}
}
PTDrakModeOption.smartPeelingTimeIntervalValue = startTime + "~" + endTime
if #available(iOS 13.0, *) {
// 1.1、只要设置了模式:就是黑或者白
UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.overrideUserInterfaceStyle = light ? .light : .dark
// 1.2、黑白模式的设置
UserDefaults.pt.userDefaultsSetValue(value: light, key: PTLightDarkKey)
} else {
// 模式存储
UserDefaults.pt.userDefaultsSetValue(value: light, key: PTLightDarkKey)
// 通知模式更新
LegacyThemeProvider.shared.updateTheme()
}
}
}
// MARK: - 动态颜色的使用
public extension PTDrakModeOption {
static func colorLightDark(lightColor: UIColor, darkColor: UIColor) -> UIColor {
if #available(iOS 13.0, *) {
return UIColor { (traitCollection) -> UIColor in
if PTDrakModeOption.isFollowSystem {
if traitCollection.userInterfaceStyle == .light {
return lightColor
} else {
return darkColor
}
} else if PTDrakModeOption.isSmartPeeling {
return isSmartPeelingTime() ? darkColor : lightColor
} else {
return PTDrakModeOption.isLight ? lightColor : darkColor
}
}
} else {
// iOS 13 以下主题色的使用
if PTDrakModeOption.isLight {
return lightColor
}
return darkColor
}
}
// MARK: 是否为智能换肤的时间:黑色
/// 是否为智能换肤的时间:黑色
/// - Returns: 结果
static func isSmartPeelingTime(startTime: String? = nil, endTime: String? = nil) -> Bool {
// 获取暗黑模式时间的区间,转为两个时间戳,取出当前的时间戳,看是否在区间内,在的话:黑色,否则白色
var timeIntervalValue: [String] = []
if startTime != nil && endTime != nil {
timeIntervalValue = [startTime!, endTime!]
} else {
timeIntervalValue = PTDrakModeOption.smartPeelingTimeIntervalValue.components(separatedBy: "~")
}
// 1、时间区间分隔为:开始时间 和 结束时间
// 2、当前的时间转时间戳
let currentDate = Date()
let currentTimeStamp = Int(currentDate.pt.dateToTimeStamp())!
let dateString = currentDate.pt.toformatterTimeString(formatter: "yyyy-MM-dd")
let startTimeStamp = Int(Date.pt.formatterTimeStringToTimestamp(timesString: dateString + " " + timeIntervalValue[0], formatter: "yyyy-MM-dd HH:mm", timestampType: .second))!
var endTimeStamp = Int(Date.pt.formatterTimeStringToTimestamp(timesString: dateString + " " + timeIntervalValue[1], formatter: "yyyy-MM-dd HH:mm", timestampType: .second))!
if startTimeStamp > endTimeStamp {
endTimeStamp = endTimeStamp + 884600
}
return currentTimeStamp >= startTimeStamp && currentTimeStamp <= endTimeStamp
}
}
// MARK: - 动态图片的使用
public extension PTDrakModeOption {
// MARK: 深色图片和浅色图片切换 (深色模式适配)
/// 深色图片和浅色图片切换 (深色模式适配)
/// - Parameters:
/// - light: 浅色图片
/// - dark: 深色图片
/// - Returns: 最终图片
static func image(light: UIImage?, dark: UIImage?) -> UIImage? {
if #available(iOS 13.0, *) {
guard let weakLight = light, let weakDark = dark, let config = weakLight.configuration else { return light }
let lightImage = weakLight.withConfiguration(config.withTraitCollection(UITraitCollection(userInterfaceStyle: UIUserInterfaceStyle.light)))
lightImage.imageAsset?.register(weakDark, with: config.withTraitCollection(UITraitCollection(userInterfaceStyle: UIUserInterfaceStyle.dark)))
return lightImage.imageAsset?.image(with: UITraitCollection.current) ?? light
} else {
// iOS 13 以下主题色的使用
if PTDrakModeOption.isLight {
return light
}
return dark
}
}
}
|
mit
|
8aa9a2781a8171344e79ddbd1d3ed67f
| 37.808 | 182 | 0.609153 | 4.057716 | false | false | false | false |
brentsimmons/Frontier
|
BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbTables/XMLVerbs.swift
|
1
|
3765
|
//
// XMLVerbs.swift
// FrontierVerbs
//
// Created by Brent Simmons on 4/15/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
// Notes:
// Original Frontier has its own XML parser.
// Instead we should build on the libxml2 SAX parser.
// RancheroXML.framework should be copied and renamed and added to this workspace.
struct XMLVerbs: VerbTable {
private enum Verb: String {
case addTable = "addtable"
case addValue = "addValue"
case compile = "compile"
case deCompile = "decompile"
case getAddress = "getaddress"
case getAddressList = "getaddresslist"
case getAttribute = "getattribute"
case getAttributeValue = "getattributevalue"
case getValue = "getvalue"
case valToString = "valtostring"
case frontierValueToTaggedText = "frontiervaluetotaggedtext"
case structToFrontierValue = "structtofrontiervalue"
case getPathAddress = "getpathaddress"
case convertToDisplayName = "converttodisplayname"
}
static func evaluate(_ lowerVerbName: String, _ params: VerbParams, _ verbAppDelegate: VerbAppDelegate) throws -> Value {
guard let verb = Verb(rawValue: lowerVerbName) else {
throw LangError(.verbNotFound)
}
do {
switch verb {
case .addTable:
return try addTable(params)
case .addValue:
return try addValue(params)
case .compile:
return try compile(params)
case .deCompile:
return try deCompile(params)
case .getAddress:
return try getAddress(params)
case .getAddressList:
return try getAddressList(params)
case .getAttribute:
return try getAttribute(params)
case .getAttributeValue:
return try getAttributeValue(params)
case .getValue:
return try getValue(params)
case .valToString:
return try valToString(params)
case .frontierValueToTaggedText:
return try frontierValueToTaggedText(params)
case .structToFrontierValue:
return try structToFrontierValue(params)
case .getPathAddress:
return try getPathAddress(params)
case .convertToDisplayName:
return try convertToDisplayName(params)
}
}
catch { throw error }
}
}
private extension XMLVerbs {
static func addTable(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func addValue(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func compile(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func deCompile(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getAddress(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getAddressList(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getAttribute(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getAttributeValue(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getValue(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func valToString(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func frontierValueToTaggedText(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func structToFrontierValue(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func getPathAddress(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
static func convertToDisplayName(_ params: VerbParams) throws -> Value {
throw LangError(.unimplementedVerb)
}
}
|
gpl-2.0
|
3f88a37459c42f2aec8bbd588d100e69
| 23.763158 | 122 | 0.725558 | 3.945493 | false | false | false | false |
rae/YelpRBC
|
YelpRBC/AppDelegate.swift
|
1
|
3180
|
//
// AppDelegate.swift
// YelpRBC
//
// Created by Reid Ellis on 2016-10-08.
// Copyright © 2016 Tnir Technologies. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
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:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.details == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
|
gpl-3.0
|
fefd0560ee50f42ee314bdae20f337ce
| 51.114754 | 279 | 0.796791 | 5.606702 | false | false | false | false |
DeepestDesire/GC
|
ProductArchitecture/Modules/Main/AppDelegate.swift
|
1
|
4610
|
//
// AppDelegate.swift
// ProductArchitecture
//
// Created by GeorgeCharles on 11/18/16.
// Copyright © 2016 GeorgeCharles. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let manager = NoticationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
manager.createLocalNotification()
UINavigationBar.initialBarStyle()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
// MARK: - Core Data stack
/*
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ProductArchitecture")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
if #available(iOS 10.0, *) {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
} else {
// Fallback on earlier versions
}
}
*/
}
|
apache-2.0
|
c47a86af3b6ee75c6f453d1c257e60c1
| 43.747573 | 285 | 0.717943 | 5.506571 | false | false | false | false |
richy486/printer-server-io
|
Sources/App/Controllers/DailyReportController.swift
|
1
|
1354
|
//
// DailyReportController.swift
// printer-server-io
//
// Created by Richard Adem on 1/12/17.
//
//
import HTTP
import Vapor
import Turnstile
// drop.config["weather","key"]
final class DailyReportController {
func addRoutes(to drop: Droplet) {
drop.get("dailyReport", handler: dailyReport)
}
func dailyReport(_ request: Request) throws -> ResponseRepresentable {
guard let accessTokenString = request.data["token"]?.string else {
throw Abort.badRequest
}
let accessToken = AccessToken(string: accessTokenString)
guard let user = try User.authenticate(accessToken: accessToken) as? User else {
throw Abort.badRequest
}
var report: [String: Node] = [:]
report["username"] = Node.string(user.username)
// Get Weather
// let date = NSDate(timeIntervalSince1970: 1415637900)
let weather = try Weather.query().filter("id", .greaterThanOrEquals, Weather.query().count() ).first()?.makeNode()
report["weather"] = weather
// Get Todo list
report["todo"] = [:]
// Get News
// Get Top tweets
// Get kitten
return try JSON(node: report)
}
}
|
mit
|
d6d45ad5d3eb8c76026c3b9d31e14d26
| 23.618182 | 122 | 0.559823 | 4.767606 | false | false | false | false |
walmartlabs/RxSwift
|
RxTests/RxSwiftTests/Tests/Observable+StandardSequenceOperatorsTest.swift
|
11
|
86573
|
//
// Observable+StandardSequenceOperatorsTest.swift
// Rx
//
// Created by Krunoslav Zaher on 2/17/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import XCTest
import RxSwift
class ObservableStandardSequenceOperators : RxTest {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
}
func isPrime(i: Int) -> Bool {
if i <= 1 {
return false
}
let max = Int(sqrt(Float(i)))
for (var j = 2; j <= max; ++j) {
if i % j == 0 {
return false
}
}
return true
}
// where
extension ObservableStandardSequenceOperators {
func test_filterComplete() {
let scheduler = TestScheduler(initialClock: 0)
var invoked = 0
let xs = scheduler.createHotObservable([
next(110, 1),
next(180, 2),
next(230, 3),
next(270, 4),
next(340, 5),
next(380, 6),
next(390, 7),
next(450, 8),
next(470, 9),
next(560, 10),
next(580, 11),
completed(600),
next(610, 12),
error(620, testError),
completed(630)
])
let res = scheduler.start { () -> Observable<Int> in
return xs.filter { (num: Int) -> Bool in
invoked++;
return isPrime(num);
}
}
XCTAssertEqual(res.messages, [
next(230, 3),
next(340, 5),
next(390, 7),
next(580, 11),
completed(600)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 600)
])
XCTAssertEqual(9, invoked)
}
func test_filterTrue() {
let scheduler = TestScheduler(initialClock: 0)
var invoked = 0
let xs = scheduler.createHotObservable([
next(110, 1),
next(180, 2),
next(230, 3),
next(270, 4),
next(340, 5),
next(380, 6),
next(390, 7),
next(450, 8),
next(470, 9),
next(560, 10),
next(580, 11),
completed(600)
])
let res = scheduler.start { () -> Observable<Int> in
return xs.filter { (num: Int) -> Bool in
invoked++
return true
}
}
XCTAssertEqual(res.messages, [
next(230, 3),
next(270, 4),
next(340, 5),
next(380, 6),
next(390, 7),
next(450, 8),
next(470, 9),
next(560, 10),
next(580, 11),
completed(600)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 600)
])
XCTAssertEqual(9, invoked)
}
func test_filterFalse() {
let scheduler = TestScheduler(initialClock: 0)
var invoked = 0
let xs = scheduler.createHotObservable([
next(110, 1),
next(180, 2),
next(230, 3),
next(270, 4),
next(340, 5),
next(380, 6),
next(390, 7),
next(450, 8),
next(470, 9),
next(560, 10),
next(580, 11),
completed(600)
])
let res = scheduler.start { () -> Observable<Int> in
return xs.filter { (num: Int) -> Bool in
invoked++
return false
}
}
XCTAssertEqual(res.messages, [
completed(600)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 600)
])
XCTAssertEqual(9, invoked)
}
func test_filterDisposed() {
let scheduler = TestScheduler(initialClock: 0)
var invoked = 0
let xs = scheduler.createHotObservable([
next(110, 1),
next(180, 2),
next(230, 3),
next(270, 4),
next(340, 5),
next(380, 6),
next(390, 7),
next(450, 8),
next(470, 9),
next(560, 10),
next(580, 11),
completed(600)
])
let res = scheduler.start(400) { () -> Observable<Int> in
return xs.filter { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
next(230, 3),
next(340, 5),
next(390, 7)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400)
])
XCTAssertEqual(5, invoked)
}
}
// takeWhile
extension ObservableStandardSequenceOperators {
func testTakeWhile_Complete_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
completed(330),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
completed(600)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
completed(330)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 330)
])
XCTAssertEqual(4, invoked)
}
func testTakeWhile_Complete_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
completed(600)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
XCTAssertEqual(6, invoked)
}
func testTakeWhile_Error_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
error(270, testError),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
completed(600)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
next(210, 2),
next(260, 5),
error(270, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
XCTAssertEqual(2, invoked)
}
func testTakeWhile_Error_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
XCTAssertEqual(6, invoked)
}
func testTakeWhile_Dispose_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start(300) { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
next(210, 2),
next(260, 5),
next(290, 13)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 300)
])
XCTAssertEqual(3, invoked)
}
func testTakeWhile_Dispose_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start(400) { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
XCTAssertEqual(6, invoked)
}
func testTakeWhile_Zero() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start(300) { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked++;
return isPrime(num)
}
}
XCTAssertEqual(res.messages, [
completed(205)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 205)
])
XCTAssertEqual(1, invoked)
}
func testTakeWhile_Index1() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
_ = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int, index) -> Bool in
return index < 5
}
}
XCTAssertEqual(res.messages, [
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
completed(350)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 350)
])
}
func testTakeWhile_Index2() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
completed(400)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int, index) -> Bool in
return index >= 0
}
}
XCTAssertEqual(res.messages, [
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
completed(400)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400)
])
}
func testTakeWhile_Index_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
error(400, testError)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int, index) -> Bool in
return index >= 0
}
}
XCTAssertEqual(res.messages, [
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
error(400, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400)
])
}
}
// map
// these test are not port from Rx
extension ObservableStandardSequenceOperators {
func testMap_Never() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages: [Recorded<Int>] = [
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Empty() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
completed(300)
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages: [Recorded<Int>] = [
completed(300)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Range() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
completed(300)
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages: [Recorded<Int>] = [
next(210, 0 * 2),
next(220, 1 * 2),
next(230, 2 * 2),
next(240, 4 * 2),
completed(300)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start { xs.map { $0 * 2 } }
let correctMessages: [Recorded<Int>] = [
next(210, 0 * 2),
next(220, 1 * 2),
next(230, 2 * 2),
next(240, 4 * 2),
error(300, testError)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start(290) { xs.map { $0 * 2 } }
let correctMessages: [Recorded<Int>] = [
next(210, 0 * 2),
next(220, 1 * 2),
next(230, 2 * 2),
next(240, 4 * 2),
]
let correctSubscriptions = [
Subscription(200, 290)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 4),
error(300, testError)
])
let res = scheduler.start { xs.map { x throws -> Int in if x < 2 { return x * 2 } else { throw testError } } }
let correctMessages: [Recorded<Int>] = [
next(210, 0 * 2),
next(220, 1 * 2),
error(230, testError)
]
let correctSubscriptions = [
Subscription(200, 230)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Never() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages: [Recorded<Int>] = [
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Empty() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
completed(300)
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages: [Recorded<Int>] = [
completed(300)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Range() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
completed(300)
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages: [Recorded<Int>] = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
next(230, (7 + 2) * 2),
next(240, (8 + 3) * 2),
completed(300)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
error(300, testError)
])
let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages: [Recorded<Int>] = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
next(230, (7 + 2) * 2),
next(240, (8 + 3) * 2),
error(300, testError)
]
let correctSubscriptions = [
Subscription(200, 300)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
error(300, testError)
])
let res = scheduler.start(290) { xs.mapWithIndex { ($0 + $1) * 2 } }
let correctMessages: [Recorded<Int>] = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
next(230, (7 + 2) * 2),
next(240, (8 + 3) * 2),
]
let correctSubscriptions = [
Subscription(200, 290)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap1_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 5),
next(220, 6),
next(230, 7),
next(240, 8),
error(300, testError)
])
let res = scheduler.start { xs.mapWithIndex { x, i throws -> Int in if x < 7 { return ((x + i) * 2) } else { throw testError } } }
let correctMessages: [Recorded<Int>] = [
next(210, (5 + 0) * 2),
next(220, (6 + 1) * 2),
error(230, testError)
]
let correctSubscriptions = [
Subscription(200, 230)
]
XCTAssertEqual(res.messages, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func testMap_DisposeOnCompleted() {
just("A")
.map { a in
return a
}
.subscribeNext { _ in
}
}
func testMap1_DisposeOnCompleted() {
just("A")
.mapWithIndex { (a, i) in
return a
}
.subscribeNext { _ in
}
}
}
// flatMap
extension ObservableStandardSequenceOperators {
func testFlatMap_Complete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start {
xs.flatMap { $0 }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
next(930, 401),
next(940, 402),
completed(960)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 900)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 960)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 950)
])
}
func testFlatMap_Complete_InnerNotComplete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
])
let res = scheduler.start {
xs.flatMap { $0 }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
next(930, 401),
next(940, 402),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 1000)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 960)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 950)
])
}
func testFlatMap_Complete_OuterNotComplete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start {
xs.flatMap { $0 }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
next(930, 401),
next(940, 402),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 900)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 1000)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 960)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 950)
])
}
func testFlatMap_Complete_ErrorOuter() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
error(900, testError)
])
let res = scheduler.start {
xs.flatMap { $0 }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
error(900, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 900)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 900)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 900)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 900)
])
}
func testFlatMap_Error_Inner() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
error(460, testError)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start {
xs.flatMap { $0 }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
error(760, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 760)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 760)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 760)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
])
}
func testFlatMap_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start(700) {
xs.flatMap { $0 }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 700)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 700)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 700)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
])
}
func testFlatMap_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
var invoked = 0
let res = scheduler.start {
return xs.flatMap { (x: ColdObservable<Int>) -> Observable<Int> in
invoked++
if invoked == 3 {
throw testError
}
return x
}
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
error(550, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 550)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 550)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 550)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
])
}
func testFlatMap_UseFunction() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(210, 4),
next(220, 3),
next(250, 5),
next(270, 1),
completed(290)
])
var invoked = 0
let res = scheduler.start {
xs.flatMap { (x) in
return interval(10, scheduler).map { _ in x } .take(x)
}
}
XCTAssertEqual(res.messages, [
next(220, 4),
next(230, 3),
next(230, 4),
next(240, 3),
next(240, 4),
next(250, 3),
next(250, 4),
next(260, 5),
next(270, 5),
next(280, 1),
next(280, 5),
next(290, 5),
next(300, 5),
completed(300)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 290)
])
}
func testFlatMapIndex_Index() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(210, 4),
next(220, 3),
next(250, 5),
next(270, 1),
completed(290)
])
let res = scheduler.start {
xs.flatMapWithIndex { (x, i) in
return just(ElementIndexPair(x, i))
}
}
XCTAssertEqual(res.messages, [
next(210, ElementIndexPair(4, 0)),
next(220, ElementIndexPair(3, 1)),
next(250, ElementIndexPair(5, 2)),
next(270, ElementIndexPair(1, 3)),
completed(290)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 290)
])
}
func testFlatMapWithIndex_Complete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start {
xs.flatMapWithIndex { x, _ in x }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
next(930, 401),
next(940, 402),
completed(960)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 900)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 960)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 950)
])
}
func testFlatMapWithIndex_Complete_InnerNotComplete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
])
let res = scheduler.start {
xs.flatMapWithIndex { x, _ in x }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
next(930, 401),
next(940, 402),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 1000)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 960)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 950)
])
}
func testFlatMapWithIndex_Complete_OuterNotComplete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start {
xs.flatMapWithIndex { x, _ in x }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
next(930, 401),
next(940, 402),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 900)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 1000)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 960)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 950)
])
}
func testFlatMapWithIndex_Complete_ErrorOuter() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
error(900, testError)
])
let res = scheduler.start {
xs.flatMapWithIndex { x, _ in x }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
next(810, 304),
next(860, 305),
error(900, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 900)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 900)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 900)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 790)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
Subscription(850, 900)
])
}
func testFlatMapWithIndex_Error_Inner() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
error(460, testError)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start {
xs.flatMapWithIndex { x, _ in x }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
next(740, 106),
error(760, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 760)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 760)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 760)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
Subscription(750, 760)
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
])
}
func testFlatMapWithIndex_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
let res = scheduler.start(700) {
xs.flatMapWithIndex { x, _ in x }
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
next(560, 301),
next(580, 202),
next(590, 203),
next(600, 302),
next(620, 303),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 700)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 700)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 605)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
Subscription(550, 700)
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
])
}
func testFlatMapWithIndex_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(5, scheduler.createColdObservable([
error(1, testError)
])),
next(105, scheduler.createColdObservable([
error(1, testError)
])),
next(300, scheduler.createColdObservable([
next(10, 102),
next(90, 103),
next(110, 104),
next(190, 105),
next(440, 106),
completed(460)
])),
next(400, scheduler.createColdObservable([
next(180, 202),
next(190, 203),
completed(205)
])),
next(550, scheduler.createColdObservable([
next(10, 301),
next(50, 302),
next(70, 303),
next(260, 304),
next(310, 305),
completed(410)
])),
next(750, scheduler.createColdObservable([
completed(40)
])),
next(850, scheduler.createColdObservable([
next(80, 401),
next(90, 402),
completed(100)
])),
completed(900)
])
var invoked = 0
let res = scheduler.start {
return xs.flatMapWithIndex { (x: ColdObservable<Int>, _: Int) -> Observable<Int> in
invoked++
if invoked == 3 {
throw testError
}
return x
}
}
XCTAssertEqual(res.messages, [
next(310, 102),
next(390, 103),
next(410, 104),
next(490, 105),
error(550, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 550)
])
XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [
Subscription(300, 550)
])
XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [
Subscription(400, 550)
])
XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [
])
XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [
])
XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [
])
}
func testFlatMapWithIndex_UseFunction() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(210, 4),
next(220, 3),
next(250, 5),
next(270, 1),
completed(290)
])
var invoked = 0
let res = scheduler.start {
xs.flatMapWithIndex { (x, _) in
return interval(10, scheduler).map { _ in x } .take(x)
}
}
XCTAssertEqual(res.messages, [
next(220, 4),
next(230, 3),
next(230, 4),
next(240, 3),
next(240, 4),
next(250, 3),
next(250, 4),
next(260, 5),
next(270, 5),
next(280, 1),
next(280, 5),
next(290, 5),
next(300, 5),
completed(300)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 290)
])
}
}
// take
extension ObservableStandardSequenceOperators {
func testTake_Complete_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
let res = scheduler.start {
xs.take(20)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testTake_Complete_Same() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
let res = scheduler.start {
xs.take(17)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(630)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 630)
])
}
func testTake_Complete_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
let res = scheduler.start {
xs.take(10)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
completed(415)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 415)
])
}
func testTake_Error_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start {
xs.take(20)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testTake_Error_Same() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start {
xs.take(17)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(630)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 630)
])
}
func testTake_Error_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start {
xs.take(3)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
completed(270)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
}
func testTake_Dispose_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start(250) {
xs.take(3)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 250)
])
}
func testTake_Dispose_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start(400) {
xs.take(3)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
completed(270)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
}
func testTake_0_DefaultScheduler() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13)
])
let res = scheduler.start {
xs.take(0)
}
XCTAssertEqual(res.messages, [
completed(200)
])
XCTAssertEqual(xs.subscriptions, [
])
}
func testTake_Take1() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
completed(400)
])
let res = scheduler.start {
xs.take(3)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
completed(270)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
}
func testTake_DecrementCountsFirst() {
let k = BehaviorSubject(value: false)
k.take(1).subscribeNext { n in
k.on(.Next(!n))
}
}
}
// skip
extension ObservableStandardSequenceOperators {
func testSkip_Complete_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
let res = scheduler.start {
xs.skip(20)
}
XCTAssertEqual(res.messages, [
completed(690)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testSkip_Complete_Some() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
let res = scheduler.start {
xs.skip(17)
}
XCTAssertEqual(res.messages, [
completed(690)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testSkip_Complete_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
let res = scheduler.start {
xs.skip(10)
}
XCTAssertEqual(res.messages, [
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testSkip_Complete_Zero() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
let res = scheduler.start {
xs.skip(0)
}
XCTAssertEqual(res.messages, [
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
completed(690)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testSkip_Error_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start {
xs.skip(20)
}
XCTAssertEqual(res.messages, [
error(690, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testSkip_Error_Same() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start {
xs.skip(17)
}
XCTAssertEqual(res.messages, [
error(690, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testSkip_Error_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
let res = scheduler.start {
xs.skip(3)
}
XCTAssertEqual(res.messages, [
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
error(690, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testSkip_Dispose_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
])
let res = scheduler.start(250) {
xs.skip(3)
}
XCTAssertEqual(res.messages, [
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 250)
])
}
func testSkip_Dispose_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(70, 6),
next(150, 4),
next(210, 9),
next(230, 13),
next(270, 7),
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
next(410, 15),
next(415, 16),
next(460, 72),
next(510, 76),
next(560, 32),
next(570, -100),
next(580, -3),
next(590, 5),
next(630, 10),
])
let res = scheduler.start(400) {
xs.skip(3)
}
XCTAssertEqual(res.messages, [
next(280, 1),
next(300, -1),
next(310, 3),
next(340, 8),
next(370, 11),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400)
])
}
}
|
mit
|
efd781a5d5d15ae52b3baf09c3d79ae9
| 26.580121 | 138 | 0.42392 | 4.780134 | false | true | false | false |
rolson/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Maps/Manage operational layers/ManageMapLayersViewController.swift
|
1
|
2957
|
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class ManageMapLayersViewController: UIViewController, MMLLayersViewControllerDelegate {
@IBOutlet weak var mapView:AGSMapView!
var map:AGSMap!
private var deletedLayers:[AGSLayer]!
override func viewDidLoad() {
super.viewDidLoad()
self.map = AGSMap(basemap: AGSBasemap.topographicBasemap())
let imageLayer = AGSArcGISMapImageLayer(URL: NSURL(string: "https://sampleserver5.arcgisonline.com/arcgis/rest/services/Elevation/WorldElevations/MapServer")!)
self.map.operationalLayers.addObject(imageLayer)
let tiledLayer = AGSArcGISMapImageLayer(URL: NSURL(string: "https://sampleserver5.arcgisonline.com/arcgis/rest/services/Census/MapServer")!)
self.map.operationalLayers.addObject(tiledLayer)
self.deletedLayers = [AGSLayer]()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ManageMapLayersViewController", "MMLLayersViewController"]
self.mapView.map = map
self.mapView.setViewpoint(AGSViewpoint(center: AGSPoint(x: -133e5, y: 45e5, spatialReference: AGSSpatialReference(WKID: 3857)), scale: 2e7))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "LayersSegue" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.viewControllers[0] as! MMLLayersViewController
controller.layers = self.map.operationalLayers
controller.deletedLayers = self.deletedLayers
controller.preferredContentSize = CGSize(width: 300, height: 300)
controller.delegate = self
}
}
//MARK: - MMLLayersViewControllerDelegate
func layersViewControllerWantsToClose(layersViewController: MMLLayersViewController, withDeletedLayers layers: [AGSLayer]) {
self.deletedLayers = layers
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
apache-2.0
|
d50023a0658776971621d36d49d8954a
| 41.242857 | 167 | 0.707136 | 4.879538 | false | false | false | false |
openbuild-sheffield/jolt
|
Sources/OpenbuildExtensionPerfect/model.ResponseModel500Messages.swift
|
1
|
3394
|
import PerfectLib
public class ResponseModel500Messages: JSONConvertibleObject, DocumentationProtocol {
static let registerName = "responseModel500Messages"
public var error: Bool = true
public var message: String = "Internal server error. This has been logged."
public var messages: [String: Any] = [:]
public var descriptions = [
"error": "An error has occurred, will always be true",
"message": "Will always be 'Internal server error. This has been logged.'",
"messages": "Key pair of error messages."
]
public init(messages: [String : Any]) {
self.messages = messages
}
public override func setJSONValues(_ values: [String : Any]) {
self.error = getJSONValue(named: "error", from: values, defaultValue: true)
self.message = getJSONValue(named: "message", from: values, defaultValue: "Internal server error. This has been logged.")
self.messages = getJSONValue(named: "messages", from: values, defaultValue: [:])
}
public override func getJSONValues() -> [String : Any] {
return [
JSONDecoding.objectIdentifierKey:ResponseModel500Messages.registerName,
"error": error,
"message": message,
"messages":messages
]
}
public static func describeRAML() -> [String] {
if let docs = ResponseDocumentation.getRAML(key: "ResponseModel500Messages") {
return docs
} else {
let model = ResponseModel500Messages(messages: [
"message": "Failed to generate a successful response."
])
let aMirror = Mirror(reflecting: model)
let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions)
ResponseDocumentation.setRAML(key: "ResponseModel500Messages", lines: docs)
return docs
}
/*
var raml:[String] = ["error: boolean"]
raml.append("errors?:")
raml.append(" description: key/value pair describing the errors")
raml.append(" type: object")
raml.append("validated?:")
raml.append(" description: validated data with possible errors")
raml.append(" type: object")
raml.append(" properties:")
raml.append(" valid: boolean")
raml.append(" validated?: object")
raml.append(" description: key/pair of validated data")
raml.append(" errors?: object")
raml.append(" description: key/pair describing the errors")
raml.append(" raw: object")
raml.append(" description: the data sent to the server")
raml.append(" properties:")
raml.append(" uri?: object")
raml.append(" description: key/value pair data sent to the server in the uri")
raml.append(" body?: object")
raml.append(" description: key/value pair data sent to the server in the body")
return raml
*/
}
}
extension ResponseModel500Messages: CustomReflectable {
open var customMirror: Mirror {
return Mirror(
self,
children: [
"error": self.error,
"message": self.message,
"messages": self.messages
],
displayStyle: Mirror.DisplayStyle.class
)
}
}
|
gpl-2.0
|
4cfef2569a416e94730812ca8f9b21cf
| 31.961165 | 130 | 0.601355 | 4.561828 | false | false | false | false |
neoneye/SwiftyFORM
|
Example/Other/StaticTextAndAttributedTextViewController.swift
|
1
|
1469
|
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
import SwiftyFORM
class StaticTextAndAttributedTextViewController: FormViewController {
override func populate(_ builder: FormBuilder) {
builder.navigationTitle = "Text"
builder.toolbarMode = .none
builder += SectionHeaderTitleFormItem(title: "Static Text")
builder += StaticTextFormItem().title("Title 0").value("Value 0")
builder += StaticTextFormItem().title("Title 1").value("Value 1")
builder += StaticTextFormItem().title("Title 2").value("Value 2")
builder += SectionHeaderTitleFormItem(title: "Attributed Text")
builder += AttributedTextFormItem().title("Title 0").value("Value 0")
builder += AttributedTextFormItem()
.title("Title 1", [NSAttributedString.Key.foregroundColor.rawValue: UIColor.gray as AnyObject])
.value("Value 1", [
NSAttributedString.Key.backgroundColor.rawValue: UIColor.black as AnyObject,
NSAttributedString.Key.foregroundColor.rawValue: UIColor.white as AnyObject
])
builder += AttributedTextFormItem()
.title("Orange 🍊", [
NSAttributedString.Key.foregroundColor.rawValue: UIColor.orange as AnyObject,
NSAttributedString.Key.font.rawValue: UIFont.boldSystemFont(ofSize: 24) as AnyObject,
NSAttributedString.Key.underlineStyle.rawValue: NSUnderlineStyle.single.rawValue as AnyObject
])
.value("Heart ❤️", [NSAttributedString.Key.foregroundColor.rawValue: UIColor.red as AnyObject])
}
}
|
mit
|
8e84203802c5a5bce4c2e81c48213d36
| 46.16129 | 98 | 0.759234 | 4.39039 | false | false | false | false |
rolson/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Maps/Manage bookmarks/BookmarksListViewController.swift
|
1
|
2435
|
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class BookmarksListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView:UITableView!
//list of bookmarks
var bookmarks:[AGSBookmark]!
//private property to store selection action for table cell
private var selectAction:((AGSViewpoint) -> Void)!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//executed for tableview row selection
func setSelectAction(action : ((AGSViewpoint) -> Void)) {
self.selectAction = action
}
//MARK: - TableView data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.bookmarks?.count ?? 0
}
//MARK: - TableView delegates
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("BookmarkCell")!
cell.backgroundColor = UIColor.clearColor()
//get the respective bookmark
let bookmark = self.bookmarks[indexPath.row]
//assign the bookmark's name as the title for the cell
cell.textLabel?.text = bookmark.name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let bookmark = self.bookmarks[indexPath.row]
//execute the closure if it exists
if self.selectAction != nil {
self.selectAction(bookmark.viewpoint!)
}
}
}
|
apache-2.0
|
642881cb1139dd152f5f058a6e92ee2f
| 31.905405 | 109 | 0.680903 | 5.202991 | false | false | false | false |
qoncept/TensorSwift
|
Sources/MNIST/CanvasView.swift
|
1
|
1617
|
import UIKit
class CanvasView: UIView {
private(set) var canvas: Canvas
required init?(coder: NSCoder) {
canvas = Canvas()
super.init(coder: coder)
self.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(CanvasView.onPanGesture(_:))))
}
var image: UIImage {
UIGraphicsBeginImageContext(bounds.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
for line in canvas.lines {
context?.setLineWidth(20.0)
context?.setStrokeColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).cgColor)
context?.setLineCap(.round)
context?.setLineJoin(.round)
for (index, point) in line.points.enumerated() {
if index == 0 {
context?.move(to: CGPoint(x: point.x, y: point.y))
} else {
context?.addLine(to: CGPoint(x: point.x, y: point.y))
}
}
}
context?.strokePath()
}
@objc func onPanGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
canvas.draw(gestureRecognizer.location(in: self))
if gestureRecognizer.state == .ended {
canvas.newLine()
}
setNeedsDisplay()
}
func clear() {
canvas = Canvas()
setNeedsDisplay()
}
}
|
mit
|
1d7d46c8bfe33acb6d803e49d307ca07
| 30.096154 | 119 | 0.569573 | 4.975385 | false | false | false | false |
cubixlabs/SocialGIST
|
Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUITableViewHeaderFooterView.swift
|
1
|
5773
|
//
// BaseUITableViewHeaderFooterView.swift
// GISTFramework
//
// Created by Shoaib Abdul on 17/08/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUITableViewHeaderFooterView is a subclass of UITableViewHeaderFooterView and implements BaseView. It has some extra proporties and support for SyncEngine.
open class BaseUITableViewHeaderFooterView: UITableViewHeaderFooterView, BaseView {
//MARK: - Properties
/// Flag for whether to resize the values for iPad.
@IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad;
/// Background color key from Sync Engine.
@IBInspectable open var bgColorStyle:String? = nil {
didSet {
guard (self.bgColorStyle != oldValue) else {
return;
}
if (self.backgroundView == nil) {
self.backgroundView = UIView();
}
self.backgroundView!.backgroundColor = SyncedColors.color(forKey: bgColorStyle);
}
}
/// Tint color key from SyncEngine.
@IBInspectable open var tintColorStyle:String? = nil {
didSet {
guard (self.tintColorStyle != oldValue) else {
return;
}
self.tintColor = SyncedColors.color(forKey: tintColorStyle);
}
}
/// Font name key from Sync Engine.
@IBInspectable open var fontName:String? = GIST_CONFIG.fontName {
didSet {
guard (self.fontName != oldValue) else {
return;
}
self.textLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontStyle, sizedForIPad: sizeForIPad);
self.detailTextLabel?.font = UIFont.font(self.fontName, fontStyle: self.detailFontStyle, sizedForIPad: sizeForIPad);
}
}
/// Font size/ style key from Sync Engine.
@IBInspectable open var fontStyle:String? = GIST_CONFIG.fontStyle {
didSet {
guard (self.fontStyle != oldValue) else {
return;
}
self.textLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontStyle, sizedForIPad: sizeForIPad);
}
}
/// Font Color key from SyncEngine.
@IBInspectable open var fontColor:String? = nil {
didSet {
guard (self.fontColor != oldValue) else {
return;
}
self.textLabel?.textColor = UIColor.color(forKey: fontColor);
}
}
/// Detail Text Font size/ style key from Sync Engine.
@IBInspectable open var detailFontStyle:String? = GIST_CONFIG.fontStyle {
didSet {
guard (self.detailFontStyle != oldValue) else {
return;
}
self.detailTextLabel?.font = UIFont.font(self.fontName, fontStyle: self.detailFontStyle, sizedForIPad: sizeForIPad);
}
}
/// Detail Text Font Color key from SyncEngine.
@IBInspectable open var detailFontColor:String? = nil {
didSet {
guard (self.detailFontColor != oldValue) else {
return;
}
self.detailTextLabel?.textColor = UIColor.color(forKey: detailFontColor);
}
}
private var _data:Any?
/// Holds Table View Header/Footer View Data.
open var data:Any? {
get {
return _data;
}
} //P.E.
//MARK: - Constructors
/// Overridden constructor to setup/ initialize components.
///
/// - Parameter reuseIdentifier: Reuse identifier
public override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier);
self.commonInit();
} //F.E.
/// Required constructor implemented.
required public init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder);
} //F.E.
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
override open func awakeFromNib() {
super.awakeFromNib();
self.commonInit();
} //F.E.
/// Recursive update of layout and content from Sync Engine.
override func updateSyncedData() {
super.updateSyncedData();
self.contentView.updateSyncedData();
} //F.E.
//MARK: - Methods
/// A common initializer to setup/initialize sub components.
private func commonInit() {
self.textLabel?.font = UIFont.font(self.fontName, fontStyle: self.fontStyle, sizedForIPad: sizeForIPad);
self.detailTextLabel?.font = UIFont.font(self.fontName, fontStyle: self.detailFontStyle, sizedForIPad: sizeForIPad);
} //F.E.
/// Updates layout and contents from SyncEngine. this is a protocol method BaseView that is called when the view is refreshed.
func updateView() {
if let bgCStyle = self.bgColorStyle {
self.bgColorStyle = bgCStyle;
}
if let fName = self.fontName {
self.fontName = fName;
}
if let fColor = self.fontColor {
self.fontColor = fColor;
}
if let dColor = self.detailFontColor {
self.detailFontColor = dColor;
}
} //F.E.
/// This method should be called in cellForRowAt:indexPath. it also must be overriden in all sub classes of BaseUITableViewHeaderFooterView to update the table view header/Footer view content.
///
/// - Parameter data: Header View Data
open func updateData(_ data:Any?) {
_data = data;
self.updateSyncedData();
} //F.E.
} //CLS END
|
gpl-3.0
|
7489e057de1a9ff280b6291d61159ead
| 31.066667 | 196 | 0.586798 | 5.01913 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/Challenge/CreateTeam.swift
|
1
|
12248
|
/**
* Copyright © 2019 Aga Khan Foundation
* 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. The name of the author may not 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.
**/
import UIKit
import NotificationCenter
class CreateTeamViewController: ViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate { // swiftlint:disable:this line_length
private let teamNameLabel = UILabel(typography: .title)
private let teamNameTextField = UITextField(.bodyRegular)
private let seperatorView = UIView()
private let uploadTeamPhotoLabel = UILabel(typography: .rowTitleRegular)
private let teamPhotoImageView: UIImageView = {
let imageview = UIImageView()
imageview.layer.cornerRadius = 64
imageview.layer.borderWidth = 1
imageview.layer.borderColor = UIColor.lightGray.cgColor
imageview.clipsToBounds = true
imageview.contentMode = .center
imageview.image = Assets.uploadImageIcon.image
return imageview
}()
private var imagePicker = UIImagePickerController()
private let uploadImageButton: UIButton = {
let button = UIButton(type: .custom)
button.addTarget(CreateTeamViewController.self, action: #selector(uploadImageButtonTapped), for: .touchUpInside)
button.setTitle(Strings.Challenge.CreateTeam.uploadImageButtonText, for: .normal)
button.setTitleColor(.blue, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
button.layer.backgroundColor = .none
return button
}()
private let teamVisibilityTitleLabel = UILabel(typography: .bodyRegular)
private var teamVisibilitySwitch = UISwitch()
private var teamVisibilitySwitchStatusLabel = UILabel(typography: .bodyRegular)
private let visibilityBodyLabel = UILabel(typography: .smallRegular, color: .gray)
private let activityView = UIActivityIndicatorView(style: .gray)
private var teamName: String = ""
private let stackView = UIStackView()
private var event: Event?
override func configureView() { // swiftlint:disable:this function_body_length
super.configureView()
title = Strings.Challenge.CreateTeam.title
navigationItem.leftBarButtonItem = UIBarButtonItem(
image: Assets.close.image,
style: .plain,
target: self,
action: #selector(closeButtonTapped))
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: Strings.Challenge.CreateTeam.create,
style: .plain,
target: self,
action: #selector(createTapped))
navigationItem.rightBarButtonItem?.isEnabled = false
teamNameLabel.text = Strings.Challenge.CreateTeam.formTitle
view.addSubview(teamNameLabel) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.top.equalTo(view.safeAreaLayoutGuide).inset(Style.Padding.p32)
}
teamNameTextField.delegate = self
teamNameTextField.placeholder = Strings.Challenge.CreateTeam.formPlaceholder
teamNameTextField.addTarget(self, action: #selector(teamNameChanged(_:)), for: .editingChanged)
view.addSubview(teamNameTextField) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.top.equalTo(teamNameLabel.snp.bottom).offset(Style.Padding.p16)
}
seperatorView.backgroundColor = Style.Colors.FoundationGreen
view.addSubview(seperatorView) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.top.equalTo(teamNameTextField.snp.bottom)
$0.height.equalTo(1)
}
uploadTeamPhotoLabel.text = Strings.Challenge.CreateTeam.uploadTeamPhotoLabelText
view.addSubview(uploadTeamPhotoLabel) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.top.equalTo(seperatorView.snp.bottom).offset(Style.Padding.p32)
}
view.addSubview(teamPhotoImageView) {
$0.top.equalTo(uploadTeamPhotoLabel.snp.bottom).offset(Style.Padding.p16)
$0.height.width.equalTo(Style.Size.s128)
$0.centerX.equalToSuperview()
}
view.addSubview(uploadImageButton) {
$0.top.equalTo(teamPhotoImageView.snp.bottom).offset(Style.Padding.p12)
$0.width.equalTo(Style.Size.s128)
$0.height.equalTo(Style.Size.s40)
$0.centerX.equalToSuperview()
}
teamVisibilitySwitch.isOn = true
teamVisibilitySwitch.addTarget(self, action: #selector(switchStateDidChange(_:)), for: .valueChanged)
view.addSubview(teamVisibilitySwitch) {
$0.top.equalTo(uploadImageButton.snp.bottom).offset(Style.Padding.p16)
$0.trailing.equalToSuperview().inset(Style.Padding.p32)
}
teamVisibilitySwitchStatusLabel.text = Strings.Challenge.CreateTeam.teamVisibilitySwitchStatusPublic
teamVisibilitySwitchStatusLabel.textAlignment = .left
view.addSubview(teamVisibilitySwitchStatusLabel) {
$0.top.equalTo(uploadImageButton.snp.bottom).offset(Style.Padding.p20)
$0.trailing.equalToSuperview().inset(Style.Size.s75)
$0.width.equalTo(Style.Size.s64)
}
teamVisibilityTitleLabel.text = Strings.Challenge.CreateTeam.teamVisibilityTitleText
view.addSubview(teamVisibilityTitleLabel) {
$0.top.equalTo(uploadImageButton.snp.bottom).offset(Style.Size.s16)
$0.leading.equalToSuperview().offset(Style.Size.s32)
}
visibilityBodyLabel.text = Strings.Challenge.CreateTeam.visibilityBodyOn
view.addSubview(visibilityBodyLabel) {
$0.top.equalTo(teamVisibilityTitleLabel.snp.bottom).offset(Style.Padding.p16)
$0.trailing.equalToSuperview().inset(Style.Size.s32)
$0.leading.equalToSuperview().offset(Style.Size.s32)
}
view.addSubview(activityView) {
$0.centerX.centerY.equalToSuperview()
}
onBackground {
AKFCausesService.getParticipant(fbid: User.id) { (result) in
guard let participant = Participant(json: result.response),
let eventId = participant.currentEvent?.id
else { return }
AKFCausesService.getEvent(event: eventId) { (result) in
self.event = Event(json: result.response)
}
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
@objc
func closeButtonTapped() {
dismiss(animated: true, completion: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
@objc
func teamNameChanged(_ sender: UITextField) {
guard let newValue = sender.text else { return }
teamName = newValue
navigationItem.rightBarButtonItem?.isEnabled = teamName.count > 3
}
@objc
func switchStateDidChange(_ sender: UISwitch) {
if sender.isOn == true {
visibilityBodyLabel.text = Strings.Challenge.CreateTeam.visibilityBodyOn
teamVisibilitySwitchStatusLabel.text = Strings.Challenge.CreateTeam.teamVisibilitySwitchStatusPublic
} else {
visibilityBodyLabel.text = Strings.Challenge.CreateTeam.visibilityBodyOff
teamVisibilitySwitchStatusLabel.text = Strings.Challenge.CreateTeam.teamVisibilitySwitchStatusPrivate
}
}
@objc
func uploadImageButtonTapped() {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
print("Button capture")
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
print("\(info)")
if let image = info[.originalImage] as? UIImage {
teamPhotoImageView.contentMode = .scaleAspectFill
teamPhotoImageView.image = image
dismiss(animated: true, completion: nil)
}
}
@objc
func createTapped() {
activityView.startAnimating()
navigationItem.rightBarButtonItem?.isEnabled = false
teamNameTextField.isEnabled = false
guard let imageData = self.teamPhotoImageView.image?.jpegData(compressionQuality: 0.25) else { return }
AZSClient.uploadImage(data: imageData, teamName: teamName) { (error, success) in
if let err = error {
print("Image cannot be uploaded: \(err)")
self.showErrorAlert()
} else {
print(self.teamName, " uploaded!")
AKFCausesService.createTeam(name: self.teamName.trimmingCharacters(in: .whitespaces), imageName: self.teamName,
lead: User.id) { [weak self] (result) in
onMain {
guard let `self` = self else { return }
self.activityView.stopAnimating()
self.teamNameTextField.isEnabled = true
self.navigationItem.rightBarButtonItem?.isEnabled = true
guard let teamID = Team(json: result.response)?.id else {
self.showErrorAlert()
return
}
AKFCausesService.joinTeam(fbid: User.id, team: teamID) { [weak self] (result) in
onMain {
guard let `self` = self else { return }
switch result {
case .success:
// swiftlint:disable:next line_length
self.navigationController?.setViewControllers([CreateTeamSuccessViewController(for: self.event, teamName: self.teamName.trimmingCharacters(in: .whitespaces))],
animated: true)
NotificationCenter.default.post(name: .teamChanged, object: nil)
case .failed:
// If creating a team is successful but joining fails - delete it.
AKFCausesService.deleteTeam(team: teamID)
self.showErrorAlert()
}
}
}
}
}
}
}
}
private func showErrorAlert() {
let alert = AlertViewController()
alert.title = Strings.Challenge.CreateTeam.errorTitle
alert.body = Strings.Challenge.CreateTeam.errorBody
alert.add(.okay())
AppController.shared.present(alert: alert, in: self, completion: nil)
}
}
|
bsd-3-clause
|
1bc98df5b7f01e21f20f8e54dfa020b7
| 41.377163 | 205 | 0.666612 | 4.873458 | false | false | false | false |
RyanMacG/poppins
|
Poppins/Models/Pasteboard.swift
|
3
|
1397
|
import UIKit
import MobileCoreServices
private let LastCheckedPasteboardVersionKey = "PoppinsLastCheckedPasteboardVersionKey"
let GIFType = CFBridgingRetain(kUTTypeGIF) as! String
let JPEGType = CFBridgingRetain(kUTTypeJPEG) as! String
let PNGType = CFBridgingRetain(kUTTypePNG) as! String
struct Pasteboard {
static func fetchImageData() -> (data: NSData, type: String)? {
let systemPasteboard = UIPasteboard.generalPasteboard()
if let gif = systemPasteboard.dataForPasteboardType(GIFType) { return (gif, GIFType) }
if let jpeg = systemPasteboard.dataForPasteboardType(JPEGType) { return (jpeg, JPEGType) }
if let png = systemPasteboard.dataForPasteboardType(PNGType) { return (png, PNGType) }
return .None
}
static var hasImageData :Bool {
if !hasPasteboardChanged { return false }
let systemPasteboard = UIPasteboard.generalPasteboard()
NSUserDefaults.standardUserDefaults().setInteger(systemPasteboard.changeCount, forKey: LastCheckedPasteboardVersionKey)
return systemPasteboard.containsPasteboardTypes([GIFType, JPEGType, PNGType])
}
private static var hasPasteboardChanged: Bool {
let lastCheckedVersion = NSUserDefaults.standardUserDefaults().integerForKey(LastCheckedPasteboardVersionKey)
return lastCheckedVersion != UIPasteboard.generalPasteboard().changeCount
}
}
|
mit
|
b63dc19f37e4f61ab145d8c23ebaa953
| 40.088235 | 127 | 0.757337 | 4.919014 | false | false | false | false |
GeekerHua/GHSwiftTest
|
GHPlayground.playground/Pages/反射.xcplaygroundpage/Contents.swift
|
1
|
1054
|
//: [Previous](@previous)
import UIKit
//var str = "Hello, playground"
let view = UIView()
class p: UIViewController {
}
//var str = UIView.self
let str = "UIView"
let cls: AnyClass = NSClassFromString(str)!
let ttt = cls.alloc()
print(cls)
print(view.dynamicType)
view.dynamicType
let v = Mirror(reflecting: view)
v.subjectType
//let p = cls()
class Dog: NSObject {
}
let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
//拼接成固定格式
let controller: AnyClass? = NSClassFromString(nameSpace + "." + "Dog")
//创建对象
//let viewController = (controller as! UIViewController.Type).init()
v.superclassMirror()
v.description
let pp = p()
let ppp = Mirror(reflecting: pp)
print(ppp.subjectType)
let s : String = String(ppp.subjectType)
ppp.superclassMirror()
print("sdfds=\(s)")
//let p = cls()
String(Mirror(reflecting: pp).subjectType)
//let v = NSClassFromString(str)()
//let str: String = NSStringFromClass(UIView.self)
//let str = NSClassFromString("UIView")
//: [Next](@next)
|
mit
|
668f8863825932d3595b4a07a4be8a53
| 17.428571 | 86 | 0.702519 | 3.474747 | false | false | false | false |
daltoniam/Starscream
|
Sources/Framer/StringHTTPHandler.swift
|
1
|
4719
|
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// StringHTTPHandler.swift
// Starscream
//
// Created by Dalton Cherry on 8/25/19.
// Copyright © 2019 Vluxe. 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
public class StringHTTPHandler: HTTPHandler {
var buffer = Data()
weak var delegate: HTTPHandlerDelegate?
public init() {
}
public func convert(request: URLRequest) -> Data {
guard let url = request.url else {
return Data()
}
var path = url.absoluteString
let offset = (url.scheme?.count ?? 2) + 3
path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
guard var data = httpBody.data(using: .utf8) else {
return Data()
}
if let body = request.httpBody {
data.append(body)
}
return data
}
public func parse(data: Data) -> Int {
let offset = findEndOfHTTP(data: data)
if offset > 0 {
buffer.append(data.subdata(in: 0..<offset))
if parseContent(data: buffer) {
buffer = Data()
}
} else {
buffer.append(data)
}
return offset
}
//returns true when the buffer should be cleared
func parseContent(data: Data) -> Bool {
guard let str = String(data: data, encoding: .utf8) else {
delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData))
return true
}
let splitArr = str.components(separatedBy: "\r\n")
var code = -1
var i = 0
var headers = [String: String]()
for str in splitArr {
if i == 0 {
let responseSplit = str.components(separatedBy: .whitespaces)
guard responseSplit.count > 1 else {
delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData))
return true
}
if let c = Int(responseSplit[1]) {
code = c
}
} else {
guard let separatorIndex = str.firstIndex(of: ":") else { break }
let key = str.prefix(upTo: separatorIndex).trimmingCharacters(in: .whitespaces)
let val = str.suffix(from: str.index(after: separatorIndex)).trimmingCharacters(in: .whitespaces)
headers[key.lowercased()] = val
}
i += 1
}
if code != HTTPWSHeader.switchProtocolCode {
delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code, headers)))
return true
}
delegate?.didReceiveHTTP(event: .success(headers))
return true
}
public func register(delegate: HTTPHandlerDelegate) {
self.delegate = delegate
}
private func findEndOfHTTP(data: Data) -> Int {
let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var pointer = [UInt8]()
data.withUnsafeBytes { pointer.append(contentsOf: $0) }
var k = 0
for i in 0..<data.count {
if pointer[i] == endBytes[k] {
k += 1
if k == 4 {
return i + 1
}
} else {
k = 0
}
}
return -1
}
}
|
apache-2.0
|
a8b1659f3c991613af14049a9bdc4462
| 31.993007 | 113 | 0.509326 | 4.62096 | false | false | false | false |
SummerHH/swift3.0WeBo
|
WeBo/Classes/Controller/Main(主要)/Welcome/WelcomeViewController.swift
|
1
|
1922
|
//
// WelcomeViewController.swift
// WeBo
//
// Created by 叶炯 on 2016/11/3.
// Copyright © 2016年 叶炯. All rights reserved.
//
import UIKit
import SDWebImage
class WelcomeViewController: UIViewController {
//MARK:- 设置属性
@IBOutlet weak var UserHeaderImg: UIImageView!
@IBOutlet weak var UserNickname: UILabel!
@IBOutlet weak var UserHeraderImgBottom: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
//使用xib设置圆角 需要使用 KVC 监听属性的的值 layer.cornerRadius 类型为 number layer.masksToBounds 类型了 Bool
let profileURLString = UserAccountViewModel.shareIntance.account?.avatar_large
//??: 如果??前面的可选类型有值,那么将前面的可选类型解包并且赋值
//如果??前面的可选类型为 nil那么直接使用后面的值
let profileURL = URL(string: profileURLString ?? "")
UserHeaderImg.sd_setImage(with: profileURL, placeholderImage: UIImage(named: "avatar_default"))
UserNickname.text = UserAccountViewModel.shareIntance.account?.screen_name ?? "欢迎回来"
// 改变约束的值
UserHeraderImgBottom.constant = UIScreen.main.bounds.height - 2_00
// 执行动画
// Damping : 阻力系数,阻力系数越大,弹动的效果越不明显 0~1
// initialSpringVelocity : 初始化速度
UIView.animate(withDuration: 2.0, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 6.0, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
}) { (_) in
UIApplication.shared.keyWindow?.rootViewController = MainViewController()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
3be038b24a690750d12bb80155151860
| 33.428571 | 150 | 0.666271 | 4.336761 | false | false | false | false |
nsgeek/ELRouter
|
ELRouterTests/RouteTests.swift
|
1
|
14589
|
//
// RouteTests.swift
// ELRouter
//
// Created by Angelo Di Paolo on 12/09/15.
// Copyright © 2015 Walmart. All rights reserved.
//
import XCTest
@testable import ELRouter
// MARK: - initialization Tests
class RouteTests: XCTestCase {
func test_initialization_withName() {
let route = Route("testName", type: .Other)
XCTAssertNotNil(route.name)
XCTAssertEqual(route.name, "testName")
XCTAssertEqual(route.type, RoutingType.Other)
XCTAssertNil(route.parentRoute)
XCTAssertNil(route.parentRouter)
XCTAssertNil(route.action)
XCTAssertTrue(route.userInfo.isEmpty)
XCTAssertTrue(route.subRoutes.isEmpty)
}
func test_initialization_withNameAndAction() {
let route = Route("testName", type: .Other) { _, _, _ in
return nil
}
XCTAssertNotNil(route.name)
XCTAssertEqual(route.name, "testName")
XCTAssertEqual(route.type, RoutingType.Other)
XCTAssertNil(route.parentRoute)
XCTAssertNil(route.parentRouter)
XCTAssertNotNil(route.action)
XCTAssertTrue(route.userInfo.isEmpty)
XCTAssertTrue(route.subRoutes.isEmpty)
}
func test_initialization_withoutName() {
let parentRoute = Route("parent", type: .Other)
let route = Route(type: .Other, parentRoute: parentRoute)
XCTAssertNil(route.name)
XCTAssertEqual(route.type, RoutingType.Other)
XCTAssertNotNil(route.parentRoute)
XCTAssertEqual(route.parentRoute, parentRoute)
XCTAssertNil(route.parentRouter)
XCTAssertNil(route.action)
XCTAssertTrue(route.userInfo.isEmpty)
XCTAssertTrue(route.subRoutes.isEmpty)
}
func test_initialization_withTypeAndAction() {
let parentRoute = Route("parent", type: .Other)
let route = Route(type: .Other, parentRoute: parentRoute) { _, _, _ in
return nil
}
XCTAssertNil(route.name)
XCTAssertEqual(route.type, RoutingType.Other)
XCTAssertNotNil(route.parentRoute)
XCTAssertEqual(route.parentRoute, parentRoute)
XCTAssertNil(route.parentRouter)
XCTAssertNotNil(route.action)
XCTAssertTrue(route.userInfo.isEmpty)
XCTAssertTrue(route.subRoutes.isEmpty)
}
func test_initialization_withNamedAndParentRoute() {
let parentRoute = Route("parent", type: .Other)
let route = Route("sub", type: .Other, parentRoute: parentRoute) { _, _, _ in
return nil
}
XCTAssertNotNil(route.name)
XCTAssertEqual(route.name, "sub")
XCTAssertEqual(route.type, RoutingType.Other)
XCTAssertNotNil(route.parentRoute)
XCTAssertNil(route.parentRouter)
XCTAssertNotNil(route.action)
XCTAssertTrue(route.userInfo.isEmpty)
XCTAssertTrue(route.subRoutes.isEmpty)
}
}
// MARK: - variable Tests
extension RouteTests {
func test_variable_appendsSubRoute() {
let parentRoute = Route("variableTest", type: .Other)
parentRoute.variable()
XCTAssertFalse(parentRoute.subRoutes.isEmpty)
XCTAssertEqual(parentRoute.subRoutes.count, 1)
}
func test_variable_returnsSubRoute() {
let parentRoute = Route("variableTest", type: .Other)
let variableRoute = parentRoute.variable()
XCTAssertEqual(variableRoute.type, RoutingType.Variable)
}
func test_variable_setsParentRouter() {
let router = Router()
let parentRoute = Route("variableTest", type: .Other)
parentRoute.parentRouter = router
parentRoute.variable()
XCTAssertEqual(parentRoute.subRoutes[0].parentRouter, router)
}
func test_variable_setsParentRoute() {
let parentRoute = Route("variableTest", type: .Other)
parentRoute.variable()
XCTAssertEqual(parentRoute.subRoutes[0].parentRoute, parentRoute)
}
}
// MARK: - route Tests
extension RouteTests {
func test_route_appendsSubRoute() {
let parentRoute = Route("routeTest", type: .Other)
parentRoute.route("sub", type: .Other)
XCTAssertFalse(parentRoute.subRoutes.isEmpty)
XCTAssertEqual(parentRoute.subRoutes.count, 1)
}
func test_route_returnsSubRoute() {
let parentRoute = Route("routeTest", type: .Other)
let subRoute = parentRoute.route("sub", type: .Other)
XCTAssertEqual(subRoute.name, "sub")
XCTAssertEqual(subRoute.type, RoutingType.Other)
}
func test_route_setsParentRouter() {
let router = Router()
let parentRoute = Route("routeTest", type: .Other)
parentRoute.parentRouter = router
parentRoute.route("sub", type: .Other)
XCTAssertEqual(parentRoute.subRoutes[0].parentRouter, router)
}
func test_route_setsParentRoute() {
let parentRoute = Route("variableTest", type: .Other)
parentRoute.route("sub", type: .Other)
XCTAssertEqual(parentRoute.subRoutes[0].parentRoute, parentRoute)
}
}
// MARK: - execute Tests
extension RouteTests {
func test_execute_returnsActionResult() {
let route = Route("executeTest", type: .Other) { variable, _, _ in
return "foo"
}
var associatedData: AssociatedData? = nil
let result = route.execute(false, variable: nil, remainingComponents: [String](), associatedData: &associatedData)
XCTAssertNotNil(result)
XCTAssertTrue(result is String)
XCTAssertEqual(result as? String, "foo")
}
func test_execute_passesVariableToActionClosure() {
let route = Route("executeTest", type: .Static) { variable, _, _ in
XCTAssertNotNil(variable)
XCTAssertEqual(variable, "foo")
return nil
}
var associatedData: AssociatedData? = nil
route.execute(false, variable: "foo", remainingComponents: [String](), associatedData: &associatedData)
}
/* Broken Test
func test_execute_pushesViewController() {
let router = Router()
let navigator = MockNavigator()
router.navigator = navigator
let route = Route("executeTest", type: .Push) { variable, _ in
let vc = UIViewController(nibName: nil, bundle: nil)
vc.title = "Push Test"
return vc
}
route.parentRouter = router
route.execute(false)
XCTAssertEqual(navigator.testNavigationController?.viewControllers.count, 2)
XCTAssertEqual(navigator.testNavigationController?.topViewController?.title, "Push Test")
}*/
// TODO: Test fails due to lack of view hierarchy and I don't have a solution at this time.
// func test_execute_presentsModalViewController() {
// let router = Router()
// let navigator = MockNavigator()
// router.navigator = navigator
// let route = Route("executeTest", type: .Modal) { variable in
// let vc = UIViewController(nibName: nil, bundle: nil)
// vc.title = "Modal Test"
// return vc
// }
// route.parentRouter = router
//
// route.execute(false)
//
// XCTAssertEqual(navigator.testNavigationController?.viewControllers.count, 1)
// XCTAssertNotNil(navigator.testNavigationController?.topViewController?.presentedViewController)
// XCTAssertEqual(navigator.testNavigationController?.topViewController?.presentedViewController?.title, "Modal Test")
// }
func test_execute_returnsStaticValue() {
let route = Route("executeTest", type: .Static) { _, _, _ in
let vc = UIViewController(nibName: nil, bundle: nil)
vc.title = "Static Test"
return vc
}
let staticValue = route.execute(false)
XCTAssertNotNil(staticValue)
XCTAssertTrue(staticValue is UIViewController)
XCTAssertEqual((staticValue as? UIViewController)?.title, "Static Test")
}
func test_execute_performsSegue() {
let router = Router()
let navigator = MockNavigator()
router.navigator = navigator
let vc = ExecuteSegueTestViewController(nibName: nil, bundle: nil)
let navVC = UINavigationController(rootViewController: vc)
navigator.setViewControllers([navVC], animated: false)
navigator.selectedViewController = navVC
let route = Route("segueTest", type: .Segue) { _, _, _ in
return "fooSegue"
}
route.parentRouter = router
route.execute(false)
XCTAssertEqual(vc.segueIdentifierValue, "fooSegue")
}
func test_execute_setsSelectedViewController() {
let router = Router()
let navigator = MockNavigator()
router.navigator = navigator
let vc = UIViewController(nibName: nil, bundle: nil)
let route = Route("selectTest", type: .Static) { _, _, _ in
return vc
}
route.parentRouter = router
route.execute(false) // setup staticValue
route.execute(false)
XCTAssertEqual(vc, navigator.selectedViewController)
}
}
// MARK: - routesForComponents Tests
extension RouteTests {
func test_routesForComponents_returnsEmptyResultsForBogusComponents() {
let route = Route("variableTest", type: .Other)
let results = route.routesForComponents(["walmart.com", "foo"])
XCTAssertTrue(results.isEmpty)
}
func test_routesForComponents_returnsEmptyResultsForEmptyComponents() {
let route = Route("variableTest", type: .Other)
let results = route.routesForComponents([])
XCTAssertTrue(results.isEmpty)
}
func test_routesForComponents_returnsNamedRoutesForValidComponents() {
let route = Route("variableTest", type: .Other)
route.route("walmart.com", type: .Other).route("foo", type: .Other)
let results = route.routesForComponents(["walmart.com", "foo"])
XCTAssertFalse(results.isEmpty)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0].name, "walmart.com")
XCTAssertEqual(results[1].name, "foo")
}
func test_routesForComponents_returnsVariableRoutesWhenNextComponentExists() {
let route = Route("variableTest", type: .Other)
route.route("walmart.com", type: .Other).variable().route("foo", type: .Other)
let results = route.routesForComponents(["walmart.com", "12345", "foo"])
XCTAssertFalse(results.isEmpty)
XCTAssertEqual(results.count, 3)
XCTAssertEqual(results[0].name, "walmart.com")
XCTAssertEqual(results[1].type, RoutingType.Variable)
XCTAssertEqual(results[2].name, "foo")
}
func test_routesForComponents_returnsVariableRoutesWhenNextComponentIsMissing() {
let route = Route("variableTest", type: .Other)
route.route("walmart.com", type: .Other).variable().route("foo", type: .Other)
let results = route.routesForComponents(["walmart.com", "12345"])
XCTAssertFalse(results.isEmpty)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0].name, "walmart.com")
XCTAssertEqual(results[1].type, RoutingType.Variable)
}
}
// MARK: - routesByName Tests
extension RouteTests {
func test_routesByName_returnsRoutesForValidName() {
let testName1 = "subRouteName1"
let route = Route("routesByName", type: .Other)
route.variable()
route.route(testName1, type: .Other)
let namedRoutes = route.routesByName(testName1)
XCTAssertFalse(namedRoutes.isEmpty)
XCTAssertEqual(namedRoutes.count, 1)
for route in namedRoutes {
XCTAssertNotNil(route.name)
XCTAssertEqual(route.name, testName1)
}
}
func test_routesByName_returnsEmptyArrayForBogusName() {
let testName1 = "subRouteName1"
let testName2 = "subRouteName2"
let route = Route("routesByName", type: .Other)
route.variable()
route.route(testName1, type: .Other)
route.route(testName2, type: .Static)
let namedRoutes = route.routesByName("bogusName")
XCTAssertTrue(namedRoutes.isEmpty)
}
}
// MARK: - routesByType Tests
extension RouteTests {
func test_routesByType_returnsRoutesForValidType() {
let testName1 = "subRouteName1"
let testName2 = "subRouteName2"
let route = Route("routesByName", type: .Other)
route.variable()
route.route(testName1, type: .Static)
route.route(testName2, type: .Static)
let filteredRoutes = route.routesByType(.Static)
XCTAssertFalse(filteredRoutes.isEmpty)
XCTAssertEqual(filteredRoutes.count, 2)
for route in filteredRoutes {
XCTAssertEqual(route.type, RoutingType.Static)
}
}
func test_routesByType_returnsEmptyArrayForBogusType() {
let testName1 = "subRouteName1"
let testName2 = "subRouteName2"
let route = Route("routesByName", type: .Other)
route.variable()
route.route(testName1, type: .Static)
route.route(testName2, type: .Static)
let filteredRoutes = route.routesByType(.Other)
XCTAssertTrue(filteredRoutes.isEmpty)
}
}
// MARK: - routeByType
extension RouteTests {
func test_routeByType_returnsRouteForValidType() {
let testName = "subRouteName"
let route = Route("routeByName", type: .Other)
route.route(testName, type: .Static)
let fetchedRoute = route.routeByType(.Static)
XCTAssertNotNil(fetchedRoute)
XCTAssertEqual(fetchedRoute?.type, RoutingType.Static)
XCTAssertEqual(fetchedRoute?.name, testName)
}
func test_routeByType_returnsNilForBogusType() {
let route = Route("routeByName", type: .Other)
let fetchedRoute = route.routeByType(.Static)
XCTAssertNil(fetchedRoute)
}
}
// MARK: - Mock vc
private class ExecuteSegueTestViewController: UIViewController {
var segueIdentifierValue: String?
override func performSegueWithIdentifier(identifier: String, sender: AnyObject?) {
segueIdentifierValue = identifier
}
}
|
mit
|
7818e179b662609473cbec0964adc024
| 33.40566 | 125 | 0.63703 | 4.53466 | false | true | false | false |
biohazardlover/i3rd
|
MaChérie/AppDelegate.swift
|
1
|
4743
|
//
// AppDelegate.swift
// MaChérie
//
// Created by Leon Li on 2018/6/14.
// Copyright © 2018 Leon & Vane. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var popInteractor: PopInteractor?
class var shared: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
application.statusBarStyle = .lightContent
UINavigationBar.appearance().barTintColor = R.color.backgroundColor()
UINavigationBar.appearance().tintColor = R.color.primaryTextColor()
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : R.color.primaryTextColor()!]
UINavigationBar.appearance().setBackgroundImage(UIImage(color: R.color.backgroundColor()!, size: CGSize(width: 1, height: 1)), for: .default)
UINavigationBar.appearance().shadowImage = R.image.navigationBarShadow()
let splitViewController = window!.rootViewController as! UISplitViewController
splitViewController.delegate = self
(splitViewController.viewControllers[0] as! UINavigationController).delegate = self
(splitViewController.viewControllers[1] as! UINavigationController).delegate = self
UserDefaults.standard.register(defaults: [
Player1PassiveHitboxHiddenKey : false,
Player1OtherVulnerabilityHitboxHiddenKey : false,
Player1ActiveHitboxHiddenKey : false,
Player1ThrowHitboxHiddenKey : false,
Player1ThrowableHitboxHiddenKey : false,
Player1PushHitboxHiddenKey : false,
Player2PassiveHitboxHiddenKey : true,
Player2OtherVulnerabilityHitboxHiddenKey : true,
Player2ActiveHitboxHiddenKey : true,
Player2ThrowHitboxHiddenKey : true,
Player2ThrowableHitboxHiddenKey : true,
Player2PushHitboxHiddenKey : true,
PreferredPassiveHitboxRGBColorKey : 0x0000FF,
PreferredOtherVulnerabilityHitboxRGBColorKey : 0x007FFF,
PreferredActiveHitboxRGBColorKey : 0xFF0000,
PreferredThrowHitboxRGBColorKey : 0xFF7F00,
PreferredThrowableHitboxRGBColorKey : 0x00FF00,
PreferredPushHitboxRGBColorKey : 0x7F00FF,
PreferredFramesPerSecondKey : 30
])
return true
}
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
UserDefaults.standard.set(version, forKey: ApplicationStateRestorationVersionKey)
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
let applicationStateRestorationVersion = UserDefaults.standard.string(forKey: ApplicationStateRestorationVersionKey)
return applicationStateRestorationVersion == version
}
}
extension AppDelegate: UISplitViewControllerDelegate {
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
let detailViewController = (secondaryViewController as! UINavigationController).topViewController as! CharacterMovesViewController
if detailViewController.sections.count == 0 {
return true
} else {
return false
}
}
}
extension AppDelegate: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
popInteractor = PopInteractor(attachTo: toVC)
return PushAnimator()
case .pop:
return PopAnimator()
case .none:
return nil
}
}
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if let popInteractor = popInteractor, popInteractor.transitionInProgress {
return popInteractor
} else {
return nil
}
}
}
|
mit
|
c2991456400cda61594ad0c9870bf5bc
| 44.586538 | 246 | 0.71293 | 5.941103 | false | false | false | false |
garthmac/ChemicalVisualizer
|
AppDelegate.swift
|
1
|
6209
|
//
// AppDelegate.swift
// ChemicalVisualizer Copyright (c) 2015 Garth MacKenzie
//
// Created by iMac 27 on 2015-12-01.
//
//
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.
NSURLProtocol.registerClass(MyURLProtocol)
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 "com.garthmackenzie.Chemical3D" 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("Chemical3D", 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("NSURLProtocolCD.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()
}
}
}
}
|
mit
|
604fb69a46734f6116e8a3fbcdae61a1
| 54.936937 | 291 | 0.712675 | 5.879735 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS
|
WordPressEditor/WordPressEditor/Classes/Plugins/WordPressPlugin/Gutenberg/GutenpackConverter.swift
|
2
|
1570
|
import Aztec
import Foundation
public extension Element {
static let gutenpack = Element("gutenpack")
}
public class GutenpackConverter: ElementConverter {
// MARK: - ElementConverter
public func convert(
_ element: ElementNode,
inheriting attributes: [NSAttributedString.Key: Any],
contentSerializer serialize: ContentSerializer) -> NSAttributedString {
precondition(element.type == .gutenpack)
let decoder = GutenbergAttributeDecoder()
guard let content = decoder.attribute(.selfCloser, from: element) else {
let serializer = HTMLSerializer()
let attachment = HTMLAttachment()
attachment.rootTagName = element.name
attachment.rawHTML = serializer.serialize(element)
let representation = NSAttributedString(attachment: attachment, attributes: attributes)
return serialize(element, representation, attributes, false)
}
let blockContent = String(content[content.startIndex ..< content.index(before: content.endIndex)])
let blockName = String(content.trimmingCharacters(in: .whitespacesAndNewlines).prefix(while: { (char) -> Bool in
char != " "
}))
let attachment = GutenpackAttachment(name: blockName, content: blockContent)
let representation = NSAttributedString(attachment: attachment, attributes: attributes)
return serialize(element, representation, attributes, false)
}
}
|
gpl-2.0
|
30e1b31c78b975643e3c8b5f1a0d9561
| 35.511628 | 120 | 0.653503 | 5.528169 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK
|
BridgeAppSDK/SBASurveyFactory.swift
|
1
|
10225
|
//
// SBASurveyFactory.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. 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(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
import BridgeSDK
import ResearchUXFactory
/**
Custom step types recognized by this Framework
*/
public enum BridgeSurveyItemSubtype: String {
case onboardingCompletion = "onboardingCompletion" // SBAOnboardingCompletionStep
case profileItem = "profileItem" // Mapped to the profile questions list
}
/**
Extend the `SBASurveyItemType` to return the custom bridge subtypes.
*/
extension SBASurveyItemType {
func bridgeSubtype() -> BridgeSurveyItemSubtype? {
if case .custom(let subtype) = self, subtype != nil {
return BridgeSurveyItemSubtype(rawValue: subtype!)
}
return nil
}
}
/**
Override the base class for the survey factory to return a subclass that includes creating
surveys from an `SBBSurvey`, and also to handle account management classes that aren't
defined in the base class.
*/
open class SBASurveyFactory : SBABaseSurveyFactory {
public static var profileQuestionSurveyItems: [SBASurveyItem]? = {
guard let json = SBAResourceFinder.shared.json(forResource: SBAProfileQuestionsJSONFilename) else { return nil }
return json["steps"] as? [NSDictionary]
}()
// use a lazy load to only load when called, but then retain the result in memory.
lazy open var currentDataGroups: Set<String> = {
return SBAProfileManager.shared?.getDataGroups() ??
Set((UIApplication.shared.delegate as? SBAAppDelegate)?.currentUser.dataGroups ?? [])
}()
/**
Factory method for creating an ORKTask from an SBBSurvey
@param survey An `SBBSurvey` bridge model object
@return Task created with this survey
*/
open func createTaskWithSurvey(_ survey: SBBSurvey) -> SBANavigableOrderedTask {
// Build the steps
let count = survey.elements.count
var usesTitleAndText: Bool = false
let steps: [ORKStep] = survey.elements.enumerated().sba_mapAndFilter({ (offset: Int, element: Any) -> ORKStep? in
guard let surveyItem = element as? SBBSurveyElement else { return nil }
let step = self.createSurveyStepWithSurveyElement(surveyItem, index: offset, count: count)
if let qStep = step as? ORKQuestionStep, qStep.title != nil {
usesTitleAndText = true
}
return step
})
// If some of the questions use the title field, then set all the questions to
// use the title field if the prompt was initially set to the text.
if usesTitleAndText {
for step in steps {
if step is ORKQuestionStep, step.title == nil {
step.title = step.text
step.text = nil
}
}
}
return SBANavigableOrderedTask(identifier: survey.identifier, steps: steps)
}
/**
Factory method for creating a survey step with an SBBSurveyElement
@param inputItem A `SBBSurveyElement` bridge model object
@return An `ORKStep`
*/
@available(*, unavailable, message: "Use `createSurveyStepWithSurveyElement(_:index:count:) instead.")
open func createSurveyStepWithSurveyElement(_ inputItem: SBBSurveyElement, isLastStep:Bool = false) -> ORKStep? {
return nil
}
/**
Factory method for creating a survey step with an SBBSurveyElement
@param inputItem A `SBBSurveyElement` bridge model object
@param index The index into the task
@param count The total number of steps
@return An `ORKStep`
*/
open func createSurveyStepWithSurveyElement(_ inputItem: SBBSurveyElement, index: Int, count: Int) -> ORKStep? {
guard let surveyItem = inputItem as? SBASurveyItem else { return nil }
return self.createSurveyStep(surveyItem)
}
open override func createTaskWithActiveTask(_ activeTask: SBAActiveTask, taskOptions: ORKPredefinedTaskOption) -> (NSCopying & NSSecureCoding & ORKTask)? {
if activeTask.taskType == .activeTask(.cardio) {
return activeTask.createBridgeCardioChallenge(options: taskOptions, factory: self)
}
return super.createTaskWithActiveTask(activeTask, taskOptions: taskOptions)
}
open override func createSurveyStep(_ inputItem: SBASurveyItem, isSubtaskStep: Bool = false) -> ORKStep? {
// If this input item conforms to the data groups rule, check against the current data groups
// and nil out the step if it should be excluded.
if let rule = inputItem as? SBADataGroupsRule, rule.shouldExcludeStep(currentDataGroups: self.currentDataGroups) {
return nil
}
return super.createSurveyStep(inputItem, isSubtaskStep: isSubtaskStep)
}
open override func createSurveyStepWithCustomType(_ inputItem: SBASurveyItem) -> ORKStep? {
guard let bridgeSubtype = inputItem.surveyItemType.bridgeSubtype() else {
return super.createSurveyStepWithCustomType(inputItem)
}
switch (bridgeSubtype) {
case .onboardingCompletion:
return SBAOnboardingCompleteStep(inputItem: inputItem)
case .profileItem:
return profileItemStep(for: inputItem.identifier)?.copy() as? ORKStep
}
}
open func profileItemStep(for profileKey: String) -> ORKStep? {
guard let inputItem = SBASurveyFactory.profileQuestionSurveyItems?.sba_find(withIdentifier: profileKey) else {
return nil
}
return self.createSurveyStep(inputItem)
}
open override func createAccountStep(inputItem: SBASurveyItem, subtype: SBASurveyItemType.AccountSubtype) -> ORKStep? {
switch (subtype) {
case .registration:
return SBARegistrationStep(inputItem: inputItem, factory: self)
case .login:
// For the login case, return a different implementation depending upon whether or not
// this is login via username or externalID. For some studies, PII (email) is not collected
// and instead the participant is assigned an external identifier that is used to log them in.
let profileOptions = SBAProfileInfoOptions(inputItem: inputItem)
if profileOptions.includes.contains(.externalID) {
return SBAExternalIDLoginStep(inputItem: inputItem)
}
else {
return SBALoginStep(inputItem: inputItem, factory: self)
}
case .emailVerification:
return SBAEmailVerificationStep(inputItem: inputItem)
case .externalID:
return SBAExternalIDAssignStep(inputItem: inputItem, factory: self)
case .permissions:
// For permissions, we want to replace the default permissions step with a
// single step (if possible) to capture info specific to that step
if let singleStep = SBASinglePermissionStep(inputItem: inputItem) {
return singleStep
}
else {
return super.createAccountStep(inputItem:inputItem, subtype: subtype)
}
default:
return super.createAccountStep(inputItem:inputItem, subtype: subtype)
}
}
// Override the base class to implement creating consent steps
override open func createConsentStep(inputItem: SBASurveyItem, subtype: SBASurveyItemType.ConsentSubtype) -> ORKStep? {
switch (subtype) {
case .visual:
return SBAVisualConsentStep(identifier: inputItem.identifier, consentDocument: self.consentDocument)
case .sharingOptions:
return SBAConsentSharingStep(inputItem: inputItem)
case .review:
if let consentReview = inputItem as? SBAConsentReviewOptions,
consentReview.usesDeprecatedOnboarding {
// Use the superclass instance of the review step
return super.createConsentStep(inputItem: inputItem, subtype: subtype)
}
else {
let review = inputItem as! SBAFormStepSurveyItem
let step = SBAConsentReviewStep(inputItem: review, inDocument: self.consentDocument, factory: self)
return step;
}
}
}
}
|
bsd-3-clause
|
3ef4eff0a0d763557a70fef49077de51
| 43.842105 | 159 | 0.666471 | 5.071429 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK
|
BridgeAppSDK/SBAActivityTableViewCell.swift
|
1
|
2769
|
//
// SBAActivityTableViewCell.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. 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(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
open class SBAActivityTableViewCell: UITableViewCell {
@IBOutlet weak var uncheckedView: UIView!
@IBOutlet weak var checkmarkImageView: UIImageView!
@IBOutlet open weak var titleLabel: UILabel!
@IBOutlet open weak var subtitleLabel: UILabel!
@IBOutlet open weak var timeLabel: UILabel?
internal var complete: Bool = false {
didSet {
self.uncheckedView.isHidden = complete
self.checkmarkImageView.isHidden = !complete
}
}
override open func layoutSubviews() {
super.layoutSubviews()
self.uncheckedView.layer.borderColor = UIColor.lightGray.cgColor
self.uncheckedView.layer.borderWidth = 1
self.uncheckedView.layer.cornerRadius = self.uncheckedView.bounds.size.height / 2
self.timeLabel?.textColor = self.tintColor
}
open override func tintColorDidChange() {
super.tintColorDidChange()
self.timeLabel?.textColor = self.tintColor
}
}
|
bsd-3-clause
|
d06d58e909b858f2a1d817886e75bdf6
| 40.939394 | 89 | 0.735549 | 4.978417 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK
|
BridgeAppSDK/SBANavigableOrderedTask.swift
|
1
|
15128
|
//
// SBANavigableOrderedTask.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. 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(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
/**
Define the navigation rule as a protocol to allow for protocol-oriented extention (multiple inheritance).
Currently defined usage is to allow the SBANavigableOrderedTask to check if a step has a navigation rule.
*/
public protocol SBANavigationRule: class, NSSecureCoding {
func nextStepIdentifier(with result: ORKTaskResult, and additionalTaskResults:[ORKTaskResult]?) -> String?
}
/**
A navigation skip rule applies to this step to allow that step to be skipped.
*/
public protocol SBANavigationSkipRule: class, NSSecureCoding {
func shouldSkipStep(with result: ORKTaskResult, and additionalTaskResults:[ORKTaskResult]?) -> Bool
}
/**
A conditional rule is appended to the navigable task to check a secondary source for whether or not the
step should be displayed.
*/
@objc
public protocol SBAConditionalRule: class, NSSecureCoding {
func shouldSkip(step: ORKStep?, with result: ORKTaskResult) -> Bool
func nextStep(previousStep: ORKStep?, nextStep: ORKStep?, with result: ORKTaskResult) -> ORKStep?
}
/**
* SBANavigableOrderedTask can process both SBASubtaskStep steps and as well as any step that conforms
* to the SBANavigationRule.
*/
open class SBANavigableOrderedTask: ORKOrderedTask, ORKTaskResultSource {
public var additionalTaskResults: [ORKTaskResult]?
public var conditionalRule: SBAConditionalRule?
@objc fileprivate var orderedStepIdentifiers: [String] = []
// Swift Fun Fact: In order to use a superclass initializer it must be overridden
// by the subclass. syoung 02/11/2016
public override init(identifier: String, steps: [ORKStep]?) {
super.init(identifier: identifier, steps: steps)
}
fileprivate func subtaskStep(identifier: String?) -> SBASubtaskStep? {
// Look for a period in the range of the string
guard let identifier = identifier,
let range = identifier.range(of: "."), range.upperBound > identifier.startIndex else {
return nil
}
// Parse out the subtask identifier and look in super for a step with that identifier
let subtaskStepIdentifier = identifier.substring(to: identifier.index(range.upperBound, offsetBy: -1))
guard let subtaskStep = super.step(withIdentifier: subtaskStepIdentifier) as? SBASubtaskStep else {
return nil
}
return subtaskStep
}
fileprivate func superStep(after step: ORKStep?, with result: ORKTaskResult) -> ORKStep? {
// Check the conditional rule to see if it returns a next step for the given previous
// step and return that with an early exit if applicable.
if let nextStep = self.conditionalRule?.nextStep(previousStep: step, nextStep: nil, with: result) {
return nextStep
}
var returnStep: ORKStep?
var previousStep: ORKStep? = step
var shouldSkip = false
repeat {
repeat {
if let navigableStep = previousStep as? SBANavigationRule,
let nextStepIdentifier = navigableStep.nextStepIdentifier(with: result, and:self.additionalTaskResults) {
// If this is a step that conforms to the SBANavigableStep protocol and
// the next step identifier is non-nil then get the next step by looking within
// the steps associated with this task
returnStep = super.step(withIdentifier: nextStepIdentifier)
}
else {
// If we've dropped through without setting the return step to something non-nil
// then look to super for the next step
returnStep = super.step(after: previousStep, with: result)
}
// Check if this is a skipable step
if let navigationSkipStep = returnStep as? SBANavigationSkipRule,
navigationSkipStep.shouldSkipStep(with: result, and: self.additionalTaskResults) {
shouldSkip = true
previousStep = returnStep
}
else {
shouldSkip = false
}
} while (shouldSkip)
// If the superclass returns a step of type subtask step, then get the first step from the subtask
// Since it is possible that the subtask will return an empty task (all steps are invalid) then
// need to also check that the return is non-nil
while let subtaskStep = returnStep as? SBASubtaskStep {
if let subtaskReturnStep = subtaskStep.stepAfterStep(nil, withResult: result) {
returnStep = subtaskReturnStep
}
else {
returnStep = super.step(after: subtaskStep, with: result)
}
}
// Check to see if this is a conditional step that *should* be skipped
shouldSkip = conditionalRule?.shouldSkip(step: returnStep, with: result) ?? false
if !shouldSkip, let navigationSkipStep = returnStep as? SBANavigationSkipRule {
shouldSkip = navigationSkipStep.shouldSkipStep(with: result, and: self.additionalTaskResults)
}
if (shouldSkip) {
previousStep = returnStep
}
} while(shouldSkip)
// If there is a conditionalRule, then check to see if the step should be mutated or replaced
if let conditionalRule = self.conditionalRule {
returnStep = conditionalRule.nextStep(previousStep: nil, nextStep: returnStep, with: result)
}
return returnStep;
}
// MARK: ORKOrderedTask overrides
override open func step(after step: ORKStep?, with result: ORKTaskResult) -> ORKStep? {
var returnStep: ORKStep?
// Look to see if this has a valid subtask step associated with this step
if let subtaskStep = subtaskStep(identifier: step?.identifier) {
returnStep = subtaskStep.stepAfterStep(step, withResult: result)
if (returnStep == nil) {
// If the subtask returns nil then it is at the last step
// Check super for more steps
returnStep = superStep(after: subtaskStep, with: result)
}
}
else {
// If this isn't a subtask step then look to super nav for the next step
returnStep = superStep(after: step, with: result)
}
// Look for step in the ordered steps and lop off everything after this one
if let previousIdentifier = step?.identifier,
let idx = self.orderedStepIdentifiers.index(of: previousIdentifier) , idx < self.orderedStepIdentifiers.endIndex {
self.orderedStepIdentifiers.removeSubrange(idx.advanced(by: 1) ..< self.orderedStepIdentifiers.endIndex)
}
if let identifier = returnStep?.identifier {
if let idx = self.orderedStepIdentifiers.index(of: identifier) {
self.orderedStepIdentifiers.removeSubrange(idx ..< self.orderedStepIdentifiers.endIndex)
}
self.orderedStepIdentifiers += [identifier]
}
return returnStep
}
override open func step(before step: ORKStep?, with result: ORKTaskResult) -> ORKStep? {
guard let identifier = step?.identifier,
let idx = self.orderedStepIdentifiers.index(of: identifier) , idx > 0 else {
return nil
}
let previousIdentifier = self.orderedStepIdentifiers[idx.advanced(by: -1)]
return self.step(withIdentifier: previousIdentifier)
}
override open func step(withIdentifier identifier: String) -> ORKStep? {
// Look for the step in the superclass
if let step = super.step(withIdentifier: identifier) {
return step
}
// If not found check to see if it is a substep
return subtaskStep(identifier: identifier)?.step(withIdentifier: identifier)
}
override open func progress(ofCurrentStep step: ORKStep, with result: ORKTaskResult) -> ORKTaskProgress {
// Do not show progress for an ordered task with navigation rules
return ORKTaskProgress(current: 0, total: 0)
}
override open func validateParameters() {
super.validateParameters()
for step in self.steps {
// Check if the step is a subtask step and validate parameters
if let subtaskStep = step as? SBASubtaskStep {
subtaskStep.subtask.validateParameters?()
}
}
}
override open var requestedHealthKitTypesForReading: Set<HKObjectType>? {
var set = super.requestedHealthKitTypesForReading ?? Set()
for step in self.steps {
// Check if the step is a subtask step and validate parameters
if let subtaskStep = step as? SBASubtaskStep,
let subset = subtaskStep.subtask.requestedHealthKitTypesForReading , subset != nil {
set = set.union(subset!)
}
}
return set.count > 0 ? set : nil
}
override open var providesBackgroundAudioPrompts: Bool {
let superRet = super.providesBackgroundAudioPrompts
if (superRet) {
return true
}
for step in self.steps {
// Check if the step is a subtask step and validate parameters
if let subtaskStep = step as? SBASubtaskStep,
let subRet = subtaskStep.subtask.providesBackgroundAudioPrompts , subRet {
return true
}
}
return false
}
// MARK: ORKTaskResultSource
public var initialResult: ORKTaskResult?
fileprivate var storedTaskResults: [ORKResult] {
if (initialResult == nil) {
initialResult = ORKTaskResult(identifier: self.identifier)
initialResult!.results = []
}
return initialResult!.results!
}
public func appendInitialResults(_ result: ORKStepResult) {
var results = storedTaskResults
results.append(result)
initialResult?.results = results
}
public func appendInitialResults(contentsOf results: [ORKResult]) {
var storedResults = storedTaskResults
storedResults.append(contentsOf: results)
initialResult?.results = storedResults
}
public func stepResult(forStepIdentifier stepIdentifier: String) -> ORKStepResult? {
// If there is an initial result then return that
if let result = initialResult?.stepResult(forStepIdentifier: stepIdentifier) {
return result
}
// Otherwise, look at the substeps
return subtaskStep(identifier: stepIdentifier)?.stepResult(forStepIdentifier: stepIdentifier)
}
// MARK: NSCopy
override open func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone)
guard let task = copy as? SBANavigableOrderedTask else { return copy }
task.additionalTaskResults = self.additionalTaskResults
task.orderedStepIdentifiers = self.orderedStepIdentifiers
task.conditionalRule = self.conditionalRule
task.initialResult = self.initialResult
return task
}
// MARK: NSCoding
required public init(coder aDecoder: NSCoder) {
self.additionalTaskResults = aDecoder.decodeObject(forKey: #keyPath(additionalTaskResults)) as? [ORKTaskResult]
self.orderedStepIdentifiers = aDecoder.decodeObject(forKey: #keyPath(orderedStepIdentifiers)) as! [String]
self.conditionalRule = aDecoder.decodeObject(forKey: #keyPath(conditionalRule)) as? SBAConditionalRule
self.initialResult = aDecoder.decodeObject(forKey: #keyPath(initialResult)) as? ORKTaskResult
super.init(coder: aDecoder);
}
override open func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(self.additionalTaskResults, forKey: #keyPath(additionalTaskResults))
aCoder.encode(self.conditionalRule, forKey: #keyPath(conditionalRule))
aCoder.encode(self.orderedStepIdentifiers, forKey: #keyPath(orderedStepIdentifiers))
aCoder.encode(self.initialResult, forKey: #keyPath(initialResult))
}
// MARK: Equality
override open func isEqual(_ object: Any?) -> Bool {
guard let object = object as? SBANavigableOrderedTask else { return false }
return super.isEqual(object) &&
SBAObjectEquality(self.additionalTaskResults, object.additionalTaskResults) &&
SBAObjectEquality(self.orderedStepIdentifiers, object.orderedStepIdentifiers) &&
SBAObjectEquality(self.conditionalRule as? NSObject, object.conditionalRule as? NSObject) &&
SBAObjectEquality(self.initialResult, self.initialResult)
}
override open var hash: Int {
return super.hash ^
SBAObjectHash(self.additionalTaskResults) ^
SBAObjectHash(self.orderedStepIdentifiers) ^
SBAObjectHash(self.conditionalRule) ^
SBAObjectHash(self.initialResult)
}
}
|
bsd-3-clause
|
51c4a982122a946ef6608a7f9e479510
| 43.491176 | 126 | 0.657235 | 5.00397 | false | false | false | false |
tzshlyt/GeekPark-mac
|
GeekPark/Network/HttpHelper.swift
|
1
|
2442
|
//
// HttpHelper.swift
// GeekPark
//
// Created by lan on 16/8/25.
// Copyright © 2016年 lan. All rights reserved.
//
import Cocoa
import Alamofire
import SwiftyJSON
class HttpHelper: NSObject {
private let url = "http://main_test.geekpark.net/api/v1/?page=1"
func getNews(_ handle: @escaping (_ models: [GPModel]) -> ()) {
AF.request(url, method: .get).responseJSON { response in
switch response.result {
case .failure(let error):
print("获取接口数据出错", error)
case .success:
print("Load data success")
guard let value = response.value else {
return
}
var models = [GPModel]()
let json = JSON(value), results = json["homepage_posts"]
for result in results.arrayValue {
let datas = result["data"]
for data in datas.arrayValue {
guard let title = data["post"]["title"].string,
let imgUrl = data["post"]["cover_url"].string,
let category = data["post"]["column"]["title"].string,
let published_timestamp = data["post"]["published_timestamp"].int,
let id = data["post"]["id"].int
else {
return
}
let href = "http://www.geekpark.net/news/\(id)"
let timeInterval = TimeInterval(published_timestamp)
let date = Date(timeIntervalSince1970: timeInterval)
let dformatter = DateFormatter()
dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let time = dformatter.string(from: date)
let model = GPModel(
title: title,
imgUrl: imgUrl,
category: category,
time: time,
href: href
)
models.append(model)
}
}
handle(models)
}
}
}
}
|
mit
|
e3188b5f342f1f5abd7f3d845af267d0
| 35.712121 | 97 | 0.414362 | 5.595843 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.